]> Creatis software - bbtk.git/blob - kernel/src/bbtkInterpreter.h
*** empty log message ***
[bbtk.git] / kernel / src / bbtkInterpreter.h
1 /*=========================================================================                                                                               
2   Program:   bbtk
3   Module:    $RCSfile: bbtkInterpreter.h,v $
4   Language:  C++
5   Date:      $Date: 2008/12/15 09:04:47 $
6   Version:   $Revision: 1.39 $
7 =========================================================================*/
8
9 /* ---------------------------------------------------------------------
10
11 * Copyright (c) CREATIS-LRMN (Centre de Recherche en Imagerie Medicale)
12 * Authors : Eduardo Davila, Laurent Guigues, Jean-Pierre Roux
13 *
14 *  This software is governed by the CeCILL-B license under French law and 
15 *  abiding by the rules of distribution of free software. You can  use, 
16 *  modify and/ or redistribute the software under the terms of the CeCILL-B 
17 *  license as circulated by CEA, CNRS and INRIA at the following URL 
18 *  http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html 
19 *  or in the file LICENSE.txt.
20 *
21 *  As a counterpart to the access to the source code and  rights to copy,
22 *  modify and redistribute granted by the license, users are provided only
23 *  with a limited warranty  and the software's author,  the holder of the
24 *  economic rights,  and the successive licensors  have only  limited
25 *  liability. 
26 *
27 *  The fact that you are presently reading this means that you have had
28 *  knowledge of the CeCILL-B license and that you accept its terms.
29 * ------------------------------------------------------------------------ */                                                                         
30
31 /**
32  *  \file 
33  *  \brief class Interpreter : The bbtk language interpreter
34  */
35 /**
36  *  \class bbtk::Interpreter 
37  *  \brief The bbtk language interpreter
38  */
39
40 #ifndef __bbtkInterpreter_h__
41 #define __bbtkInterpreter_h__
42
43 #include "bbtkVirtualExec.h"
44 #include "bbtkExecuter.h"
45
46 #include <fstream>
47 #include <deque>
48
49 // Signal/slot mechanism for 'break' commands
50 //#include <boost/signal.hpp>
51 //#include <boost/bind.hpp>
52
53 namespace bbtk
54 {
55
56 #ifdef USE_WXWIDGETS
57   class WxConsole;
58 #endif
59   
60   //=======================================================================
61   class BBTK_EXPORT InterpreterUser
62   {
63   public: 
64     InterpreterUser() {}
65     virtual ~InterpreterUser() {}
66
67     virtual bool InterpreterUserHasOwnHtmlPageViewer() { return false; }
68     virtual void InterpreterUserViewHtmlPage(const std::string&) {}
69
70
71   };
72   //=======================================================================
73
74
75
76   //=======================================================================
77   class BBTK_EXPORT InterpreterException : public Exception
78   {
79   public:
80     InterpreterException( const std::string& message,
81                       bool in_script_file,
82                       const std::string& script_file,
83                       int script_line 
84                       );
85     InterpreterException( const Exception& excep,
86                       bool in_script_file,
87                       const std::string& script_file,
88                       int script_line 
89                       );
90     ~InterpreterException() throw() {}
91
92     bool IsInScriptFile() const { return mInScriptFile; }
93     const std::string& GetScriptFile() const { return mScriptFile; }
94     int GetScriptLine() const { return mScriptLine; }
95   private:
96     bool mInScriptFile;
97     std::string mScriptFile;
98     int mScriptLine;
99   };
100   //=======================================================================
101
102   /*
103   //=======================================================================
104   // The "Quit" exception
105   class BBTK_EXPORT QuitException : public InterpreterError
106   {
107   public:
108     QuitException( bool in_script_file,
109                    const std::string& script_file,
110                    int script_line 
111                    )
112       : InterpreterError("QUIT",in_script_file,script_file,script_line) 
113     {}
114     ~QuitException() throw() {}
115   };
116   //=======================================================================
117   const std::string BREAK("BREAK");
118   //=======================================================================
119   // The "Break" exception
120   class BBTK_EXPORT BreakException : public InterpreterError
121   {
122   public:
123     BreakException( bool in_script_file,
124                     std::string script_file,
125                     int script_line 
126                     )
127       : InterpreterError(BREAK,in_script_file,script_file,script_line) 
128     { std::cout << "BUILDING BREAK"<<std::endl; }
129     ~BreakException() throw() {}
130   };
131   //=======================================================================
132   */
133
134   //=======================================================================
135   class BBTK_EXPORT Interpreter : public Object
136   {
137     BBTK_OBJECT_INTERFACE_NO_CONDES(Interpreter);
138     typedef Object Superclass;
139   public:
140     static Pointer New(const std::string& cpp_file = "");
141     static Pointer New(VirtualExec::Pointer);
142
143     typedef enum 
144       {
145         Interpreter_OK,
146         Interpreter_ERROR,
147         Interpreter_QUIT,
148         Interpreter_BREAK,
149       }
150       ExitStatus;
151
152     /// Runs the interpretation of a file
153     ExitStatus InterpretFile( const std::string& filename, bool source = false);
154
155     /// Runs the interpretation of a buffer and deletes it !
156     ExitStatus InterpretBuffer( std::stringstream* buffer );
157
158     /// Runs the interpretation of a command
159     ExitStatus InterpretLine( const std::string& line );
160
161     /// Runs the interpretation of the currently open streams
162     ExitStatus InterpretCurrentStreams();
163
164     /// Launches a command line interpreter (with a prompt)
165     void CommandLineInterpreter();
166
167
168
169     /// Sets the inputs of the workspace :
170     /// the map is passed as is to the Executer
171     void SetInputs(const std::map<std::string,std::string>& m)
172     { mVirtualExecuter->SetInputs(m); }
173
174     /// Puts the executer in "no exec" mode,
175     /// which creates but does not execute pipelines.
176     void SetNoExecMode(bool m) { mVirtualExecuter->SetNoExecMode(m); }
177
178     /// Puts the executer in "no error" mode, 
179     /// Errors do not stop execution (but warnings are produced)
180     void SetNoErrorMode(bool m) { mVirtualExecuter->SetNoErrorMode(m);}
181     ///
182     //typedef Executer::DialogModeType DialogModeType;
183     typedef VirtualExec::DialogModeType DialogModeType;
184
185     void SetDialogMode(DialogModeType t) { mVirtualExecuter->SetDialogMode(t);}
186
187     /// Sets the bool that indicates wether we are in command line context
188     void SetCommandLine(bool v = true) { mCommandLine = v; }
189
190     void SetThrow(bool b) { mThrow = b; }
191
192 #ifdef USE_WXWIDGETS
193     /// Sets the user of the interpreter (if any)
194     void SetUser(InterpreterUser* c) { mUser = c; }
195     /// Gets the InterpreterUser of this 
196     InterpreterUser* GetUser() { return mUser; }
197     /// Gets the InterpreterUser of this (const)
198     const InterpreterUser* GetUser() const { return mUser; }
199
200 #endif
201
202     /// Gets the Executer 
203     VirtualExec::Pointer GetExecuter() const { return mVirtualExecuter; }
204
205     /*
206     // For 'break' commands observation
207     typedef boost::signals::trackable BreakObserverType;
208     typedef boost::signal<void ()>  BreakSignalType;
209     typedef BreakSignalType::slot_function_type BreakCallbackType;
210   
211     // Adds a callback when 'break' command issued
212     void AddBreakObserver( BreakCallbackType );
213     */
214
215   protected:
216
217     /// The enumeration of command codes == Command name
218     typedef enum
219     {
220       cBreak, // LG 12/12/08 : Stops the current script execution (if not exec frozen) - used in tutorial + debugging 
221       cClear, // LG 12/12/08 : Clears the current complex black box (e.g. workspace) - used in tours
222       cNew,
223       cDelete,
224       cConnect,
225       cExec,
226       cPackage,
227       cEndPackage,
228       cDefine,
229       cEndDefine,
230       cInput,
231       cOutput,
232       cSet,
233       cConfig,  // JPR
234       cReset,   // EED
235       cAuthor, 
236       cCategory, // JPR
237       cDescription,
238       cHelp,
239       cMessage,
240       cInclude,
241       cQuit,
242       cLoad,
243       cUnload,
244       cGraph,
245       cPrint,
246       cIndex,
247       cKind, // LG
248       cNewGUI, // LG
249       cWorkspace, // LG
250       cDebug // LG
251     } CommandCodeType;
252
253     /// The structure storing the informations on a command 
254     typedef struct 
255     {
256       std::string keyword;
257       int argmin, argmax;
258       CommandCodeType code;
259       std::string syntax;
260       std::string help;
261     } CommandInfoType;
262
263     /// The type of dictionnary of commands 
264     typedef std::map<std::string,CommandInfoType> CommandDictType;
265
266
267     /// Interprets a line 
268     void DoInterpretLine( const std::string& line ); //, bool &insideComment );
269
270     /// Reads a line from prompt
271     void GetLineFromPrompt( std::string& line );
272
273     /// Splits a line into words
274     void SplitLine ( const std::string& line,
275                      std::vector<std::string>& words );
276
277     /// Executes the right action depending on the command name
278     void InterpretCommand( const std::vector<std::string>& words,
279                            CommandInfoType& info );
280
281     /// Switch to the interpretation of a file
282     void SwitchToFile( const std::string& filename, bool source = false );
283
284    /// Switch to the interpretation of a stringstream
285     void SwitchToStream( std::stringstream* stream );
286
287     /// Closes the currently open file
288     void CloseCurrentFile();
289
290     /// Closes all open files
291     void CloseAllFiles();
292
293     /// Resets all
294     void Reset();
295
296     /// Displays help (entry point of any help)
297     void Help(const std::vector<std::string>& words);
298
299     /// Displays help on all the commands
300     void HelpCommands();
301
302     /// Displays help on a particular command 
303     void HelpCommand( const std::string& command );
304
305     ///
306     void Graph(const std::vector<std::string>& words);
307
308     ///
309     void Config() const; 
310     /// 
311     //    void Print(const std::string&);
312
313     void Index(const std::string& filename, 
314                const std::string& type = "Initials");
315     ///
316     void FindCommandsWithPrefix( char* buf,
317                                  int n,
318                                  std::vector<std::string>& commands );
319
320     /// Creates and connects the piece of pipeline which defines a GUI 
321     /// for the box box. 
322     /// Define it as a complex box type with name instanceName+"Type"
323     /// The instance is called instanceName
324     /// and connected to the existing pipeline
325     void NewGUI(const std::string& box, 
326                 const std::string& instanceName);
327
328     void Debug(const std::string& arg);
329
330  
331   private:
332
333     /// Constructor
334     Interpreter(const std::string& cpp_file = "");
335
336     Interpreter(VirtualExec::Pointer);
337
338     void Init(VirtualExec::Pointer, const std::string& cpp_file);
339
340     /// Opens the file fullPathScriptName 
341     /// includeScriptName is the name as given to the include command 
342     void LoadScript( std::string fullPathScriptName,
343                      std::string includeScriptName);
344
345     /// 
346     void CatchInterpreterException( const InterpreterException& e );
347     void CatchBbtkException( const bbtk::Exception& e );
348     void CatchStdException( const std::exception& e );
349     void CatchUnknownException();
350
351
352   
353     //==================================================================
354     // ATTRIBUTES
355
356     /// The command executer used
357     bbtk::VirtualExec::Pointer mVirtualExecuter;
358     bbtk::Executer::WeakPointer mRealExecuter;
359
360     /// The user of  the interpreter (0 if none)
361     bbtk::InterpreterUser* mUser;
362
363     /// Vector of open files / buffers (can be stringstream)
364     std::vector<std::istream*> mFile;
365
366     /// Vector of names of open files with full path (as open)
367     std::vector<std::string> mFileName;
368
369     /// Vector of names of files which have been open 
370     /// before (and may closed then which are no more in mFileName)
371     /// with full path (as open)
372     std::vector<std::string> mFileNameHistory;
373
374     /// Vector of names of open files as given to the include command
375     std::vector<std::string> mIncludeFileName;
376
377     /// Stores the current line number in each open file
378     std::vector<int> mLine;
379
380     /// The dictionnary of commands
381     CommandDictType mCommandDict;
382
383     /// Are we in a command line context ?
384     bool mCommandLine;
385
386     /// Are we inside a commented-out zone ?
387     bool mInsideComment;
388     
389     /// The current interpreter status
390     ExitStatus mStatus;
391
392     /// The history of commands
393     std::deque< char* > mHistory;
394
395     int bufferNb;
396     
397     bool mThrow;
398
399     /// The break signal
400     //    BreakSignalType mBreakSignal;
401
402   protected:
403     ~Interpreter();
404
405   };
406   // EO class Interpreter
407
408
409
410 }
411 #endif