1 /*=========================================================================
4 Module: $RCSfile: bbtkExecuter.cxx,v $ $
6 Date: $Date: 2008/03/26 08:27:19 $
7 Version: $Revision: 1.15 $
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::Create ( const std::string& nodeType,
237 const std::string& nodeName)
239 Current()->Add(nodeType,nodeName);
241 //=======================================================================
243 //=======================================================================
244 void Executer::Destroy(const std::string &boxName)
246 bbtkError("Executer::Destroy : NOT IMPLEMENTED !");
248 //=======================================================================
250 //=======================================================================
251 void Executer::Connect (const std::string &nodeFrom,
252 const std::string &outputLabel,
253 const std::string &nodeTo,
254 const std::string &inputLabel)
256 Current()->Connect(nodeFrom, outputLabel, nodeTo, inputLabel);
258 //=======================================================================
260 //=======================================================================
261 void Executer::Execute (const std::string &nodeName)
264 if (Current()==mRootCBB)
268 Current()->GetPrototype()->bbGetBlackBox(nodeName)->bbExecute(true);
273 Current()->AddToExecutionList(nodeName) ;
276 //=======================================================================
278 //=======================================================================
279 void Executer::DefineInput ( const std::string &name,
280 const std::string &box,
281 const std::string &input,
282 const std::string& help)
284 // If the input is defined in the Root box
285 if (Current()==mRootCBB)
287 // If the dialog mode is set to NoDialog
288 // and the user passed the name in the Inputs map
289 // then the associated value is set to the box.input
290 // This is the way command line parameters are passed to the Root box
291 if (mDialogMode == NoDialog)
293 // find if name is in mInputs
294 std::map<std::string,std::string>::iterator i;
295 i = mInputs.find(name);
296 if (i!=mInputs.end()) {
297 Set(box,input,(*i).second);
300 // If the dialog mode is set to TextDialog
301 // The user is prompted for the value
302 else if (mDialogMode == TextDialog)
304 std::cout << name << "=";
309 #ifdef _USE_WXWIDGETS_
310 // If the dialog mode is set to GraphicalDialog
311 // A dialog box is pop up
312 else if (mDialogMode == GraphicalDialog)
314 std::string mess("Enter the value of '");
319 std::string title(name);
321 std::string ans = wx2std ( wxGetTextFromUser( std2wx (mess), std2wx(title)));
327 Current()->DefineInput(name,box,input,help);
330 //=======================================================================
332 //=======================================================================
333 void Executer::DefineOutput ( const std::string &name,
334 const std::string &box,
335 const std::string &output,
336 const std::string& help)
338 Current()->DefineOutput(name,box,output,help);
340 //=======================================================================
342 //=======================================================================
343 void Executer::Set (const std::string &box,
344 const std::string &input,
345 const std::string &value)
347 BlackBox* b = Current()->GetPrototype()->bbGetBlackBox(box);
348 // Looks for the adaptor
350 if ( b->bbGetInputType(input) != typeid(std::string) )
353 GetFactory()->NewAdaptor(typeid(std::string),
354 b->bbGetInputType(input),
359 TypeName(b->bbGetInputType(input))
360 <<"> to <std::string> found");
362 std::string v(value);
363 a->bbSetInput("In",v);
365 b->bbSetInput(input,a->bbGetOutput("Out"));
370 std::string v(value);
371 b->bbSetInput(input,v);
374 //=======================================================================
376 //=======================================================================
377 std::string Executer::Get(const std::string &box,
378 const std::string &output)
380 BlackBox* b = Current()->GetPrototype()->bbGetBlackBox(box);
381 // Looks for the adaptor
382 if (b->bbGetOutputType(output) != typeid(std::string))
385 GetFactory()->NewAdaptor(
386 b->bbGetOutputType(output),
392 TypeName(b->bbGetOutputType(output))
393 <<"> to <std::string> found");
397 a->bbSetInput("In",b->bbGetOutput(output));
399 std::string r = a->bbGetOutput("Out").unsafe_get<std::string>();
400 //std::string v = *((std::string*)a->bbGetOutput("Out")) ;
401 // std::cout << a->bbGetOutput("Out").unsafe_get<std::string>()
403 //std::string v(value);
404 //b->bbSetInput(input,a->bbGetOutput("Out"));
411 return b->bbGetOutput(output).unsafe_get<std::string>();
412 // std::string v = *((std::string*)b->bbGetOutput(output)) ;
413 // std::cout << b->bbGetOutput("Out").unsafe_get<std::string>()
415 // b->bbSetInput(input,&v);
418 //=======================================================================
420 //=======================================================================
421 void Executer::Author(const std::string &authorName)
423 Current()->AddToAuthor(authorName,Current()==mRootCBB);
425 //=======================================================================
427 //=======================================================================
428 void Executer::Category(const std::string &category)
430 Current()->AddToCategory(category,Current()==mRootCBB);
432 //=======================================================================
434 //=======================================================================
435 void Executer::Description(const std::string &d)
437 Current()->AddToDescription(d,Current()==mRootCBB);
439 //=======================================================================
441 //=======================================================================
442 /// prints the list of the boxes of the current descriptor
443 void Executer::PrintBoxes()
445 bbtkMessageInc("Help",1,"The black box descriptor \""
446 <<Current()->GetTypeName()<<"\" contains : "<<std::endl);
447 Current()->PrintBlackBoxes();
448 bbtkDecTab("Help",1);
450 //=======================================================================
452 //=======================================================================
453 std::string Executer::ShowGraph(const std::string &nameblackbox,
454 const std::string &detailStr,
455 const std::string &levelStr,
456 const std::string &output_html,
457 const std::string &custom_header,
458 const std::string &custom_title,
459 bool system_display )
461 int detail = atoi(detailStr.c_str());
462 int level = atoi(levelStr.c_str());
464 std::string filename_rootHtml (output_html) ;
465 std::string simplefilename_rootHtml ( Utilities::get_file_name(output_html));
467 bool relative_link = true;
469 // No output provided : automatic generation
470 if (output_html.length() == 0)
472 // Don't pollute the file store with "temp_dir" directories ...
473 std::string default_doc_dir = ConfigurationFile::GetInstance().Get_default_temp_dir();
475 char c = default_doc_dir.c_str()[strlen(default_doc_dir.c_str())-1];
477 std::string directory = default_doc_dir;
478 if (c != '/' && c !='\\') directory = directory + "/";
479 directory = directory + "temp_dir";
481 filename_rootHtml = directory + "/" + "User.html";
482 simplefilename_rootHtml = "User.html" ;
484 // Creating directory
485 std::string command0("mkdir \"" +directory + "\"");
486 system( command0.c_str() );
488 relative_link = false;
494 p = GetFactory()->GetPackage(nameblackbox);
500 // Generating documentation-help of workspace
501 p->SetDocURL(filename_rootHtml);
502 p->SetDocRelativeURL(simplefilename_rootHtml);
504 p->CreateHtmlPage(filename_rootHtml,"bbi","user package",custom_header,custom_title,detail,level,relative_link);
506 std::string page = filename_rootHtml;
510 ShowGraphTypes(nameblackbox);
512 catch (bbtk::Exception a)
514 std::cout <<"EXC"<<std::endl;
515 page = ShowGraphInstances(nameblackbox,detail,level,system_display);
520 //=======================================================================
522 //=======================================================================
523 /// Generate a png file with the actual pipeline (Graphviz-dot needed)
524 std::string Executer::ShowGraphInstances(const std::string &nameblackbox, int detail, int level,
528 BlackBox* blackbox=NULL;
529 if (nameblackbox==".")
531 blackbox=Current()->GetPrototype();
535 blackbox = Current()->GetPrototype()->bbFindBlackBox(nameblackbox);
542 // Don't pollute the file store with "temp_dir" directories ...
543 std::string default_doc_dir = ConfigurationFile::GetInstance().Get_default_temp_dir();
544 char c = default_doc_dir.c_str()[strlen(default_doc_dir.c_str())-1];
546 std::string directory = default_doc_dir;
547 if (c != '/' && c !='\\') directory = directory + "/";
549 directory = directory + "temp_dir";
550 //std::string directory("temp_dir");
551 std::string filename(directory + "/" + "bbtk_graph_pipeline");
552 std::string filename_html(filename+".html");
553 std::string command0("mkdir \""+directory + "\"");
556 std::string command2("start ");
558 std::string command2("gnome-open ");
561 command2=command2+filename_html;
562 page = filename_html;
563 // 1. Generate Html Diagram
565 s.open(filename_html.c_str());
568 s << "<html><head><title>BBtk graph diagram</title><meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\"></head>\n";
569 s << "<body bgcolor=\"#FFFFFF\" text=\"#000000\"> \n\n";
570 if ( blackbox->bbGetName()=="workspacePrototype" )
572 s << "<center>Current workspace</center>";
574 s << "<center>" << blackbox->bbGetName()<< "</center>";
577 blackbox->bbInsertHTMLGraph( s, detail, level, true, directory, false );
578 s << "</body></html>\n";
582 // 2. Starting Browser
583 if (system_display) system( command2.c_str() );
587 bbtkMessageInc("Help",1,"No black box: \""
588 <<nameblackbox<<"\" " <<std::endl);
592 //=======================================================================
594 //=======================================================================
595 void Executer::ShowRelations(const std::string &nameblackbox,
596 const std::string &detailStr,
597 const std::string &levelStr)
601 int detail = atoi(detailStr.c_str());
602 int level = atoi(levelStr.c_str());
603 BlackBox* blackbox=NULL;
604 if (nameblackbox.compare(".")==0)
606 blackbox=Current()->GetPrototype();
610 blackbox = Current()->GetPrototype()->bbFindBlackBox(nameblackbox);
616 blackbox->bbShowRelations(blackbox,detail,level); //,mFactory);
621 bbtkError("Blackbox Name not found.. <" <<nameblackbox<<">");
624 //=======================================================================
626 //=======================================================================
627 /// sets the level of message
628 void Executer::SetMessageLevel(const std::string &kind,
631 bbtk::MessageManager::SetMessageLevel(kind,level);
633 //=======================================================================
635 //=======================================================================
636 /// Prints help on the messages
637 void Executer::HelpMessages()
639 bbtk::MessageManager::PrintInfo();
641 //=======================================================================
643 //=======================================================================
645 void Executer::Print(const std::string &str)
647 if (GetNoExecMode() && (Current()==mRootCBB) ) return;
648 if (Current()!=mRootCBB) return;
650 bbtkDebugMessageInc("Interpreter",9,"Interpreter::Print(\""<<str<<"\")"<<std::endl);
653 // InterpretLine ("load std")
654 // InterpretLine("new ConcatStrings _C_ ") -> trouver un nom unique : # commande
655 // InterpretLine("new Print _P_")
656 // InterpretLine("connect _C_.Out _P_.In")
660 std::vector<std::string> chains;
661 std::string delimiters("$");
663 // Skip delimiters at beginning.
664 std::string::size_type lastPos = str.find_first_not_of(delimiters, 0);
666 if (lastPos>0) is_text = false;
668 // Find first delimiter.
669 std::string::size_type pos = str.find_first_of(delimiters, lastPos);
671 while (std::string::npos != pos || std::string::npos != lastPos)
675 // Found a text token, add it to the vector.
676 chains.push_back(str.substr(lastPos, pos - lastPos));
677 // std::string token = str.substr(lastPos, pos - lastPos)
678 // InterpretLine("set _C_.In%num% %token%")
684 // is an output (between $$) : decode
685 std::string tok,box,output;
686 tok = str.substr(lastPos, pos - lastPos);
687 Utilities::SplitAroundFirstDot(tok,box,output);
688 chains.push_back( Get(box,output) );
690 // InterpretLine("connect %tok% _C_.In%num%")
693 // Skip delimiters. Note the "not_of"
694 lastPos = str.find_first_not_of(delimiters, pos);
695 // Find next delimiter
696 pos = str.find_first_of(delimiters, lastPos);
701 // InterpretLine("exec _P_")
702 // if (IS_IN_WORKSPACE) InterpretLine("delete _C_; delete _P_");
704 std::vector<std::string>::iterator i;
705 for (i= chains.begin(); i!=chains.end(); ++i)
707 // bbtkMessage("Echo",1,*i);
708 Utilities::SubsBackslashN(*i);
709 bbtkMessage("Output",1,*i);
711 bbtkMessage("Output",1,std::endl);