]> git.mxchange.org Git - flightgear.git/blob - src/Scripting/NasalSys.hxx
Nasal: move IOrules check to better place and exit on failure.
[flightgear.git] / src / Scripting / NasalSys.hxx
1 #ifndef __NASALSYS_HXX
2 #define __NASALSYS_HXX
3
4 #include <simgear/math/SGMath.hxx> // keep before any cppbind include to enable
5                                    // SGVec2<T> conversion.
6 #include <simgear/misc/sg_dir.hxx>
7 #include <simgear/misc/sg_path.hxx>
8 #include <simgear/nasal/cppbind/NasalHash.hxx>
9 #include <simgear/nasal/nasal.h>
10 #include <simgear/props/props.hxx>
11 #include <simgear/structure/subsystem_mgr.hxx>
12 #include <simgear/threads/SGQueue.hxx>
13
14 // Required only for MSVC
15 #ifdef _MSC_VER
16 #   include <Scripting/NasalModelData.hxx>
17 #endif
18
19 #include <map>
20
21
22 class FGNasalScript;
23 class FGNasalListener;
24 class SGCondition;
25 class FGNasalModelData;
26 class NasalCommand;
27 class FGNasalModuleListener;
28
29 namespace simgear { class BufferedLogCallback; }
30
31 SGPropertyNode* ghostToPropNode(naRef ref);
32
33 class FGNasalSys : public SGSubsystem
34 {
35 public:
36     FGNasalSys();
37     virtual ~FGNasalSys();
38     virtual void init();
39     virtual void shutdown();
40     
41     virtual void update(double dt);
42
43     // Loads a nasal script from an external file and inserts it as a
44     // global module of the specified name.
45     bool loadModule(SGPath file, const char* moduleName);
46
47     // Simple hook to run arbitrary source code.  Returns a bool to
48     // indicate successful execution.  Does *not* return any Nasal
49     // values, because handling garbage-collected objects from C space
50     // is deep voodoo and violates the "simple hook" idea.
51     bool parseAndRun(const char* sourceCode);
52
53     // Slightly more complicated hook to get a handle to a precompiled
54     // Nasal script that can be invoked via a call() method.  The
55     // caller is expected to delete the FGNasalScript returned from
56     // this function.  The "name" argument specifies the "file name"
57     // for the source code that will be printed in Nasal stack traces
58     // on error.
59  //   FGNasalScript* parseScript(const char* src, const char* name=0);
60
61     // Implementation of the settimer extension function
62     void setTimer(naContext c, int argc, naRef* args);
63
64     // Implementation of the setlistener extension function
65     naRef setListener(naContext c, int argc, naRef* args);
66     naRef removeListener(naContext c, int argc, naRef* args);
67
68     // Returns a ghost wrapper for the current _cmdArg
69     naRef cmdArgGhost();
70
71     void setCmdArg(SGPropertyNode* aNode);
72     
73     /**
74      * create Nasal props.Node for an SGPropertyNode*
75      * This is the actual ghost, wrapped in a Nasal sugar class.
76      */
77     naRef wrappedPropsNode(SGPropertyNode* aProps);
78     
79     // Callbacks for command and timer bindings
80     virtual bool handleCommand( const char* moduleName,
81                                 const char* fileName,
82                                 const char* src,
83                                 const SGPropertyNode* arg = 0 );
84     virtual bool handleCommand(const SGPropertyNode* arg);
85
86     bool createModule(const char* moduleName, const char* fileName,
87                       const char* src, int len, const SGPropertyNode* cmdarg=0,
88                       int argc=0, naRef*args=0);
89
90     void deleteModule(const char* moduleName);
91
92     void addCommand(naRef func, const std::string& name);
93     void removeCommand(const std::string& name);
94     
95     /**
96      * Set member of specified hash to given value
97      */
98     void hashset(naRef hash, const char* key, naRef val);
99
100     /**
101      * Set member of globals hash to given value
102      */
103     void globalsSet(const char* key, naRef val);
104
105     naRef call(naRef code, int argc, naRef* args, naRef locals);
106     naRef callWithContext(naContext ctx, naRef code, int argc, naRef* args, naRef locals);
107   
108     naRef callMethod(naRef code, naRef self, int argc, naRef* args, naRef locals);
109     naRef callMethodWithContext(naContext ctx, naRef code, naRef self, int argc, naRef* args, naRef locals);
110   
111     naRef propNodeGhost(SGPropertyNode* handle);
112   
113     void registerToLoad(FGNasalModelData* data);
114     void registerToUnload(FGNasalModelData* data);
115
116     // can't call this 'globals' due to naming clash
117     naRef nasalGlobals() const
118     { return _globals; }
119
120     nasal::Hash getGlobals() const
121     { return nasal::Hash(_globals, _context); }
122   
123     // This mechanism is here to allow naRefs to be passed to
124     // locations "outside" the interpreter.  Normally, such a
125     // reference would be garbage collected unexpectedly.  By passing
126     // it to gcSave and getting a key/handle, it can be cached in a
127     // globals.__gcsave hash.  Be sure to release it with gcRelease
128     // when done.
129     int gcSave(naRef r);
130     void gcRelease(int key);
131
132     /**
133      * Check if IOrules correctly work to limit access from Nasal scripts to the
134      * file system.
135      *
136      * @note Just a simple test is performed to check if access to a path is
137      *       possible which should never be possible (The actual path refers to
138      *       a file/folder named 'do-not-access' in the file system root).
139      *
140      * @see http://wiki.flightgear.org/IOrules
141      *
142      * @return Whether the check was successful.
143      */
144     bool checkIOrules();
145
146     /// retrive the associated log object, for displaying log
147     /// output somewhere (a UI, presumably)
148     simgear::BufferedLogCallback* log() const
149     { return _log; }
150 private:
151     //friend class FGNasalScript;
152     friend class FGNasalListener;
153     friend class FGNasalModuleListener;
154
155     SGLockedQueue<SGSharedPtr<FGNasalModelData> > _loadList;
156     SGLockedQueue<SGSharedPtr<FGNasalModelData> > _unloadList;
157
158     // Delay removing items of the _loadList to ensure the are already attached
159     // to the scene graph (eg. enables to retrieve world position in load
160     // callback).
161     bool _delay_load;
162
163     //
164     // FGTimer subclass for handling Nasal timer callbacks.
165     // See the implementation of the settimer() extension function for
166     // more notes.
167     //
168     struct NasalTimer {
169         virtual void timerExpired();
170         virtual ~NasalTimer() {}
171         naRef handler;
172         int gcKey;
173         FGNasalSys* nasal;
174     };
175
176     // Listener
177     std::map<int, FGNasalListener *> _listener;
178     std::vector<FGNasalListener *> _dead_listener;
179     
180     std::vector<FGNasalModuleListener*> _moduleListeners;
181     
182     static int _listenerId;
183
184     void loadPropertyScripts();
185     void loadPropertyScripts(SGPropertyNode* n);
186     void loadScriptDirectory(simgear::Dir nasalDir);
187     void addModule(std::string moduleName, simgear::PathList scripts);
188     static void logError(naContext);
189     naRef parse(naContext ctx, const char* filename, const char* buf, int len);
190     naRef genPropsModule();
191
192     bool _inited;
193     naContext _context;
194     naRef _globals,
195           _string;
196
197     SGPropertyNode_ptr _cmdArg;
198
199     simgear::BufferedLogCallback* _log;
200     
201     typedef std::map<std::string, NasalCommand*> NasalCommandDict;
202     NasalCommandDict _commands;
203     
204     naRef _wrappedNodeFunc;
205 public:
206     void handleTimer(NasalTimer* t);
207 };
208
209 #if 0
210 class FGNasalScript {
211 public:
212     ~FGNasalScript() { _nas->gcRelease(_gcKey); }
213
214     bool call() {
215         naRef n = naNil();
216         naCall(_nas->_context, _code, 0, &n, naNil(), naNil());
217         return naGetError(_nas->_context) == 0;
218     }
219     
220     FGNasalSys* sys() const { return _nas; }
221 private:
222     friend class FGNasalSys;
223     naRef _code;
224     int _gcKey;
225     FGNasalSys* _nas;
226 };
227 #endif
228
229 #endif // __NASALSYS_HXX