1 /*=========================================================================
3 Module: $RCSfile: bbtkExecuter.cxx,v $
5 Date: $Date: 2009/03/30 14:42:16 $
6 Version: $Revision: 1.28 $
7 =========================================================================*/
9 /* ---------------------------------------------------------------------
11 * Copyright (c) CREATIS-LRMN (Centre de Recherche en Imagerie Medicale)
12 * Authors : Eduardo Davila, Laurent Guigues, Jean-Pierre Roux
14 * This software is governed by the CeCILL-B license under French law and
15 * abiding by the rules of distribution of free software. You can use,
16 * modify and/ or redistribute the software under the terms of the CeCILL-B
17 * license as circulated by CEA, CNRS and INRIA at the following URL
18 * http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html
19 * or in the file LICENSE.txt.
21 * As a counterpart to the access to the source code and rights to copy,
22 * modify and redistribute granted by the license, users are provided only
23 * with a limited warranty and the software's author, the holder of the
24 * economic rights, and the successive licensors have only limited
27 * The fact that you are presently reading this means that you have had
28 * knowledge of the CeCILL-B license and that you accept its terms.
29 * ------------------------------------------------------------------------ */
33 * \brief class Executer: level 0 of script execution (code)
36 #include "bbtkExecuter.h"
37 #include "bbtkMessageManager.h"
38 #include "bbtkFactory.h"
39 #include "bbtkUtilities.h"
43 #include <wx/textdlg.h>
46 #include "bbtkWxBlackBox.h"
48 #include "bbtkConfigurationFile.h"
52 //=======================================================================
53 Executer::Pointer Executer::New()
55 bbtkDebugMessage("Kernel",9,"Executer::New()"<<std::endl);
56 return MakePointer(new Executer());
58 //=======================================================================
60 //=======================================================================
67 mDialogMode(NoDialog),
70 bbtkDebugMessageInc("Kernel",9,"Executer::Executer()" <<std::endl);
71 mFactory = Factory::New();
72 // The smart pointer on this is not made yet (is made by New)
73 // -> create it to pass it to the factory
74 // We have to "lock" the smart pointer because the factory
75 // only keeps a weak pointer on the executer
76 // -> this would auto-destroy !!
77 mFactory->SetExecuter(MakePointer(this,true));
79 bbtkDebugDecTab("Kernel",9);
81 //=======================================================================
83 //=======================================================================
86 bbtkDebugMessageInc("Kernel",9,"==> Executer::~Executer()" <<std::endl);
87 mOpenDefinition.clear();
91 bbtkDebugDecTab("Kernel",9);
93 //=======================================================================
95 //=======================================================================
97 void Executer::LoadPackage(const std::string &name )
99 GetFactory()->LoadPackage(name);
101 //=======================================================================
103 //=======================================================================
104 /// Unloads a package
105 void Executer::UnLoadPackage(const std::string &name )
107 GetFactory()->UnLoadPackage(name);
109 //=======================================================================
111 //=======================================================================
112 void Executer::Reset()
114 bbtkDebugMessageInc("Kernel",9,"Executer::Reset()" <<std::endl);
116 GetFactory()->CheckPackages();
118 mOpenDefinition.clear();
119 mOpenPackage.clear();
120 GetFactory()->Reset();
122 // Create user package
124 Package::New("user","internal","User defined black boxes","");
125 // Insert the user package in the factory
126 GetFactory()->InsertPackage(p);
127 // And in the list of open packages
128 mOpenPackage.push_back(p);
131 // Create user workspace
132 ComplexBlackBoxDescriptor::Pointer r =
133 ComplexBlackBoxDescriptor::New("workspace");
134 // mRootCBB->Reference();
135 r->SetFactory(GetFactory());
136 r->AddToAuthor("bbtk");
137 r->AddToDescription("User's workspace");
138 mOpenDefinition.push_back(CBBDefinition(r,"user"));
139 // Register it into the user package
140 p->RegisterBlackBox(r);
143 // Object::PrintObjectListInfo();
144 // GetFactory()->CheckPackages();
146 bbtkDebugDecTab("Kernel",9);
148 //=======================================================================
151 //=======================================================================
152 /// changes the workspace name
153 void Executer::SetWorkspaceName( const std::string& n )
155 GetUserPackage()->ChangeBlackBoxName( GetWorkspace()->GetTypeName(), n );
157 //=======================================================================
159 //=======================================================================
160 void Executer::BeginPackage (const std::string &name)
162 bbtkDebugMessageInc("Kernel",9,"Executer::BeginPackage(\""<<name<<"\")"
167 p = GetFactory()->GetPackage(name);
171 p = Package::New(name,"","","");
172 GetFactory()->InsertPackage(p);
174 mOpenPackage.push_back(p);
176 //=======================================================================
178 //=======================================================================
179 void Executer::EndPackage()
181 if (mOpenPackage.size()>1) mOpenPackage.pop_back();
183 //=======================================================================
185 //=======================================================================
186 void Executer::Define (const std::string &name,
187 const std::string &pack,
188 const std::string &scriptfilename)
190 bbtkDebugMessageInc("Kernel",9,"Executer::Define(\""<<name<<
194 ComplexBlackBoxDescriptor::Pointer b
195 = ComplexBlackBoxDescriptor::New(name);
196 b->SetFactory(GetFactory());
197 b->SetScriptFileName(scriptfilename);
198 mOpenDefinition.push_back( CBBDefinition( b, pack ) );
200 bbtkDebugDecTab("Kernel",9);
202 //=======================================================================
204 //=======================================================================
205 /// Sets the file name to use for the current definition
206 /// (Used to set it after the Define command)
207 void Executer::SetCurrentFileName (const std::string &name )
209 mOpenDefinition.back().box->SetScriptFileName(name);
211 //=======================================================================
213 //=======================================================================
214 void Executer::Clear()
216 bbtkDebugMessageInc("Kernel",9,"Executer::Clear()" <<std::endl);
217 GetCurrentDescriptor()->GetPrototype()->Clear();
220 //=======================================================================
222 //=======================================================================
223 void Executer::EndDefine ()
225 bbtkDebugMessageInc("Kernel",9,"Executer::EndDefine(\""
226 <<GetCurrentDescriptor()->GetTypeName()<<"\")"
228 // Does current package exist ?
230 std::string pname(mOpenDefinition.back().package);
235 p = GetFactory()->GetPackage(pname);
239 p = Package::New(pname,"","","");
240 GetFactory()->InsertPackage(p);
245 p = mOpenPackage.back().lock();
247 p->RegisterBlackBox(GetCurrentDescriptor());
249 mOpenDefinition.pop_back();
251 //=======================================================================
253 //=======================================================================
254 void Executer::Kind(const std::string& kind)
258 GetCurrentDescriptor()->AddToCategory("adaptor");
259 GetCurrentDescriptor()->SetKind(bbtk::BlackBoxDescriptor::ADAPTOR);
261 else if (kind=="DEFAULT_ADAPTOR")
263 GetCurrentDescriptor()->AddToCategory("adaptor");
264 GetCurrentDescriptor()->SetKind(bbtk::BlackBoxDescriptor::DEFAULT_ADAPTOR);
268 GetCurrentDescriptor()->AddToCategory("gui");
269 GetCurrentDescriptor()->SetKind(bbtk::BlackBoxDescriptor::GUI);
271 else if (kind=="DEFAULT_GUI")
273 GetCurrentDescriptor()->AddToCategory("gui");
274 GetCurrentDescriptor()->SetKind(bbtk::BlackBoxDescriptor::DEFAULT_GUI);
278 bbtkError("Unknown box kind : '"<<kind<<"'. "
279 <<"Valid kinds are 'ADAPTOR','DEFAULT_ADAPTOR',"
280 <<"'GUI','DEFAULT_GUI'");
283 //=======================================================================
285 //=======================================================================
286 void Executer::Create ( const std::string& nodeType,
287 const std::string& nodeName)
289 GetCurrentDescriptor()->Add(nodeType,nodeName);
291 //=======================================================================
293 //=======================================================================
294 void Executer::Destroy(const std::string &boxName)
296 GetCurrentDescriptor()->Remove(boxName,true);
298 //=======================================================================
300 //=======================================================================
301 void Executer::Connect (const std::string &nodeFrom,
302 const std::string &outputLabel,
303 const std::string &nodeTo,
304 const std::string &inputLabel)
306 GetCurrentDescriptor()->Connect(nodeFrom, outputLabel, nodeTo, inputLabel);
308 //=======================================================================
310 //=======================================================================
311 void Executer::Execute (const std::string &nodeName)
314 if (GetCurrentDescriptor()==GetWorkspace())
318 GetCurrentDescriptor()->GetPrototype()->bbGetBlackBox(nodeName)->bbExecute(true);
323 GetCurrentDescriptor()->AddToExecutionList(nodeName) ;
326 //=======================================================================
328 //=======================================================================
329 void Executer::DefineInput ( const std::string &name,
330 const std::string &box,
331 const std::string &input,
332 const std::string& help)
334 // If the input is defined in the Root box
335 if (GetCurrentDescriptor()==GetWorkspace())
337 // If the dialog mode is set to NoDialog
338 // and the user passed the name in the Inputs map
339 // then the associated value is set to the box.input
340 // This is the way command line parameters are passed to the Root box
341 if (mDialogMode == NoDialog)
343 // find if name is in mInputs
344 std::map<std::string,std::string>::iterator i;
345 i = mInputs.find(name);
346 if (i!=mInputs.end()) {
347 Set(box,input,(*i).second);
350 // If the dialog mode is set to TextDialog
351 // The user is prompted for the value
352 else if (mDialogMode == TextDialog)
354 std::cout << name << "=";
360 // If the dialog mode is set to GraphicalDialog
361 // A dialog box is pop up
362 else if (mDialogMode == GraphicalDialog)
364 std::string mess("Enter the value of '");
369 std::string title(name);
371 std::string ans = wx2std ( wxGetTextFromUser( std2wx (mess), std2wx(title)));
377 GetCurrentDescriptor()->DefineInput(name,box,input,help);
380 //=======================================================================
382 //=======================================================================
383 void Executer::DefineOutput ( const std::string &name,
384 const std::string &box,
385 const std::string &output,
386 const std::string& help)
388 GetCurrentDescriptor()->DefineOutput(name,box,output,help);
390 //=======================================================================
392 //=======================================================================
393 void Executer::Set (const std::string &box,
394 const std::string &input,
395 const std::string &value)
397 BlackBox::Pointer b = GetCurrentDescriptor()->GetPrototype()->bbGetBlackBox(box);
398 // Looks for the adaptor
400 if ( ( b->bbGetInputType(input) != typeid(bbtk::any<bbtk::thing>) )&&
401 ( b->bbGetInputType(input) != typeid(std::string) ) )
403 BlackBox::Pointer a =
404 GetFactory()->NewAdaptor(typeid(std::string),
405 b->bbGetInputType(input),
410 TypeName(b->bbGetInputType(input))
411 <<"> to <std::string> found");
413 std::string v(value);
414 a->bbSetInput("In",v);
416 b->bbSetInput(input,a->bbGetOutput("Out"));
421 std::string v(value);
422 b->bbSetInput(input,v);
425 //=======================================================================
427 //=======================================================================
428 std::string Executer::Get(const std::string &box,
429 const std::string &output)
431 BlackBox::Pointer b = GetCurrentDescriptor()->GetPrototype()->bbGetBlackBox(box);
432 // Looks for the adaptor
433 if (b->bbGetOutputType(output) != typeid(std::string))
435 BlackBox::Pointer a =
436 GetFactory()->NewAdaptor(
437 b->bbGetOutputType(output),
443 TypeName(b->bbGetOutputType(output))
444 <<"> to <std::string> found");
448 a->bbSetInput("In",b->bbGetOutput(output));
450 std::string r = a->bbGetOutput("Out").unsafe_get<std::string>();
451 //std::string v = *((std::string*)a->bbGetOutput("Out")) ;
452 // std::cout << a->bbGetOutput("Out").unsafe_get<std::string>()
454 //std::string v(value);
455 //b->bbSetInput(input,a->bbGetOutput("Out"));
462 return b->bbGetOutput(output).unsafe_get<std::string>();
463 // std::string v = *((std::string*)b->bbGetOutput(output)) ;
464 // std::cout << b->bbGetOutput("Out").unsafe_get<std::string>()
466 // b->bbSetInput(input,&v);
469 //=======================================================================
471 //=======================================================================
472 void Executer::Author(const std::string &authorName)
474 GetCurrentDescriptor()->AddToAuthor(authorName,GetCurrentDescriptor()==GetWorkspace());
476 //=======================================================================
478 //=======================================================================
479 void Executer::Category(const std::string &category)
481 GetCurrentDescriptor()->AddToCategory(category,GetCurrentDescriptor()==GetWorkspace());
483 //=======================================================================
485 //=======================================================================
486 void Executer::Description(const std::string &d)
488 GetCurrentDescriptor()->AddToDescription(d,GetCurrentDescriptor()==GetWorkspace());
490 //=======================================================================
492 //=======================================================================
493 /// prints the list of the boxes of the current descriptor
494 void Executer::PrintBoxes()
496 bbtkMessageInc("Help",1,"The black box descriptor \""
497 <<GetCurrentDescriptor()->GetTypeName()<<"\" contains : "<<std::endl);
498 GetCurrentDescriptor()->PrintBlackBoxes();
499 bbtkDecTab("Help",1);
501 //=======================================================================
503 //=======================================================================
504 std::string Executer::ShowGraph(const std::string &nameblackbox,
505 const std::string &detailStr,
506 const std::string &levelStr,
507 const std::string &output_html,
508 const std::string &custom_header,
509 const std::string &custom_title,
510 bool system_display )
512 int detail = atoi(detailStr.c_str());
513 int level = atoi(levelStr.c_str());
515 std::string filename_rootHtml (output_html) ;
516 std::string simplefilename_rootHtml ( Utilities::get_file_name(output_html));
518 bool relative_link = true;
520 // No output provided : automatic generation
521 if (output_html.length() == 0)
523 // Don't pollute the file store with "temp_dir" directories ...
524 std::string default_doc_dir = ConfigurationFile::GetInstance().Get_default_temp_dir();
526 char c = default_doc_dir.c_str()[strlen(default_doc_dir.c_str())-1];
528 std::string directory = default_doc_dir;
529 if (c != '/' && c !='\\') directory = directory + "/";
530 directory = directory + "temp_dir";
532 filename_rootHtml = directory + "/" + "User.html";
533 simplefilename_rootHtml = "User.html" ;
535 // Creating directory
536 std::string command0("mkdir \"" +directory + "\"");
537 system( command0.c_str() );
539 relative_link = false;
545 p = GetFactory()->GetPackage(nameblackbox);
549 p = GetUserPackage();
551 // Generating documentation-help of workspace
552 p->SetDocURL(filename_rootHtml);
553 p->SetDocRelativeURL(simplefilename_rootHtml);
555 p->CreateHtmlPage(filename_rootHtml,"bbtk","user package",custom_header,custom_title,detail,level,relative_link);
557 std::string page = filename_rootHtml;
561 ShowGraphTypes(nameblackbox);
563 catch (bbtk::Exception a)
565 std::cout <<"EXC"<<std::endl;
566 page = ShowGraphInstances(nameblackbox,detail,level,system_display);
571 //=======================================================================
573 //=======================================================================
574 /// Generate a png file with the actual pipeline (Graphviz-dot needed)
575 std::string Executer::ShowGraphInstances(const std::string &nameblackbox, int detail, int level,
579 BlackBox::Pointer blackbox;
580 if (nameblackbox==".")
582 blackbox = GetCurrentDescriptor()->GetPrototype();
586 blackbox = GetCurrentDescriptor()->GetPrototype()->bbFindBlackBox(nameblackbox);
593 // Don't pollute the file store with "temp_dir" directories ...
594 std::string default_doc_dir = ConfigurationFile::GetInstance().Get_default_temp_dir();
595 char c = default_doc_dir.c_str()[strlen(default_doc_dir.c_str())-1];
597 std::string directory = default_doc_dir;
598 if (c != '/' && c !='\\') directory = directory + "/";
600 directory = directory + "temp_dir";
601 //std::string directory("temp_dir");
602 std::string filename(directory + "/" + "bbtk_graph_pipeline");
603 std::string filename_html(filename+".html");
604 std::string command0("mkdir \""+directory + "\"");
607 std::string command2("start ");
609 std::string command2("gnome-open ");
612 command2=command2+filename_html;
613 page = filename_html;
614 // 1. Generate Html Diagram
616 s.open(filename_html.c_str());
619 s << "<html><head><title>BBtk graph diagram</title><meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\"></head>\n";
620 s << "<body bgcolor=\"#FFFFFF\" text=\"#000000\"> \n\n";
621 if ( blackbox->bbGetName()=="workspacePrototype" )
623 s << "<center>Current workspace</center>";
625 s << "<center>" << blackbox->bbGetName()<< "</center>";
628 blackbox->bbInsertHTMLGraph( s, detail, level, true, directory, false );
629 s << "</body></html>\n";
633 // 2. Starting Browser
634 if (system_display) system( command2.c_str() );
638 bbtkMessageInc("Help",1,"No black box: \""
639 <<nameblackbox<<"\" " <<std::endl);
643 //=======================================================================
645 //=======================================================================
646 void Executer::ShowRelations(const std::string &nameblackbox,
647 const std::string &detailStr,
648 const std::string &levelStr)
652 int detail = atoi(detailStr.c_str());
653 int level = atoi(levelStr.c_str());
654 BlackBox::Pointer blackbox;
655 if (nameblackbox.compare(".")==0)
657 blackbox=GetCurrentDescriptor()->GetPrototype();
661 blackbox = GetCurrentDescriptor()->GetPrototype()->bbFindBlackBox(nameblackbox);
667 blackbox->bbShowRelations(blackbox,detail,level); //,mFactory);
672 bbtkError("Blackbox Name not found.. <" <<nameblackbox<<">");
675 //=======================================================================
677 //=======================================================================
678 /// sets the level of message
679 void Executer::SetMessageLevel(const std::string &kind,
682 bbtk::MessageManager::SetMessageLevel(kind,level);
684 //=======================================================================
686 //=======================================================================
687 /// Prints help on the messages
688 void Executer::HelpMessages()
690 bbtk::MessageManager::PrintInfo();
692 //=======================================================================
694 //=======================================================================
696 void Executer::Print(const std::string &str)
698 if (GetNoExecMode() && (GetCurrentDescriptor()==GetWorkspace()) ) return;
699 if (GetCurrentDescriptor()!=GetWorkspace()) return;
701 bbtkDebugMessageInc("Interpreter",9,"Interpreter::Print(\""<<str<<"\")"<<std::endl);
704 // InterpretLine ("load std")
705 // InterpretLine("new ConcatStrings _C_ ") -> trouver un nom unique : # commande
706 // InterpretLine("new Print _P_")
707 // InterpretLine("connect _C_.Out _P_.In")
711 std::vector<std::string> chains;
712 std::string delimiters("$");
714 // Skip delimiters at beginning.
715 std::string::size_type lastPos = str.find_first_not_of(delimiters, 0);
717 if (lastPos>0) is_text = false;
719 // Find first delimiter.
720 std::string::size_type pos = str.find_first_of(delimiters, lastPos);
722 while (std::string::npos != pos || std::string::npos != lastPos)
726 // Found a text token, add it to the vector.
727 chains.push_back(str.substr(lastPos, pos - lastPos));
728 // std::string token = str.substr(lastPos, pos - lastPos)
729 // InterpretLine("set _C_.In%num% %token%")
735 // is an output (between $$) : decode
736 std::string tok,box,output;
737 tok = str.substr(lastPos, pos - lastPos);
738 Utilities::SplitAroundFirstDot(tok,box,output);
739 chains.push_back( Get(box,output) );
741 // InterpretLine("connect %tok% _C_.In%num%")
744 // Skip delimiters. Note the "not_of"
745 lastPos = str.find_first_not_of(delimiters, pos);
746 // Find next delimiter
747 pos = str.find_first_of(delimiters, lastPos);
752 // InterpretLine("exec _P_")
753 // if (IS_IN_WORKSPACE) InterpretLine("delete _C_; delete _P_");
755 std::vector<std::string>::iterator i;
756 for (i= chains.begin(); i!=chains.end(); ++i)
758 Utilities::SubsBackslashN(*i);
759 bbtkMessage("Output",1,*i);
761 bbtkMessage("Output",1,std::endl);
763 //==========================================================================
765 //==========================================================================
766 std::string Executer::GetObjectName() const
768 return std::string("Executer");
770 //==========================================================================
772 //==========================================================================
773 std::string Executer::GetObjectInfo() const
778 //==========================================================================
779 //==========================================================================
780 size_t Executer::GetObjectSize() const
782 size_t s = Superclass::GetObjectSize();
783 s += Executer::GetObjectInternalSize();
786 //==========================================================================
787 //==========================================================================
788 size_t Executer::GetObjectInternalSize() const
790 size_t s = sizeof(Executer);
793 //==========================================================================
794 //==========================================================================
795 size_t Executer::GetObjectRecursiveSize() const
797 size_t s = Superclass::GetObjectRecursiveSize();
798 s += Executer::GetObjectInternalSize();
799 s += mFactory->GetObjectRecursiveSize();
802 //==========================================================================