1 /*=========================================================================
4 Module: $RCSfile: bbtkExecuter.cxx,v $ $
6 Date: $Date: 2008/04/08 06:59:30 $
7 Version: $Revision: 1.16 $
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");
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 // The 'user' package must be closed before all other
97 // because box destructors must not be unloaded when bb are deleted!
98 // Similarly, the 'workspace' CBB must be destroyed before
99 // all user defined CBB otherwise any instance
100 // of a user CBB that is in the 'workspace' would try to
101 // access a user CBB descriptor which has been previously freed
104 mRootPackage->UnRegisterBlackBox(mRootCBB->GetTypeName());
109 GetFactory()->UnLoadPackage("user");
111 GetFactory()->Reset();
113 // Create user package
114 mRootPackage = new Package("user","internal to bbi",
115 "User defined black boxes",
117 BBTK_STRINGIFY_SYMBOL(BBTK_VERSION));
118 // Create user workspace
119 mRootCBB = new ComplexBlackBoxDescriptor("workspace"); //,f);
120 mRootCBB->SetFactory(GetFactory());
121 mRootCBB->AddToAuthor("bbi (internal)");
122 mRootCBB->AddToDescription("User's workspace");
123 mOpenDefinition.push_back(CBBDefinition(mRootCBB,"user"));
124 // Register it into the user package
125 mRootPackage->RegisterBlackBox(mRootCBB);
126 // Insert the user package in the factory
127 GetFactory()->InsertPackage(mRootPackage);
128 // And in the list of open packages
129 mOpenPackage.push_back(mRootPackage);
131 bbtkDebugDecTab("Kernel",9);
133 //=======================================================================
135 //=======================================================================
136 /// changes the workspace name
137 void Executer::SetWorkspaceName( const std::string& n )
139 mRootPackage->ChangeBlackBoxName( mRootCBB->GetTypeName(), n );
141 //=======================================================================
143 //=======================================================================
144 void Executer::BeginPackage (const std::string &name)
146 bbtkDebugMessageInc("Kernel",9,"Executer::BeginPackage(\""<<name<<"\")"
151 p = GetFactory()->GetPackage(name);
155 p = new Package(name,
159 BBTK_STRINGIFY_SYMBOL(BBTK_VERSION));
160 GetFactory()->InsertPackage(p);
162 mOpenPackage.push_back(p);
164 //=======================================================================
166 //=======================================================================
167 void Executer::EndPackage()
169 if (mOpenPackage.size()>1) mOpenPackage.pop_back();
171 //=======================================================================
173 //=======================================================================
174 void Executer::Define (const std::string &name,
175 const std::string &pack,
176 const std::string &scriptfilename)
178 bbtkDebugMessageInc("Kernel",9,"Executer::Define(\""<<name<<
182 ComplexBlackBoxDescriptor* b = new ComplexBlackBoxDescriptor(name);
183 b->SetFactory(GetFactory());
184 b->SetScriptFileName(scriptfilename);
185 mOpenDefinition.push_back( CBBDefinition( b, pack ) );
187 bbtkDebugDecTab("Kernel",9);
189 //=======================================================================
191 //=======================================================================
192 /// Sets the file name to use for the current definition
193 /// (Used to set it after the Define command)
194 void Executer::SetCurrentFileName (const std::string &name )
196 mOpenDefinition.back().box->SetScriptFileName(name);
198 //=======================================================================
200 //=======================================================================
201 void Executer::EndDefine ()
203 bbtkDebugMessageInc("Kernel",9,"Executer::EndDefine(\""
204 <<Current()->GetTypeName()<<"\")"
206 // Does current package exist ?
208 std::string pname(mOpenDefinition.back().package);
213 p = GetFactory()->GetPackage(pname);
217 p = new Package(pname,
221 BBTK_STRINGIFY_SYMBOL(BBTK_VERSION));
222 GetFactory()->InsertPackage(p);
227 p = mOpenPackage.back();
229 p->RegisterBlackBox(Current());
231 mOpenDefinition.pop_back();
233 //=======================================================================
235 //=======================================================================
236 void Executer::Kind(const std::string& kind)
240 Current()->AddToCategory("adaptor");
241 Current()->SetKind(bbtk::BlackBoxDescriptor::ADAPTOR);
243 else if (kind=="DEFAULT_ADAPTOR")
245 Current()->AddToCategory("adaptor");
246 Current()->SetKind(bbtk::BlackBoxDescriptor::DEFAULT_ADAPTOR);
248 if (kind=="WIDGET_ADAPTOR")
250 Current()->AddToCategory("adaptor");
251 Current()->SetKind(bbtk::BlackBoxDescriptor::WIDGET_ADAPTOR);
253 else if (kind=="DEFAULT_WIDGET_ADAPTOR")
255 Current()->AddToCategory("adaptor");
256 Current()->SetKind(bbtk::BlackBoxDescriptor::DEFAULT_WIDGET_ADAPTOR);
260 bbtkError("Unknown box kind : '"<<kind<<"'. "
261 <<"Valid kinds are 'ADAPTOR','DEFAULT_ADAPTOR',"
262 <<"'WIDGET_ADAPTOR','DEFAULT_WIDGET_ADAPTOR'");
265 //=======================================================================
267 //=======================================================================
268 void Executer::Create ( const std::string& nodeType,
269 const std::string& nodeName)
271 Current()->Add(nodeType,nodeName);
273 //=======================================================================
275 //=======================================================================
276 void Executer::Destroy(const std::string &boxName)
278 bbtkError("Executer::Destroy : NOT IMPLEMENTED !");
280 //=======================================================================
282 //=======================================================================
283 void Executer::Connect (const std::string &nodeFrom,
284 const std::string &outputLabel,
285 const std::string &nodeTo,
286 const std::string &inputLabel)
288 Current()->Connect(nodeFrom, outputLabel, nodeTo, inputLabel);
290 //=======================================================================
292 //=======================================================================
293 void Executer::Execute (const std::string &nodeName)
296 if (Current()==mRootCBB)
300 Current()->GetPrototype()->bbGetBlackBox(nodeName)->bbExecute(true);
305 Current()->AddToExecutionList(nodeName) ;
308 //=======================================================================
310 //=======================================================================
311 void Executer::DefineInput ( const std::string &name,
312 const std::string &box,
313 const std::string &input,
314 const std::string& help)
316 // If the input is defined in the Root box
317 if (Current()==mRootCBB)
319 // If the dialog mode is set to NoDialog
320 // and the user passed the name in the Inputs map
321 // then the associated value is set to the box.input
322 // This is the way command line parameters are passed to the Root box
323 if (mDialogMode == NoDialog)
325 // find if name is in mInputs
326 std::map<std::string,std::string>::iterator i;
327 i = mInputs.find(name);
328 if (i!=mInputs.end()) {
329 Set(box,input,(*i).second);
332 // If the dialog mode is set to TextDialog
333 // The user is prompted for the value
334 else if (mDialogMode == TextDialog)
336 std::cout << name << "=";
341 #ifdef _USE_WXWIDGETS_
342 // If the dialog mode is set to GraphicalDialog
343 // A dialog box is pop up
344 else if (mDialogMode == GraphicalDialog)
346 std::string mess("Enter the value of '");
351 std::string title(name);
353 std::string ans = wx2std ( wxGetTextFromUser( std2wx (mess), std2wx(title)));
359 Current()->DefineInput(name,box,input,help);
362 //=======================================================================
364 //=======================================================================
365 void Executer::DefineOutput ( const std::string &name,
366 const std::string &box,
367 const std::string &output,
368 const std::string& help)
370 Current()->DefineOutput(name,box,output,help);
372 //=======================================================================
374 //=======================================================================
375 void Executer::Set (const std::string &box,
376 const std::string &input,
377 const std::string &value)
379 BlackBox* b = Current()->GetPrototype()->bbGetBlackBox(box);
380 // Looks for the adaptor
382 if ( b->bbGetInputType(input) != typeid(std::string) )
385 GetFactory()->NewAdaptor(typeid(std::string),
386 b->bbGetInputType(input),
391 TypeName(b->bbGetInputType(input))
392 <<"> to <std::string> found");
394 std::string v(value);
395 a->bbSetInput("In",v);
397 b->bbSetInput(input,a->bbGetOutput("Out"));
402 std::string v(value);
403 b->bbSetInput(input,v);
406 //=======================================================================
408 //=======================================================================
409 std::string Executer::Get(const std::string &box,
410 const std::string &output)
412 BlackBox* b = Current()->GetPrototype()->bbGetBlackBox(box);
413 // Looks for the adaptor
414 if (b->bbGetOutputType(output) != typeid(std::string))
417 GetFactory()->NewAdaptor(
418 b->bbGetOutputType(output),
424 TypeName(b->bbGetOutputType(output))
425 <<"> to <std::string> found");
429 a->bbSetInput("In",b->bbGetOutput(output));
431 std::string r = a->bbGetOutput("Out").unsafe_get<std::string>();
432 //std::string v = *((std::string*)a->bbGetOutput("Out")) ;
433 // std::cout << a->bbGetOutput("Out").unsafe_get<std::string>()
435 //std::string v(value);
436 //b->bbSetInput(input,a->bbGetOutput("Out"));
443 return b->bbGetOutput(output).unsafe_get<std::string>();
444 // std::string v = *((std::string*)b->bbGetOutput(output)) ;
445 // std::cout << b->bbGetOutput("Out").unsafe_get<std::string>()
447 // b->bbSetInput(input,&v);
450 //=======================================================================
452 //=======================================================================
453 void Executer::Author(const std::string &authorName)
455 Current()->AddToAuthor(authorName,Current()==mRootCBB);
457 //=======================================================================
459 //=======================================================================
460 void Executer::Category(const std::string &category)
462 Current()->AddToCategory(category,Current()==mRootCBB);
464 //=======================================================================
466 //=======================================================================
467 void Executer::Description(const std::string &d)
469 Current()->AddToDescription(d,Current()==mRootCBB);
471 //=======================================================================
473 //=======================================================================
474 /// prints the list of the boxes of the current descriptor
475 void Executer::PrintBoxes()
477 bbtkMessageInc("Help",1,"The black box descriptor \""
478 <<Current()->GetTypeName()<<"\" contains : "<<std::endl);
479 Current()->PrintBlackBoxes();
480 bbtkDecTab("Help",1);
482 //=======================================================================
484 //=======================================================================
485 std::string Executer::ShowGraph(const std::string &nameblackbox,
486 const std::string &detailStr,
487 const std::string &levelStr,
488 const std::string &output_html,
489 const std::string &custom_header,
490 const std::string &custom_title,
491 bool system_display )
493 int detail = atoi(detailStr.c_str());
494 int level = atoi(levelStr.c_str());
496 std::string filename_rootHtml (output_html) ;
497 std::string simplefilename_rootHtml ( Utilities::get_file_name(output_html));
499 bool relative_link = true;
501 // No output provided : automatic generation
502 if (output_html.length() == 0)
504 // Don't pollute the file store with "temp_dir" directories ...
505 std::string default_doc_dir = ConfigurationFile::GetInstance().Get_default_temp_dir();
507 char c = default_doc_dir.c_str()[strlen(default_doc_dir.c_str())-1];
509 std::string directory = default_doc_dir;
510 if (c != '/' && c !='\\') directory = directory + "/";
511 directory = directory + "temp_dir";
513 filename_rootHtml = directory + "/" + "User.html";
514 simplefilename_rootHtml = "User.html" ;
516 // Creating directory
517 std::string command0("mkdir \"" +directory + "\"");
518 system( command0.c_str() );
520 relative_link = false;
526 p = GetFactory()->GetPackage(nameblackbox);
532 // Generating documentation-help of workspace
533 p->SetDocURL(filename_rootHtml);
534 p->SetDocRelativeURL(simplefilename_rootHtml);
536 p->CreateHtmlPage(filename_rootHtml,"bbi","user package",custom_header,custom_title,detail,level,relative_link);
538 std::string page = filename_rootHtml;
542 ShowGraphTypes(nameblackbox);
544 catch (bbtk::Exception a)
546 std::cout <<"EXC"<<std::endl;
547 page = ShowGraphInstances(nameblackbox,detail,level,system_display);
552 //=======================================================================
554 //=======================================================================
555 /// Generate a png file with the actual pipeline (Graphviz-dot needed)
556 std::string Executer::ShowGraphInstances(const std::string &nameblackbox, int detail, int level,
560 BlackBox* blackbox=NULL;
561 if (nameblackbox==".")
563 blackbox=Current()->GetPrototype();
567 blackbox = Current()->GetPrototype()->bbFindBlackBox(nameblackbox);
574 // Don't pollute the file store with "temp_dir" directories ...
575 std::string default_doc_dir = ConfigurationFile::GetInstance().Get_default_temp_dir();
576 char c = default_doc_dir.c_str()[strlen(default_doc_dir.c_str())-1];
578 std::string directory = default_doc_dir;
579 if (c != '/' && c !='\\') directory = directory + "/";
581 directory = directory + "temp_dir";
582 //std::string directory("temp_dir");
583 std::string filename(directory + "/" + "bbtk_graph_pipeline");
584 std::string filename_html(filename+".html");
585 std::string command0("mkdir \""+directory + "\"");
588 std::string command2("start ");
590 std::string command2("gnome-open ");
593 command2=command2+filename_html;
594 page = filename_html;
595 // 1. Generate Html Diagram
597 s.open(filename_html.c_str());
600 s << "<html><head><title>BBtk graph diagram</title><meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\"></head>\n";
601 s << "<body bgcolor=\"#FFFFFF\" text=\"#000000\"> \n\n";
602 if ( blackbox->bbGetName()=="workspacePrototype" )
604 s << "<center>Current workspace</center>";
606 s << "<center>" << blackbox->bbGetName()<< "</center>";
609 blackbox->bbInsertHTMLGraph( s, detail, level, true, directory, false );
610 s << "</body></html>\n";
614 // 2. Starting Browser
615 if (system_display) system( command2.c_str() );
619 bbtkMessageInc("Help",1,"No black box: \""
620 <<nameblackbox<<"\" " <<std::endl);
624 //=======================================================================
626 //=======================================================================
627 void Executer::ShowRelations(const std::string &nameblackbox,
628 const std::string &detailStr,
629 const std::string &levelStr)
633 int detail = atoi(detailStr.c_str());
634 int level = atoi(levelStr.c_str());
635 BlackBox* blackbox=NULL;
636 if (nameblackbox.compare(".")==0)
638 blackbox=Current()->GetPrototype();
642 blackbox = Current()->GetPrototype()->bbFindBlackBox(nameblackbox);
648 blackbox->bbShowRelations(blackbox,detail,level); //,mFactory);
653 bbtkError("Blackbox Name not found.. <" <<nameblackbox<<">");
656 //=======================================================================
658 //=======================================================================
659 /// sets the level of message
660 void Executer::SetMessageLevel(const std::string &kind,
663 bbtk::MessageManager::SetMessageLevel(kind,level);
665 //=======================================================================
667 //=======================================================================
668 /// Prints help on the messages
669 void Executer::HelpMessages()
671 bbtk::MessageManager::PrintInfo();
673 //=======================================================================
675 //=======================================================================
677 void Executer::Print(const std::string &str)
679 if (GetNoExecMode() && (Current()==mRootCBB) ) return;
680 if (Current()!=mRootCBB) return;
682 bbtkDebugMessageInc("Interpreter",9,"Interpreter::Print(\""<<str<<"\")"<<std::endl);
685 // InterpretLine ("load std")
686 // InterpretLine("new ConcatStrings _C_ ") -> trouver un nom unique : # commande
687 // InterpretLine("new Print _P_")
688 // InterpretLine("connect _C_.Out _P_.In")
692 std::vector<std::string> chains;
693 std::string delimiters("$");
695 // Skip delimiters at beginning.
696 std::string::size_type lastPos = str.find_first_not_of(delimiters, 0);
698 if (lastPos>0) is_text = false;
700 // Find first delimiter.
701 std::string::size_type pos = str.find_first_of(delimiters, lastPos);
703 while (std::string::npos != pos || std::string::npos != lastPos)
707 // Found a text token, add it to the vector.
708 chains.push_back(str.substr(lastPos, pos - lastPos));
709 // std::string token = str.substr(lastPos, pos - lastPos)
710 // InterpretLine("set _C_.In%num% %token%")
716 // is an output (between $$) : decode
717 std::string tok,box,output;
718 tok = str.substr(lastPos, pos - lastPos);
719 Utilities::SplitAroundFirstDot(tok,box,output);
720 chains.push_back( Get(box,output) );
722 // InterpretLine("connect %tok% _C_.In%num%")
725 // Skip delimiters. Note the "not_of"
726 lastPos = str.find_first_not_of(delimiters, pos);
727 // Find next delimiter
728 pos = str.find_first_of(delimiters, lastPos);
733 // InterpretLine("exec _P_")
734 // if (IS_IN_WORKSPACE) InterpretLine("delete _C_; delete _P_");
736 std::vector<std::string>::iterator i;
737 for (i= chains.begin(); i!=chains.end(); ++i)
739 // bbtkMessage("Echo",1,*i);
740 Utilities::SubsBackslashN(*i);
741 bbtkMessage("Output",1,*i);
743 bbtkMessage("Output",1,std::endl);