]> Creatis software - bbtk.git/blob - kernel/src/bbtkFactory.cxx
*** empty log message ***
[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/03/03 14:55:55 $
8 Version:   $Revision: 1.25 $
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 #include "bbtkUtilities.h"
31
32 #include <sys/stat.h> // for struct stat stFileInfo
33
34 #if defined(_WIN32)
35 #include <direct.h> // for getcwd
36 #endif
37
38 #include <cctype>    // std::toupper
39
40 // was in gdcm ...
41 /*
42 #ifdef _MSC_VER
43 #   define getcwd _getcwd
44 #endif
45
46 #if defined(_MSC_VER) || defined(__BORLANDC__)
47 #   include <direct.h>
48 #else
49 #   include <unistd.h>
50 #endif
51
52 */
53
54
55 namespace bbtk
56 {
57   typedef Package* (*PackageAccessor)();
58   typedef void (*PackageDeleteFunction)();
59
60
61   //===================================================================
62   /// Default ctor
63   Factory::Factory()
64   {
65     bbtkDebugMessage("Kernel",7,"Factory::Factory()"<<std::endl);
66   }
67   //===================================================================
68
69   //===================================================================
70   /// Dtor
71   Factory::~Factory()
72   {
73     bbtkDebugMessageInc("Kernel",7,"Factory::~Factory()"<<std::endl);
74     CloseAllPackages();
75     bbtkDebugDecTab("Kernel",7);
76   }
77   //===================================================================
78
79
80   //===================================================================
81   void Factory::CloseAllPackages()
82   {
83     bbtkDebugMessageInc("Kernel",7,"Factory::CloseAllPackages()"<<std::endl);
84     while (mPackageMap.begin() != mPackageMap.end())
85       {
86         PackageMapType::iterator i = mPackageMap.begin();
87         ClosePackage(i);
88       }
89     bbtkDebugDecTab("Kernel",7);
90   }
91   //===================================================================
92
93   //===================================================================
94   void Factory::Reset()
95   {
96     bbtkDebugMessageInc("Kernel",7,"Factory::Reset()"<<std::endl);
97     CloseAllPackages();
98     bbtkDebugDecTab("Kernel",7);
99   }
100   //===================================================================
101
102
103   // ===================================================================
104   bool Factory::DoLoadPackage(std::string libname,
105                               std::string pkgname,
106                               std::string path)
107   {
108     
109 #if defined(__GNUC__)
110     
111     void *handler;
112     handler = dlopen(libname.c_str(),
113                      BBTK_RTLD_TIME | BBTK_RTLD_SCOPE );
114     if (!handler)
115       {
116         // The following is *NOT* a debug time message :
117         // It's a user intended message.
118         // Please don't remove it.
119         bbtkError("Could not open shared library [" <<libname<<"] : "
120                   <<dlerror() << std::endl);
121         
122         return false; // try next path
123       }
124     
125     // The following is *NOT* a debug time message :
126     // It's a user intended message.
127     // Please don't remove it.
128     bbtkMessage("Output",2,"   -->[" <<libname<<"] found" << std::endl);
129     
130     // Loads the Package accessor
131     
132     std::string getpackname(pkgname);
133     getpackname += "GetPackage";
134     void *getpack = dlsym(handler, getpackname.c_str());
135     if (!getpack)
136       {
137         dlclose(handler);
138         bbtkError("Shared library ["<<libname<<"] is not a valid bbtk package."
139                   <<" Symbol ["<<getpackname<<"] :"<<dlerror());
140       }
141     
142     // Verifies that the Package delete function is present
143     std::string delfname(pkgname);
144     delfname += "DeletePackage";
145     void *delf = dlsym(handler, delfname.c_str());
146     if (!delf)
147       {
148         dlclose(handler);
149         bbtkError("Shared library ["<<libname<<"] is not a valid bbtk package."
150                   <<" Symbol ["<<delfname<<"] :"<<dlerror());
151       }
152     
153 #elif defined(_WIN32)
154     
155     HINSTANCE handler;
156     
157     SetErrorMode(0);
158     handler = LoadLibrary(libname.c_str());
159     if (!handler)
160       {
161         // The following is *NOT* a debug time message :
162         // It's a user intended message.
163         // Please don't remove it.
164         bbtkError("Error loading library [" <<libname<<"]" << std::endl);
165         return false;// Problem with the found library
166       }
167     
168     bbtkMessage("Output",2,"   --->[" <<libname<<"] found" << std::endl);
169     
170     // Loads the Package accessor
171     
172     std::string getpackname(pkgname);
173     getpackname += "GetPackage";
174     void *getpack = GetProcAddress(handler, getpackname.c_str());
175     if (!getpack)
176       {
177         FreeLibrary(handler);
178         bbtkError("[1] Could not load package \""<<pkgname
179                   <<"\" : "<<getpackname<<" symbol not found (is it a bbtk package lib ?)");
180         // look how to get the error message on win
181         //<<dlerror());
182       }
183     // Verifies that the Package delete function is present
184     std::string delfname(pkgname);
185     delfname += "DeletePackage";
186     void *delf = GetProcAddress(handler, delfname.c_str());
187     if (!delf)
188       {
189         FreeLibrary(handler);
190         bbtkError("[2] Could not load package \""<<pkgname
191                   <<"\" : "<<delfname<<" symbol not found (is it a bbtk package lib ?)");
192         // look how to get the error message on win
193         //<<dlerror());
194       }
195 #else
196     bbtkError("neither __GNUC__ nor _WIN32 ?!? How did you compile ?");
197 #endif
198     
199     // Stores the package
200     PackageInfoType pack;
201     pack.mDynamicLibraryHandler = handler;
202     // Invokes the accessor to the PackageUnit pointer
203     pack.mPackage = ((PackageAccessor)getpack)();
204     
205     mPackageMap[pkgname] = pack;
206     
207     // Test bbtk build version ok
208     if ( pack.mPackage->GetBBTKVersion() != bbtk::GetVersion() )
209       {
210         std::string v(pack.mPackage->GetBBTKVersion());
211         UnLoadPackage(pkgname);
212         bbtkError("Cannot load package ["<<libname<<"]. "
213                   <<"Package build with bbtk version "
214                   << v
215                   << " whereas application build with version "
216                   << bbtk::GetVersion());
217       }
218     
219     std::string separator =
220       ConfigurationFile::GetInstance().Get_file_separator ();
221     //BBTK_STRINGIFY_SYMBOL(BBTK_DOC_REL_PATH)
222     std::string docreldoc = 
223       separator + "bbdoc" + separator + pkgname + separator + "index.html";
224     std::string reldoc = 
225       ".." + separator + ".." + docreldoc;
226     std::string doc = path + separator + ".." + separator
227       + BBTK_STRINGIFY_SYMBOL(BBTK_DOC_REL_PATH)
228       + docreldoc;
229     
230     pack.mPackage->SetDocURL(doc);
231     pack.mPackage->SetDocRelativeURL(reldoc);
232     
233     //===================================================================
234     bbtkMessage("Output",2,pack.mPackage->GetName()<<" "
235                 <<pack.mPackage->GetVersion()
236                 <<" (bbtk "
237                 <<pack.mPackage->GetBBTKVersion()<<") "
238                 <<pack.mPackage->GetAuthor() << " Category(s) :"
239                 <<pack.mPackage->GetCategory()
240                 <<std::endl);
241     bbtkMessage("Output",2,pack.mPackage->GetDescription()<<std::endl);
242     //===================================================================
243     
244     bbtkDebugDecTab("Kernel",7);
245     return true;
246   }
247   
248   //===================================================================
249   /// \brief Loads a package.
250   ///
251   /// The name is the system-independant name of the package (the name of the instance of bbtk::Package).
252   /// Tries to open the dynamic library :
253   /// - "libbb<name>.so" for linux systems,
254   /// - "bb<name>.dll" for windows systems.
255   /// If it succeeds, then tries to load the symbols "<name>GetPackage" and "<name>DeletePackage".
256   /// "<name>GetPackage" is called to get the pointer on the bbtk::Package of the library
257   /// ("<name>DeletePackage" is not used, its presence is just checked before loading the package).
258   
259   /// now, filename is only the last name (no longer the full name!)
260   /// it will be searched within *all* the paths given in bbtk_config.xml
261   
262
263   
264   void Factory::LoadPackage( const std::string& name )
265   {
266   // Note : in the following :
267   // name : the user supplied name
268   //      - abreviated name    e.g.       pkg   pkg.so   libbpkg   libbbpkg.so
269   //      - relative full name e.g.       ./libbbpkg.so   ../../libbbpkg.so
270   //      - absolute full name e.g.       /home/usrname/proj/lib/libbbpkg.so
271   //          same for Windows, with      c:, d: ...
272   //
273   // lastname : string before the last / (if any), or user supplied name
274
275     bbtkDebugMessageInc("Kernel",7,"Factory::LoadPackage(\""<<name<<"\")"<<std::endl);
276     bbtkMessage("Debug",1,"Factory::LoadPackage(\""<<name<<"\")"<<std::endl);
277
278     std::vector<std::string> package_paths;
279     std::string libname;  // full path library name
280     std::string pkgname;  // e.g. libbb<pkgname>.so
281
282     std::string upath;
283     pkgname = Utilities::ExtractPackageName(name,upath);
284
285     bbtkMessage("Debug",1,"Package name ["<<pkgname<<"]"<<std::endl);
286     bbtkMessage("Debug",1,"Package path ["<<upath<<"]"<<std::endl);
287
288     // no loading package if already loaded
289     PackageMapType::iterator iUnload;
290     iUnload = mPackageMap.find(pkgname);
291     if (iUnload != mPackageMap.end())
292     {
293       bbtkMessage("Output",2,"["<< pkgname <<"] already loaded" << std::endl);
294       return;
295     }
296
297 // =================================================
298 // The following structure was checked to work
299 // with any type of relative/absolute path.
300 // Please don't modify it without checking
301 // *all* the cases. JP
302 //==================================================
303
304 //std::cout << "upath [" << upath << "]" << std::endl;
305
306     bool ok = false;
307     bool foundFile = false;
308
309     // If path provided by user will be the first scanned :
310     // push it into vector of paths
311     if (upath.length()>0)   // ------------------------------------- check user supplied location
312     {
313        if (name[0] != '.' && name[0] != '/' && name[1]!= ':')
314        {
315           bbtkError("Use absolute or relative path name! ["<<name<<"] is an illegal name");
316           return;
317        }
318
319       // std::string path = Utilities::ExpandLibName(upath, false);
320        std::string path = Utilities::ExpandLibName(name,false); // keep last item, here.
321          
322        if (path != "")
323        {
324           std::string p2;
325           Utilities::ExtractPackageName(path,p2);
326           //libname = Utilities::MakeLibnameFromPath(path, pkgname);
327           libname = Utilities::MakeLibnameFromPath(p2, pkgname); // remove last item
328           // Check if library exists
329           if ( !Utilities::FileExists(libname) )
330           {
331           // The following is *NOT* a debug time message :
332           // It's a user intended message.
333           // Please don't remove it.
334             bbtkMessage("Output",3,"   [" <<libname 
335                         <<"] : doesn't exist" <<std::endl);
336           }
337           else
338           {
339              ok = DoLoadPackage( libname, pkgname, path);         
340           }
341        }
342        else
343        {
344           bbtkError("Path ["<<upath<<"] doesn't exist");
345           return;
346        }
347     }
348     else     // ----------------------------------------------------- iterate on the paths  
349     {
350
351     std::string path;
352     package_paths = ConfigurationFile::GetInstance().Get_package_paths();
353     std::vector<std::string>::iterator i;
354     for (i=package_paths.begin();i!=package_paths.end();++i)
355     {
356         foundFile = false;
357         path = *i;
358
359         // we *really* want '.' to be the current working directory
360         if (path == ".")
361         {
362           char buf[2048]; // for getcwd
363           char * currentDir = getcwd(buf, 2048);
364           std::string cwd(currentDir);
365           path = currentDir;
366         }
367
368         libname = Utilities::MakeLibnameFromPath(path, pkgname);
369
370         bbtkMessage("Debug",2,"-> Trying to load [" << libname << "]" <<std::endl);
371
372       // Check if library exists           
373         if ( !Utilities::FileExists(libname) )
374         {
375         // The following is *NOT* a debug time message :
376         // It's a user intended message.
377         // Please don't remove it.
378           bbtkMessage("Output",3,
379                       "   [" <<libname <<"] : doesn't exist" <<std::endl);
380            continue;  // try next path
381         }
382         foundFile = true; 
383
384       // Try to Load the library
385
386         ok = DoLoadPackage( libname, pkgname, path);
387         if (ok)
388         {
389            bbtkMessage("Debug",2,"   OK"<<std::endl);
390            break; // a package was found; we stop iterating
391         }
392     } //------------------ // end for ( package_paths.begin();i!=package_paths.end() )
393
394 }
395
396     if( !ok )  // nothing was loaded
397     {
398       if (!foundFile)
399       {
400         bbtkError("Could not find package ["<<pkgname<< "]");
401       }
402       else
403       {
404 #if defined(__GNUC__)
405         bbtkError("Could not load package ["<< pkgname
406                   <<"] :" << std::endl << "   " << dlerror());
407 #elif defined(_WIN32)
408         bbtkError("Could not load package ["<<pkgname
409                  <<"] : " << std::endl << "   " <<libname<<" not found");
410
411     // look how to get the error message on win
412     //<<dlerror());
413     // it is the bordel !! (the bloody fucking bordel, you mean?)
414     // look : http://msdn2.microsoft.com/en-us/library/ms680582.aspx
415 #endif
416       }
417     }
418     bbtkMessage("Output",2,"[" << libname << "] loaded" << std::endl);
419
420   }
421
422   //===================================================================
423   /// \brief UnLoads a package.
424   ///
425   /// The package must have been previously loaded by LoadPackage.
426   /// If the entry is found in the map, calls ClosePackage
427  void Factory::UnLoadPackage( const std::string& name )
428  {
429     bbtkDebugMessageInc("Kernel",7,"Factory::UnLoadPackage(\""
430                        <<name<<"\")"<<std::endl);
431   
432     PackageMapType::iterator i;
433     i = mPackageMap.find(name);
434     if (i == mPackageMap.end()) 
435     {
436       bbtkError("cannot unload package \""<<name
437                 <<"\" : package not loaded !");
438     }
439     ClosePackage(i);
440     bbtkDebugDecTab("Kernel",7);
441   }
442   //===================================================================
443
444
445   //===================================================================
446   /// \brief Close the package referenced by the iterator 
447   ///
448   /// If it is a dynamically loaded package 
449   /// - Loads and calls the function "<name>DeletePackage" of the dynamic library (responsible for package desallocation)
450   /// - Closes the dynamic library
451   /// - Erases the package entry in the packages map
452   ///
453   /// Else simply erases the package entry in the packages map
454   void Factory::ClosePackage(PackageMapType::iterator& i) 
455   {   
456      bbtkDebugMessageInc("Kernel",7,"Factory::ClosePackage(\""
457                          <<i->second.mPackage->GetName()
458                         <<"\")"<<std::endl);
459
460      if (i->second.mDynamicLibraryHandler) 
461      {
462  
463       // If it is a dynamically loaded package
464       // Loads the Package delete function
465
466         std::string delfname(i->second.mPackage->GetName());
467         delfname += "DeletePackage";
468 #if defined(__GNUC__)     
469         void *delf = dlsym(i->second.mDynamicLibraryHandler, delfname.c_str());
470         if (!delf)
471         {
472            bbtkError("could not close package \""
473                      <<i->second.mPackage->GetName()
474                      <<"\" :"<<dlerror());
475         }    
476 #elif defined(_WIN32)
477    void *delf = GetProcAddress(i->second.mDynamicLibraryHandler, 
478                                  delfname.c_str());
479      if (!delf)
480      {  
481        bbtkError("could not close package \""
482                 <<i->second.mPackage->GetName()
483                 <<"\" : "<<delfname
484                 <<" symbol not found (how did you open it ???");
485                //<<"\" :"<<dlerror());
486      }    
487 #endif     
488
489    // deletes the package
490    ((PackageDeleteFunction)delf)();
491
492    // closes the dl handler
493 #if defined(__GNUC__)  
494     dlclose(i->second.mDynamicLibraryHandler);  
495 #elif defined(_WIN32)
496
497     FreeLibrary(i->second.mDynamicLibraryHandler);
498 #endif
499     }
500     else 
501     {  
502        // If it is a manually inserted package 
503        delete i->second.mPackage;
504     }
505
506     // remove the entry in the map
507     mPackageMap.erase(i);
508     bbtkDebugDecTab("Kernel",7);
509  }
510   //===================================================================
511
512
513
514   //===================================================================  
515   /// Displays the list of packages loaded
516   void Factory::PrintPackages(bool details, bool adaptors) const
517   {
518     bbtkDebugMessageInc("Kernel",9,"Factory::PrintPackages"<<std::endl);
519
520     PackageMapType::const_iterator i;
521     for (i = mPackageMap.begin(); i!=mPackageMap.end(); ++i )
522     {
523       bbtkMessage("Help",1, i->first << std::endl);
524       if (details) {
525          i->second.mPackage->PrintBlackBoxes(false,adaptors);
526       }
527     }
528
529     bbtkDebugDecTab("Kernel",9);
530   }
531   //===================================================================
532
533   //===================================================================  
534   /// Displays help on a package
535   void Factory::HelpPackage(const std::string& name, bool adaptors) const
536   {
537     bbtkDebugMessageInc("Kernel",9,"Factory::HelpPackage(\""<<name<<"\")"
538                         <<std::endl);
539
540     PackageMapType::const_iterator i = mPackageMap.find(name);
541     if ( i != mPackageMap.end() ) 
542       {
543       bbtkMessage("Help",1, "Package "<<i->first<<" ");
544       
545       if (i->second.mPackage->GetVersion().length()>0)
546         bbtkMessageCont("Help",1,"v" <<i->second.mPackage->GetVersion());
547         
548       if (i->second.mPackage->GetAuthor().length()>0)
549         bbtkMessageCont("Help",1,"- "<<i->second.mPackage->GetAuthor());
550         
551       if (i->second.mPackage->GetCategory().length()>0)
552         bbtkMessageCont("Help",1,"- "<<i->second.mPackage->GetCategory());        
553         
554       bbtkMessageCont("Help",1,std::endl);
555       bbtkIncTab("Help",1);
556       bbtkMessage("Help",1,i->second.mPackage->GetDescription()<<std::endl);
557       if (i->second.mPackage->GetNumberOfBlackBoxes()>0) 
558         {
559           bbtkMessage("Help",1, "Black boxes : "<<std::endl);
560           i->second.mPackage->PrintBlackBoxes(true,adaptors);
561         }
562       else 
563         {
564           bbtkMessage("Help",1, "No black boxes"<<std::endl);
565         }
566       bbtkDecTab("Help",1);
567       }
568     else 
569       {
570       bbtkDebugDecTab("Kernel",9);
571       bbtkError("package \""<<name<<"\" unknown");
572       }
573     
574     bbtkDebugDecTab("Kernel",9);
575   }
576   //===================================================================
577
578   //===================================================================
579   /// Prints help on the black box of type <name>
580   /// Returns the package to which it belongs
581   void Factory::HelpBlackBox(const std::string& name, 
582                              std::string& package,
583                              bool full) const
584   {
585     bbtkDebugMessageInc("Kernel",9,"Factory::HelpBlackBox(\""<<name<<"\")"
586                         <<std::endl);
587
588     bool found = false;
589     PackageMapType::const_iterator i;
590     for (i = mPackageMap.begin(); i!=mPackageMap.end(); ++i )
591       {
592       if (i->second.mPackage->ContainsBlackBox(name)) 
593         {
594           i->second.mPackage->HelpBlackBox(name,full);
595               package = i->second.mPackage->GetName();
596           found = true;
597         }
598       }
599     
600     bbtkDebugDecTab("Kernel",9);
601     if (!found) 
602       {
603       bbtkError("No package of the factory contains any black box <"
604                  <<name<<">");
605       }
606   }  
607   //===================================================================
608
609
610   //=================================================================== 
611   /// Inserts a package in the factory
612   void Factory::InsertPackage( Package* p )
613   {
614     bbtkDebugMessageInc("Kernel",9,"Factory::InsertPackage(\""<<
615                         p->GetName()<<"\")"<<std::endl);
616
617     PackageInfoType pack;
618     pack.mDynamicLibraryHandler = 0;
619     
620     pack.mPackage = p;
621
622     mPackageMap[p->GetName()] = pack;
623     bbtkDebugDecTab("Kernel",9);
624   }
625   //===================================================================
626   
627   //=================================================================== 
628   /// Removes a package from the factory (and deletes it)
629   void Factory::RemovePackage( Package* p )
630   {
631     bbtkDebugMessageInc("Kernel",9,"Factory::RemovePackage(\""<<
632                         p->GetName()<<"\")"<<std::endl);
633
634     PackageMapType::iterator i;
635     for (i = mPackageMap.begin(); i!=mPackageMap.end(); ++i )
636       {
637          if (i->second.mPackage == p) break;
638       };
639     
640     if (i!=mPackageMap.end())
641       {
642       ClosePackage(i);
643       }
644     else 
645       {
646       bbtkError("Factory::RemovePackage(\""<<
647                  p->GetName()<<"\") : package absent from factory");
648       }
649
650     bbtkDebugDecTab("Kernel",9);
651   }
652   //===================================================================
653   
654
655   //===================================================================
656   /// Creates an instance of a black box of type <type> with name <name>
657   BlackBox* Factory::NewBlackBox(const std::string& type, 
658                                  const std::string& name) const
659   {
660     bbtkDebugMessageInc("Kernel",7,"Factory::NewBlackBox(\""
661                         <<type<<"\",\""<<name<<"\")"<<std::endl);
662
663     BlackBox* b = 0; 
664     PackageMapType::const_iterator i;
665     for (i = mPackageMap.begin(); i!=mPackageMap.end(); ++i )
666       {
667       b = i->second.mPackage->NewBlackBox(type,name);
668       if (b) break; 
669       }
670     if (!b) 
671       {
672        bbtkError("black box type \""<<type<<"\" unknown");
673       } 
674
675     bbtkDebugDecTab("Kernel",7);
676     return b;
677   }
678   //===================================================================
679
680   //===================================================================
681   /// Creates an instance of a black box of type <type> with name <name>
682   BlackBox* Factory::NewAdaptor(TypeInfo typein,
683                      TypeInfo typeout,
684                      const std::string& name) const
685   {
686     bbtkDebugMessageInc("Kernel",8,"Factory::NewAdaptor(<"
687                         <<TypeName(typein)<<">,<"
688                         <<TypeName(typeout)<<">,\""
689                         <<name<<"\")"<<bbtkendl);
690
691
692     BlackBox* b = 0; 
693     PackageMapType::const_iterator i;
694     for (i = mPackageMap.begin(); i!=mPackageMap.end(); ++i )
695       {
696       b = i->second.mPackage->NewAdaptor(typein,typeout,name);
697       if (b) break; 
698       }
699     if (!b) 
700       {
701       bbtkError("no <"
702           <<TypeName(typein)<<"> to <"
703           <<TypeName(typeout)
704           <<"> adaptor available");
705       } 
706     
707     bbtkDebugDecTab("Kernel",7);
708     return b; 
709   }
710   //===================================================================
711
712   //===================================================================
713   /// Creates an instance of a connection
714   Connection* Factory::NewConnection(BlackBox* from,
715                                      const std::string& output,
716                                      BlackBox* to,
717                                      const std::string& input) const
718   {
719     bbtkDebugMessage("Kernel",7,"Factory::NewConnection(\""
720                       <<from->bbGetName()<<"\",\""<<output<<"\",\""
721                       <<to->bbGetName()<<"\",\""<<input
722                       <<"\")"<<std::endl);
723     
724     return new Connection(from,output,to,input);
725     /*  
726        Connection* c;
727     // !!! WARNING : WE NEED TO TEST THE TYPE NAME EQUALITY 
728     // BECAUSE IN DIFFERENT DYN LIBS THE type_info EQUALITY CAN 
729     // BE FALSE (DIFFERENT INSTANCES !)
730   
731     std::string t1 ( from->bbGetOutputType(output).name() );
732     std::string t2 ( to->bbGetInputType(input).name() );
733
734
735     if ( t1 == t2 ) 
736        //from->bbGetOutputType(output) ==
737        // to->bbGetInputType(input) )
738       {
739          c = new Connection(from,output,to,input);
740       }
741     else 
742       {
743          //   std::cout << "Adaptive connection "<<std::endl;
744          std::string name;
745          name = from->bbGetName() + "." + output + "-" 
746                                   + to->bbGetName() + "." + input; 
747
748          BlackBox* b = 0; 
749          PackageMapType::const_iterator i;
750          for (i = mPackageMap.begin(); i!=mPackageMap.end(); ++i )
751          {
752              b = i->second.mPackage->NewAdaptor(from->bbGetOutputType(output),
753                                                   to->bbGetInputType(input),
754                                                   name);
755              if (b) break; 
756          } 
757          if (!b)  
758          {  
759             bbtkError("did not find any <"
760                        <<TypeName(from->bbGetOutputType(output))
761                        <<"> to <"
762                        <<TypeName(to->bbGetInputType(input))
763                        <<"> adaptor");
764          } 
765          c = new AdaptiveConnection(from,output,to,input,b);
766       }
767       bbtkDebugDecTab("Kernel",7);
768     
769       return c;
770     */
771   }
772   //===================================================================
773
774
775
776   //===================================================================
777   const Package* Factory::GetPackage(const std::string& name) const
778   {
779     bbtkDebugMessageInc("Kernel",9,"Factory::GetPackage(\""<<name<<"\")"
780                          <<std::endl);
781
782     PackageMapType::const_iterator i = mPackageMap.find(name);
783     if ( i != mPackageMap.end() ) 
784     {
785       bbtkDebugDecTab("Kernel",9); 
786       return i->second.mPackage;
787     }
788     else 
789     {
790        bbtkDebugDecTab("Kernel",9);
791        bbtkError("package \""<<name<<"\" unknown");
792     }
793     
794     bbtkDebugDecTab("Kernel",9);  
795   }
796   //===================================================================
797   
798   //===================================================================
799   Package* Factory::GetPackage(const std::string& name) 
800   {
801     bbtkDebugMessageInc("Kernel",9,"Factory::GetPackage(\""<<name<<"\")"
802                          <<std::endl);
803
804     PackageMapType::const_iterator i = mPackageMap.find(name);
805     if ( i != mPackageMap.end() ) 
806     {
807       bbtkDebugDecTab("Kernel",9); 
808       return i->second.mPackage;
809     }
810     else 
811     {
812        bbtkDebugDecTab("Kernel",9);
813        bbtkError("package \""<<name<<"\" unknown");
814     }
815     
816     bbtkDebugDecTab("Kernel",9);  
817   }
818   //===================================================================
819
820   //===================================================================
821   void Factory::WriteDotFilePackagesList(FILE *ff)
822   {
823
824     bbtkDebugMessageInc("Kernel",9,"Factory::WriteDotFilePackagesList()"
825                          <<std::endl);
826
827     fprintf( ff , "\n");
828     fprintf( ff , "subgraph cluster_FACTORY {\n");
829     fprintf( ff , "  label = \"PACKAGES\"%s\n",  ";");
830     fprintf( ff , "  style=filled%s\n",";");
831     fprintf( ff , "  color=lightgrey%s\n",";");
832     fprintf( ff , "  rankdir=TB%s\n",";");
833
834     std::string url;
835     PackageMapType::const_iterator i;
836     for (i = mPackageMap.begin(); i!=mPackageMap.end(); ++i )
837     {
838        url=GetPackage(i->first)->GetDocURL();
839        fprintf(ff,"  %s [shape=ellipse, URL=\"%s\"]%s\n",i->first.c_str(),url.c_str(),";" );
840     }
841     fprintf( ff , "}\n\n");
842     bbtkDebugDecTab("Kernel",9);
843   }
844   //===================================================================
845
846
847  void Factory::ShowGraphTypes(const std::string& name) const
848  {
849
850    bool found = false;
851    PackageMapType::const_iterator i;
852    for (i = mPackageMap.begin(); i!=mPackageMap.end(); ++i )
853    {
854       if (i->second.mPackage->ContainsBlackBox(name)) 
855       {
856          std::string separator = ConfigurationFile::GetInstance().Get_file_separator ();
857
858             // Don't pollute the file store with  "temp_dir" directories ...    
859          std::string default_doc_dir = ConfigurationFile::GetInstance().Get_default_temp_dir();
860          std::string directory = "\"" + default_doc_dir + separator + "temp_dir"  +separator + "\"";
861          std::string filename2 =  default_doc_dir + separator + "temp_dir" + separator + "tmp.html"; 
862
863 #if defined(_WIN32)  
864         std::string command("start \"Titre\" /D ");
865 #else 
866         std::string command("gnome-open ");
867 #endif
868         command=command + directory +" tmp.html";
869         FILE *ff;
870         ff=fopen(filename2.c_str(),"w");
871
872         fprintf(ff,"<html><head><title>TMP</title> <script type=\"text/javascript\"> <!--\n");
873         fprintf(ff,"  window.location=\"%s#%s\";\n" , i->second.mPackage->GetDocURL().c_str(),name.c_str() );
874         fprintf(ff,"//--></script></head><body></body></html>\n");
875
876
877         //fprintf(ff, "<a  href=\"%s#%s\">Link</a>\n", i->second.mPackage->GetDocURL().c_str(),name.c_str() );
878         fclose(ff);
879         system( command.c_str() );      
880         found = true;
881      }
882    }
883     
884    bbtkDebugDecTab("Kernel",9);
885    if (!found) 
886    {
887       bbtkError("No package of the factory contains any black box <"
888                 <<name<<">");
889    }
890  }
891     
892
893
894
895   void Factory::CreateHtmlIndex(IndexEntryType type, 
896                                 const std::string& filename)
897   {
898     bbtkDebugMessageInc("Kernel",9,"Factory::CreateHtmlIndex(\""
899                         <<filename<<"\")"<<bbtkendl);
900     
901     std::string title;
902
903     typedef std::map<std::string, std::vector<BlackBoxDescriptor*> > IndexType;
904     IndexType index;
905     // Builds the index map
906     PackageMapType::const_iterator i;
907     for (i = mPackageMap.begin(); i!=mPackageMap.end(); ++i )
908       {
909         Package* pack = i->second.mPackage;
910         if (pack->GetName()=="user") continue;
911         Package::BlackBoxMapType::const_iterator j;
912         for (j = pack->GetBlackBoxMap().begin(); 
913              j!= pack->GetBlackBoxMap().end(); 
914              ++j)
915           {
916             
917             // Skip adaptors 
918             if ( type==Adaptors )
919               {  
920                 if (j->second->GetKind() == BlackBoxDescriptor::STANDARD )
921                   continue;
922               }
923             else 
924               if (j->second->GetKind() != BlackBoxDescriptor::STANDARD )
925                 continue;
926
927             std::vector<std::string> keys;
928             if (type==Packages)
929               {
930                 std::string k("");
931                 k += pack->GetName();
932                 keys.push_back(k);
933                 title = "Boxes by package";
934               }
935             else if ((type==Initials) || (type==Adaptors))
936               {
937                 std::string init(" ");
938                 init[0] =  std::toupper(j->second->GetTypeName()[0]);
939                 keys.push_back(init);
940                 title = "Alphabetical list";
941               }
942             else if (type==Categories)
943               {
944                 // Split the category string 
945                 std::string delimiters = ";,";
946                 Utilities::SplitString(j->second->GetCategory(),
947                                        delimiters,keys);
948                 if (keys.size()==0) 
949                   keys.push_back(" NONE");
950                 title = "Boxes by category";
951               }
952     
953             
954             std::vector<std::string>::const_iterator k;
955             for (k=keys.begin(); k!=keys.end(); ++k )
956               {
957                 IndexType::iterator p;
958                 p = index.find(*k);
959                 if (p != index.end()) 
960                   {
961                     p->second.push_back(j->second);
962                   }
963                 else 
964                   {
965                     std::vector<BlackBoxDescriptor*> v;
966                     v.push_back(j->second);
967                     index[*k] = v;
968                   }
969               }
970             
971           }
972       }   
973     // Creates the file 
974     //---------------------
975     // Open output file
976     std::ofstream s;
977     s.open(filename.c_str());
978     if (!s.good()) 
979     {
980        bbtkError("Factory::CreateHtmlIndex : could not open file '"
981                  <<filename<<"'");
982     }
983     
984     //----------------------
985     // Html head
986     s << "<html lang=\"en\">\n";
987     s << "<head>\n";
988     s << "<title>"<<title<<"</title>\n";
989     s << "<meta http-equiv=\"Content-Type\" content=\"text/html\">\n";
990     s << "<meta name=\"description\" content=\""<<title<<"\">\n";
991     s << "<meta name=\"generator\" content=\"\">\n";
992     s << "<link title=\"Top\" rel=\"top\" href=\"#Top\">\n";
993     //<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">
994     s << "<meta http-equiv=\"Content-Style-Type\" content=\"text/css\"><style type=\"text/css\"><!--\n";
995     s << "pre.display { font-family:inherit }\n";
996     s << "pre.format  { font-family:inherit }\n";
997     s << "pre.smalldisplay { font-family:inherit; font-size:smaller }\n";
998     s << "pre.smallformat  { font-family:inherit; font-size:smaller }\n";
999     s << "pre.smallexample { font-size:smaller }\n";
1000     s << "pre.smalllisp    { font-size:smaller }\n";
1001     s << "span.sc    { font-variant:small-caps }\n";
1002     s << "span.roman { font-family:serif; font-weight:normal; } \n";
1003     s << "span.sansserif { font-family:sans-serif; font-weight:normal; }\n"; 
1004     s << "--></style>\n";
1005     s << "</head>\n";
1006     //----------------------
1007
1008     //----------------------
1009     // Html body
1010     s << "<body>\n";
1011     s << "<a name=\"Top\"></a>\n"; 
1012     s << "<h1 class=\"settitle\">"<<title<<"</h1>\n";
1013     s << "<p>\n";
1014     IndexType::iterator ii;
1015     for (ii=index.begin();ii!=index.end();++ii)
1016       {
1017         s << "<a href=\"#"<<ii->first<<"\">"<<ii->first<<"</a>&nbsp;";  
1018       }
1019
1020     for (ii=index.begin();ii!=index.end();++ii)
1021       {
1022         s << "<p><hr>\n";
1023         s << "<p><a href=\"#Top\">Top</a>";
1024         if (type==Packages)
1025           {
1026             s << "<a name=\""<<ii->first<<"\"></a>\n"; 
1027             s << "<p><a href=\""<<ii->first<<"/index.html\">"
1028               << ii->first<<"</a>\n"; 
1029
1030             s << "&nbsp;&nbsp;-&nbsp;&nbsp;\n"; 
1031
1032             s << "<a name=\"doxygen\"></a>\n"; 
1033             s << "<a href=..\\doxygen\\" << ii->first << "/main.html>(Doxygen documentation of the source)</a>\n"; 
1034           }
1035         else 
1036           {
1037             s << "<a name=\""<<ii->first<<"\"></a>\n"; 
1038             s << "<p><b>"<<ii->first<<"</b>\n";
1039           }
1040         s << "<ul>\n";
1041
1042         s << "<p><TABLE cellspacing=0  cellpadding=3>\n";
1043
1044         std::vector<BlackBoxDescriptor*>::iterator di;
1045         for (di=ii->second.begin();di!=ii->second.end();++di)
1046           {
1047             std::string pack = (*di)->GetPackage()->GetName();
1048             std::string name = (*di)->GetTypeName();
1049             Utilities::html_format(name);
1050             std::string descr = (*di)->GetDescription();
1051             Utilities::html_format(descr);
1052             s << "<TR>";
1053             s << "<TD style='vertical-align: top;'>";
1054             s << "&nbsp;&nbsp;&nbsp;<a href=\""<<pack
1055               <<"/index.html#"<<name<<"\">"
1056               <<pack<<"::"<<name<<"</a>";
1057             s << "</TD> ";
1058             s << " <TD style='vertical-align: top;'>" << descr << " </TD>";
1059             s << "</TR>\n";
1060           }    
1061         s << "</TABLE>\n";
1062         s << "</ul>\n";
1063         s << "</div>\n";
1064       }
1065     //----------------------
1066     // Footer 
1067     time_t rawtime;
1068     tm * ptm;
1069     time ( &rawtime );
1070     ptm = gmtime ( &rawtime );
1071
1072     s << "<p><hr>\n";
1073     s << "Automatically generated by <b>bbi</b> on "
1074       << ptm->tm_mday << "/" << ptm->tm_mon << "/" << ptm->tm_year+1900 
1075       << " - " << ptm->tm_hour << ":" << ptm->tm_min << " GMT\n";
1076     s << "</body></html>\n"; 
1077     s.close();
1078     //----------------------
1079
1080     // End
1081     bbtkDebugDecTab("Kernel",9);
1082   }
1083
1084
1085 }
1086