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