1 /*=========================================================================
3 Module: $RCSfile: bbtkExecuter.cxx,v $
5 Date: $Date: 2009/01/13 08:45:27 $
6 Version: $Revision: 1.26 $
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 //=======================================================================
69 bbtkDebugMessageInc("Kernel",9,"Executer::Executer()" <<std::endl);
70 mFactory = Factory::New();
71 // The smart pointer on this is not made yet (is made by New)
72 // -> create it to pass it to the factory
73 // We have to "lock" the smart pointer because the factory
74 // only keeps a weak pointer on the executer
75 // -> this would auto-destroy !!
76 mFactory->SetExecuter(MakePointer(this,true));
78 bbtkDebugDecTab("Kernel",9);
80 //=======================================================================
82 //=======================================================================
85 bbtkDebugMessageInc("Kernel",9,"==> Executer::~Executer()" <<std::endl);
86 mOpenDefinition.clear();
90 bbtkDebugDecTab("Kernel",9);
92 //=======================================================================
94 //=======================================================================
96 void Executer::LoadPackage(const std::string &name )
98 GetFactory()->LoadPackage(name);
100 //=======================================================================
102 //=======================================================================
103 /// Unloads a package
104 void Executer::UnLoadPackage(const std::string &name )
106 GetFactory()->UnLoadPackage(name);
108 //=======================================================================
110 //=======================================================================
111 void Executer::Reset()
113 bbtkDebugMessageInc("Kernel",9,"Executer::Reset()" <<std::endl);
115 GetFactory()->CheckPackages();
117 mOpenDefinition.clear();
118 mOpenPackage.clear();
119 GetFactory()->Reset();
121 // Create user package
123 Package::New("user","internal","User defined black boxes","");
124 // Insert the user package in the factory
125 GetFactory()->InsertPackage(p);
126 // And in the list of open packages
127 mOpenPackage.push_back(p);
130 // Create user workspace
131 ComplexBlackBoxDescriptor::Pointer r =
132 ComplexBlackBoxDescriptor::New("workspace");
133 // mRootCBB->Reference();
134 r->SetFactory(GetFactory());
135 r->AddToAuthor("bbtk");
136 r->AddToDescription("User's workspace");
137 mOpenDefinition.push_back(CBBDefinition(r,"user"));
138 // Register it into the user package
139 p->RegisterBlackBox(r);
142 // Object::PrintObjectListInfo();
143 // GetFactory()->CheckPackages();
145 bbtkDebugDecTab("Kernel",9);
147 //=======================================================================
150 //=======================================================================
151 /// changes the workspace name
152 void Executer::SetWorkspaceName( const std::string& n )
154 GetUserPackage()->ChangeBlackBoxName( GetWorkspace()->GetTypeName(), n );
156 //=======================================================================
158 //=======================================================================
159 void Executer::BeginPackage (const std::string &name)
161 bbtkDebugMessageInc("Kernel",9,"Executer::BeginPackage(\""<<name<<"\")"
166 p = GetFactory()->GetPackage(name);
170 p = Package::New(name,"","","");
171 GetFactory()->InsertPackage(p);
173 mOpenPackage.push_back(p);
175 //=======================================================================
177 //=======================================================================
178 void Executer::EndPackage()
180 if (mOpenPackage.size()>1) mOpenPackage.pop_back();
182 //=======================================================================
184 //=======================================================================
185 void Executer::Define (const std::string &name,
186 const std::string &pack,
187 const std::string &scriptfilename)
189 bbtkDebugMessageInc("Kernel",9,"Executer::Define(\""<<name<<
193 ComplexBlackBoxDescriptor::Pointer b
194 = ComplexBlackBoxDescriptor::New(name);
195 b->SetFactory(GetFactory());
196 b->SetScriptFileName(scriptfilename);
197 mOpenDefinition.push_back( CBBDefinition( b, pack ) );
199 bbtkDebugDecTab("Kernel",9);
201 //=======================================================================
203 //=======================================================================
204 /// Sets the file name to use for the current definition
205 /// (Used to set it after the Define command)
206 void Executer::SetCurrentFileName (const std::string &name )
208 mOpenDefinition.back().box->SetScriptFileName(name);
210 //=======================================================================
212 //=======================================================================
213 void Executer::Clear()
215 bbtkDebugMessageInc("Kernel",9,"Executer::Clear()" <<std::endl);
216 GetCurrentDescriptor()->GetPrototype()->Clear();
219 //=======================================================================
221 //=======================================================================
222 void Executer::EndDefine ()
224 bbtkDebugMessageInc("Kernel",9,"Executer::EndDefine(\""
225 <<GetCurrentDescriptor()->GetTypeName()<<"\")"
227 // Does current package exist ?
229 std::string pname(mOpenDefinition.back().package);
234 p = GetFactory()->GetPackage(pname);
238 p = Package::New(pname,"","","");
239 GetFactory()->InsertPackage(p);
244 p = mOpenPackage.back().lock();
246 p->RegisterBlackBox(GetCurrentDescriptor());
248 mOpenDefinition.pop_back();
250 //=======================================================================
252 //=======================================================================
253 void Executer::Kind(const std::string& kind)
257 GetCurrentDescriptor()->AddToCategory("adaptor");
258 GetCurrentDescriptor()->SetKind(bbtk::BlackBoxDescriptor::ADAPTOR);
260 else if (kind=="DEFAULT_ADAPTOR")
262 GetCurrentDescriptor()->AddToCategory("adaptor");
263 GetCurrentDescriptor()->SetKind(bbtk::BlackBoxDescriptor::DEFAULT_ADAPTOR);
267 GetCurrentDescriptor()->AddToCategory("gui");
268 GetCurrentDescriptor()->SetKind(bbtk::BlackBoxDescriptor::GUI);
270 else if (kind=="DEFAULT_GUI")
272 GetCurrentDescriptor()->AddToCategory("gui");
273 GetCurrentDescriptor()->SetKind(bbtk::BlackBoxDescriptor::DEFAULT_GUI);
277 bbtkError("Unknown box kind : '"<<kind<<"'. "
278 <<"Valid kinds are 'ADAPTOR','DEFAULT_ADAPTOR',"
279 <<"'GUI','DEFAULT_GUI'");
282 //=======================================================================
284 //=======================================================================
285 void Executer::Create ( const std::string& nodeType,
286 const std::string& nodeName)
288 GetCurrentDescriptor()->Add(nodeType,nodeName);
290 //=======================================================================
292 //=======================================================================
293 void Executer::Destroy(const std::string &boxName)
295 GetCurrentDescriptor()->Remove(boxName,true);
297 //=======================================================================
299 //=======================================================================
300 void Executer::Connect (const std::string &nodeFrom,
301 const std::string &outputLabel,
302 const std::string &nodeTo,
303 const std::string &inputLabel)
305 GetCurrentDescriptor()->Connect(nodeFrom, outputLabel, nodeTo, inputLabel);
307 //=======================================================================
309 //=======================================================================
310 void Executer::Execute (const std::string &nodeName)
313 if (GetCurrentDescriptor()==GetWorkspace())
317 GetCurrentDescriptor()->GetPrototype()->bbGetBlackBox(nodeName)->bbExecute(true);
322 GetCurrentDescriptor()->AddToExecutionList(nodeName) ;
325 //=======================================================================
327 //=======================================================================
328 void Executer::DefineInput ( const std::string &name,
329 const std::string &box,
330 const std::string &input,
331 const std::string& help)
333 // If the input is defined in the Root box
334 if (GetCurrentDescriptor()==GetWorkspace())
336 // If the dialog mode is set to NoDialog
337 // and the user passed the name in the Inputs map
338 // then the associated value is set to the box.input
339 // This is the way command line parameters are passed to the Root box
340 if (mDialogMode == NoDialog)
342 // find if name is in mInputs
343 std::map<std::string,std::string>::iterator i;
344 i = mInputs.find(name);
345 if (i!=mInputs.end()) {
346 Set(box,input,(*i).second);
349 // If the dialog mode is set to TextDialog
350 // The user is prompted for the value
351 else if (mDialogMode == TextDialog)
353 std::cout << name << "=";
359 // If the dialog mode is set to GraphicalDialog
360 // A dialog box is pop up
361 else if (mDialogMode == GraphicalDialog)
363 std::string mess("Enter the value of '");
368 std::string title(name);
370 std::string ans = wx2std ( wxGetTextFromUser( std2wx (mess), std2wx(title)));
376 GetCurrentDescriptor()->DefineInput(name,box,input,help);
379 //=======================================================================
381 //=======================================================================
382 void Executer::DefineOutput ( const std::string &name,
383 const std::string &box,
384 const std::string &output,
385 const std::string& help)
387 GetCurrentDescriptor()->DefineOutput(name,box,output,help);
389 //=======================================================================
391 //=======================================================================
392 void Executer::Set (const std::string &box,
393 const std::string &input,
394 const std::string &value)
396 BlackBox::Pointer b = GetCurrentDescriptor()->GetPrototype()->bbGetBlackBox(box);
397 // Looks for the adaptor
399 if ( b->bbGetInputType(input) != typeid(std::string) )
401 BlackBox::Pointer a =
402 GetFactory()->NewAdaptor(typeid(std::string),
403 b->bbGetInputType(input),
408 TypeName(b->bbGetInputType(input))
409 <<"> to <std::string> found");
411 std::string v(value);
412 a->bbSetInput("In",v);
414 b->bbSetInput(input,a->bbGetOutput("Out"));
419 std::string v(value);
420 b->bbSetInput(input,v);
423 //=======================================================================
425 //=======================================================================
426 std::string Executer::Get(const std::string &box,
427 const std::string &output)
429 BlackBox::Pointer b = GetCurrentDescriptor()->GetPrototype()->bbGetBlackBox(box);
430 // Looks for the adaptor
431 if (b->bbGetOutputType(output) != typeid(std::string))
433 BlackBox::Pointer a =
434 GetFactory()->NewAdaptor(
435 b->bbGetOutputType(output),
441 TypeName(b->bbGetOutputType(output))
442 <<"> to <std::string> found");
446 a->bbSetInput("In",b->bbGetOutput(output));
448 std::string r = a->bbGetOutput("Out").unsafe_get<std::string>();
449 //std::string v = *((std::string*)a->bbGetOutput("Out")) ;
450 // std::cout << a->bbGetOutput("Out").unsafe_get<std::string>()
452 //std::string v(value);
453 //b->bbSetInput(input,a->bbGetOutput("Out"));
460 return b->bbGetOutput(output).unsafe_get<std::string>();
461 // std::string v = *((std::string*)b->bbGetOutput(output)) ;
462 // std::cout << b->bbGetOutput("Out").unsafe_get<std::string>()
464 // b->bbSetInput(input,&v);
467 //=======================================================================
469 //=======================================================================
470 void Executer::Author(const std::string &authorName)
472 GetCurrentDescriptor()->AddToAuthor(authorName,GetCurrentDescriptor()==GetWorkspace());
474 //=======================================================================
476 //=======================================================================
477 void Executer::Category(const std::string &category)
479 GetCurrentDescriptor()->AddToCategory(category,GetCurrentDescriptor()==GetWorkspace());
481 //=======================================================================
483 //=======================================================================
484 void Executer::Description(const std::string &d)
486 GetCurrentDescriptor()->AddToDescription(d,GetCurrentDescriptor()==GetWorkspace());
488 //=======================================================================
490 //=======================================================================
491 /// prints the list of the boxes of the current descriptor
492 void Executer::PrintBoxes()
494 bbtkMessageInc("Help",1,"The black box descriptor \""
495 <<GetCurrentDescriptor()->GetTypeName()<<"\" contains : "<<std::endl);
496 GetCurrentDescriptor()->PrintBlackBoxes();
497 bbtkDecTab("Help",1);
499 //=======================================================================
501 //=======================================================================
502 std::string Executer::ShowGraph(const std::string &nameblackbox,
503 const std::string &detailStr,
504 const std::string &levelStr,
505 const std::string &output_html,
506 const std::string &custom_header,
507 const std::string &custom_title,
508 bool system_display )
510 int detail = atoi(detailStr.c_str());
511 int level = atoi(levelStr.c_str());
513 std::string filename_rootHtml (output_html) ;
514 std::string simplefilename_rootHtml ( Utilities::get_file_name(output_html));
516 bool relative_link = true;
518 // No output provided : automatic generation
519 if (output_html.length() == 0)
521 // Don't pollute the file store with "temp_dir" directories ...
522 std::string default_doc_dir = ConfigurationFile::GetInstance().Get_default_temp_dir();
524 char c = default_doc_dir.c_str()[strlen(default_doc_dir.c_str())-1];
526 std::string directory = default_doc_dir;
527 if (c != '/' && c !='\\') directory = directory + "/";
528 directory = directory + "temp_dir";
530 filename_rootHtml = directory + "/" + "User.html";
531 simplefilename_rootHtml = "User.html" ;
533 // Creating directory
534 std::string command0("mkdir \"" +directory + "\"");
535 system( command0.c_str() );
537 relative_link = false;
543 p = GetFactory()->GetPackage(nameblackbox);
547 p = GetUserPackage();
549 // Generating documentation-help of workspace
550 p->SetDocURL(filename_rootHtml);
551 p->SetDocRelativeURL(simplefilename_rootHtml);
553 p->CreateHtmlPage(filename_rootHtml,"bbtk","user package",custom_header,custom_title,detail,level,relative_link);
555 std::string page = filename_rootHtml;
559 ShowGraphTypes(nameblackbox);
561 catch (bbtk::Exception a)
563 std::cout <<"EXC"<<std::endl;
564 page = ShowGraphInstances(nameblackbox,detail,level,system_display);
569 //=======================================================================
571 //=======================================================================
572 /// Generate a png file with the actual pipeline (Graphviz-dot needed)
573 std::string Executer::ShowGraphInstances(const std::string &nameblackbox, int detail, int level,
577 BlackBox::Pointer blackbox;
578 if (nameblackbox==".")
580 blackbox = GetCurrentDescriptor()->GetPrototype();
584 blackbox = GetCurrentDescriptor()->GetPrototype()->bbFindBlackBox(nameblackbox);
591 // Don't pollute the file store with "temp_dir" directories ...
592 std::string default_doc_dir = ConfigurationFile::GetInstance().Get_default_temp_dir();
593 char c = default_doc_dir.c_str()[strlen(default_doc_dir.c_str())-1];
595 std::string directory = default_doc_dir;
596 if (c != '/' && c !='\\') directory = directory + "/";
598 directory = directory + "temp_dir";
599 //std::string directory("temp_dir");
600 std::string filename(directory + "/" + "bbtk_graph_pipeline");
601 std::string filename_html(filename+".html");
602 std::string command0("mkdir \""+directory + "\"");
605 std::string command2("start ");
607 std::string command2("gnome-open ");
610 command2=command2+filename_html;
611 page = filename_html;
612 // 1. Generate Html Diagram
614 s.open(filename_html.c_str());
617 s << "<html><head><title>BBtk graph diagram</title><meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\"></head>\n";
618 s << "<body bgcolor=\"#FFFFFF\" text=\"#000000\"> \n\n";
619 if ( blackbox->bbGetName()=="workspacePrototype" )
621 s << "<center>Current workspace</center>";
623 s << "<center>" << blackbox->bbGetName()<< "</center>";
626 blackbox->bbInsertHTMLGraph( s, detail, level, true, directory, false );
627 s << "</body></html>\n";
631 // 2. Starting Browser
632 if (system_display) system( command2.c_str() );
636 bbtkMessageInc("Help",1,"No black box: \""
637 <<nameblackbox<<"\" " <<std::endl);
641 //=======================================================================
643 //=======================================================================
644 void Executer::ShowRelations(const std::string &nameblackbox,
645 const std::string &detailStr,
646 const std::string &levelStr)
650 int detail = atoi(detailStr.c_str());
651 int level = atoi(levelStr.c_str());
652 BlackBox::Pointer blackbox;
653 if (nameblackbox.compare(".")==0)
655 blackbox=GetCurrentDescriptor()->GetPrototype();
659 blackbox = GetCurrentDescriptor()->GetPrototype()->bbFindBlackBox(nameblackbox);
665 blackbox->bbShowRelations(blackbox,detail,level); //,mFactory);
670 bbtkError("Blackbox Name not found.. <" <<nameblackbox<<">");
673 //=======================================================================
675 //=======================================================================
676 /// sets the level of message
677 void Executer::SetMessageLevel(const std::string &kind,
680 bbtk::MessageManager::SetMessageLevel(kind,level);
682 //=======================================================================
684 //=======================================================================
685 /// Prints help on the messages
686 void Executer::HelpMessages()
688 bbtk::MessageManager::PrintInfo();
690 //=======================================================================
692 //=======================================================================
694 void Executer::Print(const std::string &str)
696 if (GetNoExecMode() && (GetCurrentDescriptor()==GetWorkspace()) ) return;
697 if (GetCurrentDescriptor()!=GetWorkspace()) return;
699 bbtkDebugMessageInc("Interpreter",9,"Interpreter::Print(\""<<str<<"\")"<<std::endl);
702 // InterpretLine ("load std")
703 // InterpretLine("new ConcatStrings _C_ ") -> trouver un nom unique : # commande
704 // InterpretLine("new Print _P_")
705 // InterpretLine("connect _C_.Out _P_.In")
709 std::vector<std::string> chains;
710 std::string delimiters("$");
712 // Skip delimiters at beginning.
713 std::string::size_type lastPos = str.find_first_not_of(delimiters, 0);
715 if (lastPos>0) is_text = false;
717 // Find first delimiter.
718 std::string::size_type pos = str.find_first_of(delimiters, lastPos);
720 while (std::string::npos != pos || std::string::npos != lastPos)
724 // Found a text token, add it to the vector.
725 chains.push_back(str.substr(lastPos, pos - lastPos));
726 // std::string token = str.substr(lastPos, pos - lastPos)
727 // InterpretLine("set _C_.In%num% %token%")
733 // is an output (between $$) : decode
734 std::string tok,box,output;
735 tok = str.substr(lastPos, pos - lastPos);
736 Utilities::SplitAroundFirstDot(tok,box,output);
737 chains.push_back( Get(box,output) );
739 // InterpretLine("connect %tok% _C_.In%num%")
742 // Skip delimiters. Note the "not_of"
743 lastPos = str.find_first_not_of(delimiters, pos);
744 // Find next delimiter
745 pos = str.find_first_of(delimiters, lastPos);
750 // InterpretLine("exec _P_")
751 // if (IS_IN_WORKSPACE) InterpretLine("delete _C_; delete _P_");
753 std::vector<std::string>::iterator i;
754 for (i= chains.begin(); i!=chains.end(); ++i)
756 Utilities::SubsBackslashN(*i);
757 bbtkMessage("Output",1,*i);
759 bbtkMessage("Output",1,std::endl);
761 //==========================================================================
763 //==========================================================================
764 std::string Executer::GetObjectName() const
766 return std::string("Executer");
768 //==========================================================================
770 //==========================================================================
771 std::string Executer::GetObjectInfo() const
776 //==========================================================================
777 //==========================================================================
778 size_t Executer::GetObjectSize() const
780 size_t s = Superclass::GetObjectSize();
781 s += Executer::GetObjectInternalSize();
784 //==========================================================================
785 //==========================================================================
786 size_t Executer::GetObjectInternalSize() const
788 size_t s = sizeof(Executer);
791 //==========================================================================
792 //==========================================================================
793 size_t Executer::GetObjectRecursiveSize() const
795 size_t s = Superclass::GetObjectRecursiveSize();
796 s += Executer::GetObjectInternalSize();
797 s += mFactory->GetObjectRecursiveSize();
800 //==========================================================================