1 /*=========================================================================
4 Module: $RCSfile: bbtkFactory.cxx,v $
7 Date: $Date: 2008/01/30 09:28:15 $
8 Version: $Revision: 1.7 $
11 Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de
12 l'Image). All rights reserved. See doc/license.txt or
13 http://www.creatis.insa-lyon.fr/Public/bbtk/License.html for details.
15 This software is distributed WITHOUT ANY WARRANTY; without even
16 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
17 PURPOSE. See the above copyright notices for more information.
19 =========================================================================*/
22 *\brief Class bbtk::Factory : can load and unload dynamic libraries containing
23 * black boxes packages and create instances of the black boxes registered
24 * in the packages loaded.
26 #include "bbtkFactory.h"
27 #include "bbtkMessageManager.h"
28 #include "bbtkConnection.h"
29 #include "bbtkConfigurationFile.h"
30 #include "bbtkUtilities.h"
32 #include <sys/stat.h> // for struct stat stFileInfo
35 #include <direct.h> // for getcwd
42 # define getcwd _getcwd
45 #if defined(_MSC_VER) || defined(__BORLANDC__)
56 typedef Package* (*PackageAccessor)();
57 typedef void (*PackageDeleteFunction)();
60 //===================================================================
64 bbtkDebugMessage("Core",7,"Factory::Factory()"<<std::endl);
66 //===================================================================
68 //===================================================================
72 bbtkDebugMessageInc("Core",7,"Factory::~Factory()"<<std::endl);
74 bbtkDebugDecTab("Core",7);
76 //===================================================================
79 //===================================================================
80 void Factory::CloseAllPackages()
82 bbtkDebugMessageInc("Core",7,"Factory::CloseAllPackages()"<<std::endl);
83 while (mPackageMap.begin() != mPackageMap.end())
85 PackageMapType::iterator i = mPackageMap.begin();
88 bbtkDebugDecTab("Core",7);
90 //===================================================================
92 //===================================================================
95 bbtkDebugMessageInc("Core",7,"Factory::Reset()"<<std::endl);
97 bbtkDebugDecTab("Core",7);
99 //===================================================================
102 // ===================================================================================
104 bool Factory::DoLoadPackage(std::string libname,
110 #if defined(__GNUC__)
113 handler = dlopen(libname.c_str(),
114 BBTK_RTLD_TIME | BBTK_RTLD_SCOPE );
117 // The following is *NOT* a debug time message :
118 // It's a user intended message.
119 // Please don't remove it.
121 std::cout <<"[" <<libname<<"] can't be open" << std::endl;
122 std::cout << " " <<dlerror() << std::endl;
124 return false; // try next path
127 // The following is *NOT* a debug time message :
128 // It's a user intended message.
129 // Please don't remove it.
131 std::cout <<" -->[" <<libname<<"] found" << std::endl;
133 // Loads the Package accessor
135 std::string getpackname(pkgname);
136 getpackname += "GetPackage";
137 void *getpack = dlsym(handler, getpackname.c_str());
141 bbtkError("GetPackage : could not load package \""<<pkgname
142 <<"\" [symbol "<<getpackname<<"] :"<<dlerror());
145 // Verifies that the Package delete function is present
146 std::string delfname(pkgname);
147 delfname += "DeletePackage";
148 void *delf = dlsym(handler, delfname.c_str());
152 bbtkError("DeletePackage : could not load package \""<<pkgname
153 <<"\" [symbol "<<delfname<<"] :"<<dlerror());
156 #elif defined(_WIN32)
161 handler = LoadLibrary(libname.c_str());
164 // The following is *NOT* a debug time message :
165 // It's a user intended message.
166 // Please don't remove it.
167 std::cout <<" no handler for [" <<libname<<"];" << std::endl;
168 return false;// Problem with the found library
171 std::cout <<" --->[" <<libname<<"] found" << std::endl;
173 // Loads the Package accessor
175 std::string getpackname(pkgname);
176 getpackname += "GetPackage";
177 void *getpack = GetProcAddress(handler, getpackname.c_str());
180 FreeLibrary(handler);
181 bbtkError("[1]could not load package \""<<pkgname
182 <<"\" : "<<getpackname<<" symbol not found (is it a bbtk package lib ?)");
183 // look how to get the error message on win
186 // Verifies that the Package delete function is present
187 std::string delfname(pkgname);
188 delfname += "DeletePackage";
189 void *delf = GetProcAddress(handler, delfname.c_str());
192 FreeLibrary(handler);
193 bbtkError("[2]could not load package \""<<pkgname
194 <<"\" : "<<delfname<<" symbol not found (is it a bbtk package lib ?)");
195 // look how to get the error message on win
199 bbtkError("neither __GNUC__ nor _WIN32 ?!? How did you compile ?");
202 // Stores the package
203 PackageInfoType pack;
204 pack.mDynamicLibraryHandler = handler;
205 // Invokes the accessor to the PackageUnit pointer
206 pack.mPackage = ((PackageAccessor)getpack)();
208 mPackageMap[pkgname] = pack;
210 // Test bbtk build version ok
211 if ( pack.mPackage->GetBBTKVersion() != bbtk::GetVersion() )
213 std::string v(pack.mPackage->GetBBTKVersion());
214 UnLoadPackage(pkgname);
215 bbtkError(" package build with bbtk version "
217 << " whereas application build with version "
218 << bbtk::GetVersion());
221 std::string separator =
222 ConfigurationFile::GetInstance().Get_file_separator ();
223 //BBTK_STRINGIFY_SYMBOL(BBTK_DOC_REL_PATH)
224 std::string docreldoc = separator + "packages" + separator + pkgname
225 + separator + "bbdoc" + separator + "index.html";
226 std::string reldoc = ".." + separator + ".." + separator
228 std::string doc = path + separator + ".." + separator
229 + BBTK_STRINGIFY_SYMBOL(BBTK_DOC_REL_PATH)
232 pack.mPackage->SetDocURL(doc);
233 pack.mPackage->SetDocRelativeURL(reldoc);
235 //===================================================================
236 bbtkMessage("Output",2,pack.mPackage->GetName()<<" "
237 <<pack.mPackage->GetVersion()
239 <<pack.mPackage->GetBBTKVersion()<<") "
240 <<pack.mPackage->GetAuthor()
242 bbtkMessage("Output",2,pack.mPackage->GetDescription()<<std::endl);
243 //===================================================================
245 bbtkDebugDecTab("Core",7);
249 //===================================================================
250 /// \brief Loads a package.
252 /// The name is the system-independant name of the package (the name of the instance of bbtk::Package).
253 /// Tries to open the dynamic library :
254 /// - "libbb<name>.so" for linux systems,
255 /// - "bb<name>.dll" for windows systems.
256 /// If it succeeds, then tries to load the symbols "<name>GetPackage" and "<name>DeletePackage".
257 /// "<name>GetPackage" is called to get the pointer on the bbtk::Package of the library
258 /// ("<name>DeletePackage" is not used, its presence is just checked before loading the package).
260 /// now, filename is only the last name (no longer the full name!)
261 /// it will be searched within *all* the paths given in bbtk_config.xml
263 /// verbose = true (set by "config v") displays the loading process
265 void Factory::LoadPackage( const std::string& name,
266 bool use_configuration_file, bool verbose)
268 // Note : in the following :
269 // name : the user supplied name
270 // - abreviated name e.g. pkg pkg.so libbpkg libbbpkg.so
271 // - relative full name e.g. ./libbbpkg.so ../../libbbpkg.so
272 // - absolute full name e.g. /home/usrname/proj/lib/libbbpkg.so
273 // same for Windows, with c:, d: ...
275 // lastname : string before the last / (if any), or user supplied name
277 bbtkDebugMessageInc("Core",7,"Factory::LoadPackage(\""<<name<<"\")"<<std::endl);
278 bbtkMessage("Debug",1,"Factory::LoadPackage(\""<<name<<"\")"<<std::endl);
279 bbtkMessage("Debug",1,"use_configuration_file ["
280 << use_configuration_file << "]" << std::endl);
282 std::vector<std::string> package_paths;
283 std::string libname; // full path library name
284 std::string pkgname; // e.g. libbb<pkgname>.so
287 pkgname = Utilities::ExtractPackageName(name,upath);
289 bbtkMessage("Debug",1,"Package name ["<<pkgname<<"]"<<std::endl);
290 bbtkMessage("Debug",1,"Package path ["<<upath<<"]"<<std::endl);
292 // no loading package if already loaded
293 PackageMapType::iterator iUnload;
294 iUnload = mPackageMap.find(pkgname);
295 if (iUnload != mPackageMap.end())
297 bbtkMessage("Output",2,"["<< pkgname <<"] already loaded" << std::endl);
301 // =================================================
302 // The following structure was checked to work
303 // with any type of relative/absolute path.
304 // Please don't modify it without checking
305 // *all* the cases. JP
306 //==================================================
308 //std::cout << "upath [" << upath << "]" << std::endl;
311 bool foundFile = false;
313 // If path provided by user will be the first scanned :
314 // push it into vector of paths
315 if (upath.length()>0) // ------------------------------------- check user supplied location
317 if (name[0] != '.' && name[0] != '/' && name[1]!= ':')
319 bbtkError("Use absolute or relative path name! ["<<name<<"] is an illegal name");
323 // std::string path = Utilities::ExpandLibName(upath, verbose);
324 std::string path = Utilities::ExpandLibName(name, verbose); // keep last item, here.
329 Utilities::ExtractPackageName(path,p2);
330 //libname = Utilities::MakeLibnameFromPath(path, pkgname);
331 libname = Utilities::MakeLibnameFromPath(p2, pkgname); // remove last item
332 // Check if library exists
333 if ( !Utilities::FileExists(libname) )
335 // The following is *NOT* a debug time message :
336 // It's a user intended message.
337 // Please don't remove it.
339 std::cout <<" [" <<libname <<"] : doesn't exist" <<std::endl;
343 ok = DoLoadPackage( libname, pkgname, path, verbose);
348 bbtkError("Path ["<<upath<<"] doesn't exist");
352 else // ----------------------------------------------------- iterate on the paths
356 package_paths = ConfigurationFile::GetInstance().Get_package_paths();
357 std::vector<std::string>::iterator i;
358 for (i=package_paths.begin();i!=package_paths.end();++i)
363 // we *really* want '.' to be the current working directory
366 char buf[2048]; // for getcwd
367 char * currentDir = getcwd(buf, 2048);
368 std::string cwd(currentDir);
372 libname = Utilities::MakeLibnameFromPath(path, pkgname);
374 bbtkMessage("Debug",2,"-> Trying to load [" << libname << "]" <<std::endl);
376 // Check if library exists
377 if ( !Utilities::FileExists(libname) )
379 // The following is *NOT* a debug time message :
380 // It's a user intended message.
381 // Please don't remove it.
383 std::cout <<" [" <<libname <<"] : doesn't exist" <<std::endl;
384 continue; // try next path
388 // Try to Load the library
390 ok = DoLoadPackage( libname, pkgname, path, verbose);
393 bbtkMessage("Debug",2," OK"<<std::endl);
394 break; // a package was found; we stop iterating
396 } //------------------ // end for ( package_paths.begin();i!=package_paths.end() )
400 if( !ok ) // nothing was loaded
404 bbtkError("could not find package ["<<pkgname<< "]");
408 #if defined(__GNUC__)
409 bbtkError("could not load package ["<< pkgname
410 <<"] :" << std::endl << " " << dlerror());
411 #elif defined(_WIN32)
412 bbtkError("could not load package ["<<pkgname
413 <<"] : " << std::endl << " " <<libname<<" not found");
415 // look how to get the error message on win
417 // it is the bordel !! (the bloody fucking bordel, you mean?)
418 // look : http://msdn2.microsoft.com/en-us/library/ms680582.aspx
422 bbtkMessage("Output",2,"[" << libname << "] loaded" << std::endl);
426 //===================================================================
427 /// \brief UnLoads a package.
429 /// The package must have been previously loaded by LoadPackage.
430 /// If the entry is found in the map, calls ClosePackage
431 void Factory::UnLoadPackage( const std::string& name )
433 bbtkDebugMessageInc("Core",7,"Factory::UnLoadPackage(\""
434 <<name<<"\")"<<std::endl);
436 PackageMapType::iterator i;
437 i = mPackageMap.find(name);
438 if (i == mPackageMap.end())
440 bbtkError("cannot unload package \""<<name
441 <<"\" : package not loaded !");
444 bbtkDebugDecTab("Core",7);
446 //===================================================================
449 //===================================================================
450 /// \brief Close the package referenced by the iterator
452 /// If it is a dynamically loaded package
453 /// - Loads and calls the function "<name>DeletePackage" of the dynamic library (responsible for package desallocation)
454 /// - Closes the dynamic library
455 /// - Erases the package entry in the packages map
457 /// Else simply erases the package entry in the packages map
458 void Factory::ClosePackage(PackageMapType::iterator& i)
460 bbtkDebugMessageInc("Core",7,"Factory::ClosePackage(\""
461 <<i->second.mPackage->GetName()
464 if (i->second.mDynamicLibraryHandler)
467 // If it is a dynamically loaded package
468 // Loads the Package delete function
470 std::string delfname(i->second.mPackage->GetName());
471 delfname += "DeletePackage";
472 #if defined(__GNUC__)
473 void *delf = dlsym(i->second.mDynamicLibraryHandler, delfname.c_str());
476 bbtkError("could not close package \""
477 <<i->second.mPackage->GetName()
478 <<"\" :"<<dlerror());
480 #elif defined(_WIN32)
481 void *delf = GetProcAddress(i->second.mDynamicLibraryHandler,
485 bbtkError("could not close package \""
486 <<i->second.mPackage->GetName()
488 <<" symbol not found (how did you open it ???");
489 //<<"\" :"<<dlerror());
493 // deletes the package
494 ((PackageDeleteFunction)delf)();
496 // closes the dl handler
497 #if defined(__GNUC__)
498 dlclose(i->second.mDynamicLibraryHandler);
499 #elif defined(_WIN32)
501 FreeLibrary(i->second.mDynamicLibraryHandler);
506 // If it is a manually inserted package
507 delete i->second.mPackage;
510 // remove the entry in the map
511 mPackageMap.erase(i);
512 bbtkDebugDecTab("Core",7);
514 //===================================================================
518 //===================================================================
519 /// Displays the list of packages loaded
520 void Factory::PrintPackages(bool details, bool adaptors) const
522 bbtkDebugMessageInc("Core",9,"Factory::PrintPackages"<<std::endl);
524 PackageMapType::const_iterator i;
525 for (i = mPackageMap.begin(); i!=mPackageMap.end(); ++i )
527 bbtkMessage("Help",1, i->first << std::endl);
529 i->second.mPackage->PrintBlackBoxes(false,adaptors);
533 bbtkDebugDecTab("Core",9);
535 //===================================================================
537 //===================================================================
538 /// Displays help on a package
539 void Factory::HelpPackage(const std::string& name, bool adaptors) const
541 bbtkDebugMessageInc("Core",9,"Factory::HelpPackage(\""<<name<<"\")"
544 PackageMapType::const_iterator i = mPackageMap.find(name);
545 if ( i != mPackageMap.end() )
547 bbtkMessage("Help",1, "Package "<<i->first<<" ");
548 if (i->second.mPackage->GetVersion().length()>0)
549 bbtkMessageCont("Help",1,"v" <<i->second.mPackage->GetVersion());
550 if (i->second.mPackage->GetAuthor().length()>0)
551 bbtkMessageCont("Help",1,"- "<<i->second.mPackage->GetAuthor());
552 bbtkMessageCont("Help",1,std::endl);
553 bbtkIncTab("Help",1);
554 bbtkMessage("Help",1,i->second.mPackage->GetDescription()<<std::endl);
555 if (i->second.mPackage->GetNumberOfBlackBoxes()>0)
557 bbtkMessage("Help",1, "Black boxes : "<<std::endl);
558 i->second.mPackage->PrintBlackBoxes(true,adaptors);
562 bbtkMessage("Help",1, "No black boxes"<<std::endl);
564 bbtkDecTab("Help",1);
568 bbtkDebugDecTab("Core",9);
569 bbtkError("package \""<<name<<"\" unknown");
572 bbtkDebugDecTab("Core",9);
574 //===================================================================
576 //===================================================================
577 /// Prints help on the black box of type <name>
578 void Factory::HelpBlackBox(const std::string& name, bool full) const
580 bbtkDebugMessageInc("Core",9,"Factory::HelpBlackBox(\""<<name<<"\")"
584 PackageMapType::const_iterator i;
585 for (i = mPackageMap.begin(); i!=mPackageMap.end(); ++i )
587 if (i->second.mPackage->ContainsBlackBox(name))
589 i->second.mPackage->HelpBlackBox(name,full);
594 bbtkDebugDecTab("Core",9);
597 bbtkError("No package of the factory contains any black box <"
601 //===================================================================
604 //===================================================================
605 /// Inserts a package in the factory
606 void Factory::InsertPackage( Package* p )
608 bbtkDebugMessageInc("Core",9,"Factory::InsertPackage(\""<<
609 p->GetName()<<"\")"<<std::endl);
611 PackageInfoType pack;
612 pack.mDynamicLibraryHandler = 0;
616 mPackageMap[p->GetName()] = pack;
617 bbtkDebugDecTab("Core",9);
619 //===================================================================
621 //===================================================================
622 /// Removes a package from the factory (and deletes it)
623 void Factory::RemovePackage( Package* p )
625 bbtkDebugMessageInc("Core",9,"Factory::RemovePackage(\""<<
626 p->GetName()<<"\")"<<std::endl);
628 PackageMapType::iterator i;
629 for (i = mPackageMap.begin(); i!=mPackageMap.end(); ++i )
631 if (i->second.mPackage == p) break;
634 if (i!=mPackageMap.end())
640 bbtkError("Factory::RemovePackage(\""<<
641 p->GetName()<<"\") : package absent from factory");
644 bbtkDebugDecTab("Core",9);
646 //===================================================================
649 //===================================================================
650 /// Creates an instance of a black box of type <type> with name <name>
651 BlackBox* Factory::NewBlackBox(const std::string& type,
652 const std::string& name) const
654 bbtkDebugMessageInc("Core",7,"Factory::NewBlackBox(\""
655 <<type<<"\",\""<<name<<"\")"<<std::endl);
658 PackageMapType::const_iterator i;
659 for (i = mPackageMap.begin(); i!=mPackageMap.end(); ++i )
661 b = i->second.mPackage->NewBlackBox(type,name);
666 bbtkError("black box type \""<<type<<"\" unknown");
669 bbtkDebugDecTab("Core",7);
672 //===================================================================
674 //===================================================================
675 /// Creates an instance of a black box of type <type> with name <name>
676 BlackBox* Factory::NewAdaptor(TypeInfo typein,
678 const std::string& name) const
680 bbtkDebugMessageInc("Core",8,"Factory::NewAdaptor(<"
681 <<TypeName(typein)<<">,<"
682 <<TypeName(typeout)<<">,\""
683 <<name<<"\")"<<bbtkendl);
687 PackageMapType::const_iterator i;
688 for (i = mPackageMap.begin(); i!=mPackageMap.end(); ++i )
690 b = i->second.mPackage->NewAdaptor(typein,typeout,name);
696 <<TypeName(typein)<<"> to <"
698 <<"> adaptor available");
701 bbtkDebugDecTab("Core",7);
704 //===================================================================
706 //===================================================================
707 /// Creates an instance of a connection
708 Connection* Factory::NewConnection(BlackBox* from,
709 const std::string& output,
711 const std::string& input) const
713 bbtkDebugMessage("Core",7,"Factory::NewConnection(\""
714 <<from->bbGetName()<<"\",\""<<output<<"\",\""
715 <<to->bbGetName()<<"\",\""<<input
718 return new Connection(from,output,to,input);
721 // !!! WARNING : WE NEED TO TEST THE TYPE NAME EQUALITY
722 // BECAUSE IN DIFFERENT DYN LIBS THE type_info EQUALITY CAN
723 // BE FALSE (DIFFERENT INSTANCES !)
725 std::string t1 ( from->bbGetOutputType(output).name() );
726 std::string t2 ( to->bbGetInputType(input).name() );
730 //from->bbGetOutputType(output) ==
731 // to->bbGetInputType(input) )
733 c = new Connection(from,output,to,input);
737 // std::cout << "Adaptive connection "<<std::endl;
739 name = from->bbGetName() + "." + output + "-"
740 + to->bbGetName() + "." + input;
743 PackageMapType::const_iterator i;
744 for (i = mPackageMap.begin(); i!=mPackageMap.end(); ++i )
746 b = i->second.mPackage->NewAdaptor(from->bbGetOutputType(output),
747 to->bbGetInputType(input),
753 bbtkError("did not find any <"
754 <<TypeName(from->bbGetOutputType(output))
756 <<TypeName(to->bbGetInputType(input))
759 c = new AdaptiveConnection(from,output,to,input,b);
761 bbtkDebugDecTab("Core",7);
766 //===================================================================
770 //===================================================================
771 const Package* Factory::GetPackage(const std::string& name) const
773 bbtkDebugMessageInc("Core",9,"Factory::GetPackage(\""<<name<<"\")"
776 PackageMapType::const_iterator i = mPackageMap.find(name);
777 if ( i != mPackageMap.end() )
779 bbtkDebugDecTab("Core",9);
780 return i->second.mPackage;
784 bbtkDebugDecTab("Core",9);
785 bbtkError("package \""<<name<<"\" unknown");
788 bbtkDebugDecTab("Core",9);
790 //===================================================================
792 //===================================================================
793 Package* Factory::GetPackage(const std::string& name)
795 bbtkDebugMessageInc("Core",9,"Factory::GetPackage(\""<<name<<"\")"
798 PackageMapType::const_iterator i = mPackageMap.find(name);
799 if ( i != mPackageMap.end() )
801 bbtkDebugDecTab("Core",9);
802 return i->second.mPackage;
806 bbtkDebugDecTab("Core",9);
807 bbtkError("package \""<<name<<"\" unknown");
810 bbtkDebugDecTab("Core",9);
812 //===================================================================
814 //===================================================================
815 void Factory::WriteDotFilePackagesList(FILE *ff)
817 bbtkDebugMessageInc("Core",9,"Factory::WriteDotFilePackagesList()"
821 fprintf( ff , "subgraph cluster_FACTORY {\n");
822 fprintf( ff , " label = \"PACKAGES\"%s\n", ";");
823 fprintf( ff , " style=filled%s\n",";");
824 fprintf( ff , " color=lightgrey%s\n",";");
825 fprintf( ff , " rankdir=TB%s\n",";");
828 PackageMapType::const_iterator i;
829 for (i = mPackageMap.begin(); i!=mPackageMap.end(); ++i )
831 url=GetPackage(i->first)->GetDocURL();
832 fprintf(ff," %s [shape=ellipse, URL=\"%s\"]%s\n",i->first.c_str(),url.c_str(),";" );
834 fprintf( ff , "}\n\n");
835 bbtkDebugDecTab("Core",9);
837 //===================================================================
840 void Factory::ShowGraphTypes(const std::string& name) const
843 PackageMapType::const_iterator i;
844 for (i = mPackageMap.begin(); i!=mPackageMap.end(); ++i )
846 if (i->second.mPackage->ContainsBlackBox(name))
848 std::string separator = ConfigurationFile::GetInstance().Get_file_separator ();
850 // Don't pollute the file store with "doc_tmp" directories ...
851 std::string default_doc_dir = ConfigurationFile::GetInstance().Get_default_doc_tmp();
852 std::string directory = "\"" + default_doc_dir + separator + "doc_tmp" +separator + "\"";
853 std::string filename2 = default_doc_dir + separator + "doc_tmp" + separator + "tmp.html";
856 std::string command("start \"Titre\" /D ");
858 std::string command("gnome-open ");
860 command=command + directory +" tmp.html";
862 ff=fopen(filename2.c_str(),"w");
864 fprintf(ff,"<html><head><title>TMP</title> <script type=\"text/javascript\"> <!--\n");
865 fprintf(ff," window.location=\"%s#%s\";\n" , i->second.mPackage->GetDocURL().c_str(),name.c_str() );
866 fprintf(ff,"//--></script></head><body></body></html>\n");
869 //fprintf(ff, "<a href=\"%s#%s\">Link</a>\n", i->second.mPackage->GetDocURL().c_str(),name.c_str() );
871 system( command.c_str() );
876 bbtkDebugDecTab("Core",9);
879 bbtkError("No package of the factory contains any black box <"