]> Creatis software - bbtk.git/blob - kernel/src/bbtkExecuter.cxx
Add unfinished version of bbtkTranscriptor
[bbtk.git] / kernel / src / bbtkExecuter.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   bbtk
4   Module:    $RCSfile: bbtkExecuter.cxx,v $ $
5   Language:  C++
6   Date:      $Date: 2008/02/14 11:38:58 $
7   Version:   $Revision: 1.10 $
8                                                                                 
9   Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de
10   l'Image). All rights reserved. See Doc/License.txt or
11   http://www.creatis.insa-lyon.fr/Public/bbtk/License.html for details.
12                                                                                 
13      This software is distributed WITHOUT ANY WARRANTY; without even
14      the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15      PURPOSE.  See the above copyright notices for more information.
16                                                                                 
17 =========================================================================*/
18 /**
19  *  \file 
20  *  \brief class Executer: level 0 of script execution (code)
21  */
22
23 #include "bbtkExecuter.h"
24 #include "bbtkMessageManager.h"
25 #include "bbtkFactory.h"
26 #include "bbtkUtilities.h"
27 #include <fstream>
28
29 #ifdef _USE_WXWIDGETS_
30 #include <wx/textdlg.h>
31 #endif
32
33 #include "bbtkWxBlackBox.h"
34
35 #include "bbtkConfigurationFile.h"
36
37 namespace bbtk
38 {  
39 /**
40  *
41  */
42   Executer::Executer()
43     : mPackage(0),
44       mRoot(0),
45       mNoExecMode(false),
46       mDialogMode(NoDialog)
47   {
48     //VirtualExec();
49     
50     bbtkDebugMessageInc("Kernel",9,"Executer::Executer()" <<std::endl);
51     Reset();
52     bbtkDebugDecTab("Kernel",9);
53   } 
54
55 /**
56  *
57  */
58   Executer::~Executer()
59   {
60      bbtkDebugMessageInc("Kernel",9,"Executer::~Executer()" <<std::endl);
61      if (mRoot) 
62      {
63         mPackage->UnRegisterBlackBox("workspace");
64         delete mRoot;
65      }
66      if (mPackage)
67      {
68         GetGlobalFactory()->UnLoadPackage("user");
69      }
70      bbtkDebugDecTab("Kernel",9);
71   }
72   
73
74 /**
75  *
76  */
77   void Executer::Reset()
78   {
79     bbtkDebugMessageInc("Kernel",9,"Executer::Reset()" <<std::endl);
80
81     // The 'user' package must be closed before all other 
82     // because box destructors must not be unloaded when bb are deleted!
83     // Similarly, the 'workspace' CBB must be destroyed before 
84     // all user defined CBB otherwise any instance 
85     // of a user CBB that is in the 'workspace' would try to 
86     // access a user CBB descriptor which has been previously freed
87     if (mRoot)
88     {
89        mPackage->UnRegisterBlackBox(mRoot->GetTypeName());
90        delete mRoot;
91     }
92     if (mPackage) 
93     {
94        GetGlobalFactory()->UnLoadPackage("user");
95     }
96     GetGlobalFactory()->Reset();
97     // Create user package
98     mPackage = new Package("user","internal to bbi",
99                            "User defined black boxes",
100                            "",
101                            BBTK_STRINGIFY_SYMBOL(BBTK_VERSION));
102     // Create user workspace
103     mRoot = new ComplexBlackBoxDescriptor("workspace"); //,f);
104     mRoot->AddToAuthor("bbi (internal)");
105     mRoot->AddToDescription("User's workspace");
106     mOpenDefinition.push_back(CBBDefinition(mRoot,"user"));
107     // Register it into the user package
108     mPackage->RegisterBlackBox(mRoot);
109     // Insert the user package in the factory
110     InsertPackage(mPackage);
111     mOpenPackage.push_back(mPackage);
112     bbtkDebugDecTab("Kernel",9);
113   }
114
115   /// changes the workspace name
116   void Executer::SetWorkspaceName( const std::string& n )
117   {
118     mPackage->ChangeBlackBoxName( mRoot->GetTypeName(), n );
119   }
120   
121   void Executer::BeginPackage (const std::string &name)
122   {
123      bbtkDebugMessageInc("Kernel",9,"Executer::BeginPackage(\""<<name<<"\")"
124                         <<std::endl);
125      Package* p;
126      try 
127       {
128         p = GetGlobalFactory()->GetPackage(name);
129       }
130     catch (Exception e)
131       {
132         p = new Package(name,
133                         "",
134                         "",
135                         "",
136                         BBTK_STRINGIFY_SYMBOL(BBTK_VERSION));
137         InsertPackage(p);
138       }
139      mOpenPackage.push_back(p);
140   }
141
142   void Executer::EndPackage()
143   {
144     if (mOpenPackage.size()>1) mOpenPackage.pop_back();
145   }
146
147   void Executer::Define (const std::string &name,
148                          const std::string &pack,
149                          const std::string &scriptfilename)
150   {
151     bbtkDebugMessageInc("Kernel",9,"Executer::Define(\""<<name<<
152                         ","<<pack<<"\")" 
153                         <<std::endl);
154
155     ComplexBlackBoxDescriptor* b = new ComplexBlackBoxDescriptor(name);
156     b->SetScriptFileName(scriptfilename);
157     mOpenDefinition.push_back( CBBDefinition( b, pack ) );
158     
159     bbtkDebugDecTab("Kernel",9);
160   }
161
162   /// Sets the file name to use for the current definition
163   /// (Used to set it after the Define command)
164   void Executer::SetCurrentFileName (const std::string &name )
165   {
166     mOpenDefinition.back().box->SetScriptFileName(name);
167   }
168
169   void Executer::EndDefine ()
170   {
171     bbtkDebugMessageInc("Kernel",9,"Executer::EndDefine(\""
172                         <<Current()->GetTypeName()<<"\")" 
173                         <<std::endl);
174     // Does current package exist ?
175     Package* p;
176     std::string pname(mOpenDefinition.back().package);
177     if (pname.size()>0)
178     {
179       try
180       {
181             p = GetGlobalFactory()->GetPackage(pname);
182       }
183       catch (Exception e)
184       {
185              p = new Package(pname,
186                         "",
187                         "",
188                         "",
189                         BBTK_STRINGIFY_SYMBOL(BBTK_VERSION));
190             InsertPackage(p);
191       }
192     }
193     else
194     {
195            p = mOpenPackage.back();
196     }
197     p->RegisterBlackBox(Current());
198
199     mOpenDefinition.pop_back();
200   }
201
202
203   void Executer::Create ( const std::string& nodeType, 
204                           const std::string& nodeName)
205   {
206      Current()->Add(nodeType,nodeName);
207   }
208
209   /*
210     void Executer::Remove (const std::string &nodeName)
211   {
212     // Current()->RemoveBlackBox(nodeName);
213   }
214   */
215
216 /**
217  *
218  */
219   void Executer::Connect (const std::string &nodeFrom, 
220                           const std::string &outputLabel,
221                           const std::string &nodeTo, 
222                           const std::string &inputLabel)
223   {
224     Current()->Connect(nodeFrom, outputLabel, nodeTo, inputLabel);
225   }
226
227  /**
228  *
229  */ 
230   void Executer::Update (const std::string &nodeName) // would 'Execute' be more meaningfull ?
231   {
232  // if in root
233      if (Current()==mRoot) 
234      {
235         if (!mNoExecMode) 
236         {
237            Current()->GetPrototype()->bbGetBlackBox(nodeName)->bbExecute(true);
238         }
239      }
240      else 
241      {
242         Current()->AddToExecutionList(nodeName) ;
243      }
244   }
245
246 /**
247  *
248  */
249   void Executer::DefineInput ( const std::string &name,
250                                const std::string &box,
251                                const std::string &input,
252                                const std::string& help)
253   {
254     // If the input is defined in the Root box
255     if (Current()==mRoot) 
256       {
257       // If the dialog mode is set to NoDialog
258       // and the user passed the name in the Inputs map 
259       // then the associated value is set to the box.input
260       // This is the way command line parameters are passed to the Root box
261          if (mDialogMode == NoDialog) 
262          {
263          // find if name is in mInputs
264             std::map<std::string,std::string>::iterator i;
265             i = mInputs.find(name);
266             if (i!=mInputs.end()) {
267                Set(box,input,(*i).second);
268             }
269          }
270         // If the dialog mode is set to TextDialog
271         // The user is prompted for the value
272         else if (mDialogMode == TextDialog) 
273         {
274            std::cout << name << "=";
275            std::string ans;
276            std::cin >> ans;
277            Set(box,input,ans);
278         }
279        #ifdef _USE_WXWIDGETS_
280        // If the dialog mode is set to GraphicalDialog
281        // A dialog box is pop up
282        else if (mDialogMode == GraphicalDialog) 
283        {
284           std::string mess("Enter the value of '");
285           mess += name;
286           mess += "' (";
287           mess += help;
288           mess += ")";
289           std::string title(name);
290           title += " ?";
291           std::string ans = wx2std ( wxGetTextFromUser( std2wx (mess), std2wx(title)));
292           Set(box,input,ans); 
293        }
294 #endif
295     }
296
297     Current()->DefineInput(name,box,input,help);
298
299   }
300
301  /**
302  *  
303  */ 
304    void Executer::DefineOutput ( const std::string &name,
305                                  const std::string &box,
306                                  const std::string &output,
307                                  const std::string& help)
308   {
309     Current()->DefineOutput(name,box,output,help);
310   }
311
312   /**
313    *  
314    */ 
315   void Executer::Set (const std::string &box,
316                       const std::string &input,
317                       const std::string &value)
318   {
319     BlackBox* b = Current()->GetPrototype()->bbGetBlackBox(box);
320     // Looks for the adaptor
321
322     if ( b->bbGetInputType(input) !=  typeid(std::string) ) 
323       {
324          BlackBox* a = /*mFactory->*/
325          NewAdaptor(typeid(std::string),
326                     b->bbGetInputType(input),
327                     "tmp");
328          if (!a) 
329          {
330             bbtkError("No <"<<
331                       TypeName(b->bbGetInputType(input))
332                       <<"> to <std::string> found");
333          }
334          std::string v(value);
335          a->bbSetInput("In",v);
336          a->bbExecute();
337          b->bbSetInput(input,a->bbGetOutput("Out"));
338          a->bbDelete();
339       }
340     else 
341       {
342       std::string v(value);
343       b->bbSetInput(input,v);
344       }
345   }
346
347   /**
348    *
349    */
350   std::string Executer::Get(const std::string &box,
351                             const std::string &output)
352   {
353     BlackBox* b = Current()->GetPrototype()->bbGetBlackBox(box);
354     // Looks for the adaptor
355     if (b->bbGetOutputType(output) != typeid(std::string)) 
356       {
357       BlackBox* a = /*mFactory->*/
358           NewAdaptor(
359              b->bbGetOutputType(output),
360              typeid(std::string),
361              "tmp");
362       if (!a) 
363         {
364         bbtkError("No <"<<
365                    TypeName(b->bbGetOutputType(output))
366                    <<"> to <std::string> found");
367         }
368         b->bbExecute();
369
370         a->bbSetInput("In",b->bbGetOutput(output));
371         a->bbExecute();
372         std::string r = a->bbGetOutput("Out").unsafe_get<std::string>();
373        //std::string v = *((std::string*)a->bbGetOutput("Out")) ;
374        //   std::cout << a->bbGetOutput("Out").unsafe_get<std::string>() 
375        //             << std::endl;
376        //std::string v(value);
377        //b->bbSetInput(input,a->bbGetOutput("Out"));
378         a->bbDelete();
379         return r;
380       }
381     else
382       {
383        b->bbExecute();
384        return b->bbGetOutput(output).unsafe_get<std::string>();
385        // std::string v = *((std::string*)b->bbGetOutput(output)) ;
386        // std::cout << b->bbGetOutput("Out").unsafe_get<std::string>() 
387        //   << std::endl;
388        // b->bbSetInput(input,&v);
389       }
390   }
391
392
393   void Executer::Author(const std::string &authorName)
394   {
395     Current()->AddToAuthor(authorName,Current()==mRoot);
396   }
397
398   void Executer::Category(const std::string &category)
399   {
400     Current()->AddToCategory(category,Current()==mRoot);
401   }
402
403   void Executer::Description(const std::string &d)
404   {
405      Current()->AddToDescription(d,Current()==mRoot);
406   }
407
408
409   /// prints the list of the boxes of the current descriptor
410   void Executer::PrintBoxes()
411   {  
412     bbtkMessageInc("Help",1,"The black box descriptor \""
413                    <<Current()->GetTypeName()<<"\" contains : "<<std::endl);
414     Current()->PrintBlackBoxes();
415     bbtkDecTab("Help",1);
416  }
417
418   std::string Executer::ShowGraph(const std::string &nameblackbox, 
419                                   const std::string &detailStr, 
420                                   const std::string &levelStr,
421                                   const std::string &output_html,
422                                   const std::string &custom_header,
423                                   const std::string &custom_title,
424                                   bool system_display )
425   {
426     int detail  =       atoi(detailStr.c_str());
427     int level   =       atoi(levelStr.c_str());
428
429     std::string filename_rootHtml (output_html) ;
430     std::string simplefilename_rootHtml ( Utilities::get_file_name(output_html));
431
432     bool relative_link = true;
433
434     // No output provided : automatic generation
435     if (output_html.length() == 0)
436       {
437         // Don't pollute the file store with  "temp_dir" directories ...    
438         std::string default_doc_dir = ConfigurationFile::GetInstance().Get_default_temp_dir();
439         
440         char c = default_doc_dir.c_str()[strlen(default_doc_dir.c_str())-1];
441         
442         std::string directory = default_doc_dir; 
443         if (c != '/' && c !='\\') directory = directory + "/";
444         directory = directory +  "temp_dir";    
445         
446         filename_rootHtml = directory + "/" + "User.html";
447         simplefilename_rootHtml = "User.html" ;
448
449         // Creating directory
450         std::string command0("mkdir \"" +directory + "\"");
451         system( command0.c_str() );
452
453         relative_link = false;
454       }
455
456
457     Package* p;
458     try
459     {
460            p = GetGlobalFactory()->GetPackage(nameblackbox);
461     }
462     catch (Exception e)
463     {
464            p = mPackage;
465     }
466     // Generating documentation-help of workspace
467     p->SetDocURL(filename_rootHtml);
468     p->SetDocRelativeURL(simplefilename_rootHtml);
469
470     p->CreateHtmlPage(filename_rootHtml,"bbi","user package",custom_header,custom_title,detail,level,relative_link);
471
472     std::string page = filename_rootHtml;
473     /*
474     try 
475     {
476           ShowGraphTypes(nameblackbox);
477     }
478     catch (bbtk::Exception a)
479     {
480           std::cout <<"EXC"<<std::endl;
481           page = ShowGraphInstances(nameblackbox,detail,level,system_display);
482     }
483     */
484     return page;
485   }
486
487   /// Generate a png file with the actual pipeline (Graphviz-dot needed)
488   std::string Executer::ShowGraphInstances(const std::string &nameblackbox, int detail, int level,
489                                     bool system_display)
490   {
491
492     BlackBox* blackbox=NULL;
493     if (nameblackbox==".")
494     {
495           blackbox=Current()->GetPrototype();
496     }
497     else
498     {
499           blackbox = Current()->GetPrototype()->bbFindBlackBox(nameblackbox);
500     }
501     
502     std::string page;
503
504     if (blackbox)
505       {      
506         // Don't pollute the file store with  "temp_dir" directories ...
507         std::string default_doc_dir = ConfigurationFile::GetInstance().Get_default_temp_dir();
508         char c = default_doc_dir.c_str()[strlen(default_doc_dir.c_str())-1];
509
510         std::string directory = default_doc_dir; 
511         if (c != '/' && c !='\\') directory = directory + "/";
512
513         directory = directory +  "temp_dir";
514         //std::string directory("temp_dir");
515         std::string filename(directory + "/" + "bbtk_graph_pipeline");
516         std::string filename_html(filename+".html");
517         std::string command0("mkdir \""+directory + "\"");
518
519 #if defined(_WIN32)
520         std::string command2("start ");
521 #else 
522         std::string command2("gnome-open ");
523 #endif
524
525         command2=command2+filename_html;
526         page = filename_html;
527         // 1. Generate Html Diagram
528         std::ofstream s;
529         s.open(filename_html.c_str());
530         if (s.good()) 
531           {
532             s << "<html><head><title>BBtk graph diagram</title><meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\"></head>\n";
533             s << "<body bgcolor=\"#FFFFFF\" text=\"#000000\"> \n\n";
534             if ( blackbox->bbGetName()=="workspacePrototype" )
535               {
536                 s << "<center>Current workspace</center>";
537               } else {
538               s << "<center>" << blackbox->bbGetName()<< "</center>";
539             } 
540
541             blackbox->bbInsertHTMLGraph( s, detail, level, true, directory, false );
542             s << "</body></html>\n";
543           }
544         s.close();
545         
546         // 2. Starting Browser
547         if (system_display) system( command2.c_str() );      
548       } 
549     else 
550       {
551         bbtkMessageInc("Help",1,"No black box: \""
552                        <<nameblackbox<<"\" " <<std::endl);
553       }
554     return page;
555   }
556
557 void Executer::ShowRelations(const std::string &nameblackbox, const std::string &detailStr, const std::string &levelStr)
558   {
559        bool found=false;
560
561        int detail = atoi(detailStr.c_str());
562        int level  = atoi(levelStr.c_str());
563        BlackBox* blackbox=NULL;
564        if (nameblackbox.compare(".")==0)
565        {
566           blackbox=Current()->GetPrototype();
567        } else {
568           blackbox = Current()->GetPrototype()->bbFindBlackBox(nameblackbox);
569        }
570
571        if (blackbox)
572        {
573           found=true;
574           blackbox->bbShowRelations(blackbox,detail,level); //,mFactory);
575        }
576
577        if (!found) 
578        {
579           bbtkError("Blackbox Name not found.. <"  <<nameblackbox<<">");
580        }
581   }
582
583   /*
584   /// sets the level of message
585   void Executer::Message(const std::string &kind,
586                          const std::string& level)
587   {
588     int l;
589     sscanf(level.c_str(),"%d",&l);
590     bbtk::MessageManager::SetMessageLevel(kind,l);
591   }
592   */
593
594
595 }//namespace