]> Creatis software - bbtk.git/blob - kernel/src/bbtkExecuter.cxx
No longer 'Core' messages but 'Kernel' ones
[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/05 13:23:46 $
7   Version:   $Revision: 1.7 $
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   void Executer::EndDefine ()
163   {
164     bbtkDebugMessageInc("Kernel",9,"Executer::EndDefine(\""
165                         <<Current()->GetTypeName()<<"\")" 
166                         <<std::endl);
167     // Does current package exist ?
168     Package* p;
169     std::string pname(mOpenDefinition.back().package);
170     if (pname.size()>0)
171     {
172       try
173       {
174             p = GetGlobalFactory()->GetPackage(pname);
175       }
176       catch (Exception e)
177       {
178              p = new Package(pname,
179                         "",
180                         "",
181                         "",
182                         BBTK_STRINGIFY_SYMBOL(BBTK_VERSION));
183             InsertPackage(p);
184       }
185     }
186     else
187     {
188            p = mOpenPackage.back();
189     }
190     p->RegisterBlackBox(Current());
191
192     mOpenDefinition.pop_back();
193   }
194
195
196   void Executer::Create ( const std::string& nodeType, 
197                           const std::string& nodeName)
198   {
199      Current()->Add(nodeType,nodeName);
200   }
201   
202
203   /*
204     void Executer::Remove (const std::string &nodeName)
205   {
206     // Current()->RemoveBlackBox(nodeName);
207   }
208   */    
209
210 /**
211  *  
212  */
213   void Executer::Connect (const std::string &nodeFrom, 
214                           const std::string &outputLabel, 
215                           const std::string &nodeTo, 
216                           const std::string &inputLabel)
217   {
218     Current()->Connect(nodeFrom, outputLabel, nodeTo, inputLabel);
219   }
220
221  /**
222  *  
223  */ 
224   void Executer::Update (const std::string &nodeName) // would 'Execute' be more meaningfull ?
225   {
226  // if in root
227      if (Current()==mRoot) 
228      {
229         if (!mNoExecMode) 
230         {
231            Current()->GetPrototype()->bbGetBlackBox(nodeName)->bbExecute(true);
232         }
233      }
234      else 
235      {
236         Current()->AddToExecutionList(nodeName) ;
237      }
238   }
239     
240 /**
241  *  
242  */
243   void Executer::DefineInput ( const std::string &name,
244                                const std::string &box,
245                                const std::string &input,
246                                const std::string& help)
247   {
248     // If the input is defined in the Root box
249     if (Current()==mRoot) 
250       {
251       // If the dialog mode is set to NoDialog
252       // and the user passed the name in the Inputs map 
253       // then the associated value is set to the box.input
254       // This is the way command line parameters are passed to the Root box
255          if (mDialogMode == NoDialog) 
256          {
257          // find if name is in mInputs
258             std::map<std::string,std::string>::iterator i;
259             i = mInputs.find(name);
260             if (i!=mInputs.end()) {
261                Set(box,input,(*i).second);
262             }
263          }
264         // If the dialog mode is set to TextDialog
265         // The user is prompted for the value
266         else if (mDialogMode == TextDialog) 
267         {
268            std::cout << name << "=";
269            std::string ans;
270            std::cin >> ans;
271            Set(box,input,ans);
272         }
273        #ifdef _USE_WXWIDGETS_
274        // If the dialog mode is set to GraphicalDialog
275        // A dialog box is pop up
276        else if (mDialogMode == GraphicalDialog) 
277        {
278           std::string mess("Enter the value of '");
279           mess += name;
280           mess += "' (";
281           mess += help;
282           mess += ")";
283           std::string title(name);
284           title += " ?";
285     
286           std::string ans = wx2std ( wxGetTextFromUser( std2wx (mess), std2wx(title)));
287           Set(box,input,ans); 
288        }
289 #endif
290     }
291
292     Current()->DefineInput(name,box,input,help);
293
294   }
295   
296  /**
297  *  
298  */ 
299    void Executer::DefineOutput ( const std::string &name,
300                                  const std::string &box,
301                                  const std::string &output,
302                                  const std::string& help)
303   {
304     Current()->DefineOutput(name,box,output,help);
305   }
306
307   /**
308    *  
309    */ 
310   void Executer::Set (const std::string &box,
311                       const std::string &input,
312                       const std::string &value)
313   {
314     BlackBox* b = Current()->GetPrototype()->bbGetBlackBox(box);
315     // Looks for the adaptor
316
317     if ( b->bbGetInputType(input) !=  typeid(std::string) ) 
318       {
319          BlackBox* a = /*mFactory->*/
320          NewAdaptor(typeid(std::string),
321                     b->bbGetInputType(input),
322                     "tmp");
323          if (!a) 
324          {
325             bbtkError("No <"<<
326                       TypeName(b->bbGetInputType(input))
327                       <<"> to <std::string> found");
328          }
329          std::string v(value);
330          a->bbSetInput("In",v);
331          a->bbExecute();
332          b->bbSetInput(input,a->bbGetOutput("Out"));
333          a->bbDelete();
334       }
335     else 
336       {
337       std::string v(value);
338       b->bbSetInput(input,v);
339       }
340   }
341
342   /**
343    *  
344    */ 
345   std::string Executer::Get(const std::string &box,
346                             const std::string &output)
347   {
348     BlackBox* b = Current()->GetPrototype()->bbGetBlackBox(box);
349     // Looks for the adaptor
350     if (b->bbGetOutputType(output) != typeid(std::string)) 
351       {
352       BlackBox* a = /*mFactory->*/
353           NewAdaptor(
354              b->bbGetOutputType(output),
355              typeid(std::string),
356              "tmp");
357       if (!a) 
358         {
359         bbtkError("No <"<<
360                    TypeName(b->bbGetOutputType(output))
361                    <<"> to <std::string> found");
362         }
363         b->bbExecute();
364
365         a->bbSetInput("In",b->bbGetOutput(output));
366         a->bbExecute();
367         std::string r = a->bbGetOutput("Out").unsafe_get<std::string>();
368        //std::string v = *((std::string*)a->bbGetOutput("Out")) ;
369        //   std::cout << a->bbGetOutput("Out").unsafe_get<std::string>() 
370        //             << std::endl;
371        //std::string v(value);
372        //b->bbSetInput(input,a->bbGetOutput("Out"));
373         a->bbDelete();
374         return r;
375       }
376     else 
377       {
378        b->bbExecute();
379        return b->bbGetOutput(output).unsafe_get<std::string>();
380        // std::string v = *((std::string*)b->bbGetOutput(output)) ;
381        // std::cout << b->bbGetOutput("Out").unsafe_get<std::string>() 
382        //   << std::endl;
383        // b->bbSetInput(input,&v);
384       }
385   }
386
387
388   void Executer::Author(const std::string &authorName)
389   {
390     Current()->AddToAuthor(authorName,Current()==mRoot);
391   }
392
393   void Executer::Category(const std::string &category)
394   {
395     Current()->AddToCategory(category,Current()==mRoot);
396   }
397
398   void Executer::Description(const std::string &d)
399   {
400      Current()->AddToDescription(d,Current()==mRoot);
401   }
402
403
404   /// prints the list of the boxes of the current descriptor
405   void Executer::PrintBoxes()
406   {  
407     bbtkMessageInc("Help",1,"The black box descriptor \""
408                    <<Current()->GetTypeName()<<"\" contains : "<<std::endl);
409     Current()->PrintBlackBoxes();
410     bbtkDecTab("Help",1);
411  }
412
413   std::string Executer::ShowGraph(const std::string &nameblackbox, 
414                                   const std::string &detailStr, 
415                                   const std::string &levelStr,
416                                   const std::string &output_html,
417                                   const std::string &custom_header,
418                                   const std::string &custom_title,
419                                   bool system_display )
420   {
421     int detail  =       atoi(detailStr.c_str());
422     int level   =       atoi(levelStr.c_str());
423
424     std::string filename_rootHtml (output_html) ;
425     std::string simplefilename_rootHtml ( Utilities::get_file_name(output_html));
426
427     bool relative_link = true;
428
429     // No output provided : automatic generation
430     if (output_html.length() == 0)
431       {
432         // Don't pollute the file store with  "doc_tmp" directories ...    
433         std::string default_doc_dir = ConfigurationFile::GetInstance().Get_default_doc_tmp();
434         
435         char c = default_doc_dir.c_str()[strlen(default_doc_dir.c_str())-1];
436         
437         std::string directory = default_doc_dir; 
438         if (c != '/' && c !='\\') directory = directory + "/";
439         directory = directory +  "doc_tmp";    
440         
441         filename_rootHtml = directory + "/" + "User.html";
442         simplefilename_rootHtml = "User.html" ;
443
444         // Creating directory
445         std::string command0("mkdir \"" +directory + "\"");
446         system( command0.c_str() );
447
448         relative_link = false;
449       }
450
451
452     Package* p;
453     try
454     {
455            p = GetGlobalFactory()->GetPackage(nameblackbox);
456     }
457     catch (Exception e)
458     {
459            p = mPackage;
460     }
461     // Generating documentation-help of workspace
462     p->SetDocURL(filename_rootHtml);
463     p->SetDocRelativeURL(simplefilename_rootHtml);
464
465     p->CreateHtmlPage(filename_rootHtml,"bbi","user package",custom_header,custom_title,detail,level,relative_link);
466
467     std::string page = filename_rootHtml;
468     /*
469     try 
470     {
471           ShowGraphTypes(nameblackbox);
472     }
473     catch (bbtk::Exception a)
474     {
475           std::cout <<"EXC"<<std::endl;
476           page = ShowGraphInstances(nameblackbox,detail,level,system_display);
477     }
478     */
479     return page;
480   }
481
482   /// Generate a png file with the actual pipeline (Graphviz-dot needed)
483   std::string Executer::ShowGraphInstances(const std::string &nameblackbox, int detail, int level,
484                                     bool system_display)
485   {
486
487     BlackBox* blackbox=NULL;
488     if (nameblackbox==".")
489     {
490           blackbox=Current()->GetPrototype();
491     }
492     else 
493     {
494           blackbox = Current()->GetPrototype()->bbFindBlackBox(nameblackbox);
495     }
496     
497     std::string page;
498
499     if (blackbox)
500       {      
501         // Don't pollute the file store with  "doc_tmp" directories ...    
502         std::string default_doc_dir = ConfigurationFile::GetInstance().Get_default_doc_tmp();
503         char c = default_doc_dir.c_str()[strlen(default_doc_dir.c_str())-1];
504         
505         std::string directory = default_doc_dir; 
506         if (c != '/' && c !='\\') directory = directory + "/";
507
508         directory = directory +  "doc_tmp"; 
509         
510         //std::string directory("doc_tmp");
511         std::string filename(directory + "/" + "bbtk_graph_pipeline");
512         std::string filename_html(filename+".html");
513         std::string command0("mkdir \""+directory + "\"");
514
515 #if defined(_WIN32)  
516         std::string command2("start ");
517 #else 
518         std::string command2("gnome-open ");
519 #endif
520
521         command2=command2+filename_html;
522         page = filename_html;
523         // 1. Generate Html Diagram
524         std::ofstream s;
525         s.open(filename_html.c_str());
526         if (s.good()) 
527           {
528             s << "<html><head><title>BBtk graph diagram</title><meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\"></head>\n";
529             s << "<body bgcolor=\"#FFFFFF\" text=\"#000000\"> \n\n";
530             if ( blackbox->bbGetName()=="workspacePrototype" )
531               {
532                 s << "<center>Current workspace</center>";
533               } else {
534               s << "<center>" << blackbox->bbGetName()<< "</center>";
535             } 
536
537             blackbox->bbInsertHTMLGraph( s, detail, level, true, directory, false );
538             s << "</body></html>\n";      
539           }
540         s.close();
541         
542         // 2. Starting Browser
543         if (system_display) system( command2.c_str() );      
544       } 
545     else 
546       {
547         bbtkMessageInc("Help",1,"No black box: \""
548                        <<nameblackbox<<"\" " <<std::endl);
549         
550       }
551     return page;
552   }
553
554 void Executer::ShowRelations(const std::string &nameblackbox, const std::string &detailStr, const std::string &levelStr)
555   {
556        bool found=false;
557
558        int detail = atoi(detailStr.c_str());
559        int level  = atoi(levelStr.c_str());
560        BlackBox* blackbox=NULL;
561        if (nameblackbox.compare(".")==0)
562        {
563           blackbox=Current()->GetPrototype();
564        } else {
565           blackbox = Current()->GetPrototype()->bbFindBlackBox(nameblackbox);
566        }
567
568        if (blackbox)
569        {
570           found=true;
571           blackbox->bbShowRelations(blackbox,detail,level); //,mFactory);
572        }
573
574        if (!found) 
575        {
576           bbtkError("Blackbox Name not found.. <"  <<nameblackbox<<">");
577        }
578   }
579
580   /*
581   /// sets the level of message
582   void Executer::Message(const std::string &kind,
583                          const std::string& level)
584   {
585     int l;
586     sscanf(level.c_str(),"%d",&l);
587     bbtk::MessageManager::SetMessageLevel(kind,l);
588   }
589   */
590
591
592 }//namespace