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