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 !!
86 printf("EED Executer::Executer Start\n");
88 mFactory->SetExecuter(MakePointer(this,true));
89 printf("EED Executer::Executer 1\n");
92 bbtkDebugMessage("object",2,"<== Executer()" <<std::endl);
93 printf("EED Executer::Executer End\n");
95 //=======================================================================
97 //=======================================================================
100 bbtkDebugMessage("object",2,"==> ~Executer()" <<std::endl);
101 mOpenDefinition.clear();
102 mOpenPackage.clear();
105 bbtkDebugMessage("object",2,"<== ~Executer()" <<std::endl);
107 //=======================================================================
109 //=======================================================================
111 void Executer::LoadPackage(const std::string &name )
113 GetFactory()->LoadPackage(name);
115 //=======================================================================
117 //=======================================================================
118 /// Unloads a package
119 void Executer::UnLoadPackage(const std::string &name )
121 GetFactory()->UnLoadPackage(name);
123 //=======================================================================
125 //=======================================================================
126 void Executer::Reset()
128 printf("EED Executer::Reset Start\n");
129 bbtkDebugMessage("kernel",9,"==> Executer::Reset()" <<std::endl);
131 // GetFactory()->Check();
133 mOpenDefinition.clear();
134 mOpenPackage.clear();
136 // Wx::DestroyTopWindow();
138 printf("EED Executer::Reset 01\n");
139 GetFactory()->Reset();
140 printf("EED Executer::Reset 02\n");
142 printf("EED Executer::Reset 03\n");
143 Wx::ProcessPendingEvents();
145 printf("EED Executer::Reset 04\n");
148 // Create user package
150 Package::New("user","internal","User defined black boxes","");
151 // Insert the user package in the factory
152 printf("EED Executer::Reset 1\n");
153 GetFactory()->InsertPackage(p);
154 // And in the list of open packages
155 mOpenPackage.push_back(p);
158 // Create user workspace
159 ComplexBlackBoxDescriptor::Pointer r =
160 ComplexBlackBoxDescriptor::New("workspace");
161 // mRootCBB->Reference();
162 printf("EED Executer::Reset 2\n");
163 r->SetFactory(GetFactory());
164 r->AddToAuthor("bbtk");
165 r->AddToDescription("User's workspace");
166 mOpenDefinition.push_back(CBBDefinition(r,"user"));
167 // Register it into the user package
171 // Object::PrintObjectListInfo();
172 // GetFactory()->CheckPackages();
173 bbtkDebugMessage("kernel",9,"<== Executer::Reset()" <<std::endl);
174 printf("EED Executer::Reset End\n");
176 //=======================================================================
179 //=======================================================================
180 /// changes the workspace name
181 void Executer::SetWorkspaceName( const std::string& n )
183 GetUserPackage()->ChangeDescriptorName( GetWorkspace()->GetTypeName(), n );
185 //=======================================================================
187 //=======================================================================
188 void Executer::BeginPackage (const std::string &name)
190 bbtkDebugMessage("kernel",9,"==> Executer::BeginPackage(\""<<name<<"\")"
195 p = GetFactory()->GetPackage(name);
199 p = Package::New(name,"","","");
200 GetFactory()->InsertPackage(p);
202 mOpenPackage.push_back(p);
204 bbtkDebugMessage("kernel",9,"<== Executer::BeginPackage(\""<<name<<"\")"
207 //=======================================================================
209 //=======================================================================
210 void Executer::EndPackage()
212 if (mOpenPackage.size()>1) mOpenPackage.pop_back();
214 //=======================================================================
216 //=======================================================================
217 void Executer::Define (const std::string &name,
218 const std::string &pack,
219 const std::string &scriptfilename)
221 bbtkDebugMessage("kernel",9,"==> Executer::Define(\""<<name<<
225 ComplexBlackBoxDescriptor::Pointer b
226 = ComplexBlackBoxDescriptor::New(name);
227 b->SetFactory(GetFactory());
228 b->SetScriptFileName(scriptfilename);
229 mOpenDefinition.push_back( CBBDefinition( b, pack ) );
231 bbtkDebugMessage("kernel",9,"<== Executer::Define(\""<<name<<
235 //=======================================================================
237 //=======================================================================
238 /// Sets the file name to use for the current definition
239 /// (Used to set it after the Define command)
240 void Executer::SetCurrentFileName (const std::string &name )
242 mOpenDefinition.back().box->SetScriptFileName(name);
244 //=======================================================================
246 void Executer::SetTypeOfScript_Application ()
248 mOpenDefinition.back().box->SetTypeOfScript_Application();
253 //=======================================================================
254 void Executer::Clear()
256 bbtkDebugMessage("kernel",9,"==> Executer::Clear()" <<std::endl);
257 GetCurrentDescriptor()->GetPrototype()->Clear();
258 bbtkDebugMessage("kernel",9,"<== Executer::Clear()" <<std::endl);
260 //=======================================================================
262 //=======================================================================
263 void Executer::EndDefine ()
265 bbtkDebugMessage("kernel",9,"==> Executer::EndDefine(\""
266 <<GetCurrentDescriptor()->GetTypeName()<<"\")"
268 // Does current package exist ?
270 std::string pname(mOpenDefinition.back().package);
275 p = GetFactory()->GetPackage(pname);
279 p = Package::New(pname,"","","");
280 GetFactory()->InsertPackage(p);
285 p = mOpenPackage.back().lock();
287 // Register the descriptor in the current package
288 p->Register(GetCurrentDescriptor());
290 bbtkDebugMessage("kernel",9,"<== Executer::EndDefine(\""
291 <<GetCurrentDescriptor()->GetTypeName()<<"\")"
293 mOpenDefinition.pop_back();
295 //=======================================================================
297 //=======================================================================
298 void Executer::Kind(const std::string& kind)
302 GetCurrentDescriptor()->AddToCategory("adaptor");
303 GetCurrentDescriptor()->SetKind(bbtk::BlackBoxDescriptor::ADAPTOR);
305 else if (kind=="DEFAULT_ADAPTOR")
307 GetCurrentDescriptor()->AddToCategory("adaptor");
308 GetCurrentDescriptor()->SetKind(bbtk::BlackBoxDescriptor::DEFAULT_ADAPTOR);
312 GetCurrentDescriptor()->AddToCategory("gui");
313 GetCurrentDescriptor()->SetKind(bbtk::BlackBoxDescriptor::GUI);
315 else if (kind=="DEFAULT_GUI")
317 GetCurrentDescriptor()->AddToCategory("gui");
318 GetCurrentDescriptor()->SetKind(bbtk::BlackBoxDescriptor::DEFAULT_GUI);
322 bbtkError("Unknown box kind : '"<<kind<<"'. "
323 <<"Valid kinds are 'ADAPTOR','DEFAULT_ADAPTOR',"
324 <<"'GUI','DEFAULT_GUI'");
327 //=======================================================================
329 //=======================================================================
330 void Executer::Create ( const std::string& nodeType,
331 const std::string& nodeName)
333 GetCurrentDescriptor()->Add(nodeType,nodeName);
335 //=======================================================================
337 //=======================================================================
338 void Executer::Destroy(const std::string &boxName)
340 GetCurrentDescriptor()->Remove(boxName,true);
342 //=======================================================================
344 //=======================================================================
345 void Executer::Connect (const std::string &nodeFrom,
346 const std::string &outputLabel,
347 const std::string &nodeTo,
348 const std::string &inputLabel)
350 GetCurrentDescriptor()->Connect(nodeFrom, outputLabel, nodeTo, inputLabel);
352 //=======================================================================
354 //=======================================================================
355 void Executer::Execute (const std::string &nodeName)
358 if (GetCurrentDescriptor()==GetWorkspace())
362 GetCurrentDescriptor()->GetPrototype()->bbGetBlackBox(nodeName)->bbExecute(true);
367 GetCurrentDescriptor()->AddToExecutionList(nodeName) ;
370 //=======================================================================
372 //=======================================================================
373 void Executer::DefineInput ( const std::string &name,
374 const std::string &box,
375 const std::string &input,
376 const std::string& help)
378 // If the input is defined in the Root box
379 if (GetCurrentDescriptor()==GetWorkspace())
381 // If the dialog mode is set to NoDialog
382 // and the user passed the name in the Inputs map
383 // then the associated value is set to the box.input
384 // This is the way command line parameters are passed to the Root box
385 if (mDialogMode == NoDialog)
387 // find if name is in mInputs
388 std::map<std::string,std::string>::iterator i;
389 i = mInputs.find(name);
390 if (i!=mInputs.end()) {
391 Set(box,input,(*i).second);
394 // If the dialog mode is set to TextDialog
395 // The user is prompted for the value
396 else if (mDialogMode == TextDialog)
398 std::cout << name << "=";
404 // If the dialog mode is set to GraphicalDialog
405 // A dialog box is pop up
406 else if (mDialogMode == GraphicalDialog)
408 std::string mess("Enter the value of '");
413 std::string title(name);
415 std::string ans = wx2std ( wxGetTextFromUser( std2wx (mess), std2wx(title)));
421 GetCurrentDescriptor()->DefineInput(name,box,input,help);
424 //=======================================================================
426 //=======================================================================
427 void Executer::DefineOutput ( const std::string &name,
428 const std::string &box,
429 const std::string &output,
430 const std::string& help)
432 GetCurrentDescriptor()->DefineOutput(name,box,output,help);
434 //=======================================================================
436 //=======================================================================
437 void Executer::Set (const std::string &box,
438 const std::string &input,
439 const std::string &value)
441 BlackBox::Pointer b = GetCurrentDescriptor()->GetPrototype()->bbGetBlackBox(box);
442 // Looks for the adaptor
444 if ( ( b->bbGetInputType(input) != typeid(bbtk::any<bbtk::thing>) )&&
445 ( b->bbGetInputType(input) != typeid(std::string) ) )
447 BlackBox::Pointer a =
448 GetFactory()->NewAdaptor(typeid(std::string),
449 b->bbGetInputType(input),
454 TypeName(b->bbGetInputType(input))
455 <<"> to <std::string> found");
457 std::string v(value);
458 a->bbSetInput("In",v);
460 b->bbSetInput(input,a->bbGetOutput("Out"));
465 std::string v(value);
466 b->bbSetInput(input,v);
469 //=======================================================================
471 //=======================================================================
472 std::string Executer::Get(const std::string &box,
473 const std::string &output)
475 BlackBox::Pointer b = GetCurrentDescriptor()->GetPrototype()->bbGetBlackBox(box);
476 // Looks for the adaptor
477 if (b->bbGetOutputType(output) != typeid(std::string))
479 BlackBox::Pointer a =
480 GetFactory()->NewAdaptor(
481 b->bbGetOutputType(output),
487 TypeName(b->bbGetOutputType(output))
488 <<"> to <std::string> found");
492 a->bbSetInput("In",b->bbGetOutput(output));
494 std::string r = a->bbGetOutput("Out").unsafe_get<std::string>();
495 //std::string v = *((std::string*)a->bbGetOutput("Out")) ;
496 // std::cout << a->bbGetOutput("Out").unsafe_get<std::string>()
498 //std::string v(value);
499 //b->bbSetInput(input,a->bbGetOutput("Out"));
506 return b->bbGetOutput(output).unsafe_get<std::string>();
507 // std::string v = *((std::string*)b->bbGetOutput(output)) ;
508 // std::cout << b->bbGetOutput("Out").unsafe_get<std::string>()
510 // b->bbSetInput(input,&v);
513 //=======================================================================
515 //=======================================================================
516 void Executer::Author(const std::string &authorName)
518 GetCurrentDescriptor()->AddToAuthor(authorName,GetCurrentDescriptor()==GetWorkspace());
520 //=======================================================================
522 //=======================================================================
523 void Executer::Category(const std::string &category)
525 GetCurrentDescriptor()->AddToCategory(category,GetCurrentDescriptor()==GetWorkspace());
527 //=======================================================================
529 //=======================================================================
530 void Executer::Description(const std::string &d)
532 GetCurrentDescriptor()->AddToDescription(d,GetCurrentDescriptor()==GetWorkspace());
534 //=======================================================================
538 //=======================================================================
539 /// prints the list of the boxes of the current descriptor
540 void Executer::PrintHelpListBoxes()
542 bbtkMessage("help",1,"The black box descriptor \""
543 <<GetCurrentDescriptor()->GetTypeName()<<"\" contains : "<<std::endl);
544 GetCurrentDescriptor()->PrintBlackBoxes();
546 //=======================================================================
548 //=======================================================================
549 std::string Executer::ShowGraph(const std::string &nameblackbox,
550 const std::string &detailStr,
551 const std::string &levelStr,
552 const std::string &output_html,
553 const std::string &custom_header,
554 const std::string &custom_title,
555 bool system_display )
557 int detail = atoi(detailStr.c_str());
558 int level = atoi(levelStr.c_str());
559 bool relative_link = true;
564 p = GetFactory()->GetPackage(nameblackbox);
568 p = GetUserPackage();
571 std::string doc_path = bbtk::ConfigurationFile::GetInstance().Get_doc_path();
572 doc_path += bbtk::ConfigurationFile::GetInstance().Get_file_separator();
574 doc_path += bbtk::ConfigurationFile::GetInstance().Get_file_separator();
576 std::string pack_name(p->GetName());
577 std::string pack_path = doc_path + pack_name;
578 // Creating directory
579 if ( ! bbtk::Utilities::FileExists(pack_path) )
581 std::string command("mkdir \"" +pack_path+ "\"");
582 system( command.c_str() );
584 std::string pack_index(pack_path);
585 pack_index += bbtk::ConfigurationFile::GetInstance().Get_file_separator();
586 pack_index += "index.html";
589 // Generating documentation-help of workspace
590 p->SetDocURL(pack_index);
591 p->SetDocRelativeURL("index.html");
592 p->CreateHtmlPage(pack_index,"bbtk","user package",custom_header,custom_title,detail,level,relative_link);
597 ShowGraphTypes(nameblackbox);
599 catch (bbtk::Exception a)
601 std::cout <<"EXC"<<std::endl;
602 page = ShowGraphInstances(nameblackbox,detail,level,system_display);
607 //=======================================================================
609 //=======================================================================
610 /// Generate a png file with the actual pipeline (Graphviz-dot needed)
611 std::string Executer::ShowGraphInstances(const std::string &nameblackbox, int detail, int level,
615 BlackBox::Pointer blackbox;
616 if (nameblackbox==".")
618 blackbox = GetCurrentDescriptor()->GetPrototype();
622 blackbox = GetCurrentDescriptor()->GetPrototype()->bbFindBlackBox(nameblackbox);
629 // Don't pollute the file store with "temp_dir" directories ...
630 std::string default_doc_dir = ConfigurationFile::GetInstance().Get_default_temp_dir();
631 char c = default_doc_dir.c_str()[strlen(default_doc_dir.c_str())-1];
633 std::string directory = default_doc_dir;
634 if (c != '/' && c !='\\') directory = directory + "/";
636 directory = directory + "temp_dir";
637 //std::string directory("temp_dir");
638 std::string filename(directory + "/" + "bbtk_graph_pipeline");
639 std::string filename_html(filename+".html");
640 std::string command0("mkdir \""+directory + "\"");
643 std::string command2("start ");
645 std::string command2("gnome-open ");
648 command2=command2+filename_html;
649 page = filename_html;
650 // 1. Generate Html Diagram
652 s.open(filename_html.c_str());
655 s << "<html><head><title>BBtk graph diagram</title><meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\"></head>\n";
656 s << "<body bgcolor=\"#FFFFFF\" text=\"#000000\"> \n\n";
657 if ( blackbox->bbGetName()=="workspacePrototype" )
659 s << "<center>Current workspace</center>";
661 s << "<center>" << blackbox->bbGetName()<< "</center>";
663 blackbox->bbInsertHTMLGraph( s, detail, level, true, directory, false );
664 s << "</body></html>\n";
668 // 2. Starting Browser
669 if (system_display) system( command2.c_str() );
673 bbtkMessage("help",1,"No black box: \""
674 <<nameblackbox<<"\" " <<std::endl);
678 //=======================================================================
680 //=======================================================================
681 void Executer::PrintHelpBlackBox(const std::string &nameblackbox,
682 const std::string &detailStr,
683 const std::string &levelStr)
687 int detail = atoi(detailStr.c_str());
688 int level = atoi(levelStr.c_str());
689 BlackBox::Pointer blackbox;
690 if (nameblackbox.compare(".")==0)
692 blackbox=GetCurrentDescriptor()->GetPrototype();
696 blackbox = GetCurrentDescriptor()->GetPrototype()->bbFindBlackBox(nameblackbox);
702 blackbox->bbPrintHelp(blackbox,detail,level); //,mFactory);
707 bbtkError("box with name '" <<nameblackbox<<"' unknown");
710 //=======================================================================
712 //=======================================================================
713 /// sets the level of message
714 void Executer::SetMessageLevel(const std::string &kind,
717 bbtk::MessageManager::SetMessageLevel(kind,level);
719 //=======================================================================
721 //=======================================================================
722 /// Prints help on the messages
723 void Executer::HelpMessages()
725 bbtk::MessageManager::PrintInfo();
727 //=======================================================================
729 //=======================================================================
731 void Executer::Print(const std::string &str)
733 if (GetNoExecMode() && (GetCurrentDescriptor()==GetWorkspace()) ) return;
734 if (GetCurrentDescriptor()!=GetWorkspace()) return;
736 bbtkDebugMessage("kernel",9,"Executer::Print(\""<<str<<"\")"<<std::endl);
739 // InterpretLine ("load std")
740 // InterpretLine("new ConcatStrings _C_ ") -> trouver un nom unique : # commande
741 // InterpretLine("new Print _P_")
742 // InterpretLine("connect _C_.Out _P_.In")
746 std::vector<std::string> chains;
747 std::string delimiters("$");
749 // Skip delimiters at beginning.
750 std::string::size_type lastPos = str.find_first_not_of(delimiters, 0);
752 if (lastPos>0) is_text = false;
754 // Find first delimiter.
755 std::string::size_type pos = str.find_first_of(delimiters, lastPos);
757 while (std::string::npos != pos || std::string::npos != lastPos)
761 // Found a text token, add it to the vector.
762 chains.push_back(str.substr(lastPos, pos - lastPos));
763 // std::string token = str.substr(lastPos, pos - lastPos)
764 // InterpretLine("set _C_.In%num% %token%")
770 // is an output (between $$) : decode
771 std::string tok,box,output;
772 tok = str.substr(lastPos, pos - lastPos);
773 Utilities::SplitAroundFirstDot(tok,box,output);
774 chains.push_back( Get(box,output) );
776 // InterpretLine("connect %tok% _C_.In%num%")
779 // Skip delimiters. Note the "not_of"
780 lastPos = str.find_first_not_of(delimiters, pos);
781 // Find next delimiter
782 pos = str.find_first_of(delimiters, lastPos);
787 // InterpretLine("exec _P_")
788 // if (IS_IN_WORKSPACE) InterpretLine("delete _C_; delete _P_");
790 std::vector<std::string>::iterator i;
791 for (i= chains.begin(); i!=chains.end(); ++i)
793 Utilities::SubsBackslashN(*i);
794 bbtkMessage("output",1,*i);
796 bbtkMessage("output",1,std::endl);
798 //==========================================================================
800 //==========================================================================
801 std::string Executer::GetObjectName() const
803 return std::string("Executer");
805 //==========================================================================
807 //==========================================================================
808 std::string Executer::GetObjectInfo() const
813 //==========================================================================
814 //==========================================================================
815 size_t Executer::GetObjectSize() const
817 size_t s = Superclass::GetObjectSize();
818 s += Executer::GetObjectInternalSize();
821 //==========================================================================
822 //==========================================================================
823 size_t Executer::GetObjectInternalSize() const
825 size_t s = sizeof(Executer);
828 //==========================================================================
829 //==========================================================================
830 size_t Executer::GetObjectRecursiveSize() const
832 size_t s = Superclass::GetObjectRecursiveSize();
833 s += Executer::GetObjectInternalSize();
834 s += mFactory->GetObjectRecursiveSize();
837 //==========================================================================