1 /*=========================================================================
3 Module: $RCSfile: bbtkExecuter.cxx,v $
5 Date: $Date: 2008/12/12 12:11:21 $
6 Version: $Revision: 1.25 $
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",
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 //=======================================================================
153 //=======================================================================
154 /// changes the workspace name
155 void Executer::SetWorkspaceName( const std::string& n )
157 GetUserPackage()->ChangeBlackBoxName( GetWorkspace()->GetTypeName(), n );
159 //=======================================================================
161 //=======================================================================
162 void Executer::BeginPackage (const std::string &name)
164 bbtkDebugMessageInc("Kernel",9,"Executer::BeginPackage(\""<<name<<"\")"
169 p = GetFactory()->GetPackage(name);
173 p = Package::New(name,
177 BBTK_STRINGIFY_SYMBOL(BBTK_VERSION));
178 GetFactory()->InsertPackage(p);
180 mOpenPackage.push_back(p);
182 //=======================================================================
184 //=======================================================================
185 void Executer::EndPackage()
187 if (mOpenPackage.size()>1) mOpenPackage.pop_back();
189 //=======================================================================
191 //=======================================================================
192 void Executer::Define (const std::string &name,
193 const std::string &pack,
194 const std::string &scriptfilename)
196 bbtkDebugMessageInc("Kernel",9,"Executer::Define(\""<<name<<
200 ComplexBlackBoxDescriptor::Pointer b
201 = ComplexBlackBoxDescriptor::New(name);
202 b->SetFactory(GetFactory());
203 b->SetScriptFileName(scriptfilename);
204 mOpenDefinition.push_back( CBBDefinition( b, pack ) );
206 bbtkDebugDecTab("Kernel",9);
208 //=======================================================================
210 //=======================================================================
211 /// Sets the file name to use for the current definition
212 /// (Used to set it after the Define command)
213 void Executer::SetCurrentFileName (const std::string &name )
215 mOpenDefinition.back().box->SetScriptFileName(name);
217 //=======================================================================
219 //=======================================================================
220 void Executer::Clear()
222 bbtkDebugMessageInc("Kernel",9,"Executer::Clear()" <<std::endl);
223 GetCurrentDescriptor()->GetPrototype()->Clear();
226 //=======================================================================
228 //=======================================================================
229 void Executer::EndDefine ()
231 bbtkDebugMessageInc("Kernel",9,"Executer::EndDefine(\""
232 <<GetCurrentDescriptor()->GetTypeName()<<"\")"
234 // Does current package exist ?
236 std::string pname(mOpenDefinition.back().package);
241 p = GetFactory()->GetPackage(pname);
245 p = Package::New(pname,
249 BBTK_STRINGIFY_SYMBOL(BBTK_VERSION));
250 GetFactory()->InsertPackage(p);
255 p = mOpenPackage.back().lock();
257 p->RegisterBlackBox(GetCurrentDescriptor());
259 mOpenDefinition.pop_back();
261 //=======================================================================
263 //=======================================================================
264 void Executer::Kind(const std::string& kind)
268 GetCurrentDescriptor()->AddToCategory("adaptor");
269 GetCurrentDescriptor()->SetKind(bbtk::BlackBoxDescriptor::ADAPTOR);
271 else if (kind=="DEFAULT_ADAPTOR")
273 GetCurrentDescriptor()->AddToCategory("adaptor");
274 GetCurrentDescriptor()->SetKind(bbtk::BlackBoxDescriptor::DEFAULT_ADAPTOR);
278 GetCurrentDescriptor()->AddToCategory("gui");
279 GetCurrentDescriptor()->SetKind(bbtk::BlackBoxDescriptor::GUI);
281 else if (kind=="DEFAULT_GUI")
283 GetCurrentDescriptor()->AddToCategory("gui");
284 GetCurrentDescriptor()->SetKind(bbtk::BlackBoxDescriptor::DEFAULT_GUI);
288 bbtkError("Unknown box kind : '"<<kind<<"'. "
289 <<"Valid kinds are 'ADAPTOR','DEFAULT_ADAPTOR',"
290 <<"'GUI','DEFAULT_GUI'");
293 //=======================================================================
295 //=======================================================================
296 void Executer::Create ( const std::string& nodeType,
297 const std::string& nodeName)
299 GetCurrentDescriptor()->Add(nodeType,nodeName);
301 //=======================================================================
303 //=======================================================================
304 void Executer::Destroy(const std::string &boxName)
306 GetCurrentDescriptor()->Remove(boxName,true);
308 //=======================================================================
310 //=======================================================================
311 void Executer::Connect (const std::string &nodeFrom,
312 const std::string &outputLabel,
313 const std::string &nodeTo,
314 const std::string &inputLabel)
316 GetCurrentDescriptor()->Connect(nodeFrom, outputLabel, nodeTo, inputLabel);
318 //=======================================================================
320 //=======================================================================
321 void Executer::Execute (const std::string &nodeName)
324 if (GetCurrentDescriptor()==GetWorkspace())
328 GetCurrentDescriptor()->GetPrototype()->bbGetBlackBox(nodeName)->bbExecute(true);
333 GetCurrentDescriptor()->AddToExecutionList(nodeName) ;
336 //=======================================================================
338 //=======================================================================
339 void Executer::DefineInput ( const std::string &name,
340 const std::string &box,
341 const std::string &input,
342 const std::string& help)
344 // If the input is defined in the Root box
345 if (GetCurrentDescriptor()==GetWorkspace())
347 // If the dialog mode is set to NoDialog
348 // and the user passed the name in the Inputs map
349 // then the associated value is set to the box.input
350 // This is the way command line parameters are passed to the Root box
351 if (mDialogMode == NoDialog)
353 // find if name is in mInputs
354 std::map<std::string,std::string>::iterator i;
355 i = mInputs.find(name);
356 if (i!=mInputs.end()) {
357 Set(box,input,(*i).second);
360 // If the dialog mode is set to TextDialog
361 // The user is prompted for the value
362 else if (mDialogMode == TextDialog)
364 std::cout << name << "=";
370 // If the dialog mode is set to GraphicalDialog
371 // A dialog box is pop up
372 else if (mDialogMode == GraphicalDialog)
374 std::string mess("Enter the value of '");
379 std::string title(name);
381 std::string ans = wx2std ( wxGetTextFromUser( std2wx (mess), std2wx(title)));
387 GetCurrentDescriptor()->DefineInput(name,box,input,help);
390 //=======================================================================
392 //=======================================================================
393 void Executer::DefineOutput ( const std::string &name,
394 const std::string &box,
395 const std::string &output,
396 const std::string& help)
398 GetCurrentDescriptor()->DefineOutput(name,box,output,help);
400 //=======================================================================
402 //=======================================================================
403 void Executer::Set (const std::string &box,
404 const std::string &input,
405 const std::string &value)
407 BlackBox::Pointer b = GetCurrentDescriptor()->GetPrototype()->bbGetBlackBox(box);
408 // Looks for the adaptor
410 if ( b->bbGetInputType(input) != typeid(std::string) )
412 BlackBox::Pointer a =
413 GetFactory()->NewAdaptor(typeid(std::string),
414 b->bbGetInputType(input),
419 TypeName(b->bbGetInputType(input))
420 <<"> to <std::string> found");
422 std::string v(value);
423 a->bbSetInput("In",v);
425 b->bbSetInput(input,a->bbGetOutput("Out"));
430 std::string v(value);
431 b->bbSetInput(input,v);
434 //=======================================================================
436 //=======================================================================
437 std::string Executer::Get(const std::string &box,
438 const std::string &output)
440 BlackBox::Pointer b = GetCurrentDescriptor()->GetPrototype()->bbGetBlackBox(box);
441 // Looks for the adaptor
442 if (b->bbGetOutputType(output) != typeid(std::string))
444 BlackBox::Pointer a =
445 GetFactory()->NewAdaptor(
446 b->bbGetOutputType(output),
452 TypeName(b->bbGetOutputType(output))
453 <<"> to <std::string> found");
457 a->bbSetInput("In",b->bbGetOutput(output));
459 std::string r = a->bbGetOutput("Out").unsafe_get<std::string>();
460 //std::string v = *((std::string*)a->bbGetOutput("Out")) ;
461 // std::cout << a->bbGetOutput("Out").unsafe_get<std::string>()
463 //std::string v(value);
464 //b->bbSetInput(input,a->bbGetOutput("Out"));
471 return b->bbGetOutput(output).unsafe_get<std::string>();
472 // std::string v = *((std::string*)b->bbGetOutput(output)) ;
473 // std::cout << b->bbGetOutput("Out").unsafe_get<std::string>()
475 // b->bbSetInput(input,&v);
478 //=======================================================================
480 //=======================================================================
481 void Executer::Author(const std::string &authorName)
483 GetCurrentDescriptor()->AddToAuthor(authorName,GetCurrentDescriptor()==GetWorkspace());
485 //=======================================================================
487 //=======================================================================
488 void Executer::Category(const std::string &category)
490 GetCurrentDescriptor()->AddToCategory(category,GetCurrentDescriptor()==GetWorkspace());
492 //=======================================================================
494 //=======================================================================
495 void Executer::Description(const std::string &d)
497 GetCurrentDescriptor()->AddToDescription(d,GetCurrentDescriptor()==GetWorkspace());
499 //=======================================================================
501 //=======================================================================
502 /// prints the list of the boxes of the current descriptor
503 void Executer::PrintBoxes()
505 bbtkMessageInc("Help",1,"The black box descriptor \""
506 <<GetCurrentDescriptor()->GetTypeName()<<"\" contains : "<<std::endl);
507 GetCurrentDescriptor()->PrintBlackBoxes();
508 bbtkDecTab("Help",1);
510 //=======================================================================
512 //=======================================================================
513 std::string Executer::ShowGraph(const std::string &nameblackbox,
514 const std::string &detailStr,
515 const std::string &levelStr,
516 const std::string &output_html,
517 const std::string &custom_header,
518 const std::string &custom_title,
519 bool system_display )
521 int detail = atoi(detailStr.c_str());
522 int level = atoi(levelStr.c_str());
524 std::string filename_rootHtml (output_html) ;
525 std::string simplefilename_rootHtml ( Utilities::get_file_name(output_html));
527 bool relative_link = true;
529 // No output provided : automatic generation
530 if (output_html.length() == 0)
532 // Don't pollute the file store with "temp_dir" directories ...
533 std::string default_doc_dir = ConfigurationFile::GetInstance().Get_default_temp_dir();
535 char c = default_doc_dir.c_str()[strlen(default_doc_dir.c_str())-1];
537 std::string directory = default_doc_dir;
538 if (c != '/' && c !='\\') directory = directory + "/";
539 directory = directory + "temp_dir";
541 filename_rootHtml = directory + "/" + "User.html";
542 simplefilename_rootHtml = "User.html" ;
544 // Creating directory
545 std::string command0("mkdir \"" +directory + "\"");
546 system( command0.c_str() );
548 relative_link = false;
554 p = GetFactory()->GetPackage(nameblackbox);
558 p = GetUserPackage();
560 // Generating documentation-help of workspace
561 p->SetDocURL(filename_rootHtml);
562 p->SetDocRelativeURL(simplefilename_rootHtml);
564 p->CreateHtmlPage(filename_rootHtml,"bbtk","user package",custom_header,custom_title,detail,level,relative_link);
566 std::string page = filename_rootHtml;
570 ShowGraphTypes(nameblackbox);
572 catch (bbtk::Exception a)
574 std::cout <<"EXC"<<std::endl;
575 page = ShowGraphInstances(nameblackbox,detail,level,system_display);
580 //=======================================================================
582 //=======================================================================
583 /// Generate a png file with the actual pipeline (Graphviz-dot needed)
584 std::string Executer::ShowGraphInstances(const std::string &nameblackbox, int detail, int level,
588 BlackBox::Pointer blackbox;
589 if (nameblackbox==".")
591 blackbox = GetCurrentDescriptor()->GetPrototype();
595 blackbox = GetCurrentDescriptor()->GetPrototype()->bbFindBlackBox(nameblackbox);
602 // Don't pollute the file store with "temp_dir" directories ...
603 std::string default_doc_dir = ConfigurationFile::GetInstance().Get_default_temp_dir();
604 char c = default_doc_dir.c_str()[strlen(default_doc_dir.c_str())-1];
606 std::string directory = default_doc_dir;
607 if (c != '/' && c !='\\') directory = directory + "/";
609 directory = directory + "temp_dir";
610 //std::string directory("temp_dir");
611 std::string filename(directory + "/" + "bbtk_graph_pipeline");
612 std::string filename_html(filename+".html");
613 std::string command0("mkdir \""+directory + "\"");
616 std::string command2("start ");
618 std::string command2("gnome-open ");
621 command2=command2+filename_html;
622 page = filename_html;
623 // 1. Generate Html Diagram
625 s.open(filename_html.c_str());
628 s << "<html><head><title>BBtk graph diagram</title><meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\"></head>\n";
629 s << "<body bgcolor=\"#FFFFFF\" text=\"#000000\"> \n\n";
630 if ( blackbox->bbGetName()=="workspacePrototype" )
632 s << "<center>Current workspace</center>";
634 s << "<center>" << blackbox->bbGetName()<< "</center>";
637 blackbox->bbInsertHTMLGraph( s, detail, level, true, directory, false );
638 s << "</body></html>\n";
642 // 2. Starting Browser
643 if (system_display) system( command2.c_str() );
647 bbtkMessageInc("Help",1,"No black box: \""
648 <<nameblackbox<<"\" " <<std::endl);
652 //=======================================================================
654 //=======================================================================
655 void Executer::ShowRelations(const std::string &nameblackbox,
656 const std::string &detailStr,
657 const std::string &levelStr)
661 int detail = atoi(detailStr.c_str());
662 int level = atoi(levelStr.c_str());
663 BlackBox::Pointer blackbox;
664 if (nameblackbox.compare(".")==0)
666 blackbox=GetCurrentDescriptor()->GetPrototype();
670 blackbox = GetCurrentDescriptor()->GetPrototype()->bbFindBlackBox(nameblackbox);
676 blackbox->bbShowRelations(blackbox,detail,level); //,mFactory);
681 bbtkError("Blackbox Name not found.. <" <<nameblackbox<<">");
684 //=======================================================================
686 //=======================================================================
687 /// sets the level of message
688 void Executer::SetMessageLevel(const std::string &kind,
691 bbtk::MessageManager::SetMessageLevel(kind,level);
693 //=======================================================================
695 //=======================================================================
696 /// Prints help on the messages
697 void Executer::HelpMessages()
699 bbtk::MessageManager::PrintInfo();
701 //=======================================================================
703 //=======================================================================
705 void Executer::Print(const std::string &str)
707 if (GetNoExecMode() && (GetCurrentDescriptor()==GetWorkspace()) ) return;
708 if (GetCurrentDescriptor()!=GetWorkspace()) return;
710 bbtkDebugMessageInc("Interpreter",9,"Interpreter::Print(\""<<str<<"\")"<<std::endl);
713 // InterpretLine ("load std")
714 // InterpretLine("new ConcatStrings _C_ ") -> trouver un nom unique : # commande
715 // InterpretLine("new Print _P_")
716 // InterpretLine("connect _C_.Out _P_.In")
720 std::vector<std::string> chains;
721 std::string delimiters("$");
723 // Skip delimiters at beginning.
724 std::string::size_type lastPos = str.find_first_not_of(delimiters, 0);
726 if (lastPos>0) is_text = false;
728 // Find first delimiter.
729 std::string::size_type pos = str.find_first_of(delimiters, lastPos);
731 while (std::string::npos != pos || std::string::npos != lastPos)
735 // Found a text token, add it to the vector.
736 chains.push_back(str.substr(lastPos, pos - lastPos));
737 // std::string token = str.substr(lastPos, pos - lastPos)
738 // InterpretLine("set _C_.In%num% %token%")
744 // is an output (between $$) : decode
745 std::string tok,box,output;
746 tok = str.substr(lastPos, pos - lastPos);
747 Utilities::SplitAroundFirstDot(tok,box,output);
748 chains.push_back( Get(box,output) );
750 // InterpretLine("connect %tok% _C_.In%num%")
753 // Skip delimiters. Note the "not_of"
754 lastPos = str.find_first_not_of(delimiters, pos);
755 // Find next delimiter
756 pos = str.find_first_of(delimiters, lastPos);
761 // InterpretLine("exec _P_")
762 // if (IS_IN_WORKSPACE) InterpretLine("delete _C_; delete _P_");
764 std::vector<std::string>::iterator i;
765 for (i= chains.begin(); i!=chains.end(); ++i)
767 Utilities::SubsBackslashN(*i);
768 bbtkMessage("Output",1,*i);
770 bbtkMessage("Output",1,std::endl);
772 //==========================================================================
774 //==========================================================================
775 std::string Executer::GetObjectName() const
777 return std::string("Executer");
779 //==========================================================================
781 //==========================================================================
782 std::string Executer::GetObjectInfo() const
787 //==========================================================================
788 //==========================================================================
789 size_t Executer::GetObjectSize() const
791 size_t s = Superclass::GetObjectSize();
792 s += Executer::GetObjectInternalSize();
795 //==========================================================================
796 //==========================================================================
797 size_t Executer::GetObjectInternalSize() const
799 size_t s = sizeof(Executer);
802 //==========================================================================
803 //==========================================================================
804 size_t Executer::GetObjectRecursiveSize() const
806 size_t s = Superclass::GetObjectRecursiveSize();
807 s += Executer::GetObjectInternalSize();
808 s += mFactory->GetObjectRecursiveSize();
811 //==========================================================================