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();
136 // Create user package
138 Package::New("user","internal","User defined black boxes","");
139 // Insert the user package in the factory
140 GetFactory()->InsertPackage(p);
141 // And in the list of open packages
142 mOpenPackage.push_back(p);
145 // Create user workspace
146 ComplexBlackBoxDescriptor::Pointer r =
147 ComplexBlackBoxDescriptor::New("workspace");
148 // mRootCBB->Reference();
149 r->SetFactory(GetFactory());
150 r->AddToAuthor("bbtk");
151 r->AddToDescription("User's workspace");
152 mOpenDefinition.push_back(CBBDefinition(r,"user"));
153 // Register it into the user package
157 // Object::PrintObjectListInfo();
158 // GetFactory()->CheckPackages();
159 bbtkDebugMessage("kernel",9,"<== Executer::Reset()" <<std::endl);
161 //=======================================================================
164 //=======================================================================
165 /// changes the workspace name
166 void Executer::SetWorkspaceName( const std::string& n )
168 GetUserPackage()->ChangeDescriptorName( GetWorkspace()->GetTypeName(), n );
170 //=======================================================================
172 //=======================================================================
173 void Executer::BeginPackage (const std::string &name)
175 bbtkDebugMessage("kernel",9,"==> Executer::BeginPackage(\""<<name<<"\")"
180 p = GetFactory()->GetPackage(name);
184 p = Package::New(name,"","","");
185 GetFactory()->InsertPackage(p);
187 mOpenPackage.push_back(p);
189 bbtkDebugMessage("kernel",9,"<== Executer::BeginPackage(\""<<name<<"\")"
192 //=======================================================================
194 //=======================================================================
195 void Executer::EndPackage()
197 if (mOpenPackage.size()>1) mOpenPackage.pop_back();
199 //=======================================================================
201 //=======================================================================
202 void Executer::Define (const std::string &name,
203 const std::string &pack,
204 const std::string &scriptfilename)
206 bbtkDebugMessage("kernel",9,"==> Executer::Define(\""<<name<<
210 ComplexBlackBoxDescriptor::Pointer b
211 = ComplexBlackBoxDescriptor::New(name);
212 b->SetFactory(GetFactory());
213 b->SetScriptFileName(scriptfilename);
214 mOpenDefinition.push_back( CBBDefinition( b, pack ) );
216 bbtkDebugMessage("kernel",9,"<== Executer::Define(\""<<name<<
220 //=======================================================================
222 //=======================================================================
223 /// Sets the file name to use for the current definition
224 /// (Used to set it after the Define command)
225 void Executer::SetCurrentFileName (const std::string &name )
227 mOpenDefinition.back().box->SetScriptFileName(name);
229 //=======================================================================
231 void Executer::SetTypeOfScript_Application ()
233 mOpenDefinition.back().box->SetTypeOfScript_Application();
238 //=======================================================================
239 void Executer::Clear()
241 bbtkDebugMessage("kernel",9,"==> Executer::Clear()" <<std::endl);
242 GetCurrentDescriptor()->GetPrototype()->Clear();
243 bbtkDebugMessage("kernel",9,"<== Executer::Clear()" <<std::endl);
245 //=======================================================================
247 //=======================================================================
248 void Executer::EndDefine ()
250 bbtkDebugMessage("kernel",9,"==> Executer::EndDefine(\""
251 <<GetCurrentDescriptor()->GetTypeName()<<"\")"
253 // Does current package exist ?
255 std::string pname(mOpenDefinition.back().package);
260 p = GetFactory()->GetPackage(pname);
264 p = Package::New(pname,"","","");
265 GetFactory()->InsertPackage(p);
270 p = mOpenPackage.back().lock();
272 // Register the descriptor in the current package
273 p->Register(GetCurrentDescriptor());
275 bbtkDebugMessage("kernel",9,"<== Executer::EndDefine(\""
276 <<GetCurrentDescriptor()->GetTypeName()<<"\")"
278 mOpenDefinition.pop_back();
280 //=======================================================================
282 //=======================================================================
283 void Executer::Kind(const std::string& kind)
287 GetCurrentDescriptor()->AddToCategory("adaptor");
288 GetCurrentDescriptor()->SetKind(bbtk::BlackBoxDescriptor::ADAPTOR);
290 else if (kind=="DEFAULT_ADAPTOR")
292 GetCurrentDescriptor()->AddToCategory("adaptor");
293 GetCurrentDescriptor()->SetKind(bbtk::BlackBoxDescriptor::DEFAULT_ADAPTOR);
297 GetCurrentDescriptor()->AddToCategory("gui");
298 GetCurrentDescriptor()->SetKind(bbtk::BlackBoxDescriptor::GUI);
300 else if (kind=="DEFAULT_GUI")
302 GetCurrentDescriptor()->AddToCategory("gui");
303 GetCurrentDescriptor()->SetKind(bbtk::BlackBoxDescriptor::DEFAULT_GUI);
307 bbtkError("Unknown box kind : '"<<kind<<"'. "
308 <<"Valid kinds are 'ADAPTOR','DEFAULT_ADAPTOR',"
309 <<"'GUI','DEFAULT_GUI'");
312 //=======================================================================
314 //=======================================================================
315 void Executer::Create ( const std::string& nodeType,
316 const std::string& nodeName)
318 GetCurrentDescriptor()->Add(nodeType,nodeName);
320 //=======================================================================
322 //=======================================================================
323 void Executer::Destroy(const std::string &boxName)
325 GetCurrentDescriptor()->Remove(boxName,true);
327 //=======================================================================
329 //=======================================================================
330 void Executer::Connect (const std::string &nodeFrom,
331 const std::string &outputLabel,
332 const std::string &nodeTo,
333 const std::string &inputLabel)
335 GetCurrentDescriptor()->Connect(nodeFrom, outputLabel, nodeTo, inputLabel);
337 //=======================================================================
339 //=======================================================================
340 void Executer::Execute (const std::string &nodeName)
343 if (GetCurrentDescriptor()==GetWorkspace())
347 GetCurrentDescriptor()->GetPrototype()->bbGetBlackBox(nodeName)->bbExecute(true);
352 GetCurrentDescriptor()->AddToExecutionList(nodeName) ;
355 //=======================================================================
357 //=======================================================================
358 void Executer::DefineInput ( const std::string &name,
359 const std::string &box,
360 const std::string &input,
361 const std::string& help)
363 // If the input is defined in the Root box
364 if (GetCurrentDescriptor()==GetWorkspace())
366 // If the dialog mode is set to NoDialog
367 // and the user passed the name in the Inputs map
368 // then the associated value is set to the box.input
369 // This is the way command line parameters are passed to the Root box
370 if (mDialogMode == NoDialog)
372 // find if name is in mInputs
373 std::map<std::string,std::string>::iterator i;
374 i = mInputs.find(name);
375 if (i!=mInputs.end()) {
376 Set(box,input,(*i).second);
379 // If the dialog mode is set to TextDialog
380 // The user is prompted for the value
381 else if (mDialogMode == TextDialog)
383 std::cout << name << "=";
389 // If the dialog mode is set to GraphicalDialog
390 // A dialog box is pop up
391 else if (mDialogMode == GraphicalDialog)
393 std::string mess("Enter the value of '");
398 std::string title(name);
400 std::string ans = wx2std ( wxGetTextFromUser( std2wx (mess), std2wx(title)));
406 GetCurrentDescriptor()->DefineInput(name,box,input,help);
409 //=======================================================================
411 //=======================================================================
412 void Executer::DefineOutput ( const std::string &name,
413 const std::string &box,
414 const std::string &output,
415 const std::string& help)
417 GetCurrentDescriptor()->DefineOutput(name,box,output,help);
419 //=======================================================================
421 //=======================================================================
422 void Executer::Set (const std::string &box,
423 const std::string &input,
424 const std::string &value)
426 BlackBox::Pointer b = GetCurrentDescriptor()->GetPrototype()->bbGetBlackBox(box);
427 // Looks for the adaptor
429 if ( ( b->bbGetInputType(input) != typeid(bbtk::any<bbtk::thing>) )&&
430 ( b->bbGetInputType(input) != typeid(std::string) ) )
432 BlackBox::Pointer a =
433 GetFactory()->NewAdaptor(typeid(std::string),
434 b->bbGetInputType(input),
439 TypeName(b->bbGetInputType(input))
440 <<"> to <std::string> found");
442 std::string v(value);
443 a->bbSetInput("In",v);
445 b->bbSetInput(input,a->bbGetOutput("Out"));
450 std::string v(value);
451 b->bbSetInput(input,v);
454 //=======================================================================
456 //=======================================================================
457 std::string Executer::Get(const std::string &box,
458 const std::string &output)
460 BlackBox::Pointer b = GetCurrentDescriptor()->GetPrototype()->bbGetBlackBox(box);
461 // Looks for the adaptor
462 if (b->bbGetOutputType(output) != typeid(std::string))
464 BlackBox::Pointer a =
465 GetFactory()->NewAdaptor(
466 b->bbGetOutputType(output),
472 TypeName(b->bbGetOutputType(output))
473 <<"> to <std::string> found");
477 a->bbSetInput("In",b->bbGetOutput(output));
479 std::string r = a->bbGetOutput("Out").unsafe_get<std::string>();
480 //std::string v = *((std::string*)a->bbGetOutput("Out")) ;
481 // std::cout << a->bbGetOutput("Out").unsafe_get<std::string>()
483 //std::string v(value);
484 //b->bbSetInput(input,a->bbGetOutput("Out"));
491 return b->bbGetOutput(output).unsafe_get<std::string>();
492 // std::string v = *((std::string*)b->bbGetOutput(output)) ;
493 // std::cout << b->bbGetOutput("Out").unsafe_get<std::string>()
495 // b->bbSetInput(input,&v);
498 //=======================================================================
500 //=======================================================================
501 void Executer::Author(const std::string &authorName)
503 GetCurrentDescriptor()->AddToAuthor(authorName,GetCurrentDescriptor()==GetWorkspace());
505 //=======================================================================
507 //=======================================================================
508 void Executer::Category(const std::string &category)
510 GetCurrentDescriptor()->AddToCategory(category,GetCurrentDescriptor()==GetWorkspace());
512 //=======================================================================
514 //=======================================================================
515 void Executer::Description(const std::string &d)
517 GetCurrentDescriptor()->AddToDescription(d,GetCurrentDescriptor()==GetWorkspace());
519 //=======================================================================
523 //=======================================================================
524 /// prints the list of the boxes of the current descriptor
525 void Executer::PrintHelpListBoxes()
527 bbtkMessage("help",1,"The black box descriptor \""
528 <<GetCurrentDescriptor()->GetTypeName()<<"\" contains : "<<std::endl);
529 GetCurrentDescriptor()->PrintBlackBoxes();
531 //=======================================================================
533 //=======================================================================
534 std::string Executer::ShowGraph(const std::string &nameblackbox,
535 const std::string &detailStr,
536 const std::string &levelStr,
537 const std::string &output_html,
538 const std::string &custom_header,
539 const std::string &custom_title,
540 bool system_display )
542 int detail = atoi(detailStr.c_str());
543 int level = atoi(levelStr.c_str());
544 bool relative_link = true;
549 p = GetFactory()->GetPackage(nameblackbox);
553 p = GetUserPackage();
556 std::string doc_path = bbtk::ConfigurationFile::GetInstance().Get_doc_path();
557 doc_path += bbtk::ConfigurationFile::GetInstance().Get_file_separator();
559 doc_path += bbtk::ConfigurationFile::GetInstance().Get_file_separator();
561 std::string pack_name(p->GetName());
562 std::string pack_path = doc_path + pack_name;
563 // Creating directory
564 if ( ! bbtk::Utilities::FileExists(pack_path) )
566 std::string command("mkdir \"" +pack_path+ "\"");
567 system( command.c_str() );
569 std::string pack_index(pack_path);
570 pack_index += bbtk::ConfigurationFile::GetInstance().Get_file_separator();
571 pack_index += "index.html";
574 // Generating documentation-help of workspace
575 p->SetDocURL(pack_index);
576 p->SetDocRelativeURL("index.html");
577 p->CreateHtmlPage(pack_index,"bbtk","user package",custom_header,custom_title,detail,level,relative_link);
582 ShowGraphTypes(nameblackbox);
584 catch (bbtk::Exception a)
586 std::cout <<"EXC"<<std::endl;
587 page = ShowGraphInstances(nameblackbox,detail,level,system_display);
592 //=======================================================================
594 //=======================================================================
595 /// Generate a png file with the actual pipeline (Graphviz-dot needed)
596 std::string Executer::ShowGraphInstances(const std::string &nameblackbox, int detail, int level,
600 BlackBox::Pointer blackbox;
601 if (nameblackbox==".")
603 blackbox = GetCurrentDescriptor()->GetPrototype();
607 blackbox = GetCurrentDescriptor()->GetPrototype()->bbFindBlackBox(nameblackbox);
614 // Don't pollute the file store with "temp_dir" directories ...
615 std::string default_doc_dir = ConfigurationFile::GetInstance().Get_default_temp_dir();
616 char c = default_doc_dir.c_str()[strlen(default_doc_dir.c_str())-1];
618 std::string directory = default_doc_dir;
619 if (c != '/' && c !='\\') directory = directory + "/";
621 directory = directory + "temp_dir";
622 //std::string directory("temp_dir");
623 std::string filename(directory + "/" + "bbtk_graph_pipeline");
624 std::string filename_html(filename+".html");
625 std::string command0("mkdir \""+directory + "\"");
628 std::string command2("start ");
630 std::string command2("gnome-open ");
633 command2=command2+filename_html;
634 page = filename_html;
635 // 1. Generate Html Diagram
637 s.open(filename_html.c_str());
640 s << "<html><head><title>BBtk graph diagram</title><meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\"></head>\n";
641 s << "<body bgcolor=\"#FFFFFF\" text=\"#000000\"> \n\n";
642 if ( blackbox->bbGetName()=="workspacePrototype" )
644 s << "<center>Current workspace</center>";
646 s << "<center>" << blackbox->bbGetName()<< "</center>";
648 blackbox->bbInsertHTMLGraph( s, detail, level, true, directory, false );
649 s << "</body></html>\n";
653 // 2. Starting Browser
654 if (system_display) system( command2.c_str() );
658 bbtkMessage("help",1,"No black box: \""
659 <<nameblackbox<<"\" " <<std::endl);
663 //=======================================================================
665 //=======================================================================
666 void Executer::PrintHelpBlackBox(const std::string &nameblackbox,
667 const std::string &detailStr,
668 const std::string &levelStr)
672 int detail = atoi(detailStr.c_str());
673 int level = atoi(levelStr.c_str());
674 BlackBox::Pointer blackbox;
675 if (nameblackbox.compare(".")==0)
677 blackbox=GetCurrentDescriptor()->GetPrototype();
681 blackbox = GetCurrentDescriptor()->GetPrototype()->bbFindBlackBox(nameblackbox);
687 blackbox->bbPrintHelp(blackbox,detail,level); //,mFactory);
692 bbtkError("box with name '" <<nameblackbox<<"' unknown");
695 //=======================================================================
697 //=======================================================================
698 /// sets the level of message
699 void Executer::SetMessageLevel(const std::string &kind,
702 bbtk::MessageManager::SetMessageLevel(kind,level);
704 //=======================================================================
706 //=======================================================================
707 /// Prints help on the messages
708 void Executer::HelpMessages()
710 bbtk::MessageManager::PrintInfo();
712 //=======================================================================
714 //=======================================================================
716 void Executer::Print(const std::string &str)
718 if (GetNoExecMode() && (GetCurrentDescriptor()==GetWorkspace()) ) return;
719 if (GetCurrentDescriptor()!=GetWorkspace()) return;
721 bbtkDebugMessage("kernel",9,"Executer::Print(\""<<str<<"\")"<<std::endl);
724 // InterpretLine ("load std")
725 // InterpretLine("new ConcatStrings _C_ ") -> trouver un nom unique : # commande
726 // InterpretLine("new Print _P_")
727 // InterpretLine("connect _C_.Out _P_.In")
731 std::vector<std::string> chains;
732 std::string delimiters("$");
734 // Skip delimiters at beginning.
735 std::string::size_type lastPos = str.find_first_not_of(delimiters, 0);
737 if (lastPos>0) is_text = false;
739 // Find first delimiter.
740 std::string::size_type pos = str.find_first_of(delimiters, lastPos);
742 while (std::string::npos != pos || std::string::npos != lastPos)
746 // Found a text token, add it to the vector.
747 chains.push_back(str.substr(lastPos, pos - lastPos));
748 // std::string token = str.substr(lastPos, pos - lastPos)
749 // InterpretLine("set _C_.In%num% %token%")
755 // is an output (between $$) : decode
756 std::string tok,box,output;
757 tok = str.substr(lastPos, pos - lastPos);
758 Utilities::SplitAroundFirstDot(tok,box,output);
759 chains.push_back( Get(box,output) );
761 // InterpretLine("connect %tok% _C_.In%num%")
764 // Skip delimiters. Note the "not_of"
765 lastPos = str.find_first_not_of(delimiters, pos);
766 // Find next delimiter
767 pos = str.find_first_of(delimiters, lastPos);
772 // InterpretLine("exec _P_")
773 // if (IS_IN_WORKSPACE) InterpretLine("delete _C_; delete _P_");
775 std::vector<std::string>::iterator i;
776 for (i= chains.begin(); i!=chains.end(); ++i)
778 Utilities::SubsBackslashN(*i);
779 bbtkMessage("output",1,*i);
781 bbtkMessage("output",1,std::endl);
783 //==========================================================================
785 //==========================================================================
786 std::string Executer::GetObjectName() const
788 return std::string("Executer");
790 //==========================================================================
792 //==========================================================================
793 std::string Executer::GetObjectInfo() const
798 //==========================================================================
799 //==========================================================================
800 size_t Executer::GetObjectSize() const
802 size_t s = Superclass::GetObjectSize();
803 s += Executer::GetObjectInternalSize();
806 //==========================================================================
807 //==========================================================================
808 size_t Executer::GetObjectInternalSize() const
810 size_t s = sizeof(Executer);
813 //==========================================================================
814 //==========================================================================
815 size_t Executer::GetObjectRecursiveSize() const
817 size_t s = Superclass::GetObjectRecursiveSize();
818 s += Executer::GetObjectInternalSize();
819 s += mFactory->GetObjectRecursiveSize();
822 //==========================================================================