]> git.mxchange.org Git - flightgear.git/blob - src/Scripting/NasalSys.cxx
Some small updates
[flightgear.git] / src / Scripting / NasalSys.cxx
1 #include <string.h>
2 #include <stdio.h>
3 #include <sys/types.h>
4 #include <sys/stat.h>
5
6 #include <plib/ul.h>
7
8 #include <simgear/nasal/nasal.h>
9 #include <simgear/props/props.hxx>
10 #include <simgear/misc/sg_path.hxx>
11 #include <simgear/structure/commands.hxx>
12
13 #include <Main/globals.hxx>
14
15 #include "NasalSys.hxx"
16
17 // Read and return file contents in a single buffer.  Note use of
18 // stat() to get the file size.  This is a win32 function, believe it
19 // or not. :) Note the REALLY IMPORTANT use of the "b" flag to fopen.
20 // Text mode brain damage will kill us if we're trying to do bytewise
21 // I/O.
22 static char* readfile(const char* file, int* lenOut)
23 {
24     struct stat data;
25     if(stat(file, &data) != 0) return 0;
26     FILE* f = fopen(file, "rb");
27     if(!f) return 0;
28     char* buf = new char[data.st_size];
29     *lenOut = fread(buf, 1, data.st_size, f);
30     fclose(f);
31     if(*lenOut != data.st_size) {
32         // Shouldn't happen, but warn anyway since it represents a
33         // platform bug and not a typical runtime error (missing file,
34         // etc...)
35         SG_LOG(SG_NASAL, SG_ALERT,
36                "ERROR in Nasal initialization: " <<
37                "short count returned from fread().  Check your C library!");
38         delete[] buf;
39         return 0;
40     }
41     return buf;
42 }
43
44 FGNasalSys::FGNasalSys()
45 {
46     _context = 0;
47     _globals = naNil();
48     _timerHash = naNil();
49     _nextTimerHashKey = 0; // Any value will do
50 }
51
52 FGNasalSys::~FGNasalSys()
53 {
54     // Nasal doesn't have a "destroy context" API yet. :(
55     // Not a problem for a global subsystem that will never be
56     // destroyed.  And the context is actually a global, so no memory
57     // is technically leaked (although the GC pool memory obviously
58     // won't be freed).
59     _context = 0;
60     _globals = naNil();
61 }
62
63 // Utility.  Sets a named key in a hash by C string, rather than nasal
64 // string object.
65 void FGNasalSys::hashset(naRef hash, const char* key, naRef val)
66 {
67     naRef s = naNewString(_context);
68     naStr_fromdata(s, (char*)key, strlen(key));
69     naHash_set(hash, s, val);
70 }
71
72 // The get/setprop functions accept a *list* of strings and walk
73 // through the property tree with them to find the appropriate node.
74 // This allows a Nasal object to hold onto a property path and use it
75 // like a node object, e.g. setprop(ObjRoot, "size-parsecs", 2.02).  This
76 // is the utility function that walks the property tree.
77 // Future enhancement: support integer arguments to specify array
78 // elements.
79 static SGPropertyNode* findnode(naContext c, naRef vec, int len)
80 {
81     SGPropertyNode* p = globals->get_props();
82     for(int i=0; i<len; i++) {
83         naRef a = naVec_get(vec, i);
84         if(!naIsString(a)) return 0;
85         p = p->getNode(naStr_data(a));
86         if(p == 0) return 0;
87     }
88     return p;
89 }
90
91 // getprop() extension function.  Concatenates its string arguments as
92 // property names and returns the value of the specified property.  Or
93 // nil if it doesn't exist.
94 static naRef f_getprop(naContext c, naRef args)
95 {
96     const SGPropertyNode* p = findnode(c, args, naVec_size(args));
97     if(!p) return naNil();
98
99     switch(p->getType()) {
100     case SGPropertyNode::BOOL:   case SGPropertyNode::INT:
101     case SGPropertyNode::LONG:   case SGPropertyNode::FLOAT:
102     case SGPropertyNode::DOUBLE:
103         return naNum(p->getDoubleValue());
104
105     case SGPropertyNode::STRING:
106         {
107             naRef nastr = naNewString(c);
108             const char* val = p->getStringValue();
109             naStr_fromdata(nastr, (char*)val, strlen(val));
110             return nastr;
111         }
112     default:
113         return naNil();
114     }
115 }
116
117 // setprop() extension function.  Concatenates its string arguments as
118 // property names and sets the value of the specified property to the
119 // final argument.
120 static naRef f_setprop(naContext c, naRef args)
121 {
122 #define BUFLEN 1024
123     int argc = naVec_size(args);
124     char buf[BUFLEN + 1];
125     buf[BUFLEN] = 0;
126     char* p = buf;
127     int buflen = BUFLEN;
128     for(int i=0; i<argc-1; i++) {
129         naRef s = naStringValue(c, naVec_get(args, i));
130         if(naIsNil(s)) return naNil();
131         strncpy(p, naStr_data(s), buflen);
132         p += naStr_len(s);
133         buflen = BUFLEN - (p - buf);
134         if(i < (argc-2) && buflen > 0) {
135             *p++ = '/';
136             buflen--;
137         }
138     }
139
140     SGPropertyNode* props = globals->get_props();
141     naRef val = naVec_get(args, argc-1);
142     if(naIsString(val)) props->setStringValue(buf, naStr_data(val));
143     else                props->setDoubleValue(buf, naNumValue(val).num);
144     return naNil();
145 #undef BUFLEN
146 }
147
148 // print() extension function.  Concatenates and prints its arguments
149 // to the FlightGear log.  Uses the highest log level (SG_ALERT), to
150 // make sure it appears.  Is there better way to do this?
151 static naRef f_print(naContext c, naRef args)
152 {
153 #define BUFLEN 1024
154     char buf[BUFLEN + 1];
155     buf[BUFLEN] = 0; // extra nul to handle strncpy brain damage
156     char* p = buf;
157     int buflen = BUFLEN;
158     int n = naVec_size(args);
159     for(int i=0; i<n; i++) {
160         naRef s = naStringValue(c, naVec_get(args, i));
161         if(naIsNil(s)) continue;
162         strncpy(p, naStr_data(s), buflen);
163         p += naStr_len(s);
164         buflen = BUFLEN - (p - buf);
165         if(buflen <= 0) break;
166     }
167     SG_LOG(SG_GENERAL, SG_ALERT, buf);
168     return naNil();
169 #undef BUFLEN
170 }
171
172 // fgcommand() extension function.  Executes a named command via the
173 // FlightGear command manager.  Takes a single property node name as
174 // an argument.
175 static naRef f_fgcommand(naContext c, naRef args)
176 {
177     naRef cmd = naVec_get(args, 0);
178     naRef props = naVec_get(args, 1);
179     if(!naIsString(cmd) || !naIsString(props)) return naNil();
180
181     SGPropertyNode* pnode =
182         globals->get_props()->getNode(naStr_data(props));
183     if(pnode)
184         globals->get_commands()->execute(naStr_data(cmd), pnode);
185     return naNil();
186 }
187
188 // settimer(func, dt, simtime) extension function.  Falls through to
189 // FGNasalSys::setTimer().  See there for docs.
190 static naRef f_settimer(naContext c, naRef args)
191 {
192     FGNasalSys* nasal = (FGNasalSys*)globals->get_subsystem("nasal");
193     nasal->setTimer(args);
194     return naNil();
195 }
196
197 // Table of extension functions.  Terminate with zeros.
198 static struct { char* name; naCFunction func; } funcs[] = {
199     { "getprop",   f_getprop },
200     { "setprop",   f_setprop },
201     { "print",     f_print },
202     { "fgcommand", f_fgcommand },
203     { "settimer",  f_settimer },
204     { 0, 0 }
205 };
206
207 void FGNasalSys::init()
208 {
209     _context = naNewContext();
210
211     // Start with globals.  Add it to itself as a recursive
212     // sub-reference under the name "globals".  This gives client-code
213     // write access to the namespace if someone wants to do something
214     // fancy.
215     _globals = naStdLib(_context);
216     naSave(_context, _globals);
217     hashset(_globals, "globals", _globals);
218
219     // Add in the math library under "math"
220     hashset(_globals, "math", naMathLib(_context));
221
222     // Add our custom extension functions:
223     for(int i=0; funcs[i].name; i++)
224         hashset(_globals, funcs[i].name,
225                 naNewFunc(_context, naNewCCode(_context, funcs[i].func)));
226
227     // Make a "__timers" hash to hold the settimer() handlers (to
228     // protect them from begin garbage-collected).
229     _timerHash = naNewHash(_context);
230     hashset(_globals, "__timers", _timerHash);
231
232     // Now load the various source files in the Nasal directory
233     SGPath p(globals->get_fg_root());
234     p.append("Nasal");
235     ulDirEnt* dent;
236     ulDir* dir = ulOpenDir(p.c_str());
237     while(dir && (dent = ulReadDir(dir)) != 0) {
238         SGPath fullpath(p);
239         fullpath.append(dent->d_name);
240         SGPath file(dent->d_name);
241         if(file.extension() != "nas") continue;
242         readScriptFile(fullpath, file.base().c_str());
243     }
244 }
245
246 // Logs a runtime error, with stack trace, to the FlightGear log stream
247 void FGNasalSys::logError()
248 {
249     SG_LOG(SG_NASAL, SG_ALERT,
250            "Nasal runtime error: " << naGetError(_context));
251     SG_LOG(SG_NASAL, SG_ALERT,
252            "  at " << naStr_data(naGetSourceFile(_context, 0)) <<
253            ", line " << naGetLine(_context, 0));
254     for(int i=1; i<naStackDepth(_context); i++)
255         SG_LOG(SG_NASAL, SG_ALERT,
256                "  called from: " << naStr_data(naGetSourceFile(_context, i)) <<
257                ", line " << naGetLine(_context, i));
258 }
259
260 // Reads a script file, executes it, and places the resulting
261 // namespace into the global namespace under the specified module
262 // name.
263 void FGNasalSys::readScriptFile(SGPath file, const char* lib)
264 {
265     int len = 0;
266     char* buf = readfile(file.c_str(), &len);
267     if(!buf) return;
268
269     // Parse and run.  Save the local variables namespace, as it will
270     // become a sub-object of globals.
271     naRef code = parse(file.c_str(), buf, len);
272     delete[] buf;
273     if(naIsNil(code))
274         return;
275
276     naRef locals = naNewHash(_context);
277     naCall(_context, code, naNil(), naNil(), locals);
278     if(naGetError(_context)) {
279         logError();
280         return;
281     }
282
283     hashset(_globals, lib, locals);
284 }
285
286 naRef FGNasalSys::parse(const char* filename, const char* buf, int len)
287 {
288     int errLine = -1;
289     naRef srcfile = naNewString(_context);
290     naStr_fromdata(srcfile, (char*)filename, strlen(filename));
291     naRef code = naParseCode(_context, srcfile, 1, (char*)buf, len, &errLine);
292     if(naIsNil(code)) {
293         SG_LOG(SG_NASAL, SG_ALERT,
294                "Nasal parse error: " << naGetError(_context) <<
295                " in "<< filename <<", line " << errLine);
296         return naNil();
297     }
298
299     // Bind to the global namespace before returning
300     return naBindFunction(_context, code, _globals);
301 }
302
303 bool FGNasalSys::handleCommand(const SGPropertyNode* arg)
304 {
305     // Parse the Nasal source.  I'd love to use the property name of
306     // the argument, but it's actually a *clone* of the original
307     // location in the property tree.  arg->getPath() returns an empty
308     // string.
309     const char* nasal = arg->getStringValue("script");
310     naRef code = parse("<command>", nasal, strlen(nasal));
311     if(naIsNil(code)) return false;
312     
313     // FIXME: Cache the just-created code object somewhere, but watch
314     // for changes to the source in the property tree.  Maybe store an
315     // integer index into a Nasal vector in the original property
316     // location?
317
318     // Extract the "value" or "offset" arguments if present
319     naRef locals = naNil();
320     if(arg->hasValue("value")) {
321         locals = naNewHash(_context);
322         hashset(locals, "value", naNum(arg->getDoubleValue("value")));
323     } else if(arg->hasValue("offset")) {
324         locals = naNewHash(_context);
325         hashset(locals, "offset", naNum(arg->getDoubleValue("offset")));
326     }
327
328     // Call it!
329     naRef result = naCall(_context, code, naNil(), naNil(), locals);
330     if(!naGetError(_context)) return true;
331     logError();
332     return false;
333 }
334
335 // settimer(func, dt, simtime) extension function.  The first argument
336 // is a Nasal function to call, the second is a delta time (from now),
337 // in seconds.  The third, if present, is a boolean value indicating
338 // that "simulator" time (rather than real time) is to be used.
339 //
340 // Implementation note: the FGTimer objects don't live inside the
341 // garbage collector, so the Nasal handler functions have to be
342 // "saved" somehow lest they be inadvertently cleaned.  In this case,
343 // they are inserted into a globals._timers hash and removed on
344 // expiration.
345 void FGNasalSys::setTimer(naRef args)
346 {
347     // Extract the handler, delta, and simtime arguments:
348     naRef handler = naVec_get(args, 0);
349     if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler)))
350         return;
351
352     naRef delta = naNumValue(naVec_get(args, 1));
353     if(naIsNil(delta)) return;
354     
355     bool simtime = naTrue(naVec_get(args, 2)) ? true : false;
356
357     // Generate and register a C++ timer handler
358     NasalTimer* t = new NasalTimer;
359     t->handler = handler;
360     t->hashKey = _nextTimerHashKey++;
361     t->nasal = this;
362
363     globals->get_event_mgr()->addEvent("NasalTimer",
364                                        t, &NasalTimer::timerExpired,
365                                        delta.num, simtime);
366
367
368     // Save the handler in the globals.__timers hash to prevent
369     // garbage collection.
370     naHash_set(_timerHash, naNum(t->hashKey), handler);
371 }
372
373 void FGNasalSys::handleTimer(NasalTimer* t)
374 {
375     naCall(_context, t->handler, naNil(), naNil(), naNil());
376     naHash_delete(_timerHash, naNum(t->hashKey));
377 }
378
379 void FGNasalSys::NasalTimer::timerExpired()
380 {
381     nasal->handleTimer(this);
382     delete this;
383 }