]> Creatis software - bbtk.git/blob - kernel/src/bbtkExecuter.cxx
Some indentation
[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 20:26:54 $
7   Version:   $Revision: 1.11 $
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 std::cout << "====================================================== delete Executer\n";  
61      bbtkDebugMessageInc("Kernel",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("Kernel",9);
72   }
73
74
75 /**
76  *
77  */
78   void Executer::Reset()
79   {
80     bbtkDebugMessageInc("Kernel",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("Kernel",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("Kernel",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("Kernel",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("Kernel",9);
161   }
162
163   /// Sets the file name to use for the current definition
164   /// (Used to set it after the Define command)
165   void Executer::SetCurrentFileName (const std::string &name )
166   {
167     mOpenDefinition.back().box->SetScriptFileName(name);
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     void Executer::Remove (const std::string &nodeName)
212   {
213     // Current()->RemoveBlackBox(nodeName);
214   }
215   */
216
217 /**
218  *
219  */
220   void Executer::Connect (const std::string &nodeFrom,
221                           const std::string &outputLabel,
222                           const std::string &nodeTo, 
223                           const std::string &inputLabel)
224   {
225     Current()->Connect(nodeFrom, outputLabel, nodeTo, inputLabel);
226   }
227
228  /**
229  *
230  */ 
231   void Executer::Update (const std::string &nodeName) // would 'Execute' be more meaningfull ?
232   {
233  // if in root
234      if (Current()==mRoot) 
235      {
236         if (!mNoExecMode) 
237         {
238            Current()->GetPrototype()->bbGetBlackBox(nodeName)->bbExecute(true);
239         }
240      }
241      else 
242      {
243         Current()->AddToExecutionList(nodeName) ;
244      }
245   }
246
247 /**
248  *
249  */
250   void Executer::DefineInput ( const std::string &name,
251                                const std::string &box,
252                                const std::string &input,
253                                const std::string& help)
254   {
255     // If the input is defined in the Root box
256     if (Current()==mRoot) 
257       {
258       // If the dialog mode is set to NoDialog
259       // and the user passed the name in the Inputs map 
260       // then the associated value is set to the box.input
261       // This is the way command line parameters are passed to the Root box
262          if (mDialogMode == NoDialog) 
263          {
264          // find if name is in mInputs
265             std::map<std::string,std::string>::iterator i;
266             i = mInputs.find(name);
267             if (i!=mInputs.end()) {
268                Set(box,input,(*i).second);
269             }
270          }
271         // If the dialog mode is set to TextDialog
272         // The user is prompted for the value
273         else if (mDialogMode == TextDialog) 
274         {
275            std::cout << name << "=";
276            std::string ans;
277            std::cin >> ans;
278            Set(box,input,ans);
279         }
280 #ifdef _USE_WXWIDGETS_
281        // If the dialog mode is set to GraphicalDialog
282        // A dialog box is pop up
283        else if (mDialogMode == GraphicalDialog) 
284        {
285           std::string mess("Enter the value of '");
286           mess += name;
287           mess += "' (";
288           mess += help;
289           mess += ")";
290           std::string title(name);
291           title += " ?";
292           std::string ans = wx2std ( wxGetTextFromUser( std2wx (mess), std2wx(title)));
293           Set(box,input,ans); 
294        }
295 #endif
296     }
297
298     Current()->DefineInput(name,box,input,help);
299
300   }
301
302  /**
303  *  
304  */ 
305    void Executer::DefineOutput ( const std::string &name,
306                                  const std::string &box,
307                                  const std::string &output,
308                                  const std::string& help)
309   {
310     Current()->DefineOutput(name,box,output,help);
311   }
312
313   /**
314    *  
315    */ 
316   void Executer::Set (const std::string &box,
317                       const std::string &input,
318                       const std::string &value)
319   {
320     BlackBox* b = Current()->GetPrototype()->bbGetBlackBox(box);
321     // Looks for the adaptor
322
323     if ( b->bbGetInputType(input) !=  typeid(std::string) ) 
324       {
325          BlackBox* a =
326          NewAdaptor(typeid(std::string),
327                     b->bbGetInputType(input),
328                     "tmp");
329          if (!a) 
330          {
331             bbtkError("No <"<<
332                       TypeName(b->bbGetInputType(input))
333                       <<"> to <std::string> found");
334          }
335          std::string v(value);
336          a->bbSetInput("In",v);
337          a->bbExecute();
338          b->bbSetInput(input,a->bbGetOutput("Out"));
339          a->bbDelete();
340       }
341     else 
342       {
343       std::string v(value);
344       b->bbSetInput(input,v);
345       }
346   }
347
348   /**
349    *
350    */
351   std::string Executer::Get(const std::string &box,
352                             const std::string &output)
353   {
354     BlackBox* b = Current()->GetPrototype()->bbGetBlackBox(box);
355     // Looks for the adaptor
356     if (b->bbGetOutputType(output) != typeid(std::string)) 
357       {
358       BlackBox* a =
359           NewAdaptor(
360              b->bbGetOutputType(output),
361              typeid(std::string),
362              "tmp");
363       if (!a) 
364         {
365         bbtkError("No <"<<
366                    TypeName(b->bbGetOutputType(output))
367                    <<"> to <std::string> found");
368         }
369         b->bbExecute();
370
371         a->bbSetInput("In",b->bbGetOutput(output));
372         a->bbExecute();
373         std::string r = a->bbGetOutput("Out").unsafe_get<std::string>();
374        //std::string v = *((std::string*)a->bbGetOutput("Out")) ;
375        //   std::cout << a->bbGetOutput("Out").unsafe_get<std::string>() 
376        //             << std::endl;
377        //std::string v(value);
378        //b->bbSetInput(input,a->bbGetOutput("Out"));
379         a->bbDelete();
380         return r;
381       }
382     else
383       {
384        b->bbExecute();
385        return b->bbGetOutput(output).unsafe_get<std::string>();
386        // std::string v = *((std::string*)b->bbGetOutput(output)) ;
387        // std::cout << b->bbGetOutput("Out").unsafe_get<std::string>() 
388        //   << std::endl;
389        // b->bbSetInput(input,&v);
390       }
391   }
392
393
394   void Executer::Author(const std::string &authorName)
395   {
396     Current()->AddToAuthor(authorName,Current()==mRoot);
397   }
398
399   void Executer::Category(const std::string &category)
400   {
401     Current()->AddToCategory(category,Current()==mRoot);
402   }
403
404   void Executer::Description(const std::string &d)
405   {
406      Current()->AddToDescription(d,Current()==mRoot);
407   }
408
409
410   /// prints the list of the boxes of the current descriptor
411   void Executer::PrintBoxes()
412   {
413     bbtkMessageInc("Help",1,"The black box descriptor \""
414                    <<Current()->GetTypeName()<<"\" contains : "<<std::endl);
415     Current()->PrintBlackBoxes();
416     bbtkDecTab("Help",1);
417  }
418
419   std::string Executer::ShowGraph(const std::string &nameblackbox, 
420                                   const std::string &detailStr, 
421                                   const std::string &levelStr,
422                                   const std::string &output_html,
423                                   const std::string &custom_header,
424                                   const std::string &custom_title,
425                                   bool system_display )
426   {
427     int detail  =       atoi(detailStr.c_str());
428     int level   =       atoi(levelStr.c_str());
429
430     std::string filename_rootHtml (output_html) ;
431     std::string simplefilename_rootHtml ( Utilities::get_file_name(output_html));
432
433     bool relative_link = true;
434
435     // No output provided : automatic generation
436     if (output_html.length() == 0)
437       {
438         // Don't pollute the file store with  "temp_dir" directories ...    
439         std::string default_doc_dir = ConfigurationFile::GetInstance().Get_default_temp_dir();
440         
441         char c = default_doc_dir.c_str()[strlen(default_doc_dir.c_str())-1];
442         
443         std::string directory = default_doc_dir; 
444         if (c != '/' && c !='\\') directory = directory + "/";
445         directory = directory +  "temp_dir";    
446         
447         filename_rootHtml = directory + "/" + "User.html";
448         simplefilename_rootHtml = "User.html" ;
449
450         // Creating directory
451         std::string command0("mkdir \"" +directory + "\"");
452         system( command0.c_str() );
453
454         relative_link = false;
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