1 /*=========================================================================
3 Module: $RCSfile: bbtkExecuter.cxx,v $
5 Date: $Date: 2012/11/14 07:12:00 $
6 Version: $Revision: 1.33 $
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 void Executer::SetTypeOfScript_Application ()
226 mOpenDefinition.back().box->SetTypeOfScript_Application();
231 //=======================================================================
232 void Executer::Clear()
234 bbtkDebugMessage("kernel",9,"==> Executer::Clear()" <<std::endl);
235 GetCurrentDescriptor()->GetPrototype()->Clear();
236 bbtkDebugMessage("kernel",9,"<== Executer::Clear()" <<std::endl);
238 //=======================================================================
240 //=======================================================================
241 void Executer::EndDefine ()
243 bbtkDebugMessage("kernel",9,"==> Executer::EndDefine(\""
244 <<GetCurrentDescriptor()->GetTypeName()<<"\")"
246 // Does current package exist ?
248 std::string pname(mOpenDefinition.back().package);
253 p = GetFactory()->GetPackage(pname);
257 p = Package::New(pname,"","","");
258 GetFactory()->InsertPackage(p);
263 p = mOpenPackage.back().lock();
265 // Register the descriptor in the current package
266 p->Register(GetCurrentDescriptor());
268 bbtkDebugMessage("kernel",9,"<== Executer::EndDefine(\""
269 <<GetCurrentDescriptor()->GetTypeName()<<"\")"
271 mOpenDefinition.pop_back();
273 //=======================================================================
275 //=======================================================================
276 void Executer::Kind(const std::string& kind)
280 GetCurrentDescriptor()->AddToCategory("adaptor");
281 GetCurrentDescriptor()->SetKind(bbtk::BlackBoxDescriptor::ADAPTOR);
283 else if (kind=="DEFAULT_ADAPTOR")
285 GetCurrentDescriptor()->AddToCategory("adaptor");
286 GetCurrentDescriptor()->SetKind(bbtk::BlackBoxDescriptor::DEFAULT_ADAPTOR);
290 GetCurrentDescriptor()->AddToCategory("gui");
291 GetCurrentDescriptor()->SetKind(bbtk::BlackBoxDescriptor::GUI);
293 else if (kind=="DEFAULT_GUI")
295 GetCurrentDescriptor()->AddToCategory("gui");
296 GetCurrentDescriptor()->SetKind(bbtk::BlackBoxDescriptor::DEFAULT_GUI);
300 bbtkError("Unknown box kind : '"<<kind<<"'. "
301 <<"Valid kinds are 'ADAPTOR','DEFAULT_ADAPTOR',"
302 <<"'GUI','DEFAULT_GUI'");
305 //=======================================================================
307 //=======================================================================
308 void Executer::Create ( const std::string& nodeType,
309 const std::string& nodeName)
311 GetCurrentDescriptor()->Add(nodeType,nodeName);
313 //=======================================================================
315 //=======================================================================
316 void Executer::Destroy(const std::string &boxName)
318 GetCurrentDescriptor()->Remove(boxName,true);
320 //=======================================================================
322 //=======================================================================
323 void Executer::Connect (const std::string &nodeFrom,
324 const std::string &outputLabel,
325 const std::string &nodeTo,
326 const std::string &inputLabel)
328 GetCurrentDescriptor()->Connect(nodeFrom, outputLabel, nodeTo, inputLabel);
330 //=======================================================================
332 //=======================================================================
333 void Executer::Execute (const std::string &nodeName)
336 if (GetCurrentDescriptor()==GetWorkspace())
340 GetCurrentDescriptor()->GetPrototype()->bbGetBlackBox(nodeName)->bbExecute(true);
345 GetCurrentDescriptor()->AddToExecutionList(nodeName) ;
348 //=======================================================================
350 //=======================================================================
351 void Executer::DefineInput ( const std::string &name,
352 const std::string &box,
353 const std::string &input,
354 const std::string& help)
356 // If the input is defined in the Root box
357 if (GetCurrentDescriptor()==GetWorkspace())
359 // If the dialog mode is set to NoDialog
360 // and the user passed the name in the Inputs map
361 // then the associated value is set to the box.input
362 // This is the way command line parameters are passed to the Root box
363 if (mDialogMode == NoDialog)
365 // find if name is in mInputs
366 std::map<std::string,std::string>::iterator i;
367 i = mInputs.find(name);
368 if (i!=mInputs.end()) {
369 Set(box,input,(*i).second);
372 // If the dialog mode is set to TextDialog
373 // The user is prompted for the value
374 else if (mDialogMode == TextDialog)
376 std::cout << name << "=";
382 // If the dialog mode is set to GraphicalDialog
383 // A dialog box is pop up
384 else if (mDialogMode == GraphicalDialog)
386 std::string mess("Enter the value of '");
391 std::string title(name);
393 std::string ans = wx2std ( wxGetTextFromUser( std2wx (mess), std2wx(title)));
399 GetCurrentDescriptor()->DefineInput(name,box,input,help);
402 //=======================================================================
404 //=======================================================================
405 void Executer::DefineOutput ( const std::string &name,
406 const std::string &box,
407 const std::string &output,
408 const std::string& help)
410 GetCurrentDescriptor()->DefineOutput(name,box,output,help);
412 //=======================================================================
414 //=======================================================================
415 void Executer::Set (const std::string &box,
416 const std::string &input,
417 const std::string &value)
419 BlackBox::Pointer b = GetCurrentDescriptor()->GetPrototype()->bbGetBlackBox(box);
420 // Looks for the adaptor
422 if ( ( b->bbGetInputType(input) != typeid(bbtk::any<bbtk::thing>) )&&
423 ( b->bbGetInputType(input) != typeid(std::string) ) )
425 BlackBox::Pointer a =
426 GetFactory()->NewAdaptor(typeid(std::string),
427 b->bbGetInputType(input),
432 TypeName(b->bbGetInputType(input))
433 <<"> to <std::string> found");
435 std::string v(value);
436 a->bbSetInput("In",v);
438 b->bbSetInput(input,a->bbGetOutput("Out"));
443 std::string v(value);
444 b->bbSetInput(input,v);
447 //=======================================================================
449 //=======================================================================
450 std::string Executer::Get(const std::string &box,
451 const std::string &output)
453 BlackBox::Pointer b = GetCurrentDescriptor()->GetPrototype()->bbGetBlackBox(box);
454 // Looks for the adaptor
455 if (b->bbGetOutputType(output) != typeid(std::string))
457 BlackBox::Pointer a =
458 GetFactory()->NewAdaptor(
459 b->bbGetOutputType(output),
465 TypeName(b->bbGetOutputType(output))
466 <<"> to <std::string> found");
470 a->bbSetInput("In",b->bbGetOutput(output));
472 std::string r = a->bbGetOutput("Out").unsafe_get<std::string>();
473 //std::string v = *((std::string*)a->bbGetOutput("Out")) ;
474 // std::cout << a->bbGetOutput("Out").unsafe_get<std::string>()
476 //std::string v(value);
477 //b->bbSetInput(input,a->bbGetOutput("Out"));
484 return b->bbGetOutput(output).unsafe_get<std::string>();
485 // std::string v = *((std::string*)b->bbGetOutput(output)) ;
486 // std::cout << b->bbGetOutput("Out").unsafe_get<std::string>()
488 // b->bbSetInput(input,&v);
491 //=======================================================================
493 //=======================================================================
494 void Executer::Author(const std::string &authorName)
496 GetCurrentDescriptor()->AddToAuthor(authorName,GetCurrentDescriptor()==GetWorkspace());
498 //=======================================================================
500 //=======================================================================
501 void Executer::Category(const std::string &category)
503 GetCurrentDescriptor()->AddToCategory(category,GetCurrentDescriptor()==GetWorkspace());
505 //=======================================================================
507 //=======================================================================
508 void Executer::Description(const std::string &d)
510 GetCurrentDescriptor()->AddToDescription(d,GetCurrentDescriptor()==GetWorkspace());
512 //=======================================================================
516 //=======================================================================
517 /// prints the list of the boxes of the current descriptor
518 void Executer::PrintHelpListBoxes()
520 bbtkMessage("help",1,"The black box descriptor \""
521 <<GetCurrentDescriptor()->GetTypeName()<<"\" contains : "<<std::endl);
522 GetCurrentDescriptor()->PrintBlackBoxes();
524 //=======================================================================
526 //=======================================================================
527 std::string Executer::ShowGraph(const std::string &nameblackbox,
528 const std::string &detailStr,
529 const std::string &levelStr,
530 const std::string &output_html,
531 const std::string &custom_header,
532 const std::string &custom_title,
533 bool system_display )
535 int detail = atoi(detailStr.c_str());
536 int level = atoi(levelStr.c_str());
537 bool relative_link = true;
542 p = GetFactory()->GetPackage(nameblackbox);
546 p = GetUserPackage();
549 std::string doc_path = bbtk::ConfigurationFile::GetInstance().Get_doc_path();
550 doc_path += bbtk::ConfigurationFile::GetInstance().Get_file_separator();
552 doc_path += bbtk::ConfigurationFile::GetInstance().Get_file_separator();
554 std::string pack_name(p->GetName());
555 std::string pack_path = doc_path + pack_name;
556 // Creating directory
557 if ( ! bbtk::Utilities::FileExists(pack_path) )
559 std::string command("mkdir \"" +pack_path+ "\"");
560 system( command.c_str() );
562 std::string pack_index(pack_path);
563 pack_index += bbtk::ConfigurationFile::GetInstance().Get_file_separator();
564 pack_index += "index.html";
567 // Generating documentation-help of workspace
568 p->SetDocURL(pack_index);
569 p->SetDocRelativeURL("index.html");
570 p->CreateHtmlPage(pack_index,"bbtk","user package",custom_header,custom_title,detail,level,relative_link);
575 ShowGraphTypes(nameblackbox);
577 catch (bbtk::Exception a)
579 std::cout <<"EXC"<<std::endl;
580 page = ShowGraphInstances(nameblackbox,detail,level,system_display);
585 //=======================================================================
587 //=======================================================================
588 /// Generate a png file with the actual pipeline (Graphviz-dot needed)
589 std::string Executer::ShowGraphInstances(const std::string &nameblackbox, int detail, int level,
593 BlackBox::Pointer blackbox;
594 if (nameblackbox==".")
596 blackbox = GetCurrentDescriptor()->GetPrototype();
600 blackbox = GetCurrentDescriptor()->GetPrototype()->bbFindBlackBox(nameblackbox);
607 // Don't pollute the file store with "temp_dir" directories ...
608 std::string default_doc_dir = ConfigurationFile::GetInstance().Get_default_temp_dir();
609 char c = default_doc_dir.c_str()[strlen(default_doc_dir.c_str())-1];
611 std::string directory = default_doc_dir;
612 if (c != '/' && c !='\\') directory = directory + "/";
614 directory = directory + "temp_dir";
615 //std::string directory("temp_dir");
616 std::string filename(directory + "/" + "bbtk_graph_pipeline");
617 std::string filename_html(filename+".html");
618 std::string command0("mkdir \""+directory + "\"");
621 std::string command2("start ");
623 std::string command2("gnome-open ");
626 command2=command2+filename_html;
627 page = filename_html;
628 // 1. Generate Html Diagram
630 s.open(filename_html.c_str());
633 s << "<html><head><title>BBtk graph diagram</title><meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\"></head>\n";
634 s << "<body bgcolor=\"#FFFFFF\" text=\"#000000\"> \n\n";
635 if ( blackbox->bbGetName()=="workspacePrototype" )
637 s << "<center>Current workspace</center>";
639 s << "<center>" << blackbox->bbGetName()<< "</center>";
641 blackbox->bbInsertHTMLGraph( s, detail, level, true, directory, false );
642 s << "</body></html>\n";
646 // 2. Starting Browser
647 if (system_display) system( command2.c_str() );
651 bbtkMessage("help",1,"No black box: \""
652 <<nameblackbox<<"\" " <<std::endl);
656 //=======================================================================
658 //=======================================================================
659 void Executer::PrintHelpBlackBox(const std::string &nameblackbox,
660 const std::string &detailStr,
661 const std::string &levelStr)
665 int detail = atoi(detailStr.c_str());
666 int level = atoi(levelStr.c_str());
667 BlackBox::Pointer blackbox;
668 if (nameblackbox.compare(".")==0)
670 blackbox=GetCurrentDescriptor()->GetPrototype();
674 blackbox = GetCurrentDescriptor()->GetPrototype()->bbFindBlackBox(nameblackbox);
680 blackbox->bbPrintHelp(blackbox,detail,level); //,mFactory);
685 bbtkError("box with name '" <<nameblackbox<<"' unknown");
688 //=======================================================================
690 //=======================================================================
691 /// sets the level of message
692 void Executer::SetMessageLevel(const std::string &kind,
695 bbtk::MessageManager::SetMessageLevel(kind,level);
697 //=======================================================================
699 //=======================================================================
700 /// Prints help on the messages
701 void Executer::HelpMessages()
703 bbtk::MessageManager::PrintInfo();
705 //=======================================================================
707 //=======================================================================
709 void Executer::Print(const std::string &str)
711 if (GetNoExecMode() && (GetCurrentDescriptor()==GetWorkspace()) ) return;
712 if (GetCurrentDescriptor()!=GetWorkspace()) return;
714 bbtkDebugMessage("kernel",9,"Executer::Print(\""<<str<<"\")"<<std::endl);
717 // InterpretLine ("load std")
718 // InterpretLine("new ConcatStrings _C_ ") -> trouver un nom unique : # commande
719 // InterpretLine("new Print _P_")
720 // InterpretLine("connect _C_.Out _P_.In")
724 std::vector<std::string> chains;
725 std::string delimiters("$");
727 // Skip delimiters at beginning.
728 std::string::size_type lastPos = str.find_first_not_of(delimiters, 0);
730 if (lastPos>0) is_text = false;
732 // Find first delimiter.
733 std::string::size_type pos = str.find_first_of(delimiters, lastPos);
735 while (std::string::npos != pos || std::string::npos != lastPos)
739 // Found a text token, add it to the vector.
740 chains.push_back(str.substr(lastPos, pos - lastPos));
741 // std::string token = str.substr(lastPos, pos - lastPos)
742 // InterpretLine("set _C_.In%num% %token%")
748 // is an output (between $$) : decode
749 std::string tok,box,output;
750 tok = str.substr(lastPos, pos - lastPos);
751 Utilities::SplitAroundFirstDot(tok,box,output);
752 chains.push_back( Get(box,output) );
754 // InterpretLine("connect %tok% _C_.In%num%")
757 // Skip delimiters. Note the "not_of"
758 lastPos = str.find_first_not_of(delimiters, pos);
759 // Find next delimiter
760 pos = str.find_first_of(delimiters, lastPos);
765 // InterpretLine("exec _P_")
766 // if (IS_IN_WORKSPACE) InterpretLine("delete _C_; delete _P_");
768 std::vector<std::string>::iterator i;
769 for (i= chains.begin(); i!=chains.end(); ++i)
771 Utilities::SubsBackslashN(*i);
772 bbtkMessage("output",1,*i);
774 bbtkMessage("output",1,std::endl);
776 //==========================================================================
778 //==========================================================================
779 std::string Executer::GetObjectName() const
781 return std::string("Executer");
783 //==========================================================================
785 //==========================================================================
786 std::string Executer::GetObjectInfo() const
791 //==========================================================================
792 //==========================================================================
793 size_t Executer::GetObjectSize() const
795 size_t s = Superclass::GetObjectSize();
796 s += Executer::GetObjectInternalSize();
799 //==========================================================================
800 //==========================================================================
801 size_t Executer::GetObjectInternalSize() const
803 size_t s = sizeof(Executer);
806 //==========================================================================
807 //==========================================================================
808 size_t Executer::GetObjectRecursiveSize() const
810 size_t s = Superclass::GetObjectRecursiveSize();
811 s += Executer::GetObjectInternalSize();
812 s += mFactory->GetObjectRecursiveSize();
815 //==========================================================================