1 /*=========================================================================
4 Module: $RCSfile: bbtkExecuter.cxx,v $ $
6 Date: $Date: 2008/04/09 11:16:57 $
7 Version: $Revision: 1.17 $
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 //=======================================================================
48 bbtkDebugMessageInc("Kernel",9,"Executer::Executer()" <<std::endl);
49 mFactory = new Factory;
50 mFactory->SetExecuter(this);
52 bbtkDebugDecTab("Kernel",9);
54 //=======================================================================
56 //=======================================================================
59 bbtkDebugMessageInc("Kernel",9,"Executer::~Executer()" <<std::endl);
62 mRootPackage->UnRegisterBlackBox("workspace");
63 mRootCBB->UnReference();
67 GetFactory()->UnLoadPackage("user");
71 bbtkDebugDecTab("Kernel",9);
73 //=======================================================================
75 //=======================================================================
77 void Executer::LoadPackage(const std::string &name )
79 GetFactory()->LoadPackage(name);
81 //=======================================================================
83 //=======================================================================
85 void Executer::UnLoadPackage(const std::string &name )
87 GetFactory()->UnLoadPackage(name);
89 //=======================================================================
91 //=======================================================================
92 void Executer::Reset()
94 bbtkDebugMessageInc("Kernel",9,"Executer::Reset()" <<std::endl);
96 GetFactory()->CheckPackages();
98 // The 'user' package must be closed before all other
99 // because box destructors must not be unloaded when bb are deleted!
100 // Similarly, the 'workspace' CBB must be destroyed before
101 // all user defined CBB otherwise any instance
102 // of a user CBB that is in the 'workspace' would try to
103 // access a user CBB descriptor which has been previously freed
106 mRootPackage->UnRegisterBlackBox(mRootCBB->GetTypeName());
107 mRootCBB->UnReference();
111 GetFactory()->UnLoadPackage("user");
113 GetFactory()->Reset();
115 // Create user package
116 mRootPackage = new Package("user","internal to bbi",
117 "User defined black boxes",
119 BBTK_STRINGIFY_SYMBOL(BBTK_VERSION));
120 // Create user workspace
121 mRootCBB = new ComplexBlackBoxDescriptor("workspace"); //,f);
122 mRootCBB->Reference();
123 mRootCBB->SetFactory(GetFactory());
124 mRootCBB->AddToAuthor("bbi (internal)");
125 mRootCBB->AddToDescription("User's workspace");
126 mOpenDefinition.push_back(CBBDefinition(mRootCBB,"user"));
127 // Register it into the user package
128 mRootPackage->RegisterBlackBox(mRootCBB);
129 // Insert the user package in the factory
130 GetFactory()->InsertPackage(mRootPackage);
131 // And in the list of open packages
132 mOpenPackage.push_back(mRootPackage);
135 GetFactory()->CheckPackages();
137 bbtkDebugDecTab("Kernel",9);
139 //=======================================================================
141 //=======================================================================
142 /// changes the workspace name
143 void Executer::SetWorkspaceName( const std::string& n )
145 mRootPackage->ChangeBlackBoxName( mRootCBB->GetTypeName(), n );
147 //=======================================================================
149 //=======================================================================
150 void Executer::BeginPackage (const std::string &name)
152 bbtkDebugMessageInc("Kernel",9,"Executer::BeginPackage(\""<<name<<"\")"
157 p = GetFactory()->GetPackage(name);
161 p = new Package(name,
165 BBTK_STRINGIFY_SYMBOL(BBTK_VERSION));
166 GetFactory()->InsertPackage(p);
168 mOpenPackage.push_back(p);
170 //=======================================================================
172 //=======================================================================
173 void Executer::EndPackage()
175 if (mOpenPackage.size()>1) mOpenPackage.pop_back();
177 //=======================================================================
179 //=======================================================================
180 void Executer::Define (const std::string &name,
181 const std::string &pack,
182 const std::string &scriptfilename)
184 bbtkDebugMessageInc("Kernel",9,"Executer::Define(\""<<name<<
188 ComplexBlackBoxDescriptor* b = new ComplexBlackBoxDescriptor(name);
189 b->SetFactory(GetFactory());
190 b->SetScriptFileName(scriptfilename);
191 mOpenDefinition.push_back( CBBDefinition( b, pack ) );
193 bbtkDebugDecTab("Kernel",9);
195 //=======================================================================
197 //=======================================================================
198 /// Sets the file name to use for the current definition
199 /// (Used to set it after the Define command)
200 void Executer::SetCurrentFileName (const std::string &name )
202 mOpenDefinition.back().box->SetScriptFileName(name);
204 //=======================================================================
206 //=======================================================================
207 void Executer::EndDefine ()
209 bbtkDebugMessageInc("Kernel",9,"Executer::EndDefine(\""
210 <<Current()->GetTypeName()<<"\")"
212 // Does current package exist ?
214 std::string pname(mOpenDefinition.back().package);
219 p = GetFactory()->GetPackage(pname);
223 p = new Package(pname,
227 BBTK_STRINGIFY_SYMBOL(BBTK_VERSION));
228 GetFactory()->InsertPackage(p);
233 p = mOpenPackage.back();
235 p->RegisterBlackBox(Current());
237 mOpenDefinition.pop_back();
239 //=======================================================================
241 //=======================================================================
242 void Executer::Kind(const std::string& kind)
246 Current()->AddToCategory("adaptor");
247 Current()->SetKind(bbtk::BlackBoxDescriptor::ADAPTOR);
249 else if (kind=="DEFAULT_ADAPTOR")
251 Current()->AddToCategory("adaptor");
252 Current()->SetKind(bbtk::BlackBoxDescriptor::DEFAULT_ADAPTOR);
254 if (kind=="WIDGET_ADAPTOR")
256 Current()->AddToCategory("adaptor");
257 Current()->SetKind(bbtk::BlackBoxDescriptor::WIDGET_ADAPTOR);
259 else if (kind=="DEFAULT_WIDGET_ADAPTOR")
261 Current()->AddToCategory("adaptor");
262 Current()->SetKind(bbtk::BlackBoxDescriptor::DEFAULT_WIDGET_ADAPTOR);
266 bbtkError("Unknown box kind : '"<<kind<<"'. "
267 <<"Valid kinds are 'ADAPTOR','DEFAULT_ADAPTOR',"
268 <<"'WIDGET_ADAPTOR','DEFAULT_WIDGET_ADAPTOR'");
271 //=======================================================================
273 //=======================================================================
274 void Executer::Create ( const std::string& nodeType,
275 const std::string& nodeName)
277 Current()->Add(nodeType,nodeName);
279 //=======================================================================
281 //=======================================================================
282 void Executer::Destroy(const std::string &boxName)
284 bbtkError("Executer::Destroy : NOT IMPLEMENTED !");
286 //=======================================================================
288 //=======================================================================
289 void Executer::Connect (const std::string &nodeFrom,
290 const std::string &outputLabel,
291 const std::string &nodeTo,
292 const std::string &inputLabel)
294 Current()->Connect(nodeFrom, outputLabel, nodeTo, inputLabel);
296 //=======================================================================
298 //=======================================================================
299 void Executer::Execute (const std::string &nodeName)
302 if (Current()==mRootCBB)
306 Current()->GetPrototype()->bbGetBlackBox(nodeName)->bbExecute(true);
311 Current()->AddToExecutionList(nodeName) ;
314 //=======================================================================
316 //=======================================================================
317 void Executer::DefineInput ( const std::string &name,
318 const std::string &box,
319 const std::string &input,
320 const std::string& help)
322 // If the input is defined in the Root box
323 if (Current()==mRootCBB)
325 // If the dialog mode is set to NoDialog
326 // and the user passed the name in the Inputs map
327 // then the associated value is set to the box.input
328 // This is the way command line parameters are passed to the Root box
329 if (mDialogMode == NoDialog)
331 // find if name is in mInputs
332 std::map<std::string,std::string>::iterator i;
333 i = mInputs.find(name);
334 if (i!=mInputs.end()) {
335 Set(box,input,(*i).second);
338 // If the dialog mode is set to TextDialog
339 // The user is prompted for the value
340 else if (mDialogMode == TextDialog)
342 std::cout << name << "=";
347 #ifdef _USE_WXWIDGETS_
348 // If the dialog mode is set to GraphicalDialog
349 // A dialog box is pop up
350 else if (mDialogMode == GraphicalDialog)
352 std::string mess("Enter the value of '");
357 std::string title(name);
359 std::string ans = wx2std ( wxGetTextFromUser( std2wx (mess), std2wx(title)));
365 Current()->DefineInput(name,box,input,help);
368 //=======================================================================
370 //=======================================================================
371 void Executer::DefineOutput ( const std::string &name,
372 const std::string &box,
373 const std::string &output,
374 const std::string& help)
376 Current()->DefineOutput(name,box,output,help);
378 //=======================================================================
380 //=======================================================================
381 void Executer::Set (const std::string &box,
382 const std::string &input,
383 const std::string &value)
385 BlackBox* b = Current()->GetPrototype()->bbGetBlackBox(box);
386 // Looks for the adaptor
388 if ( b->bbGetInputType(input) != typeid(std::string) )
391 GetFactory()->NewAdaptor(typeid(std::string),
392 b->bbGetInputType(input),
397 TypeName(b->bbGetInputType(input))
398 <<"> to <std::string> found");
400 std::string v(value);
401 a->bbSetInput("In",v);
403 b->bbSetInput(input,a->bbGetOutput("Out"));
408 std::string v(value);
409 b->bbSetInput(input,v);
412 //=======================================================================
414 //=======================================================================
415 std::string Executer::Get(const std::string &box,
416 const std::string &output)
418 BlackBox* b = Current()->GetPrototype()->bbGetBlackBox(box);
419 // Looks for the adaptor
420 if (b->bbGetOutputType(output) != typeid(std::string))
423 GetFactory()->NewAdaptor(
424 b->bbGetOutputType(output),
430 TypeName(b->bbGetOutputType(output))
431 <<"> to <std::string> found");
435 a->bbSetInput("In",b->bbGetOutput(output));
437 std::string r = a->bbGetOutput("Out").unsafe_get<std::string>();
438 //std::string v = *((std::string*)a->bbGetOutput("Out")) ;
439 // std::cout << a->bbGetOutput("Out").unsafe_get<std::string>()
441 //std::string v(value);
442 //b->bbSetInput(input,a->bbGetOutput("Out"));
449 return b->bbGetOutput(output).unsafe_get<std::string>();
450 // std::string v = *((std::string*)b->bbGetOutput(output)) ;
451 // std::cout << b->bbGetOutput("Out").unsafe_get<std::string>()
453 // b->bbSetInput(input,&v);
456 //=======================================================================
458 //=======================================================================
459 void Executer::Author(const std::string &authorName)
461 Current()->AddToAuthor(authorName,Current()==mRootCBB);
463 //=======================================================================
465 //=======================================================================
466 void Executer::Category(const std::string &category)
468 Current()->AddToCategory(category,Current()==mRootCBB);
470 //=======================================================================
472 //=======================================================================
473 void Executer::Description(const std::string &d)
475 Current()->AddToDescription(d,Current()==mRootCBB);
477 //=======================================================================
479 //=======================================================================
480 /// prints the list of the boxes of the current descriptor
481 void Executer::PrintBoxes()
483 bbtkMessageInc("Help",1,"The black box descriptor \""
484 <<Current()->GetTypeName()<<"\" contains : "<<std::endl);
485 Current()->PrintBlackBoxes();
486 bbtkDecTab("Help",1);
488 //=======================================================================
490 //=======================================================================
491 std::string Executer::ShowGraph(const std::string &nameblackbox,
492 const std::string &detailStr,
493 const std::string &levelStr,
494 const std::string &output_html,
495 const std::string &custom_header,
496 const std::string &custom_title,
497 bool system_display )
499 int detail = atoi(detailStr.c_str());
500 int level = atoi(levelStr.c_str());
502 std::string filename_rootHtml (output_html) ;
503 std::string simplefilename_rootHtml ( Utilities::get_file_name(output_html));
505 bool relative_link = true;
507 // No output provided : automatic generation
508 if (output_html.length() == 0)
510 // Don't pollute the file store with "temp_dir" directories ...
511 std::string default_doc_dir = ConfigurationFile::GetInstance().Get_default_temp_dir();
513 char c = default_doc_dir.c_str()[strlen(default_doc_dir.c_str())-1];
515 std::string directory = default_doc_dir;
516 if (c != '/' && c !='\\') directory = directory + "/";
517 directory = directory + "temp_dir";
519 filename_rootHtml = directory + "/" + "User.html";
520 simplefilename_rootHtml = "User.html" ;
522 // Creating directory
523 std::string command0("mkdir \"" +directory + "\"");
524 system( command0.c_str() );
526 relative_link = false;
532 p = GetFactory()->GetPackage(nameblackbox);
538 // Generating documentation-help of workspace
539 p->SetDocURL(filename_rootHtml);
540 p->SetDocRelativeURL(simplefilename_rootHtml);
542 p->CreateHtmlPage(filename_rootHtml,"bbi","user package",custom_header,custom_title,detail,level,relative_link);
544 std::string page = filename_rootHtml;
548 ShowGraphTypes(nameblackbox);
550 catch (bbtk::Exception a)
552 std::cout <<"EXC"<<std::endl;
553 page = ShowGraphInstances(nameblackbox,detail,level,system_display);
558 //=======================================================================
560 //=======================================================================
561 /// Generate a png file with the actual pipeline (Graphviz-dot needed)
562 std::string Executer::ShowGraphInstances(const std::string &nameblackbox, int detail, int level,
566 BlackBox* blackbox=NULL;
567 if (nameblackbox==".")
569 blackbox=Current()->GetPrototype();
573 blackbox = Current()->GetPrototype()->bbFindBlackBox(nameblackbox);
580 // Don't pollute the file store with "temp_dir" directories ...
581 std::string default_doc_dir = ConfigurationFile::GetInstance().Get_default_temp_dir();
582 char c = default_doc_dir.c_str()[strlen(default_doc_dir.c_str())-1];
584 std::string directory = default_doc_dir;
585 if (c != '/' && c !='\\') directory = directory + "/";
587 directory = directory + "temp_dir";
588 //std::string directory("temp_dir");
589 std::string filename(directory + "/" + "bbtk_graph_pipeline");
590 std::string filename_html(filename+".html");
591 std::string command0("mkdir \""+directory + "\"");
594 std::string command2("start ");
596 std::string command2("gnome-open ");
599 command2=command2+filename_html;
600 page = filename_html;
601 // 1. Generate Html Diagram
603 s.open(filename_html.c_str());
606 s << "<html><head><title>BBtk graph diagram</title><meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\"></head>\n";
607 s << "<body bgcolor=\"#FFFFFF\" text=\"#000000\"> \n\n";
608 if ( blackbox->bbGetName()=="workspacePrototype" )
610 s << "<center>Current workspace</center>";
612 s << "<center>" << blackbox->bbGetName()<< "</center>";
615 blackbox->bbInsertHTMLGraph( s, detail, level, true, directory, false );
616 s << "</body></html>\n";
620 // 2. Starting Browser
621 if (system_display) system( command2.c_str() );
625 bbtkMessageInc("Help",1,"No black box: \""
626 <<nameblackbox<<"\" " <<std::endl);
630 //=======================================================================
632 //=======================================================================
633 void Executer::ShowRelations(const std::string &nameblackbox,
634 const std::string &detailStr,
635 const std::string &levelStr)
639 int detail = atoi(detailStr.c_str());
640 int level = atoi(levelStr.c_str());
641 BlackBox* blackbox=NULL;
642 if (nameblackbox.compare(".")==0)
644 blackbox=Current()->GetPrototype();
648 blackbox = Current()->GetPrototype()->bbFindBlackBox(nameblackbox);
654 blackbox->bbShowRelations(blackbox,detail,level); //,mFactory);
659 bbtkError("Blackbox Name not found.. <" <<nameblackbox<<">");
662 //=======================================================================
664 //=======================================================================
665 /// sets the level of message
666 void Executer::SetMessageLevel(const std::string &kind,
669 bbtk::MessageManager::SetMessageLevel(kind,level);
671 //=======================================================================
673 //=======================================================================
674 /// Prints help on the messages
675 void Executer::HelpMessages()
677 bbtk::MessageManager::PrintInfo();
679 //=======================================================================
681 //=======================================================================
683 void Executer::Print(const std::string &str)
685 if (GetNoExecMode() && (Current()==mRootCBB) ) return;
686 if (Current()!=mRootCBB) return;
688 bbtkDebugMessageInc("Interpreter",9,"Interpreter::Print(\""<<str<<"\")"<<std::endl);
691 // InterpretLine ("load std")
692 // InterpretLine("new ConcatStrings _C_ ") -> trouver un nom unique : # commande
693 // InterpretLine("new Print _P_")
694 // InterpretLine("connect _C_.Out _P_.In")
698 std::vector<std::string> chains;
699 std::string delimiters("$");
701 // Skip delimiters at beginning.
702 std::string::size_type lastPos = str.find_first_not_of(delimiters, 0);
704 if (lastPos>0) is_text = false;
706 // Find first delimiter.
707 std::string::size_type pos = str.find_first_of(delimiters, lastPos);
709 while (std::string::npos != pos || std::string::npos != lastPos)
713 // Found a text token, add it to the vector.
714 chains.push_back(str.substr(lastPos, pos - lastPos));
715 // std::string token = str.substr(lastPos, pos - lastPos)
716 // InterpretLine("set _C_.In%num% %token%")
722 // is an output (between $$) : decode
723 std::string tok,box,output;
724 tok = str.substr(lastPos, pos - lastPos);
725 Utilities::SplitAroundFirstDot(tok,box,output);
726 chains.push_back( Get(box,output) );
728 // InterpretLine("connect %tok% _C_.In%num%")
731 // Skip delimiters. Note the "not_of"
732 lastPos = str.find_first_not_of(delimiters, pos);
733 // Find next delimiter
734 pos = str.find_first_of(delimiters, lastPos);
739 // InterpretLine("exec _P_")
740 // if (IS_IN_WORKSPACE) InterpretLine("delete _C_; delete _P_");
742 std::vector<std::string>::iterator i;
743 for (i= chains.begin(); i!=chains.end(); ++i)
745 // bbtkMessage("Echo",1,*i);
746 Utilities::SubsBackslashN(*i);
747 bbtkMessage("Output",1,*i);
749 bbtkMessage("Output",1,std::endl);