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