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