1 /*=========================================================================
3 Module: $RCSfile: bbtkExecuter.cxx,v $
5 Date: $Date: 2009/03/30 15:22:51 $
6 Version: $Revision: 1.29 $
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());
514 bool relative_link = true;
519 p = GetFactory()->GetPackage(nameblackbox);
523 p = GetUserPackage();
526 std::string doc_path = bbtk::ConfigurationFile::GetInstance().Get_doc_path();
527 doc_path += bbtk::ConfigurationFile::GetInstance().Get_file_separator();
529 doc_path += bbtk::ConfigurationFile::GetInstance().Get_file_separator();
531 std::string pack_name(p->GetName());
532 std::string pack_path = doc_path + pack_name;
533 // Creating directory
534 if ( ! bbtk::Utilities::FileExists(pack_path) )
536 std::string command("mkdir \"" +pack_path+ "\"");
537 system( command.c_str() );
539 std::string pack_index(pack_path);
540 pack_index += bbtk::ConfigurationFile::GetInstance().Get_file_separator();
541 pack_index += "index.html";
544 // Generating documentation-help of workspace
545 p->SetDocURL(pack_index);
546 p->SetDocRelativeURL("index.html");
547 p->CreateHtmlPage(pack_index,"bbtk","user package",custom_header,custom_title,detail,level,relative_link);
552 ShowGraphTypes(nameblackbox);
554 catch (bbtk::Exception a)
556 std::cout <<"EXC"<<std::endl;
557 page = ShowGraphInstances(nameblackbox,detail,level,system_display);
562 //=======================================================================
564 //=======================================================================
565 /// Generate a png file with the actual pipeline (Graphviz-dot needed)
566 std::string Executer::ShowGraphInstances(const std::string &nameblackbox, int detail, int level,
570 BlackBox::Pointer blackbox;
571 if (nameblackbox==".")
573 blackbox = GetCurrentDescriptor()->GetPrototype();
577 blackbox = GetCurrentDescriptor()->GetPrototype()->bbFindBlackBox(nameblackbox);
584 // Don't pollute the file store with "temp_dir" directories ...
585 std::string default_doc_dir = ConfigurationFile::GetInstance().Get_default_temp_dir();
586 char c = default_doc_dir.c_str()[strlen(default_doc_dir.c_str())-1];
588 std::string directory = default_doc_dir;
589 if (c != '/' && c !='\\') directory = directory + "/";
591 directory = directory + "temp_dir";
592 //std::string directory("temp_dir");
593 std::string filename(directory + "/" + "bbtk_graph_pipeline");
594 std::string filename_html(filename+".html");
595 std::string command0("mkdir \""+directory + "\"");
598 std::string command2("start ");
600 std::string command2("gnome-open ");
603 command2=command2+filename_html;
604 page = filename_html;
605 // 1. Generate Html Diagram
607 s.open(filename_html.c_str());
610 s << "<html><head><title>BBtk graph diagram</title><meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\"></head>\n";
611 s << "<body bgcolor=\"#FFFFFF\" text=\"#000000\"> \n\n";
612 if ( blackbox->bbGetName()=="workspacePrototype" )
614 s << "<center>Current workspace</center>";
616 s << "<center>" << blackbox->bbGetName()<< "</center>";
618 blackbox->bbInsertHTMLGraph( s, detail, level, true, directory, false );
619 s << "</body></html>\n";
623 // 2. Starting Browser
624 if (system_display) system( command2.c_str() );
628 bbtkMessageInc("Help",1,"No black box: \""
629 <<nameblackbox<<"\" " <<std::endl);
633 //=======================================================================
635 //=======================================================================
636 void Executer::ShowRelations(const std::string &nameblackbox,
637 const std::string &detailStr,
638 const std::string &levelStr)
642 int detail = atoi(detailStr.c_str());
643 int level = atoi(levelStr.c_str());
644 BlackBox::Pointer blackbox;
645 if (nameblackbox.compare(".")==0)
647 blackbox=GetCurrentDescriptor()->GetPrototype();
651 blackbox = GetCurrentDescriptor()->GetPrototype()->bbFindBlackBox(nameblackbox);
657 blackbox->bbShowRelations(blackbox,detail,level); //,mFactory);
662 bbtkError("Blackbox Name not found.. <" <<nameblackbox<<">");
665 //=======================================================================
667 //=======================================================================
668 /// sets the level of message
669 void Executer::SetMessageLevel(const std::string &kind,
672 bbtk::MessageManager::SetMessageLevel(kind,level);
674 //=======================================================================
676 //=======================================================================
677 /// Prints help on the messages
678 void Executer::HelpMessages()
680 bbtk::MessageManager::PrintInfo();
682 //=======================================================================
684 //=======================================================================
686 void Executer::Print(const std::string &str)
688 if (GetNoExecMode() && (GetCurrentDescriptor()==GetWorkspace()) ) return;
689 if (GetCurrentDescriptor()!=GetWorkspace()) return;
691 bbtkDebugMessageInc("Interpreter",9,"Interpreter::Print(\""<<str<<"\")"<<std::endl);
694 // InterpretLine ("load std")
695 // InterpretLine("new ConcatStrings _C_ ") -> trouver un nom unique : # commande
696 // InterpretLine("new Print _P_")
697 // InterpretLine("connect _C_.Out _P_.In")
701 std::vector<std::string> chains;
702 std::string delimiters("$");
704 // Skip delimiters at beginning.
705 std::string::size_type lastPos = str.find_first_not_of(delimiters, 0);
707 if (lastPos>0) is_text = false;
709 // Find first delimiter.
710 std::string::size_type pos = str.find_first_of(delimiters, lastPos);
712 while (std::string::npos != pos || std::string::npos != lastPos)
716 // Found a text token, add it to the vector.
717 chains.push_back(str.substr(lastPos, pos - lastPos));
718 // std::string token = str.substr(lastPos, pos - lastPos)
719 // InterpretLine("set _C_.In%num% %token%")
725 // is an output (between $$) : decode
726 std::string tok,box,output;
727 tok = str.substr(lastPos, pos - lastPos);
728 Utilities::SplitAroundFirstDot(tok,box,output);
729 chains.push_back( Get(box,output) );
731 // InterpretLine("connect %tok% _C_.In%num%")
734 // Skip delimiters. Note the "not_of"
735 lastPos = str.find_first_not_of(delimiters, pos);
736 // Find next delimiter
737 pos = str.find_first_of(delimiters, lastPos);
742 // InterpretLine("exec _P_")
743 // if (IS_IN_WORKSPACE) InterpretLine("delete _C_; delete _P_");
745 std::vector<std::string>::iterator i;
746 for (i= chains.begin(); i!=chains.end(); ++i)
748 Utilities::SubsBackslashN(*i);
749 bbtkMessage("Output",1,*i);
751 bbtkMessage("Output",1,std::endl);
753 //==========================================================================
755 //==========================================================================
756 std::string Executer::GetObjectName() const
758 return std::string("Executer");
760 //==========================================================================
762 //==========================================================================
763 std::string Executer::GetObjectInfo() const
768 //==========================================================================
769 //==========================================================================
770 size_t Executer::GetObjectSize() const
772 size_t s = Superclass::GetObjectSize();
773 s += Executer::GetObjectInternalSize();
776 //==========================================================================
777 //==========================================================================
778 size_t Executer::GetObjectInternalSize() const
780 size_t s = sizeof(Executer);
783 //==========================================================================
784 //==========================================================================
785 size_t Executer::GetObjectRecursiveSize() const
787 size_t s = Superclass::GetObjectRecursiveSize();
788 s += Executer::GetObjectInternalSize();
789 s += mFactory->GetObjectRecursiveSize();
792 //==========================================================================