1 /*=========================================================================
4 Module: $RCSfile: bbtkExecuter.cxx,v $ $
6 Date: $Date: 2008/07/01 07:58:28 $
7 Version: $Revision: 1.21 $
9 Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de
10 l'Image). All rights reserved. See Doc/License.txt or
11 http://www.creatis.insa-lyon.fr/Public/bbtk/License.html for details.
13 This software is distributed WITHOUT ANY WARRANTY; without even
14 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 PURPOSE. See the above copyright notices for more information.
17 =========================================================================*/
20 * \brief class Executer: level 0 of script execution (code)
23 #include "bbtkExecuter.h"
24 #include "bbtkMessageManager.h"
25 #include "bbtkFactory.h"
26 #include "bbtkUtilities.h"
29 #ifdef _USE_WXWIDGETS_
30 #include <wx/textdlg.h>
33 #include "bbtkWxBlackBox.h"
35 #include "bbtkConfigurationFile.h"
39 //=======================================================================
40 Executer::Pointer Executer::New()
42 bbtkDebugMessage("Kernel",9,"Executer::New()"<<std::endl);
43 return MakePointer(new Executer());
45 //=======================================================================
47 //=======================================================================
56 bbtkDebugMessageInc("Kernel",9,"Executer::Executer()" <<std::endl);
57 mFactory = Factory::New();
58 // The smart pointer on this is not made yet (is made by New)
59 // -> create it to pass it to the factory
60 // We have to "lock" the smart pointer because the factory
61 // only keeps a weak pointer on the executer
62 // -> this would auto-destroy !!
63 mFactory->SetExecuter(MakePointer(this,true));
65 bbtkDebugDecTab("Kernel",9);
67 //=======================================================================
69 //=======================================================================
72 bbtkDebugMessageInc("Kernel",9,"==> Executer::~Executer()" <<std::endl);
73 mOpenDefinition.clear();
77 bbtkDebugDecTab("Kernel",9);
79 //=======================================================================
81 //=======================================================================
83 void Executer::LoadPackage(const std::string &name )
85 GetFactory()->LoadPackage(name);
87 //=======================================================================
89 //=======================================================================
91 void Executer::UnLoadPackage(const std::string &name )
93 GetFactory()->UnLoadPackage(name);
95 //=======================================================================
97 //=======================================================================
98 void Executer::Reset()
100 bbtkDebugMessageInc("Kernel",9,"Executer::Reset()" <<std::endl);
102 GetFactory()->CheckPackages();
104 mOpenDefinition.clear();
105 mOpenPackage.clear();
106 GetFactory()->Reset();
108 // Create user package
110 Package::New("user","internal",
111 "User defined black boxes",
113 BBTK_STRINGIFY_SYMBOL(BBTK_VERSION));
114 // Insert the user package in the factory
115 GetFactory()->InsertPackage(p);
116 // And in the list of open packages
117 mOpenPackage.push_back(p);
120 // Create user workspace
121 ComplexBlackBoxDescriptor::Pointer r =
122 ComplexBlackBoxDescriptor::New("workspace");
123 // mRootCBB->Reference();
124 r->SetFactory(GetFactory());
125 r->AddToAuthor("bbtk");
126 r->AddToDescription("User's workspace");
127 mOpenDefinition.push_back(CBBDefinition(r,"user"));
128 // Register it into the user package
129 p->RegisterBlackBox(r);
132 // Object::PrintObjectListInfo();
133 // GetFactory()->CheckPackages();
135 bbtkDebugDecTab("Kernel",9);
137 //=======================================================================
139 //=======================================================================
140 /// changes the workspace name
141 void Executer::SetWorkspaceName( const std::string& n )
143 GetUserPackage()->ChangeBlackBoxName( GetWorkspace()->GetTypeName(), n );
145 //=======================================================================
147 //=======================================================================
148 void Executer::BeginPackage (const std::string &name)
150 bbtkDebugMessageInc("Kernel",9,"Executer::BeginPackage(\""<<name<<"\")"
155 p = GetFactory()->GetPackage(name);
159 p = Package::New(name,
163 BBTK_STRINGIFY_SYMBOL(BBTK_VERSION));
164 GetFactory()->InsertPackage(p);
166 mOpenPackage.push_back(p);
168 //=======================================================================
170 //=======================================================================
171 void Executer::EndPackage()
173 if (mOpenPackage.size()>1) mOpenPackage.pop_back();
175 //=======================================================================
177 //=======================================================================
178 void Executer::Define (const std::string &name,
179 const std::string &pack,
180 const std::string &scriptfilename)
182 bbtkDebugMessageInc("Kernel",9,"Executer::Define(\""<<name<<
186 ComplexBlackBoxDescriptor::Pointer b
187 = ComplexBlackBoxDescriptor::New(name);
188 b->SetFactory(GetFactory());
189 b->SetScriptFileName(scriptfilename);
190 mOpenDefinition.push_back( CBBDefinition( b, pack ) );
192 bbtkDebugDecTab("Kernel",9);
194 //=======================================================================
196 //=======================================================================
197 /// Sets the file name to use for the current definition
198 /// (Used to set it after the Define command)
199 void Executer::SetCurrentFileName (const std::string &name )
201 mOpenDefinition.back().box->SetScriptFileName(name);
203 //=======================================================================
205 //=======================================================================
206 void Executer::EndDefine ()
208 bbtkDebugMessageInc("Kernel",9,"Executer::EndDefine(\""
209 <<GetCurrentDescriptor()->GetTypeName()<<"\")"
211 // Does current package exist ?
213 std::string pname(mOpenDefinition.back().package);
218 p = GetFactory()->GetPackage(pname);
222 p = Package::New(pname,
226 BBTK_STRINGIFY_SYMBOL(BBTK_VERSION));
227 GetFactory()->InsertPackage(p);
232 p = mOpenPackage.back().lock();
234 p->RegisterBlackBox(GetCurrentDescriptor());
236 mOpenDefinition.pop_back();
238 //=======================================================================
240 //=======================================================================
241 void Executer::Kind(const std::string& kind)
245 GetCurrentDescriptor()->AddToCategory("adaptor");
246 GetCurrentDescriptor()->SetKind(bbtk::BlackBoxDescriptor::ADAPTOR);
248 else if (kind=="DEFAULT_ADAPTOR")
250 GetCurrentDescriptor()->AddToCategory("adaptor");
251 GetCurrentDescriptor()->SetKind(bbtk::BlackBoxDescriptor::DEFAULT_ADAPTOR);
255 GetCurrentDescriptor()->AddToCategory("gui");
256 GetCurrentDescriptor()->SetKind(bbtk::BlackBoxDescriptor::GUI);
258 else if (kind=="DEFAULT_GUI")
260 GetCurrentDescriptor()->AddToCategory("gui");
261 GetCurrentDescriptor()->SetKind(bbtk::BlackBoxDescriptor::DEFAULT_GUI);
265 bbtkError("Unknown box kind : '"<<kind<<"'. "
266 <<"Valid kinds are 'ADAPTOR','DEFAULT_ADAPTOR',"
267 <<"'GUI','DEFAULT_GUI'");
270 //=======================================================================
272 //=======================================================================
273 void Executer::Create ( const std::string& nodeType,
274 const std::string& nodeName)
276 GetCurrentDescriptor()->Add(nodeType,nodeName);
278 //=======================================================================
280 //=======================================================================
281 void Executer::Destroy(const std::string &boxName)
283 GetCurrentDescriptor()->Remove(boxName,true);
285 //=======================================================================
287 //=======================================================================
288 void Executer::Connect (const std::string &nodeFrom,
289 const std::string &outputLabel,
290 const std::string &nodeTo,
291 const std::string &inputLabel)
293 GetCurrentDescriptor()->Connect(nodeFrom, outputLabel, nodeTo, inputLabel);
295 //=======================================================================
297 //=======================================================================
298 void Executer::Execute (const std::string &nodeName)
301 if (GetCurrentDescriptor()==GetWorkspace())
305 GetCurrentDescriptor()->GetPrototype()->bbGetBlackBox(nodeName)->bbExecute(true);
310 GetCurrentDescriptor()->AddToExecutionList(nodeName) ;
313 //=======================================================================
315 //=======================================================================
316 void Executer::DefineInput ( const std::string &name,
317 const std::string &box,
318 const std::string &input,
319 const std::string& help)
321 // If the input is defined in the Root box
322 if (GetCurrentDescriptor()==GetWorkspace())
324 // If the dialog mode is set to NoDialog
325 // and the user passed the name in the Inputs map
326 // then the associated value is set to the box.input
327 // This is the way command line parameters are passed to the Root box
328 if (mDialogMode == NoDialog)
330 // find if name is in mInputs
331 std::map<std::string,std::string>::iterator i;
332 i = mInputs.find(name);
333 if (i!=mInputs.end()) {
334 Set(box,input,(*i).second);
337 // If the dialog mode is set to TextDialog
338 // The user is prompted for the value
339 else if (mDialogMode == TextDialog)
341 std::cout << name << "=";
346 #ifdef _USE_WXWIDGETS_
347 // If the dialog mode is set to GraphicalDialog
348 // A dialog box is pop up
349 else if (mDialogMode == GraphicalDialog)
351 std::string mess("Enter the value of '");
356 std::string title(name);
358 std::string ans = wx2std ( wxGetTextFromUser( std2wx (mess), std2wx(title)));
364 GetCurrentDescriptor()->DefineInput(name,box,input,help);
367 //=======================================================================
369 //=======================================================================
370 void Executer::DefineOutput ( const std::string &name,
371 const std::string &box,
372 const std::string &output,
373 const std::string& help)
375 GetCurrentDescriptor()->DefineOutput(name,box,output,help);
377 //=======================================================================
379 //=======================================================================
380 void Executer::Set (const std::string &box,
381 const std::string &input,
382 const std::string &value)
384 BlackBox::Pointer b = GetCurrentDescriptor()->GetPrototype()->bbGetBlackBox(box);
385 // Looks for the adaptor
387 if ( b->bbGetInputType(input) != typeid(std::string) )
389 BlackBox::Pointer a =
390 GetFactory()->NewAdaptor(typeid(std::string),
391 b->bbGetInputType(input),
396 TypeName(b->bbGetInputType(input))
397 <<"> to <std::string> found");
399 std::string v(value);
400 a->bbSetInput("In",v);
402 b->bbSetInput(input,a->bbGetOutput("Out"));
407 std::string v(value);
408 b->bbSetInput(input,v);
411 //=======================================================================
413 //=======================================================================
414 std::string Executer::Get(const std::string &box,
415 const std::string &output)
417 BlackBox::Pointer b = GetCurrentDescriptor()->GetPrototype()->bbGetBlackBox(box);
418 // Looks for the adaptor
419 if (b->bbGetOutputType(output) != typeid(std::string))
421 BlackBox::Pointer a =
422 GetFactory()->NewAdaptor(
423 b->bbGetOutputType(output),
429 TypeName(b->bbGetOutputType(output))
430 <<"> to <std::string> found");
434 a->bbSetInput("In",b->bbGetOutput(output));
436 std::string r = a->bbGetOutput("Out").unsafe_get<std::string>();
437 //std::string v = *((std::string*)a->bbGetOutput("Out")) ;
438 // std::cout << a->bbGetOutput("Out").unsafe_get<std::string>()
440 //std::string v(value);
441 //b->bbSetInput(input,a->bbGetOutput("Out"));
448 return b->bbGetOutput(output).unsafe_get<std::string>();
449 // std::string v = *((std::string*)b->bbGetOutput(output)) ;
450 // std::cout << b->bbGetOutput("Out").unsafe_get<std::string>()
452 // b->bbSetInput(input,&v);
455 //=======================================================================
457 //=======================================================================
458 void Executer::Author(const std::string &authorName)
460 GetCurrentDescriptor()->AddToAuthor(authorName,GetCurrentDescriptor()==GetWorkspace());
462 //=======================================================================
464 //=======================================================================
465 void Executer::Category(const std::string &category)
467 GetCurrentDescriptor()->AddToCategory(category,GetCurrentDescriptor()==GetWorkspace());
469 //=======================================================================
471 //=======================================================================
472 void Executer::Description(const std::string &d)
474 GetCurrentDescriptor()->AddToDescription(d,GetCurrentDescriptor()==GetWorkspace());
476 //=======================================================================
478 //=======================================================================
479 /// prints the list of the boxes of the current descriptor
480 void Executer::PrintBoxes()
482 bbtkMessageInc("Help",1,"The black box descriptor \""
483 <<GetCurrentDescriptor()->GetTypeName()<<"\" contains : "<<std::endl);
484 GetCurrentDescriptor()->PrintBlackBoxes();
485 bbtkDecTab("Help",1);
487 //=======================================================================
489 //=======================================================================
490 std::string Executer::ShowGraph(const std::string &nameblackbox,
491 const std::string &detailStr,
492 const std::string &levelStr,
493 const std::string &output_html,
494 const std::string &custom_header,
495 const std::string &custom_title,
496 bool system_display )
498 int detail = atoi(detailStr.c_str());
499 int level = atoi(levelStr.c_str());
501 std::string filename_rootHtml (output_html) ;
502 std::string simplefilename_rootHtml ( Utilities::get_file_name(output_html));
504 bool relative_link = true;
506 // No output provided : automatic generation
507 if (output_html.length() == 0)
509 // Don't pollute the file store with "temp_dir" directories ...
510 std::string default_doc_dir = ConfigurationFile::GetInstance().Get_default_temp_dir();
512 char c = default_doc_dir.c_str()[strlen(default_doc_dir.c_str())-1];
514 std::string directory = default_doc_dir;
515 if (c != '/' && c !='\\') directory = directory + "/";
516 directory = directory + "temp_dir";
518 filename_rootHtml = directory + "/" + "User.html";
519 simplefilename_rootHtml = "User.html" ;
521 // Creating directory
522 std::string command0("mkdir \"" +directory + "\"");
523 system( command0.c_str() );
525 relative_link = false;
531 p = GetFactory()->GetPackage(nameblackbox);
535 p = GetUserPackage();
537 // Generating documentation-help of workspace
538 p->SetDocURL(filename_rootHtml);
539 p->SetDocRelativeURL(simplefilename_rootHtml);
541 p->CreateHtmlPage(filename_rootHtml,"bbtk","user package",custom_header,custom_title,detail,level,relative_link);
543 std::string page = filename_rootHtml;
547 ShowGraphTypes(nameblackbox);
549 catch (bbtk::Exception a)
551 std::cout <<"EXC"<<std::endl;
552 page = ShowGraphInstances(nameblackbox,detail,level,system_display);
557 //=======================================================================
559 //=======================================================================
560 /// Generate a png file with the actual pipeline (Graphviz-dot needed)
561 std::string Executer::ShowGraphInstances(const std::string &nameblackbox, int detail, int level,
565 BlackBox::Pointer blackbox;
566 if (nameblackbox==".")
568 blackbox = GetCurrentDescriptor()->GetPrototype();
572 blackbox = GetCurrentDescriptor()->GetPrototype()->bbFindBlackBox(nameblackbox);
579 // Don't pollute the file store with "temp_dir" directories ...
580 std::string default_doc_dir = ConfigurationFile::GetInstance().Get_default_temp_dir();
581 char c = default_doc_dir.c_str()[strlen(default_doc_dir.c_str())-1];
583 std::string directory = default_doc_dir;
584 if (c != '/' && c !='\\') directory = directory + "/";
586 directory = directory + "temp_dir";
587 //std::string directory("temp_dir");
588 std::string filename(directory + "/" + "bbtk_graph_pipeline");
589 std::string filename_html(filename+".html");
590 std::string command0("mkdir \""+directory + "\"");
593 std::string command2("start ");
595 std::string command2("gnome-open ");
598 command2=command2+filename_html;
599 page = filename_html;
600 // 1. Generate Html Diagram
602 s.open(filename_html.c_str());
605 s << "<html><head><title>BBtk graph diagram</title><meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\"></head>\n";
606 s << "<body bgcolor=\"#FFFFFF\" text=\"#000000\"> \n\n";
607 if ( blackbox->bbGetName()=="workspacePrototype" )
609 s << "<center>Current workspace</center>";
611 s << "<center>" << blackbox->bbGetName()<< "</center>";
614 blackbox->bbInsertHTMLGraph( s, detail, level, true, directory, false );
615 s << "</body></html>\n";
619 // 2. Starting Browser
620 if (system_display) system( command2.c_str() );
624 bbtkMessageInc("Help",1,"No black box: \""
625 <<nameblackbox<<"\" " <<std::endl);
629 //=======================================================================
631 //=======================================================================
632 void Executer::ShowRelations(const std::string &nameblackbox,
633 const std::string &detailStr,
634 const std::string &levelStr)
638 int detail = atoi(detailStr.c_str());
639 int level = atoi(levelStr.c_str());
640 BlackBox::Pointer blackbox;
641 if (nameblackbox.compare(".")==0)
643 blackbox=GetCurrentDescriptor()->GetPrototype();
647 blackbox = GetCurrentDescriptor()->GetPrototype()->bbFindBlackBox(nameblackbox);
653 blackbox->bbShowRelations(blackbox,detail,level); //,mFactory);
658 bbtkError("Blackbox Name not found.. <" <<nameblackbox<<">");
661 //=======================================================================
663 //=======================================================================
664 /// sets the level of message
665 void Executer::SetMessageLevel(const std::string &kind,
668 bbtk::MessageManager::SetMessageLevel(kind,level);
670 //=======================================================================
672 //=======================================================================
673 /// Prints help on the messages
674 void Executer::HelpMessages()
676 bbtk::MessageManager::PrintInfo();
678 //=======================================================================
680 //=======================================================================
682 void Executer::Print(const std::string &str)
684 if (GetNoExecMode() && (GetCurrentDescriptor()==GetWorkspace()) ) return;
685 if (GetCurrentDescriptor()!=GetWorkspace()) return;
687 bbtkDebugMessageInc("Interpreter",9,"Interpreter::Print(\""<<str<<"\")"<<std::endl);
690 // InterpretLine ("load std")
691 // InterpretLine("new ConcatStrings _C_ ") -> trouver un nom unique : # commande
692 // InterpretLine("new Print _P_")
693 // InterpretLine("connect _C_.Out _P_.In")
697 std::vector<std::string> chains;
698 std::string delimiters("$");
700 // Skip delimiters at beginning.
701 std::string::size_type lastPos = str.find_first_not_of(delimiters, 0);
703 if (lastPos>0) is_text = false;
705 // Find first delimiter.
706 std::string::size_type pos = str.find_first_of(delimiters, lastPos);
708 while (std::string::npos != pos || std::string::npos != lastPos)
712 // Found a text token, add it to the vector.
713 chains.push_back(str.substr(lastPos, pos - lastPos));
714 // std::string token = str.substr(lastPos, pos - lastPos)
715 // InterpretLine("set _C_.In%num% %token%")
721 // is an output (between $$) : decode
722 std::string tok,box,output;
723 tok = str.substr(lastPos, pos - lastPos);
724 Utilities::SplitAroundFirstDot(tok,box,output);
725 chains.push_back( Get(box,output) );
727 // InterpretLine("connect %tok% _C_.In%num%")
730 // Skip delimiters. Note the "not_of"
731 lastPos = str.find_first_not_of(delimiters, pos);
732 // Find next delimiter
733 pos = str.find_first_of(delimiters, lastPos);
738 // InterpretLine("exec _P_")
739 // if (IS_IN_WORKSPACE) InterpretLine("delete _C_; delete _P_");
741 std::vector<std::string>::iterator i;
742 for (i= chains.begin(); i!=chains.end(); ++i)
744 Utilities::SubsBackslashN(*i);
745 bbtkMessage("Output",1,*i);
747 bbtkMessage("Output",1,std::endl);
749 //==========================================================================
751 //==========================================================================
752 std::string Executer::GetObjectName() const
754 return std::string("Executer");
756 //==========================================================================
758 //==========================================================================
759 std::string Executer::GetObjectInfo() const
764 //==========================================================================
765 //==========================================================================
766 size_t Executer::GetObjectSize() const
768 size_t s = Superclass::GetObjectSize();
769 s += Executer::GetObjectInternalSize();
772 //==========================================================================
773 //==========================================================================
774 size_t Executer::GetObjectInternalSize() const
776 size_t s = sizeof(Executer);
779 //==========================================================================
780 //==========================================================================
781 size_t Executer::GetObjectRecursiveSize() const
783 size_t s = Superclass::GetObjectRecursiveSize();
784 s += Executer::GetObjectInternalSize();
785 s += mFactory->GetObjectRecursiveSize();
788 //==========================================================================