]> Creatis software - bbtk.git/blob - kernel/src/bbtkTranscriptor.cxx
some fixes
[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 13:48:13 $
7   Version:   $Revision: 1.2 $
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 /*
381     BlackBox* b = Current()->GetPrototype()->bbGetBlackBox(box);
382     // Looks for the adaptor
383
384     if ( b->bbGetInputType(input) !=  typeid(std::string) ) 
385       {
386          BlackBox* a = 
387          NewAdaptor(typeid(std::string),
388                     b->bbGetInputType(input),
389                     "tmp");
390          if (!a) 
391          {
392             bbtkError("No <"<<
393                       TypeName(b->bbGetInputType(input))
394                       <<"> to <std::string> found");
395          }
396          std::string v(value);
397          a->bbSetInput("In",v);
398          a->bbExecute();
399          b->bbSetInput(input,a->bbGetOutput("Out"));
400          a->bbDelete();
401       }
402     else 
403       {
404       std::string v(value);
405       b->bbSetInput(input,v);
406       }
407 */
408   }
409
410   /**
411    *  
412    */ 
413   std::string Transcriptor::Get(const std::string &box,
414                             const std::string &output)
415   {
416   
417     m_Fp << "// ==> Get() called here"                   << std::endl;  
418 /*    
419     BlackBox* b = Current()->GetPrototype()->bbGetBlackBox(box);
420     // Looks for the adaptor
421     if (b->bbGetOutputType(output) != typeid(std::string)) 
422       {
423       BlackBox* a = 
424           NewAdaptor(
425              b->bbGetOutputType(output),
426              typeid(std::string),
427              "tmp");
428       if (!a) 
429         {
430         bbtkError("No <"<<
431                    TypeName(b->bbGetOutputType(output))
432                    <<"> to <std::string> found");
433         }
434         b->bbExecute();
435
436         a->bbSetInput("In",b->bbGetOutput(output));
437         a->bbExecute();
438         std::string r = a->bbGetOutput("Out").unsafe_get<std::string>();
439        //std::string v = *((std::string*)a->bbGetOutput("Out")) ;
440        //   std::cout << a->bbGetOutput("Out").unsafe_get<std::string>() 
441        //             << std::endl;
442        //std::string v(value);
443        //b->bbSetInput(input,a->bbGetOutput("Out"));
444         a->bbDelete();
445         return r;
446       }
447     else 
448       {
449        b->bbExecute();
450        return b->bbGetOutput(output).unsafe_get<std::string>();
451        // std::string v = *((std::string*)b->bbGetOutput(output)) ;
452        // std::cout << b->bbGetOutput("Out").unsafe_get<std::string>() 
453        //   << std::endl;
454        // b->bbSetInput(input,&v);
455       }
456 */
457   }
458
459
460   void Transcriptor::Author(const std::string &authorName)
461   {
462     //Current()->AddToAuthor(authorName,Current()==mRoot);
463     if (Current()==mRoot)    
464        m_Fp << "e->AddToAuthor(\"" << authorName << "\", true)" << std::endl;
465     else
466        m_Fp << "e->AddToAuthor(\"" << authorName << "\", false)" << std::endl;
467   }
468
469   void Transcriptor::Category(const std::string &category)
470   {           
471     //Current()->AddToCategory(category,Current()==mRoot);
472     if (Current()==mRoot)    
473        m_Fp << "e->AddToCategory(\"" << category << "\", true)" << std::endl;
474     else
475        m_Fp << "e->AddToCategory(\"" << category << "\", false)" << std::endl;
476   }
477
478   void Transcriptor::Description(const std::string &d)
479   {
480     // Current()->AddToDescription(d,Current()==mRoot);
481     if (Current()==mRoot)    
482        m_Fp << "e->AddToDescription(\"" << d << "\", true)" << std::endl;
483     else
484        m_Fp << "e->AddToDescription(\"" << d << "\", false)" << std::endl;    
485   }
486
487
488   /// prints the list of the boxes of the current descriptor
489   void Transcriptor::PrintBoxes()
490   { 
491     m_Fp << "// ==> :PrintBoxes() called here"                   << std::endl;           
492  /* 
493     bbtkMessageInc("Help",1,"The black box descriptor \""
494                    <<Current()->GetTypeName()<<"\" contains : "<<std::endl);
495     Current()->PrintBlackBoxes();
496     bbtkDecTab("Help",1);
497  */
498  }
499
500 // =========================End of Battelfield ========================================================================
501
502   std::string Transcriptor::ShowGraph(const std::string &nameblackbox, 
503                                   const std::string &detailStr, 
504                                   const std::string &levelStr,
505                                   const std::string &output_html,
506                                   const std::string &custom_header,
507                                   const std::string &custom_title,
508                                   bool system_display )
509   {
510     int detail  =       atoi(detailStr.c_str());
511     int level   =       atoi(levelStr.c_str());
512
513     std::string filename_rootHtml (output_html) ;
514     std::string simplefilename_rootHtml ( Utilities::get_file_name(output_html));
515
516     bool relative_link = true;
517
518     // No output provided : automatic generation
519     if (output_html.length() == 0)
520       {
521         // Don't pollute the file store with  "temp_dir" directories ...    
522         std::string default_doc_dir = ConfigurationFile::GetInstance().Get_default_temp_dir();
523         
524         char c = default_doc_dir.c_str()[strlen(default_doc_dir.c_str())-1];
525         
526         std::string directory = default_doc_dir; 
527         if (c != '/' && c !='\\') directory = directory + "/";
528         directory = directory +  "temp_dir";    
529         
530         filename_rootHtml = directory + "/" + "User.html";
531         simplefilename_rootHtml = "User.html" ;
532
533         // Creating directory
534         std::string command0("mkdir \"" +directory + "\"");
535         system( command0.c_str() );
536
537         relative_link = false;
538       }
539
540     Package* p;
541     try
542     {
543            p = GetGlobalFactory()->GetPackage(nameblackbox);
544     }
545     catch (Exception e)
546     {
547            p = mPackage;
548     }
549     // Generating documentation-help of workspace
550     p->SetDocURL(filename_rootHtml);
551     p->SetDocRelativeURL(simplefilename_rootHtml);
552
553     p->CreateHtmlPage(filename_rootHtml,"bbi","user package",custom_header,custom_title,detail,level,relative_link);
554
555     std::string page = filename_rootHtml;
556     /*
557     try 
558     {
559           ShowGraphTypes(nameblackbox);
560     }
561     catch (bbtk::Exception a)
562     {
563           std::cout <<"EXC"<<std::endl;
564           page = ShowGraphInstances(nameblackbox,detail,level,system_display);
565     }
566     */
567     return page;
568   }
569
570   /// Generate a png file with the actual pipeline (Graphviz-dot needed)
571   std::string Transcriptor::ShowGraphInstances(const std::string &nameblackbox, int detail, int level,
572                                     bool system_display)
573   {
574
575     BlackBox* blackbox=NULL;
576     if (nameblackbox==".")
577     {
578           blackbox=Current()->GetPrototype();
579     }
580     else 
581     {
582           blackbox = Current()->GetPrototype()->bbFindBlackBox(nameblackbox);
583     }
584     
585     std::string page;
586
587     if (blackbox)
588       {      
589         // Don't pollute the file store with  "temp_dir" directories ...    
590         std::string default_doc_dir = ConfigurationFile::GetInstance().Get_default_temp_dir();
591         char c = default_doc_dir.c_str()[strlen(default_doc_dir.c_str())-1];
592         
593         std::string directory = default_doc_dir; 
594         if (c != '/' && c !='\\') directory = directory + "/";
595
596         directory = directory +  "temp_dir"; 
597         
598         //std::string directory("temp_dir");
599         std::string filename(directory + "/" + "bbtk_graph_pipeline");
600         std::string filename_html(filename+".html");
601         std::string command0("mkdir \""+directory + "\"");
602
603 #if defined(_WIN32)  
604         std::string command2("start ");
605 #else 
606         std::string command2("gnome-open ");
607 #endif
608
609         command2=command2+filename_html;
610         page = filename_html;
611         // 1. Generate Html Diagram
612         std::ofstream s;
613         s.open(filename_html.c_str());
614         if (s.good()) 
615           {
616             s << "<html><head><title>BBtk graph diagram</title><meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\"></head>\n";
617             s << "<body bgcolor=\"#FFFFFF\" text=\"#000000\"> \n\n";
618             if ( blackbox->bbGetName()=="workspacePrototype" )
619               {
620                 s << "<center>Current workspace</center>";
621               } else {
622               s << "<center>" << blackbox->bbGetName()<< "</center>";
623             } 
624
625             blackbox->bbInsertHTMLGraph( s, detail, level, true, directory, false );
626             s << "</body></html>\n";      
627           }
628         s.close();
629         
630         // 2. Starting Browser
631         if (system_display) system( command2.c_str() );      
632       } 
633     else 
634       {
635         bbtkMessageInc("Help",1,"No black box: \""
636                        <<nameblackbox<<"\" " <<std::endl);
637         
638       }
639     return page;
640   }
641
642 void Transcriptor::ShowRelations(const std::string &nameblackbox, const std::string &detailStr, const std::string &levelStr)
643   {
644        bool found=false;
645
646        int detail = atoi(detailStr.c_str());
647        int level  = atoi(levelStr.c_str());
648        BlackBox* blackbox=NULL;
649        if (nameblackbox.compare(".")==0)
650        {
651           blackbox=Current()->GetPrototype();
652        } else {
653           blackbox = Current()->GetPrototype()->bbFindBlackBox(nameblackbox);
654        }
655
656        if (blackbox)
657        {
658           found=true;
659           blackbox->bbShowRelations(blackbox,detail,level); //,mFactory);
660        }
661
662        if (!found) 
663        {
664           bbtkError("Blackbox Name not found.. <"  <<nameblackbox<<">");
665        }
666   }
667
668   /*
669   /// sets the level of message
670   void Transcriptor::Message(const std::string &kind,
671                          const std::string& level)
672   {
673     int l;
674     sscanf(level.c_str(),"%d",&l);
675     bbtk::MessageManager::SetMessageLevel(kind,l);
676   }
677   */
678
679
680 }//namespace