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