1 /*=========================================================================
3 Module: $RCSfile: bbtkExecuter.cxx,v $
5 Date: $Date: 2010/06/18 14:43:19 $
6 Version: $Revision: 1.32 $
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();
126 Wx::ProcessPendingEvents();
129 // Create user package
131 Package::New("user","internal","User defined black boxes","");
132 // Insert the user package in the factory
133 GetFactory()->InsertPackage(p);
134 // And in the list of open packages
135 mOpenPackage.push_back(p);
138 // Create user workspace
139 ComplexBlackBoxDescriptor::Pointer r =
140 ComplexBlackBoxDescriptor::New("workspace");
141 // mRootCBB->Reference();
142 r->SetFactory(GetFactory());
143 r->AddToAuthor("bbtk");
144 r->AddToDescription("User's workspace");
145 mOpenDefinition.push_back(CBBDefinition(r,"user"));
146 // Register it into the user package
150 // Object::PrintObjectListInfo();
151 // GetFactory()->CheckPackages();
152 bbtkDebugMessage("kernel",9,"<== Executer::Reset()" <<std::endl);
154 //=======================================================================
157 //=======================================================================
158 /// changes the workspace name
159 void Executer::SetWorkspaceName( const std::string& n )
161 GetUserPackage()->ChangeDescriptorName( GetWorkspace()->GetTypeName(), n );
163 //=======================================================================
165 //=======================================================================
166 void Executer::BeginPackage (const std::string &name)
168 bbtkDebugMessage("kernel",9,"==> Executer::BeginPackage(\""<<name<<"\")"
173 p = GetFactory()->GetPackage(name);
177 p = Package::New(name,"","","");
178 GetFactory()->InsertPackage(p);
180 mOpenPackage.push_back(p);
182 bbtkDebugMessage("kernel",9,"<== Executer::BeginPackage(\""<<name<<"\")"
185 //=======================================================================
187 //=======================================================================
188 void Executer::EndPackage()
190 if (mOpenPackage.size()>1) mOpenPackage.pop_back();
192 //=======================================================================
194 //=======================================================================
195 void Executer::Define (const std::string &name,
196 const std::string &pack,
197 const std::string &scriptfilename)
199 bbtkDebugMessage("kernel",9,"==> Executer::Define(\""<<name<<
203 ComplexBlackBoxDescriptor::Pointer b
204 = ComplexBlackBoxDescriptor::New(name);
205 b->SetFactory(GetFactory());
206 b->SetScriptFileName(scriptfilename);
207 mOpenDefinition.push_back( CBBDefinition( b, pack ) );
209 bbtkDebugMessage("kernel",9,"<== Executer::Define(\""<<name<<
213 //=======================================================================
215 //=======================================================================
216 /// Sets the file name to use for the current definition
217 /// (Used to set it after the Define command)
218 void Executer::SetCurrentFileName (const std::string &name )
220 mOpenDefinition.back().box->SetScriptFileName(name);
222 //=======================================================================
224 //=======================================================================
225 void Executer::Clear()
227 bbtkDebugMessage("kernel",9,"==> Executer::Clear()" <<std::endl);
228 GetCurrentDescriptor()->GetPrototype()->Clear();
229 bbtkDebugMessage("kernel",9,"<== Executer::Clear()" <<std::endl);
231 //=======================================================================
233 //=======================================================================
234 void Executer::EndDefine ()
236 bbtkDebugMessage("kernel",9,"==> Executer::EndDefine(\""
237 <<GetCurrentDescriptor()->GetTypeName()<<"\")"
239 // Does current package exist ?
241 std::string pname(mOpenDefinition.back().package);
246 p = GetFactory()->GetPackage(pname);
250 p = Package::New(pname,"","","");
251 GetFactory()->InsertPackage(p);
256 p = mOpenPackage.back().lock();
258 // Register the descriptor in the current package
259 p->Register(GetCurrentDescriptor());
261 bbtkDebugMessage("kernel",9,"<== Executer::EndDefine(\""
262 <<GetCurrentDescriptor()->GetTypeName()<<"\")"
264 mOpenDefinition.pop_back();
266 //=======================================================================
268 //=======================================================================
269 void Executer::Kind(const std::string& kind)
273 GetCurrentDescriptor()->AddToCategory("adaptor");
274 GetCurrentDescriptor()->SetKind(bbtk::BlackBoxDescriptor::ADAPTOR);
276 else if (kind=="DEFAULT_ADAPTOR")
278 GetCurrentDescriptor()->AddToCategory("adaptor");
279 GetCurrentDescriptor()->SetKind(bbtk::BlackBoxDescriptor::DEFAULT_ADAPTOR);
283 GetCurrentDescriptor()->AddToCategory("gui");
284 GetCurrentDescriptor()->SetKind(bbtk::BlackBoxDescriptor::GUI);
286 else if (kind=="DEFAULT_GUI")
288 GetCurrentDescriptor()->AddToCategory("gui");
289 GetCurrentDescriptor()->SetKind(bbtk::BlackBoxDescriptor::DEFAULT_GUI);
293 bbtkError("Unknown box kind : '"<<kind<<"'. "
294 <<"Valid kinds are 'ADAPTOR','DEFAULT_ADAPTOR',"
295 <<"'GUI','DEFAULT_GUI'");
298 //=======================================================================
300 //=======================================================================
301 void Executer::Create ( const std::string& nodeType,
302 const std::string& nodeName)
304 GetCurrentDescriptor()->Add(nodeType,nodeName);
306 //=======================================================================
308 //=======================================================================
309 void Executer::Destroy(const std::string &boxName)
311 GetCurrentDescriptor()->Remove(boxName,true);
313 //=======================================================================
315 //=======================================================================
316 void Executer::Connect (const std::string &nodeFrom,
317 const std::string &outputLabel,
318 const std::string &nodeTo,
319 const std::string &inputLabel)
321 GetCurrentDescriptor()->Connect(nodeFrom, outputLabel, nodeTo, inputLabel);
323 //=======================================================================
325 //=======================================================================
326 void Executer::Execute (const std::string &nodeName)
329 if (GetCurrentDescriptor()==GetWorkspace())
333 GetCurrentDescriptor()->GetPrototype()->bbGetBlackBox(nodeName)->bbExecute(true);
338 GetCurrentDescriptor()->AddToExecutionList(nodeName) ;
341 //=======================================================================
343 //=======================================================================
344 void Executer::DefineInput ( const std::string &name,
345 const std::string &box,
346 const std::string &input,
347 const std::string& help)
349 // If the input is defined in the Root box
350 if (GetCurrentDescriptor()==GetWorkspace())
352 // If the dialog mode is set to NoDialog
353 // and the user passed the name in the Inputs map
354 // then the associated value is set to the box.input
355 // This is the way command line parameters are passed to the Root box
356 if (mDialogMode == NoDialog)
358 // find if name is in mInputs
359 std::map<std::string,std::string>::iterator i;
360 i = mInputs.find(name);
361 if (i!=mInputs.end()) {
362 Set(box,input,(*i).second);
365 // If the dialog mode is set to TextDialog
366 // The user is prompted for the value
367 else if (mDialogMode == TextDialog)
369 std::cout << name << "=";
375 // If the dialog mode is set to GraphicalDialog
376 // A dialog box is pop up
377 else if (mDialogMode == GraphicalDialog)
379 std::string mess("Enter the value of '");
384 std::string title(name);
386 std::string ans = wx2std ( wxGetTextFromUser( std2wx (mess), std2wx(title)));
392 GetCurrentDescriptor()->DefineInput(name,box,input,help);
395 //=======================================================================
397 //=======================================================================
398 void Executer::DefineOutput ( const std::string &name,
399 const std::string &box,
400 const std::string &output,
401 const std::string& help)
403 GetCurrentDescriptor()->DefineOutput(name,box,output,help);
405 //=======================================================================
407 //=======================================================================
408 void Executer::Set (const std::string &box,
409 const std::string &input,
410 const std::string &value)
412 BlackBox::Pointer b = GetCurrentDescriptor()->GetPrototype()->bbGetBlackBox(box);
413 // Looks for the adaptor
415 if ( ( b->bbGetInputType(input) != typeid(bbtk::any<bbtk::thing>) )&&
416 ( b->bbGetInputType(input) != typeid(std::string) ) )
418 BlackBox::Pointer a =
419 GetFactory()->NewAdaptor(typeid(std::string),
420 b->bbGetInputType(input),
425 TypeName(b->bbGetInputType(input))
426 <<"> to <std::string> found");
428 std::string v(value);
429 a->bbSetInput("In",v);
431 b->bbSetInput(input,a->bbGetOutput("Out"));
436 std::string v(value);
437 b->bbSetInput(input,v);
440 //=======================================================================
442 //=======================================================================
443 std::string Executer::Get(const std::string &box,
444 const std::string &output)
446 BlackBox::Pointer b = GetCurrentDescriptor()->GetPrototype()->bbGetBlackBox(box);
447 // Looks for the adaptor
448 if (b->bbGetOutputType(output) != typeid(std::string))
450 BlackBox::Pointer a =
451 GetFactory()->NewAdaptor(
452 b->bbGetOutputType(output),
458 TypeName(b->bbGetOutputType(output))
459 <<"> to <std::string> found");
463 a->bbSetInput("In",b->bbGetOutput(output));
465 std::string r = a->bbGetOutput("Out").unsafe_get<std::string>();
466 //std::string v = *((std::string*)a->bbGetOutput("Out")) ;
467 // std::cout << a->bbGetOutput("Out").unsafe_get<std::string>()
469 //std::string v(value);
470 //b->bbSetInput(input,a->bbGetOutput("Out"));
477 return b->bbGetOutput(output).unsafe_get<std::string>();
478 // std::string v = *((std::string*)b->bbGetOutput(output)) ;
479 // std::cout << b->bbGetOutput("Out").unsafe_get<std::string>()
481 // b->bbSetInput(input,&v);
484 //=======================================================================
486 //=======================================================================
487 void Executer::Author(const std::string &authorName)
489 GetCurrentDescriptor()->AddToAuthor(authorName,GetCurrentDescriptor()==GetWorkspace());
491 //=======================================================================
493 //=======================================================================
494 void Executer::Category(const std::string &category)
496 GetCurrentDescriptor()->AddToCategory(category,GetCurrentDescriptor()==GetWorkspace());
498 //=======================================================================
500 //=======================================================================
501 void Executer::Description(const std::string &d)
503 GetCurrentDescriptor()->AddToDescription(d,GetCurrentDescriptor()==GetWorkspace());
505 //=======================================================================
509 //=======================================================================
510 /// prints the list of the boxes of the current descriptor
511 void Executer::PrintHelpListBoxes()
513 bbtkMessage("help",1,"The black box descriptor \""
514 <<GetCurrentDescriptor()->GetTypeName()<<"\" contains : "<<std::endl);
515 GetCurrentDescriptor()->PrintBlackBoxes();
517 //=======================================================================
519 //=======================================================================
520 std::string Executer::ShowGraph(const std::string &nameblackbox,
521 const std::string &detailStr,
522 const std::string &levelStr,
523 const std::string &output_html,
524 const std::string &custom_header,
525 const std::string &custom_title,
526 bool system_display )
528 int detail = atoi(detailStr.c_str());
529 int level = atoi(levelStr.c_str());
530 bool relative_link = true;
535 p = GetFactory()->GetPackage(nameblackbox);
539 p = GetUserPackage();
542 std::string doc_path = bbtk::ConfigurationFile::GetInstance().Get_doc_path();
543 doc_path += bbtk::ConfigurationFile::GetInstance().Get_file_separator();
545 doc_path += bbtk::ConfigurationFile::GetInstance().Get_file_separator();
547 std::string pack_name(p->GetName());
548 std::string pack_path = doc_path + pack_name;
549 // Creating directory
550 if ( ! bbtk::Utilities::FileExists(pack_path) )
552 std::string command("mkdir \"" +pack_path+ "\"");
553 system( command.c_str() );
555 std::string pack_index(pack_path);
556 pack_index += bbtk::ConfigurationFile::GetInstance().Get_file_separator();
557 pack_index += "index.html";
560 // Generating documentation-help of workspace
561 p->SetDocURL(pack_index);
562 p->SetDocRelativeURL("index.html");
563 p->CreateHtmlPage(pack_index,"bbtk","user package",custom_header,custom_title,detail,level,relative_link);
568 ShowGraphTypes(nameblackbox);
570 catch (bbtk::Exception a)
572 std::cout <<"EXC"<<std::endl;
573 page = ShowGraphInstances(nameblackbox,detail,level,system_display);
578 //=======================================================================
580 //=======================================================================
581 /// Generate a png file with the actual pipeline (Graphviz-dot needed)
582 std::string Executer::ShowGraphInstances(const std::string &nameblackbox, int detail, int level,
586 BlackBox::Pointer blackbox;
587 if (nameblackbox==".")
589 blackbox = GetCurrentDescriptor()->GetPrototype();
593 blackbox = GetCurrentDescriptor()->GetPrototype()->bbFindBlackBox(nameblackbox);
600 // Don't pollute the file store with "temp_dir" directories ...
601 std::string default_doc_dir = ConfigurationFile::GetInstance().Get_default_temp_dir();
602 char c = default_doc_dir.c_str()[strlen(default_doc_dir.c_str())-1];
604 std::string directory = default_doc_dir;
605 if (c != '/' && c !='\\') directory = directory + "/";
607 directory = directory + "temp_dir";
608 //std::string directory("temp_dir");
609 std::string filename(directory + "/" + "bbtk_graph_pipeline");
610 std::string filename_html(filename+".html");
611 std::string command0("mkdir \""+directory + "\"");
614 std::string command2("start ");
616 std::string command2("gnome-open ");
619 command2=command2+filename_html;
620 page = filename_html;
621 // 1. Generate Html Diagram
623 s.open(filename_html.c_str());
626 s << "<html><head><title>BBtk graph diagram</title><meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\"></head>\n";
627 s << "<body bgcolor=\"#FFFFFF\" text=\"#000000\"> \n\n";
628 if ( blackbox->bbGetName()=="workspacePrototype" )
630 s << "<center>Current workspace</center>";
632 s << "<center>" << blackbox->bbGetName()<< "</center>";
634 blackbox->bbInsertHTMLGraph( s, detail, level, true, directory, false );
635 s << "</body></html>\n";
639 // 2. Starting Browser
640 if (system_display) system( command2.c_str() );
644 bbtkMessage("help",1,"No black box: \""
645 <<nameblackbox<<"\" " <<std::endl);
649 //=======================================================================
651 //=======================================================================
652 void Executer::PrintHelpBlackBox(const std::string &nameblackbox,
653 const std::string &detailStr,
654 const std::string &levelStr)
658 int detail = atoi(detailStr.c_str());
659 int level = atoi(levelStr.c_str());
660 BlackBox::Pointer blackbox;
661 if (nameblackbox.compare(".")==0)
663 blackbox=GetCurrentDescriptor()->GetPrototype();
667 blackbox = GetCurrentDescriptor()->GetPrototype()->bbFindBlackBox(nameblackbox);
673 blackbox->bbPrintHelp(blackbox,detail,level); //,mFactory);
678 bbtkError("box with name '" <<nameblackbox<<"' unknown");
681 //=======================================================================
683 //=======================================================================
684 /// sets the level of message
685 void Executer::SetMessageLevel(const std::string &kind,
688 bbtk::MessageManager::SetMessageLevel(kind,level);
690 //=======================================================================
692 //=======================================================================
693 /// Prints help on the messages
694 void Executer::HelpMessages()
696 bbtk::MessageManager::PrintInfo();
698 //=======================================================================
700 //=======================================================================
702 void Executer::Print(const std::string &str)
704 if (GetNoExecMode() && (GetCurrentDescriptor()==GetWorkspace()) ) return;
705 if (GetCurrentDescriptor()!=GetWorkspace()) return;
707 bbtkDebugMessage("kernel",9,"Executer::Print(\""<<str<<"\")"<<std::endl);
710 // InterpretLine ("load std")
711 // InterpretLine("new ConcatStrings _C_ ") -> trouver un nom unique : # commande
712 // InterpretLine("new Print _P_")
713 // InterpretLine("connect _C_.Out _P_.In")
717 std::vector<std::string> chains;
718 std::string delimiters("$");
720 // Skip delimiters at beginning.
721 std::string::size_type lastPos = str.find_first_not_of(delimiters, 0);
723 if (lastPos>0) is_text = false;
725 // Find first delimiter.
726 std::string::size_type pos = str.find_first_of(delimiters, lastPos);
728 while (std::string::npos != pos || std::string::npos != lastPos)
732 // Found a text token, add it to the vector.
733 chains.push_back(str.substr(lastPos, pos - lastPos));
734 // std::string token = str.substr(lastPos, pos - lastPos)
735 // InterpretLine("set _C_.In%num% %token%")
741 // is an output (between $$) : decode
742 std::string tok,box,output;
743 tok = str.substr(lastPos, pos - lastPos);
744 Utilities::SplitAroundFirstDot(tok,box,output);
745 chains.push_back( Get(box,output) );
747 // InterpretLine("connect %tok% _C_.In%num%")
750 // Skip delimiters. Note the "not_of"
751 lastPos = str.find_first_not_of(delimiters, pos);
752 // Find next delimiter
753 pos = str.find_first_of(delimiters, lastPos);
758 // InterpretLine("exec _P_")
759 // if (IS_IN_WORKSPACE) InterpretLine("delete _C_; delete _P_");
761 std::vector<std::string>::iterator i;
762 for (i= chains.begin(); i!=chains.end(); ++i)
764 Utilities::SubsBackslashN(*i);
765 bbtkMessage("output",1,*i);
767 bbtkMessage("output",1,std::endl);
769 //==========================================================================
771 //==========================================================================
772 std::string Executer::GetObjectName() const
774 return std::string("Executer");
776 //==========================================================================
778 //==========================================================================
779 std::string Executer::GetObjectInfo() const
784 //==========================================================================
785 //==========================================================================
786 size_t Executer::GetObjectSize() const
788 size_t s = Superclass::GetObjectSize();
789 s += Executer::GetObjectInternalSize();
792 //==========================================================================
793 //==========================================================================
794 size_t Executer::GetObjectInternalSize() const
796 size_t s = sizeof(Executer);
799 //==========================================================================
800 //==========================================================================
801 size_t Executer::GetObjectRecursiveSize() const
803 size_t s = Superclass::GetObjectRecursiveSize();
804 s += Executer::GetObjectInternalSize();
805 s += mFactory->GetObjectRecursiveSize();
808 //==========================================================================