1 /*=========================================================================
3 Module: $RCSfile: bbtkExecuter.cxx,v $
5 Date: $Date: 2008/10/17 08:18:13 $
6 Version: $Revision: 1.23 $
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"
42 #ifdef _USE_WXWIDGETS_
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",
124 "User defined black boxes",
126 BBTK_STRINGIFY_SYMBOL(BBTK_VERSION));
127 // Insert the user package in the factory
128 GetFactory()->InsertPackage(p);
129 // And in the list of open packages
130 mOpenPackage.push_back(p);
133 // Create user workspace
134 ComplexBlackBoxDescriptor::Pointer r =
135 ComplexBlackBoxDescriptor::New("workspace");
136 // mRootCBB->Reference();
137 r->SetFactory(GetFactory());
138 r->AddToAuthor("bbtk");
139 r->AddToDescription("User's workspace");
140 mOpenDefinition.push_back(CBBDefinition(r,"user"));
141 // Register it into the user package
142 p->RegisterBlackBox(r);
145 // Object::PrintObjectListInfo();
146 // GetFactory()->CheckPackages();
148 bbtkDebugDecTab("Kernel",9);
150 //=======================================================================
152 //=======================================================================
153 /// changes the workspace name
154 void Executer::SetWorkspaceName( const std::string& n )
156 GetUserPackage()->ChangeBlackBoxName( GetWorkspace()->GetTypeName(), n );
158 //=======================================================================
160 //=======================================================================
161 void Executer::BeginPackage (const std::string &name)
163 bbtkDebugMessageInc("Kernel",9,"Executer::BeginPackage(\""<<name<<"\")"
168 p = GetFactory()->GetPackage(name);
172 p = Package::New(name,
176 BBTK_STRINGIFY_SYMBOL(BBTK_VERSION));
177 GetFactory()->InsertPackage(p);
179 mOpenPackage.push_back(p);
181 //=======================================================================
183 //=======================================================================
184 void Executer::EndPackage()
186 if (mOpenPackage.size()>1) mOpenPackage.pop_back();
188 //=======================================================================
190 //=======================================================================
191 void Executer::Define (const std::string &name,
192 const std::string &pack,
193 const std::string &scriptfilename)
195 bbtkDebugMessageInc("Kernel",9,"Executer::Define(\""<<name<<
199 ComplexBlackBoxDescriptor::Pointer b
200 = ComplexBlackBoxDescriptor::New(name);
201 b->SetFactory(GetFactory());
202 b->SetScriptFileName(scriptfilename);
203 mOpenDefinition.push_back( CBBDefinition( b, pack ) );
205 bbtkDebugDecTab("Kernel",9);
207 //=======================================================================
209 //=======================================================================
210 /// Sets the file name to use for the current definition
211 /// (Used to set it after the Define command)
212 void Executer::SetCurrentFileName (const std::string &name )
214 mOpenDefinition.back().box->SetScriptFileName(name);
216 //=======================================================================
218 //=======================================================================
219 void Executer::EndDefine ()
221 bbtkDebugMessageInc("Kernel",9,"Executer::EndDefine(\""
222 <<GetCurrentDescriptor()->GetTypeName()<<"\")"
224 // Does current package exist ?
226 std::string pname(mOpenDefinition.back().package);
231 p = GetFactory()->GetPackage(pname);
235 p = Package::New(pname,
239 BBTK_STRINGIFY_SYMBOL(BBTK_VERSION));
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 << "=";
359 #ifdef _USE_WXWIDGETS_
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(std::string) )
402 BlackBox::Pointer a =
403 GetFactory()->NewAdaptor(typeid(std::string),
404 b->bbGetInputType(input),
409 TypeName(b->bbGetInputType(input))
410 <<"> to <std::string> found");
412 std::string v(value);
413 a->bbSetInput("In",v);
415 b->bbSetInput(input,a->bbGetOutput("Out"));
420 std::string v(value);
421 b->bbSetInput(input,v);
424 //=======================================================================
426 //=======================================================================
427 std::string Executer::Get(const std::string &box,
428 const std::string &output)
430 BlackBox::Pointer b = GetCurrentDescriptor()->GetPrototype()->bbGetBlackBox(box);
431 // Looks for the adaptor
432 if (b->bbGetOutputType(output) != typeid(std::string))
434 BlackBox::Pointer a =
435 GetFactory()->NewAdaptor(
436 b->bbGetOutputType(output),
442 TypeName(b->bbGetOutputType(output))
443 <<"> to <std::string> found");
447 a->bbSetInput("In",b->bbGetOutput(output));
449 std::string r = a->bbGetOutput("Out").unsafe_get<std::string>();
450 //std::string v = *((std::string*)a->bbGetOutput("Out")) ;
451 // std::cout << a->bbGetOutput("Out").unsafe_get<std::string>()
453 //std::string v(value);
454 //b->bbSetInput(input,a->bbGetOutput("Out"));
461 return b->bbGetOutput(output).unsafe_get<std::string>();
462 // std::string v = *((std::string*)b->bbGetOutput(output)) ;
463 // std::cout << b->bbGetOutput("Out").unsafe_get<std::string>()
465 // b->bbSetInput(input,&v);
468 //=======================================================================
470 //=======================================================================
471 void Executer::Author(const std::string &authorName)
473 GetCurrentDescriptor()->AddToAuthor(authorName,GetCurrentDescriptor()==GetWorkspace());
475 //=======================================================================
477 //=======================================================================
478 void Executer::Category(const std::string &category)
480 GetCurrentDescriptor()->AddToCategory(category,GetCurrentDescriptor()==GetWorkspace());
482 //=======================================================================
484 //=======================================================================
485 void Executer::Description(const std::string &d)
487 GetCurrentDescriptor()->AddToDescription(d,GetCurrentDescriptor()==GetWorkspace());
489 //=======================================================================
491 //=======================================================================
492 /// prints the list of the boxes of the current descriptor
493 void Executer::PrintBoxes()
495 bbtkMessageInc("Help",1,"The black box descriptor \""
496 <<GetCurrentDescriptor()->GetTypeName()<<"\" contains : "<<std::endl);
497 GetCurrentDescriptor()->PrintBlackBoxes();
498 bbtkDecTab("Help",1);
500 //=======================================================================
502 //=======================================================================
503 std::string Executer::ShowGraph(const std::string &nameblackbox,
504 const std::string &detailStr,
505 const std::string &levelStr,
506 const std::string &output_html,
507 const std::string &custom_header,
508 const std::string &custom_title,
509 bool system_display )
511 int detail = atoi(detailStr.c_str());
512 int level = atoi(levelStr.c_str());
514 std::string filename_rootHtml (output_html) ;
515 std::string simplefilename_rootHtml ( Utilities::get_file_name(output_html));
517 bool relative_link = true;
519 // No output provided : automatic generation
520 if (output_html.length() == 0)
522 // Don't pollute the file store with "temp_dir" directories ...
523 std::string default_doc_dir = ConfigurationFile::GetInstance().Get_default_temp_dir();
525 char c = default_doc_dir.c_str()[strlen(default_doc_dir.c_str())-1];
527 std::string directory = default_doc_dir;
528 if (c != '/' && c !='\\') directory = directory + "/";
529 directory = directory + "temp_dir";
531 filename_rootHtml = directory + "/" + "User.html";
532 simplefilename_rootHtml = "User.html" ;
534 // Creating directory
535 std::string command0("mkdir \"" +directory + "\"");
536 system( command0.c_str() );
538 relative_link = false;
544 p = GetFactory()->GetPackage(nameblackbox);
548 p = GetUserPackage();
550 // Generating documentation-help of workspace
551 p->SetDocURL(filename_rootHtml);
552 p->SetDocRelativeURL(simplefilename_rootHtml);
554 p->CreateHtmlPage(filename_rootHtml,"bbtk","user package",custom_header,custom_title,detail,level,relative_link);
556 std::string page = filename_rootHtml;
560 ShowGraphTypes(nameblackbox);
562 catch (bbtk::Exception a)
564 std::cout <<"EXC"<<std::endl;
565 page = ShowGraphInstances(nameblackbox,detail,level,system_display);
570 //=======================================================================
572 //=======================================================================
573 /// Generate a png file with the actual pipeline (Graphviz-dot needed)
574 std::string Executer::ShowGraphInstances(const std::string &nameblackbox, int detail, int level,
578 BlackBox::Pointer blackbox;
579 if (nameblackbox==".")
581 blackbox = GetCurrentDescriptor()->GetPrototype();
585 blackbox = GetCurrentDescriptor()->GetPrototype()->bbFindBlackBox(nameblackbox);
592 // Don't pollute the file store with "temp_dir" directories ...
593 std::string default_doc_dir = ConfigurationFile::GetInstance().Get_default_temp_dir();
594 char c = default_doc_dir.c_str()[strlen(default_doc_dir.c_str())-1];
596 std::string directory = default_doc_dir;
597 if (c != '/' && c !='\\') directory = directory + "/";
599 directory = directory + "temp_dir";
600 //std::string directory("temp_dir");
601 std::string filename(directory + "/" + "bbtk_graph_pipeline");
602 std::string filename_html(filename+".html");
603 std::string command0("mkdir \""+directory + "\"");
606 std::string command2("start ");
608 std::string command2("gnome-open ");
611 command2=command2+filename_html;
612 page = filename_html;
613 // 1. Generate Html Diagram
615 s.open(filename_html.c_str());
618 s << "<html><head><title>BBtk graph diagram</title><meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\"></head>\n";
619 s << "<body bgcolor=\"#FFFFFF\" text=\"#000000\"> \n\n";
620 if ( blackbox->bbGetName()=="workspacePrototype" )
622 s << "<center>Current workspace</center>";
624 s << "<center>" << blackbox->bbGetName()<< "</center>";
627 blackbox->bbInsertHTMLGraph( s, detail, level, true, directory, false );
628 s << "</body></html>\n";
632 // 2. Starting Browser
633 if (system_display) system( command2.c_str() );
637 bbtkMessageInc("Help",1,"No black box: \""
638 <<nameblackbox<<"\" " <<std::endl);
642 //=======================================================================
644 //=======================================================================
645 void Executer::ShowRelations(const std::string &nameblackbox,
646 const std::string &detailStr,
647 const std::string &levelStr)
651 int detail = atoi(detailStr.c_str());
652 int level = atoi(levelStr.c_str());
653 BlackBox::Pointer blackbox;
654 if (nameblackbox.compare(".")==0)
656 blackbox=GetCurrentDescriptor()->GetPrototype();
660 blackbox = GetCurrentDescriptor()->GetPrototype()->bbFindBlackBox(nameblackbox);
666 blackbox->bbShowRelations(blackbox,detail,level); //,mFactory);
671 bbtkError("Blackbox Name not found.. <" <<nameblackbox<<">");
674 //=======================================================================
676 //=======================================================================
677 /// sets the level of message
678 void Executer::SetMessageLevel(const std::string &kind,
681 bbtk::MessageManager::SetMessageLevel(kind,level);
683 //=======================================================================
685 //=======================================================================
686 /// Prints help on the messages
687 void Executer::HelpMessages()
689 bbtk::MessageManager::PrintInfo();
691 //=======================================================================
693 //=======================================================================
695 void Executer::Print(const std::string &str)
697 if (GetNoExecMode() && (GetCurrentDescriptor()==GetWorkspace()) ) return;
698 if (GetCurrentDescriptor()!=GetWorkspace()) return;
700 bbtkDebugMessageInc("Interpreter",9,"Interpreter::Print(\""<<str<<"\")"<<std::endl);
703 // InterpretLine ("load std")
704 // InterpretLine("new ConcatStrings _C_ ") -> trouver un nom unique : # commande
705 // InterpretLine("new Print _P_")
706 // InterpretLine("connect _C_.Out _P_.In")
710 std::vector<std::string> chains;
711 std::string delimiters("$");
713 // Skip delimiters at beginning.
714 std::string::size_type lastPos = str.find_first_not_of(delimiters, 0);
716 if (lastPos>0) is_text = false;
718 // Find first delimiter.
719 std::string::size_type pos = str.find_first_of(delimiters, lastPos);
721 while (std::string::npos != pos || std::string::npos != lastPos)
725 // Found a text token, add it to the vector.
726 chains.push_back(str.substr(lastPos, pos - lastPos));
727 // std::string token = str.substr(lastPos, pos - lastPos)
728 // InterpretLine("set _C_.In%num% %token%")
734 // is an output (between $$) : decode
735 std::string tok,box,output;
736 tok = str.substr(lastPos, pos - lastPos);
737 Utilities::SplitAroundFirstDot(tok,box,output);
738 chains.push_back( Get(box,output) );
740 // InterpretLine("connect %tok% _C_.In%num%")
743 // Skip delimiters. Note the "not_of"
744 lastPos = str.find_first_not_of(delimiters, pos);
745 // Find next delimiter
746 pos = str.find_first_of(delimiters, lastPos);
751 // InterpretLine("exec _P_")
752 // if (IS_IN_WORKSPACE) InterpretLine("delete _C_; delete _P_");
754 std::vector<std::string>::iterator i;
755 for (i= chains.begin(); i!=chains.end(); ++i)
757 Utilities::SubsBackslashN(*i);
758 bbtkMessage("Output",1,*i);
760 bbtkMessage("Output",1,std::endl);
762 //==========================================================================
764 //==========================================================================
765 std::string Executer::GetObjectName() const
767 return std::string("Executer");
769 //==========================================================================
771 //==========================================================================
772 std::string Executer::GetObjectInfo() const
777 //==========================================================================
778 //==========================================================================
779 size_t Executer::GetObjectSize() const
781 size_t s = Superclass::GetObjectSize();
782 s += Executer::GetObjectInternalSize();
785 //==========================================================================
786 //==========================================================================
787 size_t Executer::GetObjectInternalSize() const
789 size_t s = sizeof(Executer);
792 //==========================================================================
793 //==========================================================================
794 size_t Executer::GetObjectRecursiveSize() const
796 size_t s = Superclass::GetObjectRecursiveSize();
797 s += Executer::GetObjectInternalSize();
798 s += mFactory->GetObjectRecursiveSize();
801 //==========================================================================