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