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