1 /*=========================================================================
3 Module: $RCSfile: bbtkExecuter.cxx,v $
5 Date: $Date: 2009/05/28 08:12:05 $
6 Version: $Revision: 1.30 $
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()->CheckPackages();
119 mOpenDefinition.clear();
120 mOpenPackage.clear();
122 // Wx::DestroyTopWindow();
124 GetFactory()->Reset();
125 Wx::ProcessPendingEvents();
127 // Create user package
129 Package::New("user","internal","User defined black boxes","");
130 // Insert the user package in the factory
131 GetFactory()->InsertPackage(p);
132 // And in the list of open packages
133 mOpenPackage.push_back(p);
136 // Create user workspace
137 ComplexBlackBoxDescriptor::Pointer r =
138 ComplexBlackBoxDescriptor::New("workspace");
139 // mRootCBB->Reference();
140 r->SetFactory(GetFactory());
141 r->AddToAuthor("bbtk");
142 r->AddToDescription("User's workspace");
143 mOpenDefinition.push_back(CBBDefinition(r,"user"));
144 // Register it into the user package
145 p->RegisterBlackBox(r);
148 // Object::PrintObjectListInfo();
149 // GetFactory()->CheckPackages();
150 bbtkDebugMessage("kernel",9,"<== Executer::Reset()" <<std::endl);
152 //=======================================================================
155 //=======================================================================
156 /// changes the workspace name
157 void Executer::SetWorkspaceName( const std::string& n )
159 GetUserPackage()->ChangeBlackBoxName( GetWorkspace()->GetTypeName(), n );
161 //=======================================================================
163 //=======================================================================
164 void Executer::BeginPackage (const std::string &name)
166 bbtkDebugMessage("kernel",9,"==> Executer::BeginPackage(\""<<name<<"\")"
171 p = GetFactory()->GetPackage(name);
175 p = Package::New(name,"","","");
176 GetFactory()->InsertPackage(p);
178 mOpenPackage.push_back(p);
180 bbtkDebugMessage("kernel",9,"<== Executer::BeginPackage(\""<<name<<"\")"
183 //=======================================================================
185 //=======================================================================
186 void Executer::EndPackage()
188 if (mOpenPackage.size()>1) mOpenPackage.pop_back();
190 //=======================================================================
192 //=======================================================================
193 void Executer::Define (const std::string &name,
194 const std::string &pack,
195 const std::string &scriptfilename)
197 bbtkDebugMessage("kernel",9,"==> Executer::Define(\""<<name<<
201 ComplexBlackBoxDescriptor::Pointer b
202 = ComplexBlackBoxDescriptor::New(name);
203 b->SetFactory(GetFactory());
204 b->SetScriptFileName(scriptfilename);
205 mOpenDefinition.push_back( CBBDefinition( b, pack ) );
207 bbtkDebugMessage("kernel",9,"<== Executer::Define(\""<<name<<
211 //=======================================================================
213 //=======================================================================
214 /// Sets the file name to use for the current definition
215 /// (Used to set it after the Define command)
216 void Executer::SetCurrentFileName (const std::string &name )
218 mOpenDefinition.back().box->SetScriptFileName(name);
220 //=======================================================================
222 //=======================================================================
223 void Executer::Clear()
225 bbtkDebugMessage("kernel",9,"==> Executer::Clear()" <<std::endl);
226 GetCurrentDescriptor()->GetPrototype()->Clear();
227 bbtkDebugMessage("kernel",9,"<== Executer::Clear()" <<std::endl);
229 //=======================================================================
231 //=======================================================================
232 void Executer::EndDefine ()
234 bbtkDebugMessage("kernel",9,"==> Executer::EndDefine(\""
235 <<GetCurrentDescriptor()->GetTypeName()<<"\")"
237 // Does current package exist ?
239 std::string pname(mOpenDefinition.back().package);
244 p = GetFactory()->GetPackage(pname);
248 p = Package::New(pname,"","","");
249 GetFactory()->InsertPackage(p);
254 p = mOpenPackage.back().lock();
256 p->RegisterBlackBox(GetCurrentDescriptor());
258 bbtkDebugMessage("kernel",9,"<== Executer::EndDefine(\""
259 <<GetCurrentDescriptor()->GetTypeName()<<"\")"
261 mOpenDefinition.pop_back();
263 //=======================================================================
265 //=======================================================================
266 void Executer::Kind(const std::string& kind)
270 GetCurrentDescriptor()->AddToCategory("adaptor");
271 GetCurrentDescriptor()->SetKind(bbtk::BlackBoxDescriptor::ADAPTOR);
273 else if (kind=="DEFAULT_ADAPTOR")
275 GetCurrentDescriptor()->AddToCategory("adaptor");
276 GetCurrentDescriptor()->SetKind(bbtk::BlackBoxDescriptor::DEFAULT_ADAPTOR);
280 GetCurrentDescriptor()->AddToCategory("gui");
281 GetCurrentDescriptor()->SetKind(bbtk::BlackBoxDescriptor::GUI);
283 else if (kind=="DEFAULT_GUI")
285 GetCurrentDescriptor()->AddToCategory("gui");
286 GetCurrentDescriptor()->SetKind(bbtk::BlackBoxDescriptor::DEFAULT_GUI);
290 bbtkError("Unknown box kind : '"<<kind<<"'. "
291 <<"Valid kinds are 'ADAPTOR','DEFAULT_ADAPTOR',"
292 <<"'GUI','DEFAULT_GUI'");
295 //=======================================================================
297 //=======================================================================
298 void Executer::Create ( const std::string& nodeType,
299 const std::string& nodeName)
301 GetCurrentDescriptor()->Add(nodeType,nodeName);
303 //=======================================================================
305 //=======================================================================
306 void Executer::Destroy(const std::string &boxName)
308 GetCurrentDescriptor()->Remove(boxName,true);
310 //=======================================================================
312 //=======================================================================
313 void Executer::Connect (const std::string &nodeFrom,
314 const std::string &outputLabel,
315 const std::string &nodeTo,
316 const std::string &inputLabel)
318 GetCurrentDescriptor()->Connect(nodeFrom, outputLabel, nodeTo, inputLabel);
320 //=======================================================================
322 //=======================================================================
323 void Executer::Execute (const std::string &nodeName)
326 if (GetCurrentDescriptor()==GetWorkspace())
330 GetCurrentDescriptor()->GetPrototype()->bbGetBlackBox(nodeName)->bbExecute(true);
335 GetCurrentDescriptor()->AddToExecutionList(nodeName) ;
338 //=======================================================================
340 //=======================================================================
341 void Executer::DefineInput ( const std::string &name,
342 const std::string &box,
343 const std::string &input,
344 const std::string& help)
346 // If the input is defined in the Root box
347 if (GetCurrentDescriptor()==GetWorkspace())
349 // If the dialog mode is set to NoDialog
350 // and the user passed the name in the Inputs map
351 // then the associated value is set to the box.input
352 // This is the way command line parameters are passed to the Root box
353 if (mDialogMode == NoDialog)
355 // find if name is in mInputs
356 std::map<std::string,std::string>::iterator i;
357 i = mInputs.find(name);
358 if (i!=mInputs.end()) {
359 Set(box,input,(*i).second);
362 // If the dialog mode is set to TextDialog
363 // The user is prompted for the value
364 else if (mDialogMode == TextDialog)
366 std::cout << name << "=";
372 // If the dialog mode is set to GraphicalDialog
373 // A dialog box is pop up
374 else if (mDialogMode == GraphicalDialog)
376 std::string mess("Enter the value of '");
381 std::string title(name);
383 std::string ans = wx2std ( wxGetTextFromUser( std2wx (mess), std2wx(title)));
389 GetCurrentDescriptor()->DefineInput(name,box,input,help);
392 //=======================================================================
394 //=======================================================================
395 void Executer::DefineOutput ( const std::string &name,
396 const std::string &box,
397 const std::string &output,
398 const std::string& help)
400 GetCurrentDescriptor()->DefineOutput(name,box,output,help);
402 //=======================================================================
404 //=======================================================================
405 void Executer::Set (const std::string &box,
406 const std::string &input,
407 const std::string &value)
409 BlackBox::Pointer b = GetCurrentDescriptor()->GetPrototype()->bbGetBlackBox(box);
410 // Looks for the adaptor
412 if ( ( b->bbGetInputType(input) != typeid(bbtk::any<bbtk::thing>) )&&
413 ( b->bbGetInputType(input) != typeid(std::string) ) )
415 BlackBox::Pointer a =
416 GetFactory()->NewAdaptor(typeid(std::string),
417 b->bbGetInputType(input),
422 TypeName(b->bbGetInputType(input))
423 <<"> to <std::string> found");
425 std::string v(value);
426 a->bbSetInput("In",v);
428 b->bbSetInput(input,a->bbGetOutput("Out"));
433 std::string v(value);
434 b->bbSetInput(input,v);
437 //=======================================================================
439 //=======================================================================
440 std::string Executer::Get(const std::string &box,
441 const std::string &output)
443 BlackBox::Pointer b = GetCurrentDescriptor()->GetPrototype()->bbGetBlackBox(box);
444 // Looks for the adaptor
445 if (b->bbGetOutputType(output) != typeid(std::string))
447 BlackBox::Pointer a =
448 GetFactory()->NewAdaptor(
449 b->bbGetOutputType(output),
455 TypeName(b->bbGetOutputType(output))
456 <<"> to <std::string> found");
460 a->bbSetInput("In",b->bbGetOutput(output));
462 std::string r = a->bbGetOutput("Out").unsafe_get<std::string>();
463 //std::string v = *((std::string*)a->bbGetOutput("Out")) ;
464 // std::cout << a->bbGetOutput("Out").unsafe_get<std::string>()
466 //std::string v(value);
467 //b->bbSetInput(input,a->bbGetOutput("Out"));
474 return b->bbGetOutput(output).unsafe_get<std::string>();
475 // std::string v = *((std::string*)b->bbGetOutput(output)) ;
476 // std::cout << b->bbGetOutput("Out").unsafe_get<std::string>()
478 // b->bbSetInput(input,&v);
481 //=======================================================================
483 //=======================================================================
484 void Executer::Author(const std::string &authorName)
486 GetCurrentDescriptor()->AddToAuthor(authorName,GetCurrentDescriptor()==GetWorkspace());
488 //=======================================================================
490 //=======================================================================
491 void Executer::Category(const std::string &category)
493 GetCurrentDescriptor()->AddToCategory(category,GetCurrentDescriptor()==GetWorkspace());
495 //=======================================================================
497 //=======================================================================
498 void Executer::Description(const std::string &d)
500 GetCurrentDescriptor()->AddToDescription(d,GetCurrentDescriptor()==GetWorkspace());
502 //=======================================================================
504 //=======================================================================
505 /// prints the list of the boxes of the current descriptor
506 void Executer::PrintBoxes()
508 bbtkMessage("help",1,"The black box descriptor \""
509 <<GetCurrentDescriptor()->GetTypeName()<<"\" contains : "<<std::endl);
510 GetCurrentDescriptor()->PrintBlackBoxes();
512 //=======================================================================
514 //=======================================================================
515 std::string Executer::ShowGraph(const std::string &nameblackbox,
516 const std::string &detailStr,
517 const std::string &levelStr,
518 const std::string &output_html,
519 const std::string &custom_header,
520 const std::string &custom_title,
521 bool system_display )
523 int detail = atoi(detailStr.c_str());
524 int level = atoi(levelStr.c_str());
525 bool relative_link = true;
530 p = GetFactory()->GetPackage(nameblackbox);
534 p = GetUserPackage();
537 std::string doc_path = bbtk::ConfigurationFile::GetInstance().Get_doc_path();
538 doc_path += bbtk::ConfigurationFile::GetInstance().Get_file_separator();
540 doc_path += bbtk::ConfigurationFile::GetInstance().Get_file_separator();
542 std::string pack_name(p->GetName());
543 std::string pack_path = doc_path + pack_name;
544 // Creating directory
545 if ( ! bbtk::Utilities::FileExists(pack_path) )
547 std::string command("mkdir \"" +pack_path+ "\"");
548 system( command.c_str() );
550 std::string pack_index(pack_path);
551 pack_index += bbtk::ConfigurationFile::GetInstance().Get_file_separator();
552 pack_index += "index.html";
555 // Generating documentation-help of workspace
556 p->SetDocURL(pack_index);
557 p->SetDocRelativeURL("index.html");
558 p->CreateHtmlPage(pack_index,"bbtk","user package",custom_header,custom_title,detail,level,relative_link);
563 ShowGraphTypes(nameblackbox);
565 catch (bbtk::Exception a)
567 std::cout <<"EXC"<<std::endl;
568 page = ShowGraphInstances(nameblackbox,detail,level,system_display);
573 //=======================================================================
575 //=======================================================================
576 /// Generate a png file with the actual pipeline (Graphviz-dot needed)
577 std::string Executer::ShowGraphInstances(const std::string &nameblackbox, int detail, int level,
581 BlackBox::Pointer blackbox;
582 if (nameblackbox==".")
584 blackbox = GetCurrentDescriptor()->GetPrototype();
588 blackbox = GetCurrentDescriptor()->GetPrototype()->bbFindBlackBox(nameblackbox);
595 // Don't pollute the file store with "temp_dir" directories ...
596 std::string default_doc_dir = ConfigurationFile::GetInstance().Get_default_temp_dir();
597 char c = default_doc_dir.c_str()[strlen(default_doc_dir.c_str())-1];
599 std::string directory = default_doc_dir;
600 if (c != '/' && c !='\\') directory = directory + "/";
602 directory = directory + "temp_dir";
603 //std::string directory("temp_dir");
604 std::string filename(directory + "/" + "bbtk_graph_pipeline");
605 std::string filename_html(filename+".html");
606 std::string command0("mkdir \""+directory + "\"");
609 std::string command2("start ");
611 std::string command2("gnome-open ");
614 command2=command2+filename_html;
615 page = filename_html;
616 // 1. Generate Html Diagram
618 s.open(filename_html.c_str());
621 s << "<html><head><title>BBtk graph diagram</title><meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\"></head>\n";
622 s << "<body bgcolor=\"#FFFFFF\" text=\"#000000\"> \n\n";
623 if ( blackbox->bbGetName()=="workspacePrototype" )
625 s << "<center>Current workspace</center>";
627 s << "<center>" << blackbox->bbGetName()<< "</center>";
629 blackbox->bbInsertHTMLGraph( s, detail, level, true, directory, false );
630 s << "</body></html>\n";
634 // 2. Starting Browser
635 if (system_display) system( command2.c_str() );
639 bbtkMessage("help",1,"No black box: \""
640 <<nameblackbox<<"\" " <<std::endl);
644 //=======================================================================
646 //=======================================================================
647 void Executer::ShowRelations(const std::string &nameblackbox,
648 const std::string &detailStr,
649 const std::string &levelStr)
653 int detail = atoi(detailStr.c_str());
654 int level = atoi(levelStr.c_str());
655 BlackBox::Pointer blackbox;
656 if (nameblackbox.compare(".")==0)
658 blackbox=GetCurrentDescriptor()->GetPrototype();
662 blackbox = GetCurrentDescriptor()->GetPrototype()->bbFindBlackBox(nameblackbox);
668 blackbox->bbShowRelations(blackbox,detail,level); //,mFactory);
673 bbtkError("Blackbox Name not found.. <" <<nameblackbox<<">");
676 //=======================================================================
678 //=======================================================================
679 /// sets the level of message
680 void Executer::SetMessageLevel(const std::string &kind,
683 bbtk::MessageManager::SetMessageLevel(kind,level);
685 //=======================================================================
687 //=======================================================================
688 /// Prints help on the messages
689 void Executer::HelpMessages()
691 bbtk::MessageManager::PrintInfo();
693 //=======================================================================
695 //=======================================================================
697 void Executer::Print(const std::string &str)
699 if (GetNoExecMode() && (GetCurrentDescriptor()==GetWorkspace()) ) return;
700 if (GetCurrentDescriptor()!=GetWorkspace()) return;
702 bbtkDebugMessage("kernel",9,"Executer::Print(\""<<str<<"\")"<<std::endl);
705 // InterpretLine ("load std")
706 // InterpretLine("new ConcatStrings _C_ ") -> trouver un nom unique : # commande
707 // InterpretLine("new Print _P_")
708 // InterpretLine("connect _C_.Out _P_.In")
712 std::vector<std::string> chains;
713 std::string delimiters("$");
715 // Skip delimiters at beginning.
716 std::string::size_type lastPos = str.find_first_not_of(delimiters, 0);
718 if (lastPos>0) is_text = false;
720 // Find first delimiter.
721 std::string::size_type pos = str.find_first_of(delimiters, lastPos);
723 while (std::string::npos != pos || std::string::npos != lastPos)
727 // Found a text token, add it to the vector.
728 chains.push_back(str.substr(lastPos, pos - lastPos));
729 // std::string token = str.substr(lastPos, pos - lastPos)
730 // InterpretLine("set _C_.In%num% %token%")
736 // is an output (between $$) : decode
737 std::string tok,box,output;
738 tok = str.substr(lastPos, pos - lastPos);
739 Utilities::SplitAroundFirstDot(tok,box,output);
740 chains.push_back( Get(box,output) );
742 // InterpretLine("connect %tok% _C_.In%num%")
745 // Skip delimiters. Note the "not_of"
746 lastPos = str.find_first_not_of(delimiters, pos);
747 // Find next delimiter
748 pos = str.find_first_of(delimiters, lastPos);
753 // InterpretLine("exec _P_")
754 // if (IS_IN_WORKSPACE) InterpretLine("delete _C_; delete _P_");
756 std::vector<std::string>::iterator i;
757 for (i= chains.begin(); i!=chains.end(); ++i)
759 Utilities::SubsBackslashN(*i);
760 bbtkMessage("output",1,*i);
762 bbtkMessage("output",1,std::endl);
764 //==========================================================================
766 //==========================================================================
767 std::string Executer::GetObjectName() const
769 return std::string("Executer");
771 //==========================================================================
773 //==========================================================================
774 std::string Executer::GetObjectInfo() const
779 //==========================================================================
780 //==========================================================================
781 size_t Executer::GetObjectSize() const
783 size_t s = Superclass::GetObjectSize();
784 s += Executer::GetObjectInternalSize();
787 //==========================================================================
788 //==========================================================================
789 size_t Executer::GetObjectInternalSize() const
791 size_t s = sizeof(Executer);
794 //==========================================================================
795 //==========================================================================
796 size_t Executer::GetObjectRecursiveSize() const
798 size_t s = Superclass::GetObjectRecursiveSize();
799 s += Executer::GetObjectInternalSize();
800 s += mFactory->GetObjectRecursiveSize();
803 //==========================================================================