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