1 /*=========================================================================
3 Module: $RCSfile: bbtkExecuter.cxx,v $
5 Date: $Date: 2009/06/08 14:50:03 $
6 Version: $Revision: 1.31 $
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"
44 #include <wx/textdlg.h>
47 #include "bbtkWxBlackBox.h"
49 #include "bbtkConfigurationFile.h"
53 //=======================================================================
54 Executer::Pointer Executer::New()
56 bbtkDebugMessage("object",9,"Executer::New()"<<std::endl);
57 return MakePointer(new Executer());
59 //=======================================================================
61 //=======================================================================
68 mDialogMode(NoDialog),
71 bbtkDebugMessage("object",2,"==> Executer()" <<std::endl);
72 mFactory = Factory::New();
73 // The smart pointer on this is not made yet (is made by New)
74 // -> create it to pass it to the factory
75 // We have to "lock" the smart pointer because the factory
76 // only keeps a weak pointer on the executer
77 // -> this would auto-destroy !!
78 mFactory->SetExecuter(MakePointer(this,true));
80 bbtkDebugMessage("object",2,"<== Executer()" <<std::endl);
82 //=======================================================================
84 //=======================================================================
87 bbtkDebugMessage("object",2,"==> ~Executer()" <<std::endl);
88 mOpenDefinition.clear();
92 bbtkDebugMessage("object",2,"<== ~Executer()" <<std::endl);
94 //=======================================================================
96 //=======================================================================
98 void Executer::LoadPackage(const std::string &name )
100 GetFactory()->LoadPackage(name);
102 //=======================================================================
104 //=======================================================================
105 /// Unloads a package
106 void Executer::UnLoadPackage(const std::string &name )
108 GetFactory()->UnLoadPackage(name);
110 //=======================================================================
112 //=======================================================================
113 void Executer::Reset()
115 bbtkDebugMessage("kernel",9,"==> Executer::Reset()" <<std::endl);
117 // GetFactory()->Check();
119 mOpenDefinition.clear();
120 mOpenPackage.clear();
122 // Wx::DestroyTopWindow();
124 GetFactory()->Reset();
125 Wx::ProcessPendingEvents();
127 // Create user package
129 Package::New("user","internal","User defined black boxes","");
130 // Insert the user package in the factory
131 GetFactory()->InsertPackage(p);
132 // And in the list of open packages
133 mOpenPackage.push_back(p);
136 // Create user workspace
137 ComplexBlackBoxDescriptor::Pointer r =
138 ComplexBlackBoxDescriptor::New("workspace");
139 // mRootCBB->Reference();
140 r->SetFactory(GetFactory());
141 r->AddToAuthor("bbtk");
142 r->AddToDescription("User's workspace");
143 mOpenDefinition.push_back(CBBDefinition(r,"user"));
144 // Register it into the user package
148 // Object::PrintObjectListInfo();
149 // GetFactory()->CheckPackages();
150 bbtkDebugMessage("kernel",9,"<== Executer::Reset()" <<std::endl);
152 //=======================================================================
155 //=======================================================================
156 /// changes the workspace name
157 void Executer::SetWorkspaceName( const std::string& n )
159 GetUserPackage()->ChangeDescriptorName( GetWorkspace()->GetTypeName(), n );
161 //=======================================================================
163 //=======================================================================
164 void Executer::BeginPackage (const std::string &name)
166 bbtkDebugMessage("kernel",9,"==> Executer::BeginPackage(\""<<name<<"\")"
171 p = GetFactory()->GetPackage(name);
175 p = Package::New(name,"","","");
176 GetFactory()->InsertPackage(p);
178 mOpenPackage.push_back(p);
180 bbtkDebugMessage("kernel",9,"<== Executer::BeginPackage(\""<<name<<"\")"
183 //=======================================================================
185 //=======================================================================
186 void Executer::EndPackage()
188 if (mOpenPackage.size()>1) mOpenPackage.pop_back();
190 //=======================================================================
192 //=======================================================================
193 void Executer::Define (const std::string &name,
194 const std::string &pack,
195 const std::string &scriptfilename)
197 bbtkDebugMessage("kernel",9,"==> Executer::Define(\""<<name<<
201 ComplexBlackBoxDescriptor::Pointer b
202 = ComplexBlackBoxDescriptor::New(name);
203 b->SetFactory(GetFactory());
204 b->SetScriptFileName(scriptfilename);
205 mOpenDefinition.push_back( CBBDefinition( b, pack ) );
207 bbtkDebugMessage("kernel",9,"<== Executer::Define(\""<<name<<
211 //=======================================================================
213 //=======================================================================
214 /// Sets the file name to use for the current definition
215 /// (Used to set it after the Define command)
216 void Executer::SetCurrentFileName (const std::string &name )
218 mOpenDefinition.back().box->SetScriptFileName(name);
220 //=======================================================================
222 //=======================================================================
223 void Executer::Clear()
225 bbtkDebugMessage("kernel",9,"==> Executer::Clear()" <<std::endl);
226 GetCurrentDescriptor()->GetPrototype()->Clear();
227 bbtkDebugMessage("kernel",9,"<== Executer::Clear()" <<std::endl);
229 //=======================================================================
231 //=======================================================================
232 void Executer::EndDefine ()
234 bbtkDebugMessage("kernel",9,"==> Executer::EndDefine(\""
235 <<GetCurrentDescriptor()->GetTypeName()<<"\")"
237 // Does current package exist ?
239 std::string pname(mOpenDefinition.back().package);
244 p = GetFactory()->GetPackage(pname);
248 p = Package::New(pname,"","","");
249 GetFactory()->InsertPackage(p);
254 p = mOpenPackage.back().lock();
256 // Register the descriptor in the current package
257 p->Register(GetCurrentDescriptor());
259 bbtkDebugMessage("kernel",9,"<== Executer::EndDefine(\""
260 <<GetCurrentDescriptor()->GetTypeName()<<"\")"
262 mOpenDefinition.pop_back();
264 //=======================================================================
266 //=======================================================================
267 void Executer::Kind(const std::string& kind)
271 GetCurrentDescriptor()->AddToCategory("adaptor");
272 GetCurrentDescriptor()->SetKind(bbtk::BlackBoxDescriptor::ADAPTOR);
274 else if (kind=="DEFAULT_ADAPTOR")
276 GetCurrentDescriptor()->AddToCategory("adaptor");
277 GetCurrentDescriptor()->SetKind(bbtk::BlackBoxDescriptor::DEFAULT_ADAPTOR);
281 GetCurrentDescriptor()->AddToCategory("gui");
282 GetCurrentDescriptor()->SetKind(bbtk::BlackBoxDescriptor::GUI);
284 else if (kind=="DEFAULT_GUI")
286 GetCurrentDescriptor()->AddToCategory("gui");
287 GetCurrentDescriptor()->SetKind(bbtk::BlackBoxDescriptor::DEFAULT_GUI);
291 bbtkError("Unknown box kind : '"<<kind<<"'. "
292 <<"Valid kinds are 'ADAPTOR','DEFAULT_ADAPTOR',"
293 <<"'GUI','DEFAULT_GUI'");
296 //=======================================================================
298 //=======================================================================
299 void Executer::Create ( const std::string& nodeType,
300 const std::string& nodeName)
302 GetCurrentDescriptor()->Add(nodeType,nodeName);
304 //=======================================================================
306 //=======================================================================
307 void Executer::Destroy(const std::string &boxName)
309 GetCurrentDescriptor()->Remove(boxName,true);
311 //=======================================================================
313 //=======================================================================
314 void Executer::Connect (const std::string &nodeFrom,
315 const std::string &outputLabel,
316 const std::string &nodeTo,
317 const std::string &inputLabel)
319 GetCurrentDescriptor()->Connect(nodeFrom, outputLabel, nodeTo, inputLabel);
321 //=======================================================================
323 //=======================================================================
324 void Executer::Execute (const std::string &nodeName)
327 if (GetCurrentDescriptor()==GetWorkspace())
331 GetCurrentDescriptor()->GetPrototype()->bbGetBlackBox(nodeName)->bbExecute(true);
336 GetCurrentDescriptor()->AddToExecutionList(nodeName) ;
339 //=======================================================================
341 //=======================================================================
342 void Executer::DefineInput ( const std::string &name,
343 const std::string &box,
344 const std::string &input,
345 const std::string& help)
347 // If the input is defined in the Root box
348 if (GetCurrentDescriptor()==GetWorkspace())
350 // If the dialog mode is set to NoDialog
351 // and the user passed the name in the Inputs map
352 // then the associated value is set to the box.input
353 // This is the way command line parameters are passed to the Root box
354 if (mDialogMode == NoDialog)
356 // find if name is in mInputs
357 std::map<std::string,std::string>::iterator i;
358 i = mInputs.find(name);
359 if (i!=mInputs.end()) {
360 Set(box,input,(*i).second);
363 // If the dialog mode is set to TextDialog
364 // The user is prompted for the value
365 else if (mDialogMode == TextDialog)
367 std::cout << name << "=";
373 // If the dialog mode is set to GraphicalDialog
374 // A dialog box is pop up
375 else if (mDialogMode == GraphicalDialog)
377 std::string mess("Enter the value of '");
382 std::string title(name);
384 std::string ans = wx2std ( wxGetTextFromUser( std2wx (mess), std2wx(title)));
390 GetCurrentDescriptor()->DefineInput(name,box,input,help);
393 //=======================================================================
395 //=======================================================================
396 void Executer::DefineOutput ( const std::string &name,
397 const std::string &box,
398 const std::string &output,
399 const std::string& help)
401 GetCurrentDescriptor()->DefineOutput(name,box,output,help);
403 //=======================================================================
405 //=======================================================================
406 void Executer::Set (const std::string &box,
407 const std::string &input,
408 const std::string &value)
410 BlackBox::Pointer b = GetCurrentDescriptor()->GetPrototype()->bbGetBlackBox(box);
411 // Looks for the adaptor
413 if ( ( b->bbGetInputType(input) != typeid(bbtk::any<bbtk::thing>) )&&
414 ( b->bbGetInputType(input) != typeid(std::string) ) )
416 BlackBox::Pointer a =
417 GetFactory()->NewAdaptor(typeid(std::string),
418 b->bbGetInputType(input),
423 TypeName(b->bbGetInputType(input))
424 <<"> to <std::string> found");
426 std::string v(value);
427 a->bbSetInput("In",v);
429 b->bbSetInput(input,a->bbGetOutput("Out"));
434 std::string v(value);
435 b->bbSetInput(input,v);
438 //=======================================================================
440 //=======================================================================
441 std::string Executer::Get(const std::string &box,
442 const std::string &output)
444 BlackBox::Pointer b = GetCurrentDescriptor()->GetPrototype()->bbGetBlackBox(box);
445 // Looks for the adaptor
446 if (b->bbGetOutputType(output) != typeid(std::string))
448 BlackBox::Pointer a =
449 GetFactory()->NewAdaptor(
450 b->bbGetOutputType(output),
456 TypeName(b->bbGetOutputType(output))
457 <<"> to <std::string> found");
461 a->bbSetInput("In",b->bbGetOutput(output));
463 std::string r = a->bbGetOutput("Out").unsafe_get<std::string>();
464 //std::string v = *((std::string*)a->bbGetOutput("Out")) ;
465 // std::cout << a->bbGetOutput("Out").unsafe_get<std::string>()
467 //std::string v(value);
468 //b->bbSetInput(input,a->bbGetOutput("Out"));
475 return b->bbGetOutput(output).unsafe_get<std::string>();
476 // std::string v = *((std::string*)b->bbGetOutput(output)) ;
477 // std::cout << b->bbGetOutput("Out").unsafe_get<std::string>()
479 // b->bbSetInput(input,&v);
482 //=======================================================================
484 //=======================================================================
485 void Executer::Author(const std::string &authorName)
487 GetCurrentDescriptor()->AddToAuthor(authorName,GetCurrentDescriptor()==GetWorkspace());
489 //=======================================================================
491 //=======================================================================
492 void Executer::Category(const std::string &category)
494 GetCurrentDescriptor()->AddToCategory(category,GetCurrentDescriptor()==GetWorkspace());
496 //=======================================================================
498 //=======================================================================
499 void Executer::Description(const std::string &d)
501 GetCurrentDescriptor()->AddToDescription(d,GetCurrentDescriptor()==GetWorkspace());
503 //=======================================================================
507 //=======================================================================
508 /// prints the list of the boxes of the current descriptor
509 void Executer::PrintHelpListBoxes()
511 bbtkMessage("help",1,"The black box descriptor \""
512 <<GetCurrentDescriptor()->GetTypeName()<<"\" contains : "<<std::endl);
513 GetCurrentDescriptor()->PrintBlackBoxes();
515 //=======================================================================
517 //=======================================================================
518 std::string Executer::ShowGraph(const std::string &nameblackbox,
519 const std::string &detailStr,
520 const std::string &levelStr,
521 const std::string &output_html,
522 const std::string &custom_header,
523 const std::string &custom_title,
524 bool system_display )
526 int detail = atoi(detailStr.c_str());
527 int level = atoi(levelStr.c_str());
528 bool relative_link = true;
533 p = GetFactory()->GetPackage(nameblackbox);
537 p = GetUserPackage();
540 std::string doc_path = bbtk::ConfigurationFile::GetInstance().Get_doc_path();
541 doc_path += bbtk::ConfigurationFile::GetInstance().Get_file_separator();
543 doc_path += bbtk::ConfigurationFile::GetInstance().Get_file_separator();
545 std::string pack_name(p->GetName());
546 std::string pack_path = doc_path + pack_name;
547 // Creating directory
548 if ( ! bbtk::Utilities::FileExists(pack_path) )
550 std::string command("mkdir \"" +pack_path+ "\"");
551 system( command.c_str() );
553 std::string pack_index(pack_path);
554 pack_index += bbtk::ConfigurationFile::GetInstance().Get_file_separator();
555 pack_index += "index.html";
558 // Generating documentation-help of workspace
559 p->SetDocURL(pack_index);
560 p->SetDocRelativeURL("index.html");
561 p->CreateHtmlPage(pack_index,"bbtk","user package",custom_header,custom_title,detail,level,relative_link);
566 ShowGraphTypes(nameblackbox);
568 catch (bbtk::Exception a)
570 std::cout <<"EXC"<<std::endl;
571 page = ShowGraphInstances(nameblackbox,detail,level,system_display);
576 //=======================================================================
578 //=======================================================================
579 /// Generate a png file with the actual pipeline (Graphviz-dot needed)
580 std::string Executer::ShowGraphInstances(const std::string &nameblackbox, int detail, int level,
584 BlackBox::Pointer blackbox;
585 if (nameblackbox==".")
587 blackbox = GetCurrentDescriptor()->GetPrototype();
591 blackbox = GetCurrentDescriptor()->GetPrototype()->bbFindBlackBox(nameblackbox);
598 // Don't pollute the file store with "temp_dir" directories ...
599 std::string default_doc_dir = ConfigurationFile::GetInstance().Get_default_temp_dir();
600 char c = default_doc_dir.c_str()[strlen(default_doc_dir.c_str())-1];
602 std::string directory = default_doc_dir;
603 if (c != '/' && c !='\\') directory = directory + "/";
605 directory = directory + "temp_dir";
606 //std::string directory("temp_dir");
607 std::string filename(directory + "/" + "bbtk_graph_pipeline");
608 std::string filename_html(filename+".html");
609 std::string command0("mkdir \""+directory + "\"");
612 std::string command2("start ");
614 std::string command2("gnome-open ");
617 command2=command2+filename_html;
618 page = filename_html;
619 // 1. Generate Html Diagram
621 s.open(filename_html.c_str());
624 s << "<html><head><title>BBtk graph diagram</title><meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\"></head>\n";
625 s << "<body bgcolor=\"#FFFFFF\" text=\"#000000\"> \n\n";
626 if ( blackbox->bbGetName()=="workspacePrototype" )
628 s << "<center>Current workspace</center>";
630 s << "<center>" << blackbox->bbGetName()<< "</center>";
632 blackbox->bbInsertHTMLGraph( s, detail, level, true, directory, false );
633 s << "</body></html>\n";
637 // 2. Starting Browser
638 if (system_display) system( command2.c_str() );
642 bbtkMessage("help",1,"No black box: \""
643 <<nameblackbox<<"\" " <<std::endl);
647 //=======================================================================
649 //=======================================================================
650 void Executer::PrintHelpBlackBox(const std::string &nameblackbox,
651 const std::string &detailStr,
652 const std::string &levelStr)
656 int detail = atoi(detailStr.c_str());
657 int level = atoi(levelStr.c_str());
658 BlackBox::Pointer blackbox;
659 if (nameblackbox.compare(".")==0)
661 blackbox=GetCurrentDescriptor()->GetPrototype();
665 blackbox = GetCurrentDescriptor()->GetPrototype()->bbFindBlackBox(nameblackbox);
671 blackbox->bbPrintHelp(blackbox,detail,level); //,mFactory);
676 bbtkError("box with name '" <<nameblackbox<<"' unknown");
679 //=======================================================================
681 //=======================================================================
682 /// sets the level of message
683 void Executer::SetMessageLevel(const std::string &kind,
686 bbtk::MessageManager::SetMessageLevel(kind,level);
688 //=======================================================================
690 //=======================================================================
691 /// Prints help on the messages
692 void Executer::HelpMessages()
694 bbtk::MessageManager::PrintInfo();
696 //=======================================================================
698 //=======================================================================
700 void Executer::Print(const std::string &str)
702 if (GetNoExecMode() && (GetCurrentDescriptor()==GetWorkspace()) ) return;
703 if (GetCurrentDescriptor()!=GetWorkspace()) return;
705 bbtkDebugMessage("kernel",9,"Executer::Print(\""<<str<<"\")"<<std::endl);
708 // InterpretLine ("load std")
709 // InterpretLine("new ConcatStrings _C_ ") -> trouver un nom unique : # commande
710 // InterpretLine("new Print _P_")
711 // InterpretLine("connect _C_.Out _P_.In")
715 std::vector<std::string> chains;
716 std::string delimiters("$");
718 // Skip delimiters at beginning.
719 std::string::size_type lastPos = str.find_first_not_of(delimiters, 0);
721 if (lastPos>0) is_text = false;
723 // Find first delimiter.
724 std::string::size_type pos = str.find_first_of(delimiters, lastPos);
726 while (std::string::npos != pos || std::string::npos != lastPos)
730 // Found a text token, add it to the vector.
731 chains.push_back(str.substr(lastPos, pos - lastPos));
732 // std::string token = str.substr(lastPos, pos - lastPos)
733 // InterpretLine("set _C_.In%num% %token%")
739 // is an output (between $$) : decode
740 std::string tok,box,output;
741 tok = str.substr(lastPos, pos - lastPos);
742 Utilities::SplitAroundFirstDot(tok,box,output);
743 chains.push_back( Get(box,output) );
745 // InterpretLine("connect %tok% _C_.In%num%")
748 // Skip delimiters. Note the "not_of"
749 lastPos = str.find_first_not_of(delimiters, pos);
750 // Find next delimiter
751 pos = str.find_first_of(delimiters, lastPos);
756 // InterpretLine("exec _P_")
757 // if (IS_IN_WORKSPACE) InterpretLine("delete _C_; delete _P_");
759 std::vector<std::string>::iterator i;
760 for (i= chains.begin(); i!=chains.end(); ++i)
762 Utilities::SubsBackslashN(*i);
763 bbtkMessage("output",1,*i);
765 bbtkMessage("output",1,std::endl);
767 //==========================================================================
769 //==========================================================================
770 std::string Executer::GetObjectName() const
772 return std::string("Executer");
774 //==========================================================================
776 //==========================================================================
777 std::string Executer::GetObjectInfo() const
782 //==========================================================================
783 //==========================================================================
784 size_t Executer::GetObjectSize() const
786 size_t s = Superclass::GetObjectSize();
787 s += Executer::GetObjectInternalSize();
790 //==========================================================================
791 //==========================================================================
792 size_t Executer::GetObjectInternalSize() const
794 size_t s = sizeof(Executer);
797 //==========================================================================
798 //==========================================================================
799 size_t Executer::GetObjectRecursiveSize() const
801 size_t s = Superclass::GetObjectRecursiveSize();
802 s += Executer::GetObjectInternalSize();
803 s += mFactory->GetObjectRecursiveSize();
806 //==========================================================================