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