2 # ---------------------------------------------------------------------
4 # Copyright (c) CREATIS (Centre de Recherche en Acquisition et Traitement de l'Image
6 # Authors : Eduardo Davila, Frederic Cervenansky, Claire Mouton
7 # Previous Authors : Laurent Guigues, Jean-Pierre Roux
8 # CreaTools website : www.creatis.insa-lyon.fr/site/fr/creatools_accueil
10 # This software is governed by the CeCILL-B license under French law and
11 # abiding by the rules of distribution of free software. You can use,
12 # modify and/ or redistribute the software under the terms of the CeCILL-B
13 # license as circulated by CEA, CNRS and INRIA at the following URL
14 # http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html
15 # or in the file LICENSE.txt.
17 # As a counterpart to the access to the source code and rights to copy,
18 # modify and redistribute granted by the license, users are provided only
19 # with a limited warranty and the software's author, the holder of the
20 # economic rights, and the successive licensors have only limited
23 # The fact that you are presently reading this means that you have had
24 # knowledge of the CeCILL-B license and that you accept its terms.
25 # ------------------------------------------------------------------------ */
28 /*=========================================================================
30 Module: $RCSfile: bbtkExecuter.cxx,v $
32 Date: $Date: 2012/11/16 08:49:01 $
33 Version: $Revision: 1.34 $
34 =========================================================================*/
40 * \brief class Executer: level 0 of script execution (code)
43 #include "bbtkExecuter.h"
44 #include "bbtkMessageManager.h"
45 #include "bbtkFactory.h"
46 #include "bbtkUtilities.h"
51 #include <wx/textdlg.h>
54 #include "bbtkWxBlackBox.h"
56 #include "bbtkConfigurationFile.h"
60 //=======================================================================
61 Executer::Pointer Executer::New()
63 bbtkDebugMessage("object",9,"Executer::New()"<<std::endl);
64 return MakePointer(new Executer());
66 //=======================================================================
68 //=======================================================================
75 mDialogMode(NoDialog),
78 bbtkDebugMessage("object",2,"==> Executer()" <<std::endl);
79 mFactory = Factory::New();
80 // The smart pointer on this is not made yet (is made by New)
81 // -> create it to pass it to the factory
82 // We have to "lock" the smart pointer because the factory
83 // only keeps a weak pointer on the executer
84 // -> this would auto-destroy !!
85 mFactory->SetExecuter(MakePointer(this,true));
87 bbtkDebugMessage("object",2,"<== Executer()" <<std::endl);
89 //=======================================================================
91 //=======================================================================
94 bbtkDebugMessage("object",2,"==> ~Executer()" <<std::endl);
95 mOpenDefinition.clear();
99 bbtkDebugMessage("object",2,"<== ~Executer()" <<std::endl);
101 //=======================================================================
103 //=======================================================================
105 void Executer::LoadPackage(const std::string &name )
107 GetFactory()->LoadPackage(name);
109 //=======================================================================
111 //=======================================================================
112 /// Unloads a package
113 void Executer::UnLoadPackage(const std::string &name )
115 GetFactory()->UnLoadPackage(name);
117 //=======================================================================
119 //=======================================================================
120 void Executer::Reset()
122 bbtkDebugMessage("kernel",9,"==> Executer::Reset()" <<std::endl);
124 // GetFactory()->Check();
126 mOpenDefinition.clear();
127 mOpenPackage.clear();
129 // Wx::DestroyTopWindow();
131 GetFactory()->Reset();
133 Wx::ProcessPendingEvents();
137 // Create user package
139 Package::New("user","internal","User defined black boxes","");
140 // Insert the user package in the factory
141 GetFactory()->InsertPackage(p);
142 // And in the list of open packages
143 mOpenPackage.push_back(p);
146 // Create user workspace
147 ComplexBlackBoxDescriptor::Pointer r =
148 ComplexBlackBoxDescriptor::New("workspace");
149 // mRootCBB->Reference();
150 r->SetFactory(GetFactory());
151 r->AddToAuthor("bbtk");
152 r->AddToDescription("User's workspace");
153 mOpenDefinition.push_back(CBBDefinition(r,"user"));
154 // Register it into the user package
158 // Object::PrintObjectListInfo();
159 // GetFactory()->CheckPackages();
160 bbtkDebugMessage("kernel",9,"<== Executer::Reset()" <<std::endl);
162 //=======================================================================
165 //=======================================================================
166 /// changes the workspace name
167 void Executer::SetWorkspaceName( const std::string& n )
169 GetUserPackage()->ChangeDescriptorName( GetWorkspace()->GetTypeName(), n );
171 //=======================================================================
173 //=======================================================================
174 void Executer::BeginPackage (const std::string &name)
176 bbtkDebugMessage("kernel",9,"==> Executer::BeginPackage(\""<<name<<"\")"
181 p = GetFactory()->GetPackage(name);
185 p = Package::New(name,"","","");
186 GetFactory()->InsertPackage(p);
188 mOpenPackage.push_back(p);
190 bbtkDebugMessage("kernel",9,"<== Executer::BeginPackage(\""<<name<<"\")"
193 //=======================================================================
195 //=======================================================================
196 void Executer::EndPackage()
198 if (mOpenPackage.size()>1) mOpenPackage.pop_back();
200 //=======================================================================
202 //=======================================================================
203 void Executer::Define (const std::string &name,
204 const std::string &pack,
205 const std::string &scriptfilename)
207 bbtkDebugMessage("kernel",9,"==> Executer::Define(\""<<name<<
211 ComplexBlackBoxDescriptor::Pointer b
212 = ComplexBlackBoxDescriptor::New(name);
213 b->SetFactory(GetFactory());
214 b->SetScriptFileName(scriptfilename);
215 mOpenDefinition.push_back( CBBDefinition( b, pack ) );
217 bbtkDebugMessage("kernel",9,"<== Executer::Define(\""<<name<<
221 //=======================================================================
223 //=======================================================================
224 /// Sets the file name to use for the current definition
225 /// (Used to set it after the Define command)
226 void Executer::SetCurrentFileName (const std::string &name )
228 mOpenDefinition.back().box->SetScriptFileName(name);
230 //=======================================================================
232 void Executer::SetTypeOfScript_Application ()
234 mOpenDefinition.back().box->SetTypeOfScript_Application();
239 //=======================================================================
240 void Executer::Clear()
242 bbtkDebugMessage("kernel",9,"==> Executer::Clear()" <<std::endl);
243 GetCurrentDescriptor()->GetPrototype()->Clear();
244 bbtkDebugMessage("kernel",9,"<== Executer::Clear()" <<std::endl);
246 //=======================================================================
248 //=======================================================================
249 void Executer::EndDefine ()
251 bbtkDebugMessage("kernel",9,"==> Executer::EndDefine(\""
252 <<GetCurrentDescriptor()->GetTypeName()<<"\")"
254 // Does current package exist ?
256 std::string pname(mOpenDefinition.back().package);
261 p = GetFactory()->GetPackage(pname);
265 p = Package::New(pname,"","","");
266 GetFactory()->InsertPackage(p);
271 p = mOpenPackage.back().lock();
273 // Register the descriptor in the current package
274 p->Register(GetCurrentDescriptor());
276 bbtkDebugMessage("kernel",9,"<== Executer::EndDefine(\""
277 <<GetCurrentDescriptor()->GetTypeName()<<"\")"
279 mOpenDefinition.pop_back();
281 //=======================================================================
283 //=======================================================================
284 void Executer::Kind(const std::string& kind)
288 GetCurrentDescriptor()->AddToCategory("adaptor");
289 GetCurrentDescriptor()->SetKind(bbtk::BlackBoxDescriptor::ADAPTOR);
291 else if (kind=="DEFAULT_ADAPTOR")
293 GetCurrentDescriptor()->AddToCategory("adaptor");
294 GetCurrentDescriptor()->SetKind(bbtk::BlackBoxDescriptor::DEFAULT_ADAPTOR);
298 GetCurrentDescriptor()->AddToCategory("gui");
299 GetCurrentDescriptor()->SetKind(bbtk::BlackBoxDescriptor::GUI);
301 else if (kind=="DEFAULT_GUI")
303 GetCurrentDescriptor()->AddToCategory("gui");
304 GetCurrentDescriptor()->SetKind(bbtk::BlackBoxDescriptor::DEFAULT_GUI);
308 bbtkError("Unknown box kind : '"<<kind<<"'. "
309 <<"Valid kinds are 'ADAPTOR','DEFAULT_ADAPTOR',"
310 <<"'GUI','DEFAULT_GUI'");
313 //=======================================================================
315 //=======================================================================
316 void Executer::Create ( const std::string& nodeType,
317 const std::string& nodeName)
319 GetCurrentDescriptor()->Add(nodeType,nodeName);
321 //=======================================================================
323 //=======================================================================
324 void Executer::Destroy(const std::string &boxName)
326 GetCurrentDescriptor()->Remove(boxName,true);
328 //=======================================================================
330 //=======================================================================
331 void Executer::Connect (const std::string &nodeFrom,
332 const std::string &outputLabel,
333 const std::string &nodeTo,
334 const std::string &inputLabel)
336 GetCurrentDescriptor()->Connect(nodeFrom, outputLabel, nodeTo, inputLabel);
338 //=======================================================================
340 //=======================================================================
341 void Executer::Execute (const std::string &nodeName)
344 if (GetCurrentDescriptor()==GetWorkspace())
348 GetCurrentDescriptor()->GetPrototype()->bbGetBlackBox(nodeName)->bbExecute(true);
353 GetCurrentDescriptor()->AddToExecutionList(nodeName) ;
356 //=======================================================================
358 //=======================================================================
359 void Executer::DefineInput ( const std::string &name,
360 const std::string &box,
361 const std::string &input,
362 const std::string& help)
364 // If the input is defined in the Root box
365 if (GetCurrentDescriptor()==GetWorkspace())
367 // If the dialog mode is set to NoDialog
368 // and the user passed the name in the Inputs map
369 // then the associated value is set to the box.input
370 // This is the way command line parameters are passed to the Root box
371 if (mDialogMode == NoDialog)
373 // find if name is in mInputs
374 std::map<std::string,std::string>::iterator i;
375 i = mInputs.find(name);
376 if (i!=mInputs.end()) {
377 Set(box,input,(*i).second);
380 // If the dialog mode is set to TextDialog
381 // The user is prompted for the value
382 else if (mDialogMode == TextDialog)
384 std::cout << name << "=";
390 // If the dialog mode is set to GraphicalDialog
391 // A dialog box is pop up
392 else if (mDialogMode == GraphicalDialog)
394 std::string mess("Enter the value of '");
399 std::string title(name);
401 std::string ans = wx2std ( wxGetTextFromUser( std2wx (mess), std2wx(title)));
407 GetCurrentDescriptor()->DefineInput(name,box,input,help);
410 //=======================================================================
412 //=======================================================================
413 void Executer::DefineOutput ( const std::string &name,
414 const std::string &box,
415 const std::string &output,
416 const std::string& help)
418 GetCurrentDescriptor()->DefineOutput(name,box,output,help);
420 //=======================================================================
422 //=======================================================================
423 void Executer::Set (const std::string &box,
424 const std::string &input,
425 const std::string &value)
427 BlackBox::Pointer b = GetCurrentDescriptor()->GetPrototype()->bbGetBlackBox(box);
428 // Looks for the adaptor
430 if ( ( b->bbGetInputType(input) != typeid(bbtk::any<bbtk::thing>) )&&
431 ( b->bbGetInputType(input) != typeid(std::string) ) )
433 BlackBox::Pointer a =
434 GetFactory()->NewAdaptor(typeid(std::string),
435 b->bbGetInputType(input),
440 TypeName(b->bbGetInputType(input))
441 <<"> to <std::string> found");
443 std::string v(value);
444 a->bbSetInput("In",v);
446 b->bbSetInput(input,a->bbGetOutput("Out"));
451 std::string v(value);
452 b->bbSetInput(input,v);
455 //=======================================================================
457 //=======================================================================
458 std::string Executer::Get(const std::string &box,
459 const std::string &output)
461 BlackBox::Pointer b = GetCurrentDescriptor()->GetPrototype()->bbGetBlackBox(box);
462 // Looks for the adaptor
463 if (b->bbGetOutputType(output) != typeid(std::string))
465 BlackBox::Pointer a =
466 GetFactory()->NewAdaptor(
467 b->bbGetOutputType(output),
473 TypeName(b->bbGetOutputType(output))
474 <<"> to <std::string> found");
478 a->bbSetInput("In",b->bbGetOutput(output));
480 std::string r = a->bbGetOutput("Out").unsafe_get<std::string>();
481 //std::string v = *((std::string*)a->bbGetOutput("Out")) ;
482 // std::cout << a->bbGetOutput("Out").unsafe_get<std::string>()
484 //std::string v(value);
485 //b->bbSetInput(input,a->bbGetOutput("Out"));
492 return b->bbGetOutput(output).unsafe_get<std::string>();
493 // std::string v = *((std::string*)b->bbGetOutput(output)) ;
494 // std::cout << b->bbGetOutput("Out").unsafe_get<std::string>()
496 // b->bbSetInput(input,&v);
499 //=======================================================================
501 //=======================================================================
502 void Executer::Author(const std::string &authorName)
504 GetCurrentDescriptor()->AddToAuthor(authorName,GetCurrentDescriptor()==GetWorkspace());
506 //=======================================================================
508 //=======================================================================
509 void Executer::Category(const std::string &category)
511 GetCurrentDescriptor()->AddToCategory(category,GetCurrentDescriptor()==GetWorkspace());
513 //=======================================================================
515 //=======================================================================
516 void Executer::Description(const std::string &d)
518 GetCurrentDescriptor()->AddToDescription(d,GetCurrentDescriptor()==GetWorkspace());
520 //=======================================================================
524 //=======================================================================
525 /// prints the list of the boxes of the current descriptor
526 void Executer::PrintHelpListBoxes()
528 bbtkMessage("help",1,"The black box descriptor \""
529 <<GetCurrentDescriptor()->GetTypeName()<<"\" contains : "<<std::endl);
530 GetCurrentDescriptor()->PrintBlackBoxes();
532 //=======================================================================
534 //=======================================================================
535 std::string Executer::ShowGraph(const std::string &nameblackbox,
536 const std::string &detailStr,
537 const std::string &levelStr,
538 const std::string &output_html,
539 const std::string &custom_header,
540 const std::string &custom_title,
541 bool system_display )
543 int detail = atoi(detailStr.c_str());
544 int level = atoi(levelStr.c_str());
545 bool relative_link = true;
550 p = GetFactory()->GetPackage(nameblackbox);
554 p = GetUserPackage();
557 std::string doc_path = bbtk::ConfigurationFile::GetInstance().Get_doc_path();
558 doc_path += bbtk::ConfigurationFile::GetInstance().Get_file_separator();
560 doc_path += bbtk::ConfigurationFile::GetInstance().Get_file_separator();
562 std::string pack_name(p->GetName());
563 std::string pack_path = doc_path + pack_name;
564 // Creating directory
565 if ( ! bbtk::Utilities::FileExists(pack_path) )
567 std::string command("mkdir \"" +pack_path+ "\"");
568 system( command.c_str() );
570 std::string pack_index(pack_path);
571 pack_index += bbtk::ConfigurationFile::GetInstance().Get_file_separator();
572 pack_index += "index.html";
575 // Generating documentation-help of workspace
576 p->SetDocURL(pack_index);
577 p->SetDocRelativeURL("index.html");
578 p->CreateHtmlPage(pack_index,"bbtk","user package",custom_header,custom_title,detail,level,relative_link);
583 ShowGraphTypes(nameblackbox);
585 catch (bbtk::Exception a)
587 std::cout <<"EXC"<<std::endl;
588 page = ShowGraphInstances(nameblackbox,detail,level,system_display);
593 //=======================================================================
595 //=======================================================================
596 /// Generate a png file with the actual pipeline (Graphviz-dot needed)
597 std::string Executer::ShowGraphInstances(const std::string &nameblackbox, int detail, int level,
601 BlackBox::Pointer blackbox;
602 if (nameblackbox==".")
604 blackbox = GetCurrentDescriptor()->GetPrototype();
608 blackbox = GetCurrentDescriptor()->GetPrototype()->bbFindBlackBox(nameblackbox);
615 // Don't pollute the file store with "temp_dir" directories ...
616 std::string default_doc_dir = ConfigurationFile::GetInstance().Get_default_temp_dir();
617 char c = default_doc_dir.c_str()[strlen(default_doc_dir.c_str())-1];
619 std::string directory = default_doc_dir;
620 if (c != '/' && c !='\\') directory = directory + "/";
622 directory = directory + "temp_dir";
623 //std::string directory("temp_dir");
624 std::string filename(directory + "/" + "bbtk_graph_pipeline");
625 std::string filename_html(filename+".html");
626 std::string command0("mkdir \""+directory + "\"");
629 std::string command2("start ");
631 std::string command2("gnome-open ");
634 command2=command2+filename_html;
635 page = filename_html;
636 // 1. Generate Html Diagram
638 s.open(filename_html.c_str());
641 s << "<html><head><title>BBtk graph diagram</title><meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\"></head>\n";
642 s << "<body bgcolor=\"#FFFFFF\" text=\"#000000\"> \n\n";
643 if ( blackbox->bbGetName()=="workspacePrototype" )
645 s << "<center>Current workspace</center>";
647 s << "<center>" << blackbox->bbGetName()<< "</center>";
649 blackbox->bbInsertHTMLGraph( s, detail, level, true, directory, false );
650 s << "</body></html>\n";
654 // 2. Starting Browser
655 if (system_display) system( command2.c_str() );
659 bbtkMessage("help",1,"No black box: \""
660 <<nameblackbox<<"\" " <<std::endl);
664 //=======================================================================
666 //=======================================================================
667 void Executer::PrintHelpBlackBox(const std::string &nameblackbox,
668 const std::string &detailStr,
669 const std::string &levelStr)
673 int detail = atoi(detailStr.c_str());
674 int level = atoi(levelStr.c_str());
675 BlackBox::Pointer blackbox;
676 if (nameblackbox.compare(".")==0)
678 blackbox=GetCurrentDescriptor()->GetPrototype();
682 blackbox = GetCurrentDescriptor()->GetPrototype()->bbFindBlackBox(nameblackbox);
688 blackbox->bbPrintHelp(blackbox,detail,level); //,mFactory);
693 bbtkError("box with name '" <<nameblackbox<<"' unknown");
696 //=======================================================================
698 //=======================================================================
699 /// sets the level of message
700 void Executer::SetMessageLevel(const std::string &kind,
703 bbtk::MessageManager::SetMessageLevel(kind,level);
705 //=======================================================================
707 //=======================================================================
708 /// Prints help on the messages
709 void Executer::HelpMessages()
711 bbtk::MessageManager::PrintInfo();
713 //=======================================================================
715 //=======================================================================
717 void Executer::Print(const std::string &str)
719 if (GetNoExecMode() && (GetCurrentDescriptor()==GetWorkspace()) ) return;
720 if (GetCurrentDescriptor()!=GetWorkspace()) return;
722 bbtkDebugMessage("kernel",9,"Executer::Print(\""<<str<<"\")"<<std::endl);
725 // InterpretLine ("load std")
726 // InterpretLine("new ConcatStrings _C_ ") -> trouver un nom unique : # commande
727 // InterpretLine("new Print _P_")
728 // InterpretLine("connect _C_.Out _P_.In")
732 std::vector<std::string> chains;
733 std::string delimiters("$");
735 // Skip delimiters at beginning.
736 std::string::size_type lastPos = str.find_first_not_of(delimiters, 0);
738 if (lastPos>0) is_text = false;
740 // Find first delimiter.
741 std::string::size_type pos = str.find_first_of(delimiters, lastPos);
743 while (std::string::npos != pos || std::string::npos != lastPos)
747 // Found a text token, add it to the vector.
748 chains.push_back(str.substr(lastPos, pos - lastPos));
749 // std::string token = str.substr(lastPos, pos - lastPos)
750 // InterpretLine("set _C_.In%num% %token%")
756 // is an output (between $$) : decode
757 std::string tok,box,output;
758 tok = str.substr(lastPos, pos - lastPos);
759 Utilities::SplitAroundFirstDot(tok,box,output);
760 chains.push_back( Get(box,output) );
762 // InterpretLine("connect %tok% _C_.In%num%")
765 // Skip delimiters. Note the "not_of"
766 lastPos = str.find_first_not_of(delimiters, pos);
767 // Find next delimiter
768 pos = str.find_first_of(delimiters, lastPos);
773 // InterpretLine("exec _P_")
774 // if (IS_IN_WORKSPACE) InterpretLine("delete _C_; delete _P_");
776 std::vector<std::string>::iterator i;
777 for (i= chains.begin(); i!=chains.end(); ++i)
779 Utilities::SubsBackslashN(*i);
780 bbtkMessage("output",1,*i);
782 bbtkMessage("output",1,std::endl);
784 //==========================================================================
786 //==========================================================================
787 std::string Executer::GetObjectName() const
789 return std::string("Executer");
791 //==========================================================================
793 //==========================================================================
794 std::string Executer::GetObjectInfo() const
799 //==========================================================================
800 //==========================================================================
801 size_t Executer::GetObjectSize() const
803 size_t s = Superclass::GetObjectSize();
804 s += Executer::GetObjectInternalSize();
807 //==========================================================================
808 //==========================================================================
809 size_t Executer::GetObjectInternalSize() const
811 size_t s = sizeof(Executer);
814 //==========================================================================
815 //==========================================================================
816 size_t Executer::GetObjectRecursiveSize() const
818 size_t s = Superclass::GetObjectRecursiveSize();
819 s += Executer::GetObjectInternalSize();
820 s += mFactory->GetObjectRecursiveSize();
823 //==========================================================================