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