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>
13 #include <Main/globals.hxx>
15 #include "NasalSys.hxx"
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
22 static char* readfile(const char* file, int* lenOut)
25 if(stat(file, &data) != 0) return 0;
26 FILE* f = fopen(file, "rb");
28 char* buf = new char[data.st_size];
29 *lenOut = fread(buf, 1, data.st_size, 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,
35 SG_LOG(SG_NASAL, SG_ALERT,
36 "ERROR in Nasal initialization: " <<
37 "short count returned from fread(). Check your C library!");
44 FGNasalSys::FGNasalSys()
49 _nextTimerHashKey = 0; // Any value will do
52 FGNasalSys::~FGNasalSys()
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
63 // Utility. Sets a named key in a hash by C string, rather than nasal
65 void FGNasalSys::hashset(naRef hash, const char* key, naRef val)
67 naRef s = naNewString(_context);
68 naStr_fromdata(s, (char*)key, strlen(key));
69 naHash_set(hash, s, val);
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
79 static SGPropertyNode* findnode(naContext c, naRef vec, int len)
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));
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)
96 const SGPropertyNode* p = findnode(c, args, naVec_size(args));
97 if(!p) return naNil();
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());
105 case SGPropertyNode::STRING:
107 naRef nastr = naNewString(c);
108 const char* val = p->getStringValue();
109 naStr_fromdata(nastr, (char*)val, strlen(val));
117 // setprop() extension function. Concatenates its string arguments as
118 // property names and sets the value of the specified property to the
120 static naRef f_setprop(naContext c, naRef args)
123 int argc = naVec_size(args);
124 char buf[BUFLEN + 1];
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);
133 buflen = BUFLEN - (p - buf);
134 if(i < (argc-2) && buflen > 0) {
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);
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)
154 char buf[BUFLEN + 1];
155 buf[BUFLEN] = 0; // extra nul to handle strncpy brain damage
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);
164 buflen = BUFLEN - (p - buf);
165 if(buflen <= 0) break;
167 SG_LOG(SG_GENERAL, SG_ALERT, buf);
172 // fgcommand() extension function. Executes a named command via the
173 // FlightGear command manager. Takes a single property node name as
175 static naRef f_fgcommand(naContext c, naRef args)
177 naRef cmd = naVec_get(args, 0);
178 naRef props = naVec_get(args, 1);
179 if(!naIsString(cmd) || !naIsString(props)) return naNil();
181 SGPropertyNode* pnode =
182 globals->get_props()->getNode(naStr_data(props));
184 globals->get_commands()->execute(naStr_data(cmd), pnode);
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)
192 FGNasalSys* nasal = (FGNasalSys*)globals->get_subsystem("nasal");
193 nasal->setTimer(args);
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 },
207 void FGNasalSys::init()
209 _context = naNewContext();
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
215 _globals = naStdLib(_context);
216 naSave(_context, _globals);
217 hashset(_globals, "globals", _globals);
219 // Add in the math library under "math"
220 hashset(_globals, "math", naMathLib(_context));
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)));
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);
232 // Now load the various source files in the Nasal directory
233 SGPath p(globals->get_fg_root());
236 ulDir* dir = ulOpenDir(p.c_str());
237 while(dir && (dent = ulReadDir(dir)) != 0) {
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());
246 // Logs a runtime error, with stack trace, to the FlightGear log stream
247 void FGNasalSys::logError()
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));
260 // Reads a script file, executes it, and places the resulting
261 // namespace into the global namespace under the specified module
263 void FGNasalSys::readScriptFile(SGPath file, const char* lib)
266 char* buf = readfile(file.c_str(), &len);
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);
276 naRef locals = naNewHash(_context);
277 naCall(_context, code, naNil(), naNil(), locals);
278 if(naGetError(_context)) {
283 hashset(_globals, lib, locals);
286 naRef FGNasalSys::parse(const char* filename, const char* buf, int len)
289 naRef srcfile = naNewString(_context);
290 naStr_fromdata(srcfile, (char*)filename, strlen(filename));
291 naRef code = naParseCode(_context, srcfile, 1, (char*)buf, len, &errLine);
293 SG_LOG(SG_NASAL, SG_ALERT,
294 "Nasal parse error: " << naGetError(_context) <<
295 " in "<< filename <<", line " << errLine);
299 // Bind to the global namespace before returning
300 return naBindFunction(_context, code, _globals);
303 bool FGNasalSys::handleCommand(const SGPropertyNode* arg)
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
309 const char* nasal = arg->getStringValue("script");
310 naRef code = parse("<command>", nasal, strlen(nasal));
311 if(naIsNil(code)) return false;
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
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")));
329 naRef result = naCall(_context, code, naNil(), naNil(), locals);
330 if(!naGetError(_context)) return true;
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.
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
345 void FGNasalSys::setTimer(naRef args)
347 // Extract the handler, delta, and simtime arguments:
348 naRef handler = naVec_get(args, 0);
349 if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler)))
352 naRef delta = naNumValue(naVec_get(args, 1));
353 if(naIsNil(delta)) return;
355 bool simtime = naTrue(naVec_get(args, 2)) ? true : false;
357 // Generate and register a C++ timer handler
358 NasalTimer* t = new NasalTimer;
359 t->handler = handler;
360 t->hashKey = _nextTimerHashKey++;
363 globals->get_event_mgr()->addEvent("NasalTimer",
364 t, &NasalTimer::timerExpired,
368 // Save the handler in the globals.__timers hash to prevent
369 // garbage collection.
370 naHash_set(_timerHash, naNum(t->hashKey), handler);
373 void FGNasalSys::handleTimer(NasalTimer* t)
375 naCall(_context, t->handler, naNil(), naNil(), naNil());
376 naHash_delete(_timerHash, naNum(t->hashKey));
379 void FGNasalSys::NasalTimer::timerExpired()
381 nasal->handleTimer(this);