| 1 |
// Copyright (C) 2013 James Turner |
| 2 |
// |
| 3 |
// This program is free software; you can redistribute it and/or |
| 4 |
// modify it under the terms of the GNU General Public License as |
| 5 |
// published by the Free Software Foundation; either version 2 of the |
| 6 |
// License, or (at your option) any later version. |
| 7 |
// |
| 8 |
// This program is distributed in the hope that it will be useful, but |
| 9 |
// WITHOUT ANY WARRANTY; without even the implied warranty of |
| 10 |
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
| 11 |
// General Public License for more details. |
| 12 |
// |
| 13 |
// You should have received a copy of the GNU General Public License |
| 14 |
// along with this program; if not, write to the Free Software |
| 15 |
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. |
| 16 |
|
| 17 |
#include "config.h" |
| 18 |
|
| 19 |
#ifdef HAVE_WINDOWS_H |
| 20 |
#include <windows.h> |
| 21 |
#endif |
| 22 |
|
| 23 |
#ifdef HAVE_SYS_TIME_H |
| 24 |
# include <sys/time.h> // gettimeofday |
| 25 |
#endif |
| 26 |
|
| 27 |
#include <algorithm> |
| 28 |
#include <errno.h> |
| 29 |
#include <stdio.h> |
| 30 |
#include <string.h> |
| 31 |
#include <sys/types.h> |
| 32 |
#include <sys/stat.h> |
| 33 |
#include <fstream> |
| 34 |
#include <sstream> |
| 35 |
|
| 36 |
#include <simgear/debug/ErrorReportingCallback.hxx> |
| 37 |
#include <simgear/io/iostreams/sgstream.hxx> |
| 38 |
#include <simgear/math/sg_geodesy.hxx> |
| 39 |
#include <simgear/math/sg_random.hxx> |
| 40 |
#include <simgear/misc/SimpleMarkdown.hxx> |
| 41 |
#include <simgear/misc/sg_dir.hxx> |
| 42 |
#include <simgear/misc/sg_path.hxx> |
| 43 |
#include <simgear/misc/strutils.hxx> |
| 44 |
#include <simgear/nasal/iolib.h> |
| 45 |
#include <simgear/nasal/nasal.h> |
| 46 |
#include <simgear/props/props.hxx> |
| 47 |
#include <simgear/structure/commands.hxx> |
| 48 |
#include <simgear/structure/event_mgr.hxx> |
| 49 |
#include <simgear/io/sg_mmap.hxx> |
| 50 |
|
| 51 |
#include <simgear/nasal/cppbind/from_nasal.hxx> |
| 52 |
#include <simgear/nasal/cppbind/to_nasal.hxx> |
| 53 |
#include <simgear/nasal/cppbind/Ghost.hxx> |
| 54 |
#include <simgear/nasal/cppbind/NasalHash.hxx> |
| 55 |
#include <simgear/timing/timestamp.hxx> |
| 56 |
|
| 57 |
#include "NasalAddons.hxx" |
| 58 |
#include "NasalAircraft.hxx" |
| 59 |
#include "NasalCanvas.hxx" |
| 60 |
#include "NasalClipboard.hxx" |
| 61 |
#include "NasalCondition.hxx" |
| 62 |
#include "NasalFlightPlan.hxx" |
| 63 |
#include "NasalHTTP.hxx" |
| 64 |
#include "NasalPositioned.hxx" |
| 65 |
#include "NasalSGPath.hxx" |
| 66 |
#include "NasalString.hxx" |
| 67 |
#include "NasalSys.hxx" |
| 68 |
#include "NasalSys_private.hxx" |
| 69 |
#include "NasalUnitTesting.hxx" |
| 70 |
|
| 71 |
#include <Main/globals.hxx> |
| 72 |
#include <Main/fg_props.hxx> |
| 73 |
#include <Main/sentryIntegration.hxx> |
| 74 |
#include <Main/locale.hxx> |
| 75 |
|
| 76 |
using std::map; |
| 77 |
using std::string; |
| 78 |
using std::vector; |
| 79 |
|
| 80 |
void postinitNasalGUI(naRef globals, naContext c); |
| 81 |
|
| 82 |
static FGNasalSys* nasalSys = nullptr; |
| 83 |
|
| 84 |
// this is used by the test-suite to simplify |
| 85 |
// how much Nasal modules we load by default |
| 86 |
bool global_nasalMinimalInit = false; |
| 87 |
|
| 88 |
|
| 89 |
// Listener class for loading Nasal modules on demand |
| 90 |
class FGNasalModuleListener : public SGPropertyChangeListener |
| 91 |
{ |
| 92 |
public: |
| 93 |
FGNasalModuleListener(SGPropertyNode* node); |
| 94 |
|
| 95 |
virtual void valueChanged(SGPropertyNode* node); |
| 96 |
|
| 97 |
private: |
| 98 |
SGPropertyNode_ptr _node; |
| 99 |
}; |
| 100 |
|
| 101 |
FGNasalModuleListener::FGNasalModuleListener(SGPropertyNode* node) : _node(node) |
| 102 |
{ |
| 103 |
} |
| 104 |
|
| 105 |
void FGNasalModuleListener::valueChanged(SGPropertyNode*) |
| 106 |
{ |
| 107 |
const auto enabled = _node->getBoolValue("enabled", false); |
| 108 |
const auto loaded = _node->getBoolValue("loaded", true); |
| 109 |
if (enabled && !loaded) { |
| 110 |
nasalSys->loadPropertyScripts(_node); |
| 111 |
} else if (!enabled && loaded) { |
| 112 |
// delete the module |
| 113 |
std::string module = _node->getNameString(); |
| 114 |
if (_node->hasChild("module")) { |
| 115 |
module = _node->getStringValue("module"); |
| 116 |
} |
| 117 |
|
| 118 |
nasalSys->deleteModule(module.c_str()); |
| 119 |
} |
| 120 |
} |
| 121 |
|
| 122 |
////////////////////////////////////////////////////////////////////////// |
| 123 |
|
| 124 |
class TimerObj : public SGReferenced |
| 125 |
{ |
| 126 |
public: |
| 127 |
TimerObj(Context *c, FGNasalSys* sys, naRef f, naRef self, double interval) : |
| 128 |
_sys(sys), |
| 129 |
_func(f), |
| 130 |
_self(self), |
| 131 |
_interval(interval) |
| 132 |
{ |
| 133 |
char nm[256]; |
| 134 |
if (c) { |
| 135 |
snprintf(nm, 128, "maketimer-[%p]-%s:%d", (void*)this, naStr_data(naGetSourceFile(c, 0)), naGetLine(c, 0)); |
| 136 |
} |
| 137 |
else { |
| 138 |
snprintf(nm, 128, "maketimer-%p", this); |
| 139 |
} |
| 140 |
_name = nm; |
| 141 |
_gcRoot = naGCSave(f); |
| 142 |
_gcSelf = naGCSave(self); |
| 143 |
sys->addPersistentTimer(this); |
| 144 |
} |
| 145 |
|
| 146 |
virtual ~TimerObj() |
| 147 |
{ |
| 148 |
stop(); |
| 149 |
naGCRelease(_gcRoot); |
| 150 |
naGCRelease(_gcSelf); |
| 151 |
_sys->removePersistentTimer(this); |
| 152 |
} |
| 153 |
|
| 154 |
bool isRunning() const { return _isRunning; } |
| 155 |
|
| 156 |
void stop() |
| 157 |
{ |
| 158 |
if (_isRunning) { |
| 159 |
globals->get_event_mgr()->removeTask(_name); |
| 160 |
_isRunning = false; |
| 161 |
} |
| 162 |
} |
| 163 |
|
| 164 |
bool isSimTime() const { return _isSimTime; } |
| 165 |
|
| 166 |
void setSimTime(bool value) |
| 167 |
{ |
| 168 |
if (_isRunning) { |
| 169 |
SG_LOG(SG_NASAL, SG_WARN, "can't change type of running timer!"); |
| 170 |
return; |
| 171 |
} |
| 172 |
|
| 173 |
_isSimTime = value; |
| 174 |
} |
| 175 |
|
| 176 |
void start() |
| 177 |
{ |
| 178 |
if (_isRunning) { |
| 179 |
return; |
| 180 |
} |
| 181 |
|
| 182 |
_isRunning = true; |
| 183 |
if (_singleShot) { |
| 184 |
globals->get_event_mgr()->addEvent(_name, [this](){ this->invoke(); }, _interval, _isSimTime); |
| 185 |
} else { |
| 186 |
globals->get_event_mgr()->addTask(_name, [this](){ this->invoke(); }, |
| 187 |
_interval, _interval /* delay */, |
| 188 |
_isSimTime); |
| 189 |
} |
| 190 |
} |
| 191 |
|
| 192 |
// stop and then start - |
| 193 |
void restart(double newInterval) |
| 194 |
{ |
| 195 |
_interval = newInterval; |
| 196 |
stop(); |
| 197 |
start(); |
| 198 |
} |
| 199 |
|
| 200 |
void invoke() |
| 201 |
{ |
| 202 |
if( _singleShot ) |
| 203 |
// Callback may restart the timer, so update status before callback is |
| 204 |
// called (Prevent warnings of deleting not existing tasks from the |
| 205 |
// event manager). |
| 206 |
_isRunning = false; |
| 207 |
|
| 208 |
naRef *args = nullptr; |
| 209 |
_sys->callMethod(_func, _self, 0, args, naNil() /* locals */); |
| 210 |
} |
| 211 |
|
| 212 |
void setSingleShot(bool aSingleShot) |
| 213 |
{ |
| 214 |
_singleShot = aSingleShot; |
| 215 |
} |
| 216 |
|
| 217 |
bool isSingleShot() const |
| 218 |
{ return _singleShot; } |
| 219 |
|
| 220 |
const std::string& name() const |
| 221 |
{ return _name; } |
| 222 |
private: |
| 223 |
std::string _name; |
| 224 |
FGNasalSys* _sys; |
| 225 |
naRef _func, _self; |
| 226 |
int _gcRoot, _gcSelf; |
| 227 |
bool _isRunning = false; |
| 228 |
double _interval; |
| 229 |
bool _singleShot = false; |
| 230 |
bool _isSimTime = false; |
| 231 |
}; |
| 232 |
|
| 233 |
typedef SGSharedPtr<TimerObj> TimerObjRef; |
| 234 |
typedef nasal::Ghost<TimerObjRef> NasalTimerObj; |
| 235 |
|
| 236 |
static void f_timerObj_setSimTime(TimerObj& timer, naContext c, naRef value) |
| 237 |
{ |
| 238 |
if (timer.isRunning()) { |
| 239 |
naRuntimeError(c, "Timer is running, cannot change type between real/sim time"); |
| 240 |
return; |
| 241 |
} |
| 242 |
|
| 243 |
timer.setSimTime(nasal::from_nasal<bool>(c, value)); |
| 244 |
} |
| 245 |
//////////////////// |
| 246 |
/// Timestamp - used to provide millisecond based timing of operations. See SGTimeStamp |
| 247 |
//// |
| 248 |
/// 0.373404us to perform elapsedUSec from Nasal : Tested i7-4790K, Win64 |
| 249 |
class TimeStampObj : public SGReferenced |
| 250 |
{ |
| 251 |
public: |
| 252 |
TimeStampObj(Context *c) |
| 253 |
{ |
| 254 |
timestamp.stamp(); |
| 255 |
} |
| 256 |
|
| 257 |
virtual ~TimeStampObj() = default; |
| 258 |
|
| 259 |
void stamp() |
| 260 |
{ |
| 261 |
timestamp.stamp(); |
| 262 |
} |
| 263 |
double elapsedMSec() |
| 264 |
{ |
| 265 |
return timestamp.elapsedMSec(); |
| 266 |
} |
| 267 |
double elapsedUSec() |
| 268 |
{ |
| 269 |
return timestamp.elapsedUSec(); |
| 270 |
} |
| 271 |
private: |
| 272 |
SGTimeStamp timestamp; |
| 273 |
}; |
| 274 |
|
| 275 |
typedef SGSharedPtr<TimeStampObj> TimeStampObjRef; |
| 276 |
typedef nasal::Ghost<TimeStampObjRef> NasalTimeStampObj; |
| 277 |
|
| 278 |
/////////////////////////////////////////////////////////////////////////// |
| 279 |
|
| 280 |
NasalSysPrivate::~NasalSysPrivate() |
| 281 |
{ |
| 282 |
} |
| 283 |
|
| 284 |
/////////////////////////////////////////////////////////////////////////// |
| 285 |
|
| 286 |
FGNasalSys::FGNasalSys() : d(new NasalSysPrivate) |
| 287 |
{ |
| 288 |
nasalSys = this; |
| 289 |
d->_globals = naNil(); |
| 290 |
d->_string = naNil(); |
| 291 |
d->_wrappedNodeFunc = naNil(); |
| 292 |
|
| 293 |
d->_log.reset(new simgear::BufferedLogCallback(SG_NASAL, SG_INFO)); |
| 294 |
d->_log->truncateAt(255); |
| 295 |
sglog().addCallback(d->_log.get()); |
| 296 |
|
| 297 |
naSetErrorHandler(&logError); |
| 298 |
} |
| 299 |
|
| 300 |
// Utility. Sets a named key in a hash by C string, rather than nasal |
| 301 |
// string object. |
| 302 |
void FGNasalSys::hashset(naRef hash, const char* key, naRef val) |
| 303 |
{ |
| 304 |
naRef s = naNewString(d->_context); |
| 305 |
naStr_fromdata(s, (char*)key, strlen(key)); |
| 306 |
naHash_set(hash, s, val); |
| 307 |
} |
| 308 |
|
| 309 |
void FGNasalSys::globalsSet(const char* key, naRef val) |
| 310 |
{ |
| 311 |
hashset(d->_globals, key, val); |
| 312 |
} |
| 313 |
|
| 314 |
naRef FGNasalSys::call(naRef code, int argc, naRef* args, naRef locals) |
| 315 |
{ |
| 316 |
return callMethod(code, naNil(), argc, args, locals); |
| 317 |
} |
| 318 |
|
| 319 |
naRef FGNasalSys::callWithContext(naContext ctx, naRef code, int argc, naRef* args, naRef locals) |
| 320 |
{ |
| 321 |
return callMethodWithContext(ctx, code, naNil(), argc, args, locals); |
| 322 |
} |
| 323 |
|
| 324 |
// Does a naCall() in a new context. Wrapped here to make lock |
| 325 |
// tracking easier. Extension functions are called with the lock, but |
| 326 |
// we have to release it before making a new naCall(). So rather than |
| 327 |
// drop the lock in every extension function that might call back into |
| 328 |
// Nasal, we keep a stack depth counter here and only unlock/lock |
| 329 |
// around the naCall if it isn't the first one. |
| 330 |
|
| 331 |
naRef FGNasalSys::callMethod(naRef code, naRef self, int argc, naRef* args, naRef locals) |
| 332 |
{ |
| 333 |
try { |
| 334 |
return naCallMethod(code, self, argc, args, locals); |
| 335 |
} catch (sg_exception& e) { |
| 336 |
SG_LOG(SG_NASAL, SG_DEV_ALERT, "caught exception invoking nasal method:" << e.what()); |
| 337 |
return naNil(); |
| 338 |
} |
| 339 |
} |
| 340 |
|
| 341 |
naRef FGNasalSys::callMethodWithContext(naContext ctx, naRef code, naRef self, int argc, naRef* args, naRef locals) |
| 342 |
{ |
| 343 |
try { |
| 344 |
return naCallMethodCtx(ctx, code, self, argc, args, locals); |
| 345 |
} catch (sg_exception& e) { |
| 346 |
SG_LOG(SG_NASAL, SG_DEV_ALERT, "caught exception invoking nasal method:" << e.what()); |
| 347 |
string_list nasalStack; |
| 348 |
logNasalStack(ctx, nasalStack); |
| 349 |
flightgear::sentryReportNasalError(string{"Exception invoking nasal method:"} + e.what(), nasalStack); |
| 350 |
return naNil(); |
| 351 |
} |
| 352 |
} |
| 353 |
|
| 354 |
FGNasalSys::~FGNasalSys() |
| 355 |
{ |
| 356 |
if (d->_inited) { |
| 357 |
SG_LOG(SG_GENERAL, SG_ALERT, "Nasal was not shutdown"); |
| 358 |
} |
| 359 |
sglog().removeCallback(d->_log.get()); |
| 360 |
|
| 361 |
nasalSys = nullptr; |
| 362 |
} |
| 363 |
|
| 364 |
bool FGNasalSys::parseAndRunWithOutput(const std::string& source, std::string& output, std::string& errors) |
| 365 |
{ |
| 366 |
naContext ctx = naNewContext(); |
| 367 |
naRef code = parse(ctx, "FGNasalSys::parseAndRun()", source.c_str(), |
| 368 |
source.size(), errors); |
| 369 |
if(naIsNil(code)) { |
| 370 |
naFreeContext(ctx); |
| 371 |
return false; |
| 372 |
} |
| 373 |
naRef result = callWithContext(ctx, code, 0, 0, naNil()); |
| 374 |
|
| 375 |
// if there was a result value, try to convert it to a string |
| 376 |
// value. |
| 377 |
if (!naIsNil(result)) { |
| 378 |
naRef s = naStringValue(ctx, result); |
| 379 |
if (!naIsNil(s)) { |
| 380 |
output = naStr_data(s); |
| 381 |
} |
| 382 |
} |
| 383 |
|
| 384 |
naFreeContext(ctx); |
| 385 |
return true; |
| 386 |
} |
| 387 |
|
| 388 |
bool FGNasalSys::parseAndRun(const std::string& source) |
| 389 |
{ |
| 390 |
std::string errors; |
| 391 |
std::string output; |
| 392 |
return parseAndRunWithOutput(source, output, errors); |
| 393 |
} |
| 394 |
|
| 395 |
#if 0 |
| 396 |
FGNasalScript* FGNasalSys::parseScript(const char* src, const char* name) |
| 397 |
{ |
| 398 |
FGNasalScript* script = new FGNasalScript(); |
| 399 |
script->_gcKey = -1; // important, if we delete it on a parse |
| 400 |
script->_nas = this; // error, don't clobber a real handle! |
| 401 |
|
| 402 |
char buf[256]; |
| 403 |
if(!name) { |
| 404 |
snprintf(buf, 256, "FGNasalScript@%p", (void *)script); |
| 405 |
name = buf; |
| 406 |
} |
| 407 |
|
| 408 |
script->_code = parse(name, src, strlen(src)); |
| 409 |
if(naIsNil(script->_code)) { |
| 410 |
delete script; |
| 411 |
return 0; |
| 412 |
} |
| 413 |
|
| 414 |
script->_gcKey = gcSave(script->_code); |
| 415 |
return script; |
| 416 |
} |
| 417 |
#endif |
| 418 |
|
| 419 |
// The get/setprop functions accept a *list* of strings and walk |
| 420 |
// through the property tree with them to find the appropriate node. |
| 421 |
// This allows a Nasal object to hold onto a property path and use it |
| 422 |
// like a node object, e.g. setprop(ObjRoot, "size-parsecs", 2.02). This |
| 423 |
// is the utility function that walks the property tree. |
| 424 |
static SGPropertyNode* findnode(naContext c, naRef* vec, int len, bool create=false) |
| 425 |
{ |
| 426 |
SGPropertyNode* p = globals->get_props(); |
| 427 |
try { |
| 428 |
for(int i=0; i<len; i++) { |
| 429 |
naRef a = vec[i]; |
| 430 |
if(!naIsString(a)) { |
| 431 |
naRuntimeError(c, "bad argument to setprop/getprop path: expected a string"); |
| 432 |
} |
| 433 |
naRef b = i < len-1 ? naNumValue(vec[i+1]) : naNil(); |
| 434 |
if (!naIsNil(b)) { |
| 435 |
p = p->getNode(naStr_data(a), (int)b.num, create); |
| 436 |
i++; |
| 437 |
} else { |
| 438 |
p = p->getNode(naStr_data(a), create); |
| 439 |
} |
| 440 |
if(p == 0) return 0; |
| 441 |
} |
| 442 |
} catch (const string& err) { |
| 443 |
naRuntimeError(c, (char *)err.c_str()); |
| 444 |
} |
| 445 |
return p; |
| 446 |
} |
| 447 |
|
| 448 |
// getprop() extension function. Concatenates its string arguments as |
| 449 |
// property names and returns the value of the specified property. Or |
| 450 |
// nil if it doesn't exist. |
| 451 |
static naRef f_getprop(naContext c, naRef me, int argc, naRef* args) |
| 452 |
{ |
| 453 |
using namespace simgear; |
| 454 |
if (argc < 1) { |
| 455 |
naRuntimeError(c, "getprop() expects at least 1 argument"); |
| 456 |
} |
| 457 |
const SGPropertyNode* p = findnode(c, args, argc, false); |
| 458 |
if(!p) return naNil(); |
| 459 |
|
| 460 |
switch(p->getType()) { |
| 461 |
case props::BOOL: case props::INT: |
| 462 |
case props::LONG: case props::FLOAT: |
| 463 |
case props::DOUBLE: |
| 464 |
{ |
| 465 |
double dv = p->getDoubleValue(); |
| 466 |
if (SGMisc<double>::isNaN(dv)) { |
| 467 |
SG_LOG(SG_NASAL, SG_ALERT, "Nasal getprop: property " << p->getPath() << " is NaN"); |
| 468 |
return naNil(); |
| 469 |
} |
| 470 |
|
| 471 |
return naNum(dv); |
| 472 |
} |
| 473 |
|
| 474 |
case props::STRING: |
| 475 |
case props::UNSPECIFIED: |
| 476 |
{ |
| 477 |
naRef nastr = naNewString(c); |
| 478 |
std::string val = p->getStringValue(); |
| 479 |
naStr_fromdata(nastr, val.c_str(), val.length()); |
| 480 |
return nastr; |
| 481 |
} |
| 482 |
case props::ALIAS: // <--- FIXME, recurse? |
| 483 |
default: |
| 484 |
return naNil(); |
| 485 |
} |
| 486 |
} |
| 487 |
|
| 488 |
// setprop() extension function. Concatenates its string arguments as |
| 489 |
// property names and sets the value of the specified property to the |
| 490 |
// final argument. |
| 491 |
static naRef f_setprop(naContext c, naRef me, int argc, naRef* args) |
| 492 |
{ |
| 493 |
if (argc < 2) { |
| 494 |
naRuntimeError(c, "setprop() expects at least 2 arguments"); |
| 495 |
} |
| 496 |
naRef val = args[argc - 1]; |
| 497 |
SGPropertyNode* p = findnode(c, args, argc-1, true); |
| 498 |
|
| 499 |
bool result = false; |
| 500 |
try { |
| 501 |
if(naIsString(val)) result = p->setStringValue(naStr_data(val)); |
| 502 |
else { |
| 503 |
if(!naIsNum(val)) |
| 504 |
naRuntimeError(c, "setprop() value is not string or number"); |
| 505 |
|
| 506 |
if (SGMisc<double>::isNaN(val.num)) { |
| 507 |
naRuntimeError(c, "setprop() passed a NaN"); |
| 508 |
} |
| 509 |
|
| 510 |
result = p->setDoubleValue(val.num); |
| 511 |
} |
| 512 |
} catch (const string& err) { |
| 513 |
naRuntimeError(c, (char *)err.c_str()); |
| 514 |
} |
| 515 |
return naNum(result); |
| 516 |
} |
| 517 |
|
| 518 |
|
| 519 |
struct SimNasalLogFileLine : SGPropertyChangeListener |
| 520 |
{ |
| 521 |
SimNasalLogFileLine() { |
| 522 |
SGPropertyNode* node = fgGetNode("/sim/nasal-log-file-line", true /*create*/); |
| 523 |
node->addChangeListener(this, true /*initial*/); |
| 524 |
} |
| 525 |
void valueChanged(SGPropertyNode* node) override { |
| 526 |
_file_line = node->getIntValue(); |
| 527 |
} |
| 528 |
|
| 529 |
static bool _file_line; |
| 530 |
}; |
| 531 |
|
| 532 |
bool SimNasalLogFileLine::_file_line = false; |
| 533 |
|
| 534 |
// print() extension function. Concatenates and prints its arguments |
| 535 |
// to the FlightGear log. Uses the mandatory log level (SG_MANDATORY_INFO), to |
| 536 |
// make sure it appears. Users should be converted to use logprint() instead, |
| 537 |
// and specify a level explicitly. |
| 538 |
static naRef f_print(naContext c, naRef me, int argc, naRef* args) |
| 539 |
{ |
| 540 |
static SimNasalLogFileLine snlfl; |
| 541 |
string buf; |
| 542 |
int n = argc; |
| 543 |
for(int i=0; i<n; i++) { |
| 544 |
naRef s = naStringValue(c, args[i]); |
| 545 |
if(naIsNil(s)) continue; |
| 546 |
buf += naStr_data(s); |
| 547 |
} |
| 548 |
if (snlfl._file_line) { |
| 549 |
/* Copy what SG_LOG() does, but use nasal file:line instead of |
| 550 |
our own __FILE__ and __LINE__. We don't (yet) attempt to find |
| 551 |
the nasal function name. */ |
| 552 |
int frame = 0; |
| 553 |
const char* file = naStr_data(naGetSourceFile(c, 0)); |
| 554 |
if (simgear::strutils::ends_with( file, "/globals.nas")) { |
| 555 |
/* This generally means have been called by globals.nas's |
| 556 |
printf function; go one step up the stack so we give the |
| 557 |
file:line of the caller of printf, which is generally more |
| 558 |
useful. */ |
| 559 |
frame += 1; |
| 560 |
file = naStr_data(naGetSourceFile(c, frame)); |
| 561 |
} |
| 562 |
int line = naGetLine(c, frame); |
| 563 |
const char* function = ""; |
| 564 |
if (sglog().would_log(SG_NASAL, SG_MANDATORY_INFO, file, line, function)) { |
| 565 |
sglog().logCopyingFilename(SG_NASAL, SG_MANDATORY_INFO, file, line, function, buf); |
| 566 |
} |
| 567 |
} else { |
| 568 |
SG_LOG(SG_NASAL, SG_MANDATORY_INFO, buf); |
| 569 |
} |
| 570 |
return naNum(buf.length()); |
| 571 |
} |
| 572 |
|
| 573 |
// logprint() extension function. Same as above, all arguments after the |
| 574 |
// first argument are concatenated. Argument 0 is the log-level, matching |
| 575 |
// sgDebugPriority. |
| 576 |
static naRef f_logprint(naContext c, naRef me, int argc, naRef* args) |
| 577 |
{ |
| 578 |
if (argc < 1) |
| 579 |
naRuntimeError(c, "no prioirty argument to logprint()"); |
| 580 |
|
| 581 |
naRef priority = args[0]; |
| 582 |
string buf; |
| 583 |
int n = argc; |
| 584 |
for(int i=1; i<n; i++) { |
| 585 |
naRef s = naStringValue(c, args[i]); |
| 586 |
if(naIsNil(s)) continue; |
| 587 |
buf += naStr_data(s); |
| 588 |
} |
| 589 |
// use the nasal source file and line for the message location, since |
| 590 |
// that's more useful than the location here! |
| 591 |
sglog().logCopyingFilename(SG_NASAL, (sgDebugPriority)(int) priority.num, |
| 592 |
naStr_data(naGetSourceFile(c, 0)), |
| 593 |
naGetLine(c, 0), "" /*function*/, buf); |
| 594 |
return naNum(buf.length()); |
| 595 |
} |
| 596 |
|
| 597 |
|
| 598 |
// fgcommand() extension function. Executes a named command via the |
| 599 |
// FlightGear command manager. Takes a single property node name as |
| 600 |
// an argument. |
| 601 |
static naRef f_fgcommand(naContext c, naRef me, int argc, naRef* args) |
| 602 |
{ |
| 603 |
naRef cmd = argc > 0 ? args[0] : naNil(); |
| 604 |
naRef props = argc > 1 ? args[1] : naNil(); |
| 605 |
if(!naIsString(cmd) || (!naIsNil(props) && !naIsGhost(props))) |
| 606 |
naRuntimeError(c, "bad arguments to fgcommand()"); |
| 607 |
SGPropertyNode_ptr node; |
| 608 |
if(!naIsNil(props)) |
| 609 |
node = static_cast<SGPropertyNode*>(naGhost_ptr(props)); |
| 610 |
else |
| 611 |
node = new SGPropertyNode; |
| 612 |
|
| 613 |
return naNum(globals->get_commands()->execute(naStr_data(cmd), node, nullptr)); |
| 614 |
} |
| 615 |
|
| 616 |
// settimer(func, dt, simtime) extension function. Falls through to |
| 617 |
// FGNasalSys::setTimer(). See there for docs. |
| 618 |
static naRef f_settimer(naContext c, naRef me, int argc, naRef* args) |
| 619 |
{ |
| 620 |
nasalSys->setTimer(c, argc, args); |
| 621 |
return naNil(); |
| 622 |
} |
| 623 |
|
| 624 |
static naRef f_makeTimer(naContext c, naRef me, int argc, naRef* args) |
| 625 |
{ |
| 626 |
if (!naIsNum(args[0])) { |
| 627 |
naRuntimeError(c, "bad interval argument to maketimer"); |
| 628 |
} |
| 629 |
|
| 630 |
naRef func, self = naNil(); |
| 631 |
if (naIsFunc(args[1])) { |
| 632 |
func = args[1]; |
| 633 |
} else if ((argc == 3) && naIsFunc(args[2])) { |
| 634 |
self = args[1]; |
| 635 |
func = args[2]; |
| 636 |
} else { |
| 637 |
naRuntimeError(c, "bad function/self arguments to maketimer"); |
| 638 |
} |
| 639 |
|
| 640 |
TimerObj* timerObj = new TimerObj(c, nasalSys, func, self, args[0].num); |
| 641 |
return nasal::to_nasal(c, timerObj); |
| 642 |
} |
| 643 |
|
| 644 |
static naRef f_makeSingleShot(naContext c, naRef me, int argc, naRef* args) |
| 645 |
{ |
| 646 |
if (!naIsNum(args[0])) { |
| 647 |
naRuntimeError(c, "bad interval argument to makesingleshot"); |
| 648 |
} |
| 649 |
|
| 650 |
naRef func, self = naNil(); |
| 651 |
if (naIsFunc(args[1])) { |
| 652 |
func = args[1]; |
| 653 |
} else if ((argc == 3) && naIsFunc(args[2])) { |
| 654 |
self = args[1]; |
| 655 |
func = args[2]; |
| 656 |
} else { |
| 657 |
naRuntimeError(c, "bad function/self arguments to makesingleshot"); |
| 658 |
} |
| 659 |
|
| 660 |
auto timerObj = new TimerObj(c, nasalSys, func, self, args[0].num); |
| 661 |
timerObj->setSingleShot(true); |
| 662 |
timerObj->start(); |
| 663 |
return nasal::to_nasal(c, timerObj); |
| 664 |
} |
| 665 |
|
| 666 |
static naRef f_maketimeStamp(naContext c, naRef me, int argc, naRef* args) |
| 667 |
{ |
| 668 |
TimeStampObj* timeStampObj = new TimeStampObj(c); |
| 669 |
return nasal::to_nasal(c, timeStampObj); |
| 670 |
} |
| 671 |
|
| 672 |
// setlistener(func, property, bool) extension function. Falls through to |
| 673 |
// FGNasalSys::setListener(). See there for docs. |
| 674 |
static naRef f_setlistener(naContext c, naRef me, int argc, naRef* args) |
| 675 |
{ |
| 676 |
return nasalSys->setListener(c, argc, args); |
| 677 |
} |
| 678 |
|
| 679 |
// removelistener(int) extension function. Falls through to |
| 680 |
// FGNasalSys::removeListener(). See there for docs. |
| 681 |
static naRef f_removelistener(naContext c, naRef me, int argc, naRef* args) |
| 682 |
{ |
| 683 |
return nasalSys->removeListener(c, argc, args); |
| 684 |
} |
| 685 |
|
| 686 |
// Returns a ghost handle to the argument to the currently executing |
| 687 |
// command |
| 688 |
static naRef f_cmdarg(naContext c, naRef me, int argc, naRef* args) |
| 689 |
{ |
| 690 |
return nasalSys->cmdArgGhost(); |
| 691 |
} |
| 692 |
|
| 693 |
// Sets up a property interpolation. The first argument is either a |
| 694 |
// ghost (SGPropertyNode*) or a string (global property path) to |
| 695 |
// interpolate. The second argument is a vector of pairs of |
| 696 |
// value/delta numbers. |
| 697 |
static naRef f_interpolate(naContext c, naRef me, int argc, naRef* args) |
| 698 |
{ |
| 699 |
SGPropertyNode* node; |
| 700 |
naRef prop = argc > 0 ? args[0] : naNil(); |
| 701 |
if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true); |
| 702 |
else if(naIsGhost(prop)) node = static_cast<SGPropertyNode*>(naGhost_ptr(prop)); |
| 703 |
else return naNil(); |
| 704 |
|
| 705 |
naRef curve = argc > 1 ? args[1] : naNil(); |
| 706 |
if(!naIsVector(curve)) return naNil(); |
| 707 |
int nPoints = naVec_size(curve) / 2; |
| 708 |
|
| 709 |
simgear::PropertyList value_nodes; |
| 710 |
value_nodes.reserve(nPoints); |
| 711 |
double_list deltas; |
| 712 |
deltas.reserve(nPoints); |
| 713 |
|
| 714 |
for( int i = 0; i < nPoints; ++i ) |
| 715 |
{ |
| 716 |
SGPropertyNode* val = new SGPropertyNode; |
| 717 |
val->setDoubleValue(naNumValue(naVec_get(curve, 2*i)).num); |
| 718 |
value_nodes.push_back(val); |
| 719 |
deltas.push_back(naNumValue(naVec_get(curve, 2*i+1)).num); |
| 720 |
} |
| 721 |
|
| 722 |
node->interpolate("numeric", value_nodes, deltas, "linear"); |
| 723 |
return naNil(); |
| 724 |
} |
| 725 |
|
| 726 |
// This is a better RNG than the one in the default Nasal distribution |
| 727 |
// (which is based on the C library rand() implementation). It will |
| 728 |
// override. |
| 729 |
static naRef f_rand(naContext c, naRef me, int argc, naRef* args) |
| 730 |
{ |
| 731 |
return naNum(sg_random()); |
| 732 |
} |
| 733 |
|
| 734 |
static naRef f_srand(naContext c, naRef me, int argc, naRef* args) |
| 735 |
{ |
| 736 |
sg_srandom_time(); |
| 737 |
return naNum(0); |
| 738 |
} |
| 739 |
|
| 740 |
static naRef f_abort(naContext c, naRef me, int argc, naRef* args) |
| 741 |
{ |
| 742 |
abort(); |
| 743 |
return naNil(); |
| 744 |
} |
| 745 |
|
| 746 |
// Return an array listing of all files in a directory |
| 747 |
static naRef f_directory(naContext c, naRef me, int argc, naRef* args) |
| 748 |
{ |
| 749 |
if(argc != 1 || !naIsString(args[0])) |
| 750 |
naRuntimeError(c, "bad arguments to directory()"); |
| 751 |
|
| 752 |
SGPath dirname = SGPath::fromUtf8(naStr_data(args[0])).validate(false); |
| 753 |
if(dirname.isNull()) { |
| 754 |
SG_LOG(SG_NASAL, SG_ALERT, "directory(): listing '" << |
| 755 |
naStr_data(args[0]) << "' denied (unauthorized directory - authorization" |
| 756 |
" no longer follows symlinks; to authorize reading additional " |
| 757 |
"directories, pass them to --allow-nasal-read)"); |
| 758 |
// to avoid breaking dialogs, pretend it doesn't exist rather than erroring out |
| 759 |
return naNil(); |
| 760 |
} |
| 761 |
|
| 762 |
simgear::Dir d(dirname); |
| 763 |
if(!d.exists()) return naNil(); |
| 764 |
naRef result = naNewVector(c); |
| 765 |
|
| 766 |
simgear::PathList paths = d.children(simgear::Dir::TYPE_FILE | simgear::Dir::TYPE_DIR); |
| 767 |
for (unsigned int i=0; i<paths.size(); ++i) { |
| 768 |
std::string p = paths[i].file(); |
| 769 |
naVec_append(result, naStr_fromdata(naNewString(c), p.c_str(), p.size())); |
| 770 |
} |
| 771 |
|
| 772 |
return result; |
| 773 |
} |
| 774 |
|
| 775 |
/** |
| 776 |
* Given a data path, resolve it in FG_ROOT or an FG_AIRCRFT directory |
| 777 |
*/ |
| 778 |
static naRef f_resolveDataPath(naContext c, naRef me, int argc, naRef* args) |
| 779 |
{ |
| 780 |
if(argc != 1 || !naIsString(args[0])) |
| 781 |
naRuntimeError(c, "bad arguments to resolveDataPath()"); |
| 782 |
|
| 783 |
SGPath p = globals->resolve_maybe_aircraft_path(naStr_data(args[0])); |
| 784 |
std::string pdata = p.utf8Str(); |
| 785 |
return naStr_fromdata(naNewString(c), const_cast<char*>(pdata.c_str()), pdata.length()); |
| 786 |
} |
| 787 |
|
| 788 |
static naRef f_findDataDir(naContext c, naRef me, int argc, naRef* args) |
| 789 |
{ |
| 790 |
if(argc != 1 || !naIsString(args[0])) |
| 791 |
naRuntimeError(c, "bad arguments to findDataDir()"); |
| 792 |
|
| 793 |
SGPath p = globals->findDataPath(naStr_data(args[0])); |
| 794 |
std::string pdata = p.utf8Str(); |
| 795 |
return naStr_fromdata(naNewString(c), const_cast<char*>(pdata.c_str()), pdata.length()); |
| 796 |
} |
| 797 |
|
| 798 |
class NasalCommand : public SGCommandMgr::Command |
| 799 |
{ |
| 800 |
public: |
| 801 |
NasalCommand(FGNasalSys* sys, naRef f, const std::string& name) : |
| 802 |
_sys(sys), |
| 803 |
_func(f), |
| 804 |
_name(name) |
| 805 |
{ |
| 806 |
globals->get_commands()->addCommandObject(_name, this); |
| 807 |
_gcRoot = sys->gcSave(f); |
| 808 |
} |
| 809 |
|
| 810 |
virtual ~NasalCommand() |
| 811 |
{ |
| 812 |
_sys->gcRelease(_gcRoot); |
| 813 |
} |
| 814 |
|
| 815 |
bool operator()(const SGPropertyNode* aNode, SGPropertyNode* root) override |
| 816 |
{ |
| 817 |
_sys->setCmdArg(const_cast<SGPropertyNode*>(aNode)); |
| 818 |
naRef args[1]; |
| 819 |
args[0] = _sys->wrappedPropsNode(const_cast<SGPropertyNode*>(aNode)); |
| 820 |
|
| 821 |
_sys->callMethod(_func, naNil(), 1, args, naNil() /* locals */); |
| 822 |
|
| 823 |
return true; |
| 824 |
} |
| 825 |
|
| 826 |
private: |
| 827 |
FGNasalSys* _sys; |
| 828 |
naRef _func; |
| 829 |
int _gcRoot; |
| 830 |
std::string _name; |
| 831 |
}; |
| 832 |
|
| 833 |
static naRef f_addCommand(naContext c, naRef me, int argc, naRef* args) |
| 834 |
{ |
| 835 |
if(argc != 2 || !naIsString(args[0]) || !naIsFunc(args[1])) |
| 836 |
naRuntimeError(c, "bad arguments to addcommand()"); |
| 837 |
|
| 838 |
const string commandName(naStr_data(args[0])); |
| 839 |
bool ok = nasalSys->addCommand(args[1], commandName); |
| 840 |
if (!ok) { |
| 841 |
naRuntimeError(c, "Failed to add command:%s : likely a duplicate name ", commandName.c_str()); |
| 842 |
} |
| 843 |
|
| 844 |
return naNil(); |
| 845 |
} |
| 846 |
|
| 847 |
static naRef f_removeCommand(naContext c, naRef me, int argc, naRef* args) |
| 848 |
{ |
| 849 |
if ((argc < 1) || !naIsString(args[0])) |
| 850 |
naRuntimeError(c, "bad argument to removecommand()"); |
| 851 |
|
| 852 |
const string commandName(naStr_data(args[0])); |
| 853 |
bool ok = nasalSys->removeCommand(commandName); |
| 854 |
if (!ok) { |
| 855 |
return naNum(0); |
| 856 |
} |
| 857 |
return naNum(1); |
| 858 |
} |
| 859 |
|
| 860 |
static naRef f_open(naContext c, naRef me, int argc, naRef* args) |
| 861 |
{ |
| 862 |
FILE* f; |
| 863 |
naRef file = argc > 0 ? naStringValue(c, args[0]) : naNil(); |
| 864 |
naRef mode = argc > 1 ? naStringValue(c, args[1]) : naNil(); |
| 865 |
if(!naStr_data(file)) naRuntimeError(c, "bad argument to open()"); |
| 866 |
const char* modestr = naStr_data(mode) ? naStr_data(mode) : "rb"; |
| 867 |
const SGPath filename = SGPath::fromUtf8(naStr_data(file)).validate( |
| 868 |
strcmp(modestr, "rb") && strcmp(modestr, "r")); |
| 869 |
if(filename.isNull()) { |
| 870 |
SG_LOG(SG_NASAL, SG_ALERT, "open(): reading/writing '" << |
| 871 |
naStr_data(file) << "' denied (unauthorized directory - authorization" |
| 872 |
" no longer follows symlinks; to authorize reading additional " |
| 873 |
"directories, pass them to --allow-nasal-read)"); |
| 874 |
naRuntimeError(c, "open(): access denied (unauthorized directory)"); |
| 875 |
return naNil(); |
| 876 |
} |
| 877 |
|
| 878 |
#if defined(SG_WINDOWS) |
| 879 |
std::wstring fp = filename.wstr(); |
| 880 |
std::wstring wmodestr = simgear::strutils::convertUtf8ToWString(modestr); |
| 881 |
f = _wfopen(fp.c_str(), wmodestr.c_str()); |
| 882 |
#else |
| 883 |
std::string fp = filename.utf8Str(); |
| 884 |
f = fopen(fp.c_str(), modestr); |
| 885 |
#endif |
| 886 |
if(!f) naRuntimeError(c, strerror(errno)); |
| 887 |
return naIOGhost(c, f); |
| 888 |
} |
| 889 |
|
| 890 |
static naRef ftype(naContext ctx, const SGPath& f) |
| 891 |
{ |
| 892 |
const char* t = "unk"; |
| 893 |
if (f.isFile()) t = "reg"; |
| 894 |
else if(f.isDir()) t = "dir"; |
| 895 |
return naStr_fromdata(naNewString(ctx), t, strlen(t)); |
| 896 |
} |
| 897 |
|
| 898 |
// io.stat with UTF-8 path support, replaces the default one in |
| 899 |
// Nasal iolib.c which does not support UTF-8 paths |
| 900 |
static naRef f_custom_stat(naContext ctx, naRef me, int argc, naRef* args) |
| 901 |
{ |
| 902 |
naRef pathArg = argc > 0 ? naStringValue(ctx, args[0]) : naNil(); |
| 903 |
if (!naIsString(pathArg)) |
| 904 |
naRuntimeError(ctx, "bad argument to stat()"); |
| 905 |
|
| 906 |
const auto path = SGPath::fromUtf8(naStr_data(pathArg)); |
| 907 |
if (!path.exists()) { |
| 908 |
return naNil(); |
| 909 |
} |
| 910 |
|
| 911 |
const SGPath filename = SGPath(path).validate(false); |
| 912 |
if (filename.isNull()) { |
| 913 |
SG_LOG(SG_NASAL, SG_ALERT, "stat(): reading '" << |
| 914 |
naStr_data(pathArg) << "' denied (unauthorized directory - authorization" |
| 915 |
" no longer follows symlinks; to authorize reading additional " |
| 916 |
"directories, pass them to --allow-nasal-read)"); |
| 917 |
naRuntimeError(ctx, "stat(): access denied (unauthorized directory)"); |
| 918 |
return naNil(); |
| 919 |
} |
| 920 |
|
| 921 |
naRef result = naNewVector(ctx); |
| 922 |
naVec_setsize(ctx, result, 12); |
| 923 |
|
| 924 |
// every use in fgdata/Nasal only uses stat() to test existence of |
| 925 |
// files, not to check any of this information. |
| 926 |
int n = 0; |
| 927 |
naVec_set(result, n++, naNum(0)); // device |
| 928 |
naVec_set(result, n++, naNum(0)); // inode |
| 929 |
naVec_set(result, n++, naNum(0)); // mode |
| 930 |
naVec_set(result, n++, naNum(0)); // nlink |
| 931 |
naVec_set(result, n++, naNum(0)); // uid |
| 932 |
naVec_set(result, n++, naNum(0)); // guid |
| 933 |
naVec_set(result, n++, naNum(0)); // rdev |
| 934 |
naVec_set(result, n++, naNum(filename.sizeInBytes())); // size |
| 935 |
naVec_set(result, n++, naNum(0)); // atime |
| 936 |
naVec_set(result, n++, naNum(0)); // mtime |
| 937 |
naVec_set(result, n++, naNum(0)); // ctime |
| 938 |
naVec_set(result, n++, ftype(ctx, filename)); |
| 939 |
return result; |
| 940 |
} |
| 941 |
|
| 942 |
// Parse XML file. |
| 943 |
// parsexml(<path> [, <start-tag> [, <end-tag> [, <data> [, <pi>]]]]); |
| 944 |
// |
| 945 |
// <path> ... absolute path to an XML file |
| 946 |
// <start-tag> ... callback function with two args: tag name, attribute hash |
| 947 |
// <end-tag> ... callback function with one arg: tag name |
| 948 |
// <data> ... callback function with one arg: data |
| 949 |
// <pi> ... callback function with two args: target, data |
| 950 |
// (pi = "processing instruction") |
| 951 |
// All four callback functions are optional and default to nil. |
| 952 |
// The function returns nil on error, or the validated file name otherwise. |
| 953 |
static naRef f_parsexml(naContext c, naRef me, int argc, naRef* args) |
| 954 |
{ |
| 955 |
if(argc < 1 || !naIsString(args[0])) |
| 956 |
naRuntimeError(c, "parsexml(): path argument missing or not a string"); |
| 957 |
if(argc > 5) argc = 5; |
| 958 |
for(int i=1; i<argc; i++) |
| 959 |
if(!(naIsNil(args[i]) || naIsFunc(args[i]))) |
| 960 |
naRuntimeError(c, "parsexml(): callback argument not a function"); |
| 961 |
|
| 962 |
const SGPath file = SGPath::fromUtf8(naStr_data(args[0])).validate(false); |
| 963 |
if(file.isNull()) { |
| 964 |
SG_LOG(SG_NASAL, SG_ALERT, "parsexml(): reading '" << |
| 965 |
naStr_data(args[0]) << "' denied (unauthorized directory - authorization" |
| 966 |
" no longer follows symlinks; to authorize reading additional " |
| 967 |
"directories, pass them to --allow-nasal-read)"); |
| 968 |
naRuntimeError(c, "parsexml(): access denied (unauthorized directory)"); |
| 969 |
return naNil(); |
| 970 |
} |
| 971 |
|
| 972 |
NasalXMLVisitor visitor(c, argc, args); |
| 973 |
try { |
| 974 |
readXML(file, visitor); |
| 975 |
} catch (const sg_exception& e) { |
| 976 |
std::string fp = file.utf8Str(); |
| 977 |
naRuntimeError(c, "parsexml(): file '%s' %s", fp.c_str(), e.getFormattedMessage().c_str()); |
| 978 |
return naNil(); |
| 979 |
} |
| 980 |
|
| 981 |
std::string fs = file.utf8Str(); |
| 982 |
return naStr_fromdata(naNewString(c), fs.c_str(), fs.length()); |
| 983 |
} |
| 984 |
|
| 985 |
/** |
| 986 |
* Parse very simple and small subset of markdown |
| 987 |
* |
| 988 |
* parse_markdown(src) |
| 989 |
*/ |
| 990 |
static naRef f_parse_markdown(naContext c, naRef me, int argc, naRef* args) |
| 991 |
{ |
| 992 |
nasal::CallContext ctx(c, me, argc, args); |
| 993 |
return ctx.to_nasal( |
| 994 |
simgear::SimpleMarkdown::parse(ctx.requireArg<std::string>(0)) |
| 995 |
); |
| 996 |
} |
| 997 |
|
| 998 |
/** |
| 999 |
* Create md5 hash from given string |
| 1000 |
* |
| 1001 |
* md5(str) |
| 1002 |
*/ |
| 1003 |
static naRef f_md5(naContext c, naRef me, int argc, naRef* args) |
| 1004 |
{ |
| 1005 |
if( argc != 1 || !naIsString(args[0]) ) |
| 1006 |
naRuntimeError(c, "md5(): wrong type or number of arguments"); |
| 1007 |
|
| 1008 |
return nasal::to_nasal( |
| 1009 |
c, |
| 1010 |
simgear::strutils::md5(naStr_data(args[0]), naStr_len(args[0])) |
| 1011 |
); |
| 1012 |
} |
| 1013 |
|
| 1014 |
static naRef f_translate(naContext c, naRef me, int argc, naRef* args) |
| 1015 |
{ |
| 1016 |
nasal::CallContext ctx(c, me, argc, args); |
| 1017 |
const auto id = ctx.requireArg<std::string>(0); |
| 1018 |
const auto res = ctx.requireArg<std::string>(1); |
| 1019 |
const auto defaultText = ctx.getArg<std::string>(2); |
| 1020 |
|
| 1021 |
auto t = globals->get_locale()->getLocalizedString(id, res.c_str(), defaultText); |
| 1022 |
return nasal::to_nasal(c, t); |
| 1023 |
} |
| 1024 |
|
| 1025 |
// Return UNIX epoch time in seconds. |
| 1026 |
static naRef f_systime(naContext c, naRef me, int argc, naRef* args) |
| 1027 |
{ |
| 1028 |
#ifdef _WIN32 |
| 1029 |
FILETIME ft; |
| 1030 |
GetSystemTimeAsFileTime(&ft); |
| 1031 |
double t = (4294967296.0 * ft.dwHighDateTime + ft.dwLowDateTime); |
| 1032 |
// Converts from 100ns units in 1601 epoch to unix epoch in sec |
| 1033 |
return naNum((t * 1e-7) - 11644473600.0); |
| 1034 |
#else |
| 1035 |
struct timeval td; |
| 1036 |
gettimeofday(&td, 0); |
| 1037 |
return naNum(td.tv_sec + 1e-6 * td.tv_usec); |
| 1038 |
#endif |
| 1039 |
} |
| 1040 |
|
| 1041 |
// Table of extension functions. Terminate with zeros. |
| 1042 |
static struct { const char* name; naCFunction func; |
| 1043 |
} funcs[] = { |
| 1044 |
{"getprop", f_getprop}, |
| 1045 |
{"setprop", f_setprop}, |
| 1046 |
{"print", f_print}, |
| 1047 |
{"logprint", f_logprint}, |
| 1048 |
{"_fgcommand", f_fgcommand}, |
| 1049 |
{"settimer", f_settimer}, |
| 1050 |
{"maketimer", f_makeTimer}, |
| 1051 |
{"makesingleshot", f_makeSingleShot}, |
| 1052 |
{"_setlistener", f_setlistener}, |
| 1053 |
{"removelistener", f_removelistener}, |
| 1054 |
{"addcommand", f_addCommand}, |
| 1055 |
{"removecommand", f_removeCommand}, |
| 1056 |
{"_cmdarg", f_cmdarg}, |
| 1057 |
{"_interpolate", f_interpolate}, |
| 1058 |
{"rand", f_rand}, |
| 1059 |
{"srand", f_srand}, |
| 1060 |
{"abort", f_abort}, |
| 1061 |
{"directory", f_directory}, |
| 1062 |
{"resolvepath", f_resolveDataPath}, |
| 1063 |
{"finddata", f_findDataDir}, |
| 1064 |
{"parsexml", f_parsexml}, |
| 1065 |
{"parse_markdown", f_parse_markdown}, |
| 1066 |
{"md5", f_md5}, |
| 1067 |
{"systime", f_systime}, |
| 1068 |
{"maketimestamp", f_maketimeStamp}, |
| 1069 |
{"translate", f_translate}, |
| 1070 |
{nullptr, nullptr}}; |
| 1071 |
|
| 1072 |
naRef FGNasalSys::cmdArgGhost() |
| 1073 |
{ |
| 1074 |
return propNodeGhost(d->_cmdArg); |
| 1075 |
} |
| 1076 |
|
| 1077 |
void FGNasalSys::initLogLevelConstants() |
| 1078 |
{ |
| 1079 |
hashset(d->_globals, "LOG_BULK", naNum(SG_BULK)); |
| 1080 |
hashset(d->_globals, "LOG_WARN", naNum(SG_WARN)); |
| 1081 |
hashset(d->_globals, "LOG_DEBUG", naNum(SG_DEBUG)); |
| 1082 |
hashset(d->_globals, "LOG_INFO", naNum(SG_INFO)); |
| 1083 |
hashset(d->_globals, "LOG_ALERT", naNum(SG_ALERT)); |
| 1084 |
hashset(d->_globals, "DEV_WARN", naNum(SG_DEV_WARN)); |
| 1085 |
hashset(d->_globals, "DEV_ALERT", naNum(SG_DEV_ALERT)); |
| 1086 |
hashset(d->_globals, "MANDATORY_INFO", naNum(SG_MANDATORY_INFO)); |
| 1087 |
} |
| 1088 |
|
| 1089 |
void FGNasalSys::setCmdArg(SGPropertyNode* aNode) |
| 1090 |
{ |
| 1091 |
d->_cmdArg = aNode; |
| 1092 |
} |
| 1093 |
|
| 1094 |
void FGNasalSys::init() |
| 1095 |
{ |
| 1096 |
if (d->_inited) { |
| 1097 |
SG_LOG(SG_GENERAL, SG_ALERT, "duplicate init of Nasal"); |
| 1098 |
} |
| 1099 |
int i; |
| 1100 |
|
| 1101 |
d->_context = naNewContext(); |
| 1102 |
|
| 1103 |
// Start with globals. Add it to itself as a recursive |
| 1104 |
// sub-reference under the name "globals". This gives client-code |
| 1105 |
// write access to the namespace if someone wants to do something |
| 1106 |
// fancy. |
| 1107 |
d->_globals = naInit_std(d->_context); |
| 1108 |
naSave(d->_context, d->_globals); |
| 1109 |
hashset(d->_globals, "globals", d->_globals); |
| 1110 |
|
| 1111 |
hashset(d->_globals, "math", naInit_math(d->_context)); |
| 1112 |
hashset(d->_globals, "bits", naInit_bits(d->_context)); |
| 1113 |
hashset(d->_globals, "io", naInit_io(d->_context)); |
| 1114 |
hashset(d->_globals, "thread", naInit_thread(d->_context)); |
| 1115 |
hashset(d->_globals, "utf8", naInit_utf8(d->_context)); |
| 1116 |
hashset(d->_globals, "sqlite", naInit_sqlite(d->_context)); |
| 1117 |
|
| 1118 |
initLogLevelConstants(); |
| 1119 |
|
| 1120 |
// Add our custom extension functions: |
| 1121 |
for(i=0; funcs[i].name; i++) |
| 1122 |
hashset(d->_globals, funcs[i].name, |
| 1123 |
naNewFunc(d->_context, naNewCCode(d->_context, funcs[i].func))); |
| 1124 |
nasal::Hash io_module = getGlobals().get<nasal::Hash>("io"); |
| 1125 |
io_module.set("open", f_open); |
| 1126 |
io_module.set("stat", f_custom_stat); |
| 1127 |
|
| 1128 |
// And our SGPropertyNode wrapper |
| 1129 |
hashset(d->_globals, "props", genPropsModule()); |
| 1130 |
|
| 1131 |
// Add string methods |
| 1132 |
d->_string = naInit_string(d->_context); |
| 1133 |
naSave(d->_context, d->_string); |
| 1134 |
initNasalString(d->_globals, d->_string, d->_context); |
| 1135 |
|
| 1136 |
#if defined (BUILDING_TESTSUITE) |
| 1137 |
initNasalUnitTestCppUnit(d->_globals, d->_context); |
| 1138 |
#else |
| 1139 |
initNasalUnitTestInSim(d->_globals, d->_context); |
| 1140 |
#endif |
| 1141 |
|
| 1142 |
if (!global_nasalMinimalInit) { |
| 1143 |
initNasalPositioned(d->_globals, d->_context); |
| 1144 |
initNasalFlightPlan(d->_globals, d->_context); |
| 1145 |
initNasalPositioned_cppbind(d->_globals, d->_context); |
| 1146 |
initNasalAircraft(d->_globals, d->_context); |
| 1147 |
|
| 1148 |
#if !defined (BUILDING_TESTSUITE) |
| 1149 |
// on Linux, clipboard init crashes in headless mode (DISPLAY no set) |
| 1150 |
// so don't do this for testing. |
| 1151 |
NasalClipboard::init(this); |
| 1152 |
#endif |
| 1153 |
initNasalCanvas(d->_globals, d->_context); |
| 1154 |
initNasalCondition(d->_globals, d->_context); |
| 1155 |
initNasalHTTP(d->_globals, d->_context); |
| 1156 |
initNasalSGPath(d->_globals, d->_context); |
| 1157 |
} |
| 1158 |
|
| 1159 |
NasalTimerObj::init("Timer") |
| 1160 |
.method("start", &TimerObj::start) |
| 1161 |
.method("stop", &TimerObj::stop) |
| 1162 |
.method("restart", &TimerObj::restart) |
| 1163 |
.member("singleShot", &TimerObj::isSingleShot, &TimerObj::setSingleShot) |
| 1164 |
.member("simulatedTime", &TimerObj::isSimTime, &f_timerObj_setSimTime) |
| 1165 |
.member("isRunning", &TimerObj::isRunning); |
| 1166 |
|
| 1167 |
NasalTimeStampObj::init("TimeStamp") |
| 1168 |
.method("stamp", &TimeStampObj::stamp) |
| 1169 |
.method("elapsedMSec", &TimeStampObj::elapsedMSec) |
| 1170 |
.method("elapsedUSec", &TimeStampObj::elapsedUSec) |
| 1171 |
; |
| 1172 |
|
| 1173 |
// everything after here, skip if we're doing minimal init, so |
| 1174 |
// we don'tload FG_DATA/Nasal or add-ons |
| 1175 |
if (global_nasalMinimalInit) { |
| 1176 |
d->_inited = true; |
| 1177 |
return; |
| 1178 |
} |
| 1179 |
|
| 1180 |
flightgear::addons::initAddonClassesForNasal(d->_globals, d->_context); |
| 1181 |
|
| 1182 |
// Now load the various source files in the Nasal directory |
| 1183 |
simgear::Dir nasalDir(SGPath(globals->get_fg_root(), "Nasal")); |
| 1184 |
|
| 1185 |
// load core Nasal scripts. In GUI startup mode, we restrict to a limited |
| 1186 |
// set of modules deliberately |
| 1187 |
loadScriptDirectory(nasalDir, |
| 1188 |
globals->get_props()->getNode("/sim/nasal-load-priority"), |
| 1189 |
fgGetBool("/sim/gui/startup")); |
| 1190 |
|
| 1191 |
// Add modules in Nasal subdirectories to property tree |
| 1192 |
simgear::PathList directories = nasalDir.children(simgear::Dir::TYPE_DIR+ |
| 1193 |
simgear::Dir::NO_DOT_OR_DOTDOT, ""); |
| 1194 |
for (unsigned int i=0; i<directories.size(); ++i) { |
| 1195 |
simgear::Dir dir(directories[i]); |
| 1196 |
simgear::PathList scripts = dir.children(simgear::Dir::TYPE_FILE, ".nas"); |
| 1197 |
addModule(directories[i].file(), scripts); |
| 1198 |
} |
| 1199 |
|
| 1200 |
// set signal and remove node to avoid restoring at reinit |
| 1201 |
const char *s = "nasal-dir-initialized"; |
| 1202 |
SGPropertyNode *signal = fgGetNode("/sim/signals", true); |
| 1203 |
signal->setBoolValue(s, true); |
| 1204 |
signal->removeChildren(s); |
| 1205 |
|
| 1206 |
// Pull scripts out of the property tree, too |
| 1207 |
loadPropertyScripts(); |
| 1208 |
|
| 1209 |
// now Nasal modules are loaded, we can do some delayed work |
| 1210 |
postinitNasalPositioned(d->_globals, d->_context); |
| 1211 |
postinitNasalGUI(d->_globals, d->_context); |
| 1212 |
|
| 1213 |
d->_inited = true; |
| 1214 |
} |
| 1215 |
|
| 1216 |
void FGNasalSys::shutdown() |
| 1217 |
{ |
| 1218 |
if (!d->_inited) { |
| 1219 |
return; |
| 1220 |
} |
| 1221 |
|
| 1222 |
shutdownNasalPositioned(); |
| 1223 |
shutdownNasalFlightPlan(); |
| 1224 |
shutdownNasalUnitTestInSim(); |
| 1225 |
|
| 1226 |
for (auto l : d->_listener) |
| 1227 |
delete l.second; |
| 1228 |
d->_listener.clear(); |
| 1229 |
|
| 1230 |
for (auto c : d->_commands) { |
| 1231 |
globals->get_commands()->removeCommand(c.first); |
| 1232 |
} |
| 1233 |
d->_commands.clear(); |
| 1234 |
|
| 1235 |
for (auto ml : d->_moduleListeners) |
| 1236 |
delete ml; |
| 1237 |
d->_moduleListeners.clear(); |
| 1238 |
|
| 1239 |
for (auto t : d->_nasalTimers) { |
| 1240 |
delete t; |
| 1241 |
} |
| 1242 |
d->_nasalTimers.clear(); |
| 1243 |
|
| 1244 |
naClearSaved(); |
| 1245 |
|
| 1246 |
d->_string = naNil(); // will be freed by _context |
| 1247 |
naFreeContext(d->_context); |
| 1248 |
|
| 1249 |
//setWatchedRef(d->_globals); |
| 1250 |
|
| 1251 |
// remove the recursive reference in globals |
| 1252 |
hashset(d->_globals, "globals", naNil()); |
| 1253 |
d->_globals = naNil(); |
| 1254 |
|
| 1255 |
naGC(); |
| 1256 |
|
| 1257 |
// Destroy all queued ghosts : important to ensure persistent timers are |
| 1258 |
// destroyed now. |
| 1259 |
nasal::ghostProcessDestroyList(); |
| 1260 |
|
| 1261 |
if (!d->_persistentTimers.empty()) { |
| 1262 |
SG_LOG(SG_NASAL, SG_DEV_WARN, "Extant persistent timer count:" << d->_persistentTimers.size()); |
| 1263 |
|
| 1264 |
for (auto pt : d->_persistentTimers) { |
| 1265 |
SG_LOG(SG_NASAL, SG_DEV_WARN, "Extant:" << pt << " : " << pt->name()); |
| 1266 |
} |
| 1267 |
} |
| 1268 |
|
| 1269 |
d->_inited = false; |
| 1270 |
} |
| 1271 |
|
| 1272 |
naRef FGNasalSys::wrappedPropsNode(SGPropertyNode* aProps) |
| 1273 |
{ |
| 1274 |
if (naIsNil(d->_wrappedNodeFunc)) { |
| 1275 |
nasal::Hash props = getGlobals().get<nasal::Hash>("props"); |
| 1276 |
d->_wrappedNodeFunc = props.get("wrapNode"); |
| 1277 |
} |
| 1278 |
|
| 1279 |
naRef args[1]; |
| 1280 |
args[0] = propNodeGhost(aProps); |
| 1281 |
naContext ctx = naNewContext(); |
| 1282 |
naRef wrapped = naCallMethodCtx(ctx, d->_wrappedNodeFunc, naNil(), 1, args, naNil()); |
| 1283 |
naFreeContext(ctx); |
| 1284 |
return wrapped; |
| 1285 |
} |
| 1286 |
|
| 1287 |
void FGNasalSys::update(double) |
| 1288 |
{ |
| 1289 |
if( NasalClipboard::getInstance() ) |
| 1290 |
NasalClipboard::getInstance()->update(); |
| 1291 |
|
| 1292 |
std::for_each(d->_dead_listener.begin(), d->_dead_listener.end(), |
| 1293 |
[](FGNasalListener* l) { delete l; }); |
| 1294 |
d->_dead_listener.clear(); |
| 1295 |
|
| 1296 |
if (!d->_loadList.empty()) { |
| 1297 |
if (d->_delay_load) |
| 1298 |
d->_delay_load = false; |
| 1299 |
else |
| 1300 |
// process Nasal load hook (only one per update loop to avoid excessive lags) |
| 1301 |
d->_loadList.pop()->load(); |
| 1302 |
} else if (!d->_unloadList.empty()) { |
| 1303 |
// process pending Nasal unload hooks after _all_ load hooks were processed |
| 1304 |
// (only unload one per update loop to avoid excessive lags) |
| 1305 |
d->_unloadList.pop()->unload(); |
| 1306 |
} |
| 1307 |
// Destroy all queued ghosts |
| 1308 |
nasal::ghostProcessDestroyList(); |
| 1309 |
|
| 1310 |
// The global context is a legacy thing. We use dynamically |
| 1311 |
// created contexts for naCall() now, so that we can call them |
| 1312 |
// recursively. But there are still spots that want to use it for |
| 1313 |
// naNew*() calls, which end up leaking memory because the context |
| 1314 |
// only clears out its temporary vector when it's *used*. So just |
| 1315 |
// junk it and fetch a new/reinitialized one every frame. This is |
| 1316 |
// clumsy: the right solution would use the dynamic context in all |
| 1317 |
// cases and eliminate _context entirely. But that's more work, |
| 1318 |
// and this works fine (yes, they say "New" and "Free", but |
| 1319 |
// they're very fast, just trust me). -Andy |
| 1320 |
naFreeContext(d->_context); |
| 1321 |
d->_context = naNewContext(); |
| 1322 |
} |
| 1323 |
|
| 1324 |
bool pathSortPredicate(const SGPath& p1, const SGPath& p2) |
| 1325 |
{ |
| 1326 |
return p1.file() < p2.file(); |
| 1327 |
} |
| 1328 |
|
| 1329 |
// Loads all scripts in given directory, with an optional partial ordering of |
| 1330 |
// files defined in loadorder. |
| 1331 |
void FGNasalSys::loadScriptDirectory(simgear::Dir nasalDir, SGPropertyNode* loadorder, |
| 1332 |
bool excludeUnspecifiedInLoadOrder) |
| 1333 |
{ |
| 1334 |
simgear::PathList scripts = nasalDir.children(simgear::Dir::TYPE_FILE, ".nas"); |
| 1335 |
|
| 1336 |
if (loadorder != nullptr && loadorder->hasChild("file")) { |
| 1337 |
// Load any scripts defined in the loadorder in order, removing them from |
| 1338 |
// the list so they don't get loaded twice. |
| 1339 |
simgear::PropertyList files = loadorder->getChildren("file"); |
| 1340 |
|
| 1341 |
auto loadAndErase = [ &scripts, &nasalDir, this ] (SGPropertyNode_ptr n) { |
| 1342 |
SGPath p = SGPath(nasalDir.path(), n->getStringValue()); |
| 1343 |
auto script = std::find(scripts.begin(), scripts.end(), p); |
| 1344 |
if (script != scripts.end()) { |
| 1345 |
this->loadModule(p, p.file_base().c_str()); |
| 1346 |
scripts.erase(script); |
| 1347 |
} |
| 1348 |
}; |
| 1349 |
|
| 1350 |
std::for_each(files.begin(), files.end(), loadAndErase); |
| 1351 |
} |
| 1352 |
|
| 1353 |
if (excludeUnspecifiedInLoadOrder) { |
| 1354 |
return; |
| 1355 |
} |
| 1356 |
|
| 1357 |
// Load any remaining scripts. |
| 1358 |
// Note: simgear::Dir already reports file entries in a deterministic order, |
| 1359 |
// so a fixed loading sequence is guaranteed (same for every user) |
| 1360 |
std::for_each(scripts.begin(), scripts.end(), [this](SGPath p) { this->loadModule(p, p.file_base().c_str()); }); |
| 1361 |
} |
| 1362 |
|
| 1363 |
// Create module with list of scripts |
| 1364 |
void FGNasalSys::addModule(string moduleName, simgear::PathList scripts) |
| 1365 |
{ |
| 1366 |
if (! scripts.empty()) |
| 1367 |
{ |
| 1368 |
SGPropertyNode* nasal = globals->get_props()->getNode("nasal", true); |
| 1369 |
SGPropertyNode* module_node = nasal->getChild(moduleName,0,true); |
| 1370 |
for (unsigned int i=0; i<scripts.size(); ++i) { |
| 1371 |
SGPropertyNode* pFileNode = module_node->getChild("file",i,true); |
| 1372 |
pFileNode->setStringValue(scripts[i].utf8Str()); |
| 1373 |
} |
| 1374 |
if (!module_node->hasChild("enabled",0)) |
| 1375 |
{ |
| 1376 |
SGPropertyNode* node = module_node->getChild("enabled",0,true); |
| 1377 |
node->setBoolValue(false); |
| 1378 |
node->setAttribute(SGPropertyNode::USERARCHIVE,false); |
| 1379 |
#ifndef BUILDING_TESTSUITE |
| 1380 |
SG_LOG(SG_NASAL, SG_ALERT, "Nasal module " << moduleName |
| 1381 |
<< " present in FGDATA/Nasal but not configured in defaults.xml. " |
| 1382 |
<< " Please add an entry to defaults.xml, and set " << node->getPath() |
| 1383 |
<< "=true to load the module on-demand at runtime when required." |
| 1384 |
); |
| 1385 |
#endif |
| 1386 |
} |
| 1387 |
} |
| 1388 |
} |
| 1389 |
|
| 1390 |
// Loads the scripts found under /nasal in the global tree |
| 1391 |
void FGNasalSys::loadPropertyScripts() |
| 1392 |
{ |
| 1393 |
SGPropertyNode* nasal = globals->get_props()->getNode("nasal"); |
| 1394 |
if(!nasal) return; |
| 1395 |
|
| 1396 |
for(int i=0; i<nasal->nChildren(); i++) |
| 1397 |
{ |
| 1398 |
SGPropertyNode* n = nasal->getChild(i); |
| 1399 |
loadPropertyScripts(n); |
| 1400 |
} |
| 1401 |
} |
| 1402 |
|
| 1403 |
// Loads the scripts found under /nasal in the global tree |
| 1404 |
void FGNasalSys::loadPropertyScripts(SGPropertyNode* n) |
| 1405 |
{ |
| 1406 |
bool is_loaded = false; |
| 1407 |
|
| 1408 |
std::string module = n->getNameString(); |
| 1409 |
if(n->hasChild("module")) |
| 1410 |
module = n->getStringValue("module"); |
| 1411 |
if (n->getBoolValue("enabled",true)) |
| 1412 |
{ |
| 1413 |
// allow multiple files to be specified within a single |
| 1414 |
// Nasal module tag |
| 1415 |
int j = 0; |
| 1416 |
SGPropertyNode *fn; |
| 1417 |
bool file_specified = false; |
| 1418 |
bool ok=true; |
| 1419 |
while((fn = n->getChild("file", j)) != NULL) { |
| 1420 |
file_specified = true; |
| 1421 |
std::string file = fn->getStringValue(); |
| 1422 |
SGPath p(file); |
| 1423 |
if (!p.isAbsolute() || !p.exists()) |
| 1424 |
{ |
| 1425 |
p = globals->resolve_maybe_aircraft_path(file); |
| 1426 |
if (p.isNull()) { |
| 1427 |
simgear::reportFailure(simgear::LoadFailure::NotFound, simgear::ErrorCode::AircraftSystems, |
| 1428 |
string{"Missing nasal file for module:"} + module, sg_location{file}); |
| 1429 |
} |
| 1430 |
} |
| 1431 |
ok &= p.isNull() ? false : loadModule(p, module.c_str()); |
| 1432 |
j++; |
| 1433 |
} |
| 1434 |
|
| 1435 |
std::string src = n->getStringValue("script"); |
| 1436 |
if(!n->hasChild("script")) src = ""; // Hrm... |
| 1437 |
if(!src.empty()) |
| 1438 |
createModule(module.c_str(), n->getPath().c_str(), src.c_str(), src.length()); |
| 1439 |
|
| 1440 |
if(!file_specified && src.empty()) |
| 1441 |
{ |
| 1442 |
// module no longer exists - clear the archived "enable" flag |
| 1443 |
n->setAttribute(SGPropertyNode::USERARCHIVE,false); |
| 1444 |
SGPropertyNode* node = n->getChild("enabled",0,false); |
| 1445 |
if (node) |
| 1446 |
node->setAttribute(SGPropertyNode::USERARCHIVE,false); |
| 1447 |
|
| 1448 |
SG_LOG(SG_NASAL, SG_ALERT, "Nasal error: " << |
| 1449 |
"no <file> or <script> defined in " << |
| 1450 |
"/nasal/" << module); |
| 1451 |
} |
| 1452 |
else |
| 1453 |
is_loaded = ok; |
| 1454 |
} |
| 1455 |
else |
| 1456 |
{ |
| 1457 |
SGPropertyNode* enable = n->getChild("enabled"); |
| 1458 |
if (enable) |
| 1459 |
{ |
| 1460 |
FGNasalModuleListener* listener = new FGNasalModuleListener(n); |
| 1461 |
d->_moduleListeners.push_back(listener); |
| 1462 |
enable->addChangeListener(listener, false); |
| 1463 |
} |
| 1464 |
} |
| 1465 |
SGPropertyNode* loaded = n->getChild("loaded",0,true); |
| 1466 |
loaded->setAttribute(SGPropertyNode::PRESERVE,true); |
| 1467 |
loaded->setBoolValue(is_loaded); |
| 1468 |
} |
| 1469 |
|
| 1470 |
#if defined(BUILDING_TESTSUITE) |
| 1471 |
|
| 1472 |
static string_list global_nasalErrors; |
| 1473 |
|
| 1474 |
string_list FGNasalSys::getAndClearErrorList() |
| 1475 |
{ |
| 1476 |
string_list r; |
| 1477 |
global_nasalErrors.swap(r); |
| 1478 |
return r; |
| 1479 |
} |
| 1480 |
#endif |
| 1481 |
|
| 1482 |
// Logs a runtime error, with stack trace, to the FlightGear log stream |
| 1483 |
void FGNasalSys::logError(naContext context) |
| 1484 |
{ |
| 1485 |
string errorMessage = naGetError(context); |
| 1486 |
#if defined(BUILDING_TESTSUITE) |
| 1487 |
global_nasalErrors.push_back(errorMessage); |
| 1488 |
#else |
| 1489 |
SG_LOG(SG_NASAL, SG_ALERT, "Nasal runtime error: " << errorMessage); |
| 1490 |
|
| 1491 |
string_list nasalStack; |
| 1492 |
logNasalStack(context, nasalStack); |
| 1493 |
flightgear::sentryReportNasalError(errorMessage, nasalStack); |
| 1494 |
#endif |
| 1495 |
} |
| 1496 |
|
| 1497 |
|
| 1498 |
void FGNasalSys::logNasalStack(naContext context, string_list& stack) |
| 1499 |
{ |
| 1500 |
const int stack_depth = naStackDepth(context); |
| 1501 |
for (int i=0; i<stack_depth; ++i) { |
| 1502 |
std::string text = std::string(naStr_data(naGetSourceFile(context, i))) |
| 1503 |
+ ", line " + std::to_string(naGetLine(context, i)); |
| 1504 |
stack.push_back(text); |
| 1505 |
SG_LOG(SG_NASAL, SG_ALERT, ((i) ? " called from: " : " at ") << text); |
| 1506 |
} |
| 1507 |
return; |
| 1508 |
} |
| 1509 |
|
| 1510 |
// Reads a script file, executes it, and places the resulting |
| 1511 |
// namespace into the global namespace under the specified module |
| 1512 |
// name. |
| 1513 |
bool FGNasalSys::loadModule(SGPath file, const char* module) |
| 1514 |
{ |
| 1515 |
if (!file.exists()) { |
| 1516 |
SG_LOG(SG_NASAL, SG_ALERT, "Cannot load module, missing file:" << file); |
| 1517 |
return false; |
| 1518 |
} |
| 1519 |
|
| 1520 |
#if 1 |
| 1521 |
// MMap the contents of the file. |
| 1522 |
// This saves an alloc, memcpy and free |
| 1523 |
SGMMapFile mmap(file); |
| 1524 |
mmap.open(SG_IO_IN); |
| 1525 |
|
| 1526 |
auto pathStr = file.utf8Str(); |
| 1527 |
return createModule(module, pathStr.c_str(), mmap.get(), mmap.get_size()); |
| 1528 |
#else |
| 1529 |
sg_ifstream file_in(file); |
| 1530 |
string buf; |
| 1531 |
while (!file_in.eof()) { |
| 1532 |
char bytes[8192]; |
| 1533 |
file_in.read(bytes, 8192); |
| 1534 |
buf.append(bytes, file_in.gcount()); |
| 1535 |
} |
| 1536 |
file_in.close(); |
| 1537 |
auto pathStr = file.utf8Str(); |
| 1538 |
return createModule(module, pathStr.c_str(), buf.data(), buf.length()); |
| 1539 |
#endif |
| 1540 |
} |
| 1541 |
|
| 1542 |
// Parse and run. Save the local variables namespace, as it will |
| 1543 |
// become a sub-object of globals. The optional "arg" argument can be |
| 1544 |
// used to pass an associated property node to the module, which can then |
| 1545 |
// be accessed via cmdarg(). (This is, for example, used by XML dialogs.) |
| 1546 |
bool FGNasalSys::createModule(const char* moduleName, const char* fileName, |
| 1547 |
const char* src, int len, |
| 1548 |
const SGPropertyNode* cmdarg, |
| 1549 |
int argc, naRef* args) |
| 1550 |
{ |
| 1551 |
naContext ctx = naNewContext(); |
| 1552 |
std::string errors; |
| 1553 |
naRef code = parse(ctx, fileName, src, len, errors); |
| 1554 |
if(naIsNil(code)) { |
| 1555 |
naFreeContext(ctx); |
| 1556 |
return false; |
| 1557 |
} |
| 1558 |
|
| 1559 |
|
| 1560 |
// See if we already have a module hash to use. This allows the |
| 1561 |
// user to, for example, add functions to the built-in math |
| 1562 |
// module. Make a new one if necessary. |
| 1563 |
naRef locals; |
| 1564 |
naRef modname = naNewString(ctx); |
| 1565 |
naStr_fromdata(modname, (char*)moduleName, strlen(moduleName)); |
| 1566 |
if (naIsNil(d->_globals)) |
| 1567 |
return false; |
| 1568 |
|
| 1569 |
if (!naHash_get(d->_globals, modname, &locals)) { |
| 1570 |
// if we are re-creating the module for canvas, ensure the C++ |
| 1571 |
// pieces are re-defined first. As far as I can see, Canvas is the only |
| 1572 |
// hybrid module where C++ pieces and Nasal code are combined. |
| 1573 |
const auto isCanvas = strcmp(moduleName, "canvas") == 0; |
| 1574 |
if (isCanvas) { |
| 1575 |
initNasalCanvas(d->_globals, d->_context); |
| 1576 |
naHash_get(d->_globals, modname, &locals); |
| 1577 |
} else { |
| 1578 |
locals = naNewHash(ctx); |
| 1579 |
} |
| 1580 |
} |
| 1581 |
|
| 1582 |
// store the filename in the module hash, so we could reload it |
| 1583 |
// this is only needed for 'top-level' single file modules; for |
| 1584 |
// 'directory' modules we use the file path nodes defined by |
| 1585 |
// FGNasalSys::addModule |
| 1586 |
naRef modFilePath = naNewString(ctx); |
| 1587 |
naStr_fromdata(modFilePath, (char*)fileName, strlen(fileName)); |
| 1588 |
hashset(locals, "__moduleFilePath", modFilePath); |
| 1589 |
|
| 1590 |
d->_cmdArg = (SGPropertyNode*)cmdarg; |
| 1591 |
callWithContext(ctx, code, argc, args, locals); |
| 1592 |
hashset(d->_globals, moduleName, locals); |
| 1593 |
|
| 1594 |
naFreeContext(ctx); |
| 1595 |
return true; |
| 1596 |
} |
| 1597 |
|
| 1598 |
void FGNasalSys::deleteModule(const char* moduleName) |
| 1599 |
{ |
| 1600 |
if (!d->_inited || naIsNil(d->_globals)) { |
| 1601 |
// can occur on shutdown due to us being shutdown first, but other |
| 1602 |
// subsystems having Nasal objects. |
| 1603 |
return; |
| 1604 |
} |
| 1605 |
|
| 1606 |
auto nasalNode = globals->get_props()->getNode("nasal", true); |
| 1607 |
auto moduleNode = nasalNode->getChild(moduleName, 0); |
| 1608 |
if (moduleNode) { |
| 1609 |
// modules can use this value going false, to trigger unload |
| 1610 |
// behaviours |
| 1611 |
moduleNode->setBoolValue("loaded", false); |
| 1612 |
} |
| 1613 |
|
| 1614 |
naContext ctx = naNewContext(); |
| 1615 |
naRef modname = naNewString(ctx); |
| 1616 |
naStr_fromdata(modname, (char*)moduleName, strlen(moduleName)); |
| 1617 |
|
| 1618 |
naRef locals; |
| 1619 |
if (naHash_get(d->_globals, modname, &locals)) { |
| 1620 |
naRef unloadFunc = naHash_cget(locals, (char*)"unload"); |
| 1621 |
if (naIsFunc(unloadFunc)) { |
| 1622 |
callWithContext(ctx, unloadFunc, 0, nullptr, locals); |
| 1623 |
} |
| 1624 |
|
| 1625 |
// now delete the module hash |
| 1626 |
naHash_delete(d->_globals, modname); |
| 1627 |
} |
| 1628 |
|
| 1629 |
naFreeContext(ctx); |
| 1630 |
} |
| 1631 |
|
| 1632 |
bool FGNasalSys::reloadModuleFromFile(const std::string& moduleName) |
| 1633 |
{ |
| 1634 |
if (!d->_inited || naIsNil(d->_globals)) { |
| 1635 |
return false; |
| 1636 |
} |
| 1637 |
|
| 1638 |
naRef locals = naHash_cget(d->_globals, (char*)moduleName.c_str()); |
| 1639 |
if (naIsNil(locals)) { |
| 1640 |
// no such module |
| 1641 |
return false; |
| 1642 |
} |
| 1643 |
|
| 1644 |
// check if we have a module entry under /nasal/ - if so, use |
| 1645 |
// this to determine the list of files. We don't (yet) re-run |
| 1646 |
// addModule here so adding new .nas files isn't possible, but |
| 1647 |
// in principle it could be done |
| 1648 |
auto nasalNode = globals->get_props()->getNode("nasal", true); |
| 1649 |
auto moduleNode = nasalNode->getChild(moduleName, 0); |
| 1650 |
if (moduleNode) { |
| 1651 |
deleteModule(moduleName.c_str()); |
| 1652 |
loadPropertyScripts(moduleNode); |
| 1653 |
return true; |
| 1654 |
} else { |
| 1655 |
// assume it's a single-file module for now |
| 1656 |
naRef filePath = naHash_cget(locals, (char*)"__moduleFilePath"); |
| 1657 |
if (naIsNil(filePath)) { |
| 1658 |
return false; |
| 1659 |
} |
| 1660 |
|
| 1661 |
SGPath path = SGPath::fromUtf8(naStr_data(filePath)); |
| 1662 |
deleteModule(moduleName.c_str()); |
| 1663 |
return loadModule(path, moduleName.c_str()); |
| 1664 |
} |
| 1665 |
} |
| 1666 |
|
| 1667 |
naRef FGNasalSys::getModule(const std::string& moduleName) const |
| 1668 |
{ |
| 1669 |
naRef mod = naHash_cget(d->_globals, (char*)moduleName.c_str()); |
| 1670 |
return mod; |
| 1671 |
} |
| 1672 |
|
| 1673 |
naRef FGNasalSys::getModule(const char* moduleName) |
| 1674 |
{ |
| 1675 |
naRef mod = naHash_cget(d->_globals, (char*)moduleName); |
| 1676 |
return mod; |
| 1677 |
} |
| 1678 |
|
| 1679 |
naRef FGNasalSys::parse(naContext ctx, const char* filename, |
| 1680 |
const char* buf, int len, |
| 1681 |
std::string& errors) |
| 1682 |
{ |
| 1683 |
int errLine = -1; |
| 1684 |
naRef srcfile = naNewString(ctx); |
| 1685 |
naStr_fromdata(srcfile, (char*)filename, strlen(filename)); |
| 1686 |
naRef code = naParseCode(ctx, srcfile, 1, (char*)buf, len, &errLine); |
| 1687 |
if(naIsNil(code)) { |
| 1688 |
std::ostringstream errorMessageStream; |
| 1689 |
errorMessageStream << "Nasal parse error: " << naGetError(ctx) << |
| 1690 |
" in "<< filename <<", line " << errLine; |
| 1691 |
errors = errorMessageStream.str(); |
| 1692 |
SG_LOG(SG_NASAL, SG_ALERT, errors); |
| 1693 |
|
| 1694 |
// Show the line, in case <filename> isn't a real file, e.g. nasal code |
| 1695 |
// is in an .xml file. |
| 1696 |
const char* line_begin = buf; |
| 1697 |
const char* line_end = nullptr; |
| 1698 |
int line_num = 1; |
| 1699 |
for(;;) { |
| 1700 |
line_end = strchr(line_begin, '\n'); |
| 1701 |
if (!line_end) { |
| 1702 |
line_end = line_begin + strlen(line_begin); |
| 1703 |
break; |
| 1704 |
} |
| 1705 |
if (line_num == errLine) break; |
| 1706 |
line_begin = line_end + 1; |
| 1707 |
line_num += 1; |
| 1708 |
} |
| 1709 |
if (line_num == errLine) { |
| 1710 |
SG_LOG(SG_NASAL, SG_ALERT, std::string(line_begin, line_end) << "\n"); |
| 1711 |
} |
| 1712 |
else { |
| 1713 |
SG_LOG(SG_NASAL, SG_ALERT, "[Could not find line " << errLine << " - only " << line_num << " lines."); |
| 1714 |
} |
| 1715 |
|
| 1716 |
return naNil(); |
| 1717 |
} |
| 1718 |
|
| 1719 |
// Bind to the global namespace before returning |
| 1720 |
return naBindFunction(ctx, code, d->_globals); |
| 1721 |
} |
| 1722 |
|
| 1723 |
bool FGNasalSys::handleCommand( const char* moduleName, |
| 1724 |
const char* fileName, |
| 1725 |
const char* src, |
| 1726 |
const SGPropertyNode* arg, |
| 1727 |
SGPropertyNode* root) |
| 1728 |
{ |
| 1729 |
naContext ctx = naNewContext(); |
| 1730 |
std::string errorMessage; |
| 1731 |
naRef code = parse(ctx, fileName, src, strlen(src), errorMessage); |
| 1732 |
if(naIsNil(code)) { |
| 1733 |
naFreeContext(ctx); |
| 1734 |
return false; |
| 1735 |
} |
| 1736 |
|
| 1737 |
// Commands can be run "in" a module. Make sure that module |
| 1738 |
// exists, and set it up as the local variables hash for the |
| 1739 |
// command. |
| 1740 |
naRef locals = naNil(); |
| 1741 |
if(moduleName[0]) { |
| 1742 |
naRef modname = naNewString(ctx); |
| 1743 |
naStr_fromdata(modname, (char*)moduleName, strlen(moduleName)); |
| 1744 |
if (!naHash_get(d->_globals, modname, &locals)) { |
| 1745 |
locals = naNewHash(ctx); |
| 1746 |
naHash_set(d->_globals, modname, locals); |
| 1747 |
} |
| 1748 |
} |
| 1749 |
|
| 1750 |
// Cache this command's argument for inspection via cmdarg(). For |
| 1751 |
// performance reasons, we won't bother with it if the invoked |
| 1752 |
// code doesn't need it. |
| 1753 |
d->_cmdArg = (SGPropertyNode*)arg; |
| 1754 |
|
| 1755 |
callWithContext(ctx, code, 0, 0, locals); |
| 1756 |
naFreeContext(ctx); |
| 1757 |
return true; |
| 1758 |
} |
| 1759 |
|
| 1760 |
bool FGNasalSys::handleCommand(const SGPropertyNode * arg, SGPropertyNode * root) |
| 1761 |
{ |
| 1762 |
std::string src = arg->getStringValue("script"); |
| 1763 |
std::string moduleName = arg->getStringValue("module"); |
| 1764 |
|
| 1765 |
return handleCommand( moduleName.c_str(), |
| 1766 |
arg->getPath(true).c_str(), |
| 1767 |
src.c_str(), |
| 1768 |
arg, |
| 1769 |
root); |
| 1770 |
} |
| 1771 |
|
| 1772 |
// settimer(func, dt, simtime) extension function. The first argument |
| 1773 |
// is a Nasal function to call, the second is a delta time (from now), |
| 1774 |
// in seconds. The third, if present, is a boolean value indicating |
| 1775 |
// that "real world" time (rather than simulator time) is to be used. |
| 1776 |
// |
| 1777 |
// Implementation note: the FGTimer objects don't live inside the |
| 1778 |
// garbage collector, so the Nasal handler functions have to be |
| 1779 |
// "saved" somehow lest they be inadvertently cleaned. In this case, |
| 1780 |
// they are inserted into a globals.__gcsave hash and removed on |
| 1781 |
// expiration. |
| 1782 |
void FGNasalSys::setTimer(naContext c, int argc, naRef* args) |
| 1783 |
{ |
| 1784 |
// Extract the handler, delta, and simtime arguments: |
| 1785 |
naRef handler = argc > 0 ? args[0] : naNil(); |
| 1786 |
if(!(naIsCode(handler) || naIsCCode(handler) || naIsFunc(handler))) { |
| 1787 |
naRuntimeError(c, "settimer() with invalid function argument"); |
| 1788 |
return; |
| 1789 |
} |
| 1790 |
|
| 1791 |
naRef delta = argc > 1 ? args[1] : naNil(); |
| 1792 |
if(naIsNil(delta)) { |
| 1793 |
naRuntimeError(c, "settimer() with invalid time argument"); |
| 1794 |
return; |
| 1795 |
} |
| 1796 |
|
| 1797 |
bool simtime = (argc > 2 && naTrue(args[2])) ? false : true; |
| 1798 |
|
| 1799 |
// A unique name for the timer based on the file name and line number of the function. |
| 1800 |
std::string name = "settimer-"; |
| 1801 |
name.append(naStr_data(naGetSourceFile(c, 0))); |
| 1802 |
name.append(":"); |
| 1803 |
name.append(std::to_string(naGetLine(c, 0))); |
| 1804 |
|
| 1805 |
// Generate and register a C++ timer handler |
| 1806 |
NasalTimer* t = new NasalTimer(handler, this); |
| 1807 |
d->_nasalTimers.push_back(t); |
| 1808 |
globals->get_event_mgr()->addEvent(name, |
| 1809 |
[t](){ t->timerExpired(); }, |
| 1810 |
delta.num, simtime); |
| 1811 |
} |
| 1812 |
|
| 1813 |
void FGNasalSys::handleTimer(NasalTimer* t) |
| 1814 |
{ |
| 1815 |
call(t->handler, 0, 0, naNil()); |
| 1816 |
auto it = std::find(d->_nasalTimers.begin(), d->_nasalTimers.end(), t); |
| 1817 |
assert(it != d->_nasalTimers.end()); |
| 1818 |
d->_nasalTimers.erase(it); |
| 1819 |
delete t; |
| 1820 |
} |
| 1821 |
|
| 1822 |
int FGNasalSys::gcSave(naRef r) |
| 1823 |
{ |
| 1824 |
return naGCSave(r); |
| 1825 |
} |
| 1826 |
|
| 1827 |
void FGNasalSys::gcRelease(int key) |
| 1828 |
{ |
| 1829 |
naGCRelease(key); |
| 1830 |
} |
| 1831 |
|
| 1832 |
|
| 1833 |
//------------------------------------------------------------------------------ |
| 1834 |
|
| 1835 |
NasalTimer::NasalTimer(naRef h, FGNasalSys* sys) : |
| 1836 |
handler(h), nasal(sys) |
| 1837 |
{ |
| 1838 |
assert(sys); |
| 1839 |
gcKey = naGCSave(handler); |
| 1840 |
} |
| 1841 |
|
| 1842 |
NasalTimer::~NasalTimer() |
| 1843 |
{ |
| 1844 |
naGCRelease(gcKey); |
| 1845 |
} |
| 1846 |
|
| 1847 |
void NasalTimer::timerExpired() |
| 1848 |
{ |
| 1849 |
nasal->handleTimer(this); |
| 1850 |
// note handleTimer calls delete on us, don't do anything |
| 1851 |
// which requires 'this' to be valid here |
| 1852 |
} |
| 1853 |
|
| 1854 |
|
| 1855 |
int NasalSysPrivate::_listenerId = 0; |
| 1856 |
|
| 1857 |
// setlistener(<property>, <func> [, <initial=0> [, <persistent=1>]]) |
| 1858 |
// Attaches a callback function to a property (specified as a global |
| 1859 |
// property path string or a SGPropertyNode* ghost). If the third, |
| 1860 |
// optional argument (default=0) is set to 1, then the function is also |
| 1861 |
// called initially. If the fourth, optional argument is set to 0, then the |
| 1862 |
// function is only called when the property node value actually changes. |
| 1863 |
// Otherwise it's called independent of the value whenever the node is |
| 1864 |
// written to (default). The setlistener() function returns a unique |
| 1865 |
// id number, which is to be used as argument to the removelistener() |
| 1866 |
// function. |
| 1867 |
naRef FGNasalSys::setListener(naContext c, int argc, naRef* args) |
| 1868 |
{ |
| 1869 |
SGPropertyNode_ptr node; |
| 1870 |
naRef prop = argc > 0 ? args[0] : naNil(); |
| 1871 |
if(naIsString(prop)) node = fgGetNode(naStr_data(prop), true); |
| 1872 |
else if(naIsGhost(prop)) node = static_cast<SGPropertyNode*>(naGhost_ptr(prop)); |
| 1873 |
else { |
| 1874 |
naRuntimeError(c, "setlistener() with invalid property argument"); |
| 1875 |
return naNil(); |
| 1876 |
} |
| 1877 |
|
| 1878 |
if (node->isTied() || node->isAlias()) { |
| 1879 |
const auto isSafe = node->getAttribute(SGPropertyNode::LISTENER_SAFE); |
| 1880 |
if (!isSafe) { |
| 1881 |
SG_LOG(SG_NASAL, SG_DEV_ALERT, "ERROR: Cannot add listener to tied property " << |
| 1882 |
node->getPath()); |
| 1883 |
} |
| 1884 |
} |
| 1885 |
|
| 1886 |
naRef code = argc > 1 ? args[1] : naNil(); |
| 1887 |
if(!(naIsCode(code) || naIsCCode(code) || naIsFunc(code))) { |
| 1888 |
naRuntimeError(c, "setlistener() with invalid function argument"); |
| 1889 |
return naNil(); |
| 1890 |
} |
| 1891 |
|
| 1892 |
int init = argc > 2 && naIsNum(args[2]) ? int(args[2].num) : 0; // do not trigger when created |
| 1893 |
int type = argc > 3 && naIsNum(args[3]) ? int(args[3].num) : 1; // trigger will always be triggered when the property is written |
| 1894 |
FGNasalListener* nl = new FGNasalListener(node, code, this, |
| 1895 |
gcSave(code), d->_listenerId, init, type); |
| 1896 |
|
| 1897 |
node->addChangeListener(nl, init != 0); |
| 1898 |
|
| 1899 |
d->_listener[d->_listenerId] = nl; |
| 1900 |
return naNum(d->_listenerId++); |
| 1901 |
} |
| 1902 |
|
| 1903 |
// removelistener(int) extension function. The argument is the id of |
| 1904 |
// a listener as returned by the setlistener() function. |
| 1905 |
naRef FGNasalSys::removeListener(naContext c, int argc, naRef* args) |
| 1906 |
{ |
| 1907 |
naRef id = argc > 0 ? args[0] : naNil(); |
| 1908 |
auto it = d->_listener.find(int(id.num)); |
| 1909 |
if (!naIsNum(id) || it == d->_listener.end() || it->second->_dead) { |
| 1910 |
naRuntimeError(c, "removelistener() with invalid listener id"); |
| 1911 |
return naNil(); |
| 1912 |
} |
| 1913 |
|
| 1914 |
it->second->_dead = true; |
| 1915 |
d->_dead_listener.push_back(it->second); |
| 1916 |
d->_listener.erase(it); |
| 1917 |
return naNum(d->_listener.size()); |
| 1918 |
} |
| 1919 |
|
| 1920 |
void FGNasalSys::registerToLoad(FGNasalModelData *data) |
| 1921 |
{ |
| 1922 |
if (d->_loadList.empty()) |
| 1923 |
d->_delay_load = true; |
| 1924 |
d->_loadList.push(data); |
| 1925 |
} |
| 1926 |
|
| 1927 |
void FGNasalSys::registerToUnload(FGNasalModelData *data) |
| 1928 |
{ |
| 1929 |
d->_unloadList.push(data); |
| 1930 |
} |
| 1931 |
|
| 1932 |
bool FGNasalSys::addCommand(naRef func, const std::string& name) |
| 1933 |
{ |
| 1934 |
if (d->_commands.find(name) != d->_commands.end()) { |
| 1935 |
SG_LOG(SG_NASAL, SG_WARN, "duplicate add of command:" << name); |
| 1936 |
return false; |
| 1937 |
} |
| 1938 |
|
| 1939 |
NasalCommand* cmd = new NasalCommand(this, func, name); |
| 1940 |
d->_commands[name] = cmd; |
| 1941 |
return true; |
| 1942 |
} |
| 1943 |
|
| 1944 |
bool FGNasalSys::removeCommand(const std::string& name) |
| 1945 |
{ |
| 1946 |
auto it = d->_commands.find(name); |
| 1947 |
if (it == d->_commands.end()) { |
| 1948 |
SG_LOG(SG_NASAL, SG_WARN, "remove of unknwon command:" << name); |
| 1949 |
return false; |
| 1950 |
} |
| 1951 |
|
| 1952 |
// will delete the NasalCommand instance |
| 1953 |
bool ok = globals->get_commands()->removeCommand(name); |
| 1954 |
d->_commands.erase(it); |
| 1955 |
return ok; |
| 1956 |
} |
| 1957 |
|
| 1958 |
void FGNasalSys::addPersistentTimer(TimerObj* pto) |
| 1959 |
{ |
| 1960 |
d->_persistentTimers.push_back(pto); |
| 1961 |
} |
| 1962 |
|
| 1963 |
void FGNasalSys::removePersistentTimer(TimerObj* obj) |
| 1964 |
{ |
| 1965 |
auto it = std::find(d->_persistentTimers.begin(), d->_persistentTimers.end(), obj); |
| 1966 |
assert(it != d->_persistentTimers.end()); |
| 1967 |
d->_persistentTimers.erase(it); |
| 1968 |
} |
| 1969 |
|
| 1970 |
// Register the subsystem. |
| 1971 |
SGSubsystemMgr::Registrant<FGNasalSys> registrantFGNasalSys( |
| 1972 |
SGSubsystemMgr::INIT); |
| 1973 |
|
| 1974 |
|
| 1975 |
////////////////////////////////////////////////////////////////////////// |
| 1976 |
// FGNasalListener class. |
| 1977 |
|
| 1978 |
FGNasalListener::FGNasalListener(SGPropertyNode *node, naRef code, |
| 1979 |
FGNasalSys* nasal, int key, int id, |
| 1980 |
int init, int type) : |
| 1981 |
_node(node), |
| 1982 |
_code(code), |
| 1983 |
_gcKey(key), |
| 1984 |
_id(id), |
| 1985 |
_nas(nasal), |
| 1986 |
_init(init), |
| 1987 |
_type(type), |
| 1988 |
_active(0), |
| 1989 |
_dead(false), |
| 1990 |
_last_int(0L), |
| 1991 |
_last_float(0.0) |
| 1992 |
{ |
| 1993 |
if(_type == 0 && !_init) |
| 1994 |
changed(node); |
| 1995 |
} |
| 1996 |
|
| 1997 |
FGNasalListener::~FGNasalListener() |
| 1998 |
{ |
| 1999 |
_node->removeChangeListener(this); |
| 2000 |
_nas->gcRelease(_gcKey); |
| 2001 |
} |
| 2002 |
|
| 2003 |
void FGNasalListener::call(SGPropertyNode* which, naRef mode) |
| 2004 |
{ |
| 2005 |
if(_active || _dead) return; |
| 2006 |
_active++; |
| 2007 |
naRef arg[4]; |
| 2008 |
arg[0] = _nas->propNodeGhost(which); |
| 2009 |
arg[1] = _nas->propNodeGhost(_node); |
| 2010 |
arg[2] = mode; // value changed, child added/removed |
| 2011 |
arg[3] = naNum(_node != which); // child event? |
| 2012 |
_nas->call(_code, 4, arg, naNil()); |
| 2013 |
_active--; |
| 2014 |
} |
| 2015 |
|
| 2016 |
void FGNasalListener::valueChanged(SGPropertyNode* node) |
| 2017 |
{ |
| 2018 |
if(_type < 2 && node != _node) return; // skip child events |
| 2019 |
if(_type > 0 || changed(_node) || _init) |
| 2020 |
call(node, naNum(0)); |
| 2021 |
|
| 2022 |
_init = 0; |
| 2023 |
} |
| 2024 |
|
| 2025 |
void FGNasalListener::childAdded(SGPropertyNode*, SGPropertyNode* child) |
| 2026 |
{ |
| 2027 |
if(_type == 2) call(child, naNum(1)); |
| 2028 |
} |
| 2029 |
|
| 2030 |
void FGNasalListener::childRemoved(SGPropertyNode*, SGPropertyNode* child) |
| 2031 |
{ |
| 2032 |
if(_type == 2) call(child, naNum(-1)); |
| 2033 |
} |
| 2034 |
|
| 2035 |
bool FGNasalListener::changed(SGPropertyNode* node) |
| 2036 |
{ |
| 2037 |
using namespace simgear; |
| 2038 |
props::Type type = node->getType(); |
| 2039 |
if(type == props::NONE) return false; |
| 2040 |
if(type == props::UNSPECIFIED) return true; |
| 2041 |
|
| 2042 |
bool result; |
| 2043 |
switch(type) { |
| 2044 |
case props::BOOL: |
| 2045 |
case props::INT: |
| 2046 |
case props::LONG: |
| 2047 |
{ |
| 2048 |
long l = node->getLongValue(); |
| 2049 |
result = l != _last_int; |
| 2050 |
_last_int = l; |
| 2051 |
return result; |
| 2052 |
} |
| 2053 |
case props::FLOAT: |
| 2054 |
case props::DOUBLE: |
| 2055 |
{ |
| 2056 |
double d = node->getDoubleValue(); |
| 2057 |
result = d != _last_float; |
| 2058 |
_last_float = d; |
| 2059 |
return result; |
| 2060 |
} |
| 2061 |
default: |
| 2062 |
{ |
| 2063 |
string s = node->getStringValue(); |
| 2064 |
result = s != _last_string; |
| 2065 |
_last_string = s; |
| 2066 |
return result; |
| 2067 |
} |
| 2068 |
} |
| 2069 |
} |
| 2070 |
|
| 2071 |
// NasalXMLVisitor class: handles EasyXML visitor callback for parsexml() |
| 2072 |
// |
| 2073 |
NasalXMLVisitor::NasalXMLVisitor(naContext c, int argc, naRef* args) : |
| 2074 |
_c(naSubContext(c)), |
| 2075 |
_start_element(argc > 1 ? args[1] : naNil()), |
| 2076 |
_end_element(argc > 2 ? args[2] : naNil()), |
| 2077 |
_data(argc > 3 ? args[3] : naNil()), |
| 2078 |
_pi(argc > 4 ? args[4] : naNil()) |
| 2079 |
{ |
| 2080 |
} |
| 2081 |
|
| 2082 |
void NasalXMLVisitor::startElement(const char* tag, const XMLAttributes& a) |
| 2083 |
{ |
| 2084 |
if(naIsNil(_start_element)) return; |
| 2085 |
naRef attr = naNewHash(_c); |
| 2086 |
for(int i=0; i<a.size(); i++) { |
| 2087 |
naRef name = make_string(a.getName(i)); |
| 2088 |
naRef value = make_string(a.getValue(i)); |
| 2089 |
naHash_set(attr, name, value); |
| 2090 |
} |
| 2091 |
call(_start_element, 2, make_string(tag), attr); |
| 2092 |
} |
| 2093 |
|
| 2094 |
void NasalXMLVisitor::endElement(const char* tag) |
| 2095 |
{ |
| 2096 |
if(!naIsNil(_end_element)) call(_end_element, 1, make_string(tag)); |
| 2097 |
} |
| 2098 |
|
| 2099 |
void NasalXMLVisitor::data(const char* str, int len) |
| 2100 |
{ |
| 2101 |
if(!naIsNil(_data)) call(_data, 1, make_string(str, len)); |
| 2102 |
} |
| 2103 |
|
| 2104 |
void NasalXMLVisitor::pi(const char* target, const char* data) |
| 2105 |
{ |
| 2106 |
if(!naIsNil(_pi)) call(_pi, 2, make_string(target), make_string(data)); |
| 2107 |
} |
| 2108 |
|
| 2109 |
void NasalXMLVisitor::call(naRef func, int num, naRef a, naRef b) |
| 2110 |
{ |
| 2111 |
naRef args[2]; |
| 2112 |
args[0] = a; |
| 2113 |
args[1] = b; |
| 2114 |
naCall(_c, func, num, args, naNil(), naNil()); |
| 2115 |
if(naGetError(_c)) |
| 2116 |
naRethrowError(_c); |
| 2117 |
} |
| 2118 |
|
| 2119 |
naRef NasalXMLVisitor::make_string(const char* s, int n) |
| 2120 |
{ |
| 2121 |
return naStr_fromdata(naNewString(_c), const_cast<char *>(s), |
| 2122 |
n < 0 ? strlen(s) : n); |
| 2123 |
} |
| 2124 |
|
| 2125 |
// like naEqual, but checks vector/hash recursively |
| 2126 |
// note this will not tolerate a recursively defined Nasal structure |
| 2127 |
// (such as globals.) |
| 2128 |
int nasalStructEqual(naContext ctx, naRef a, naRef b) |
| 2129 |
{ |
| 2130 |
if (naIsVector(a) && naIsVector(b)) { |
| 2131 |
const int aSz = naVec_size(a), |
| 2132 |
bSz = naVec_size(b); |
| 2133 |
|
| 2134 |
if (aSz != bSz) |
| 2135 |
return 0; |
| 2136 |
|
| 2137 |
for (int i = 0; i < aSz; ++i) { |
| 2138 |
int eq = nasalStructEqual(ctx, naVec_get(a, i), naVec_get(b, i)); |
| 2139 |
if (!eq) |
| 2140 |
return 0; |
| 2141 |
} |
| 2142 |
|
| 2143 |
// all elements equal, we're done |
| 2144 |
return 1; |
| 2145 |
} |
| 2146 |
|
| 2147 |
if (naIsHash(a) && naIsHash(b)) { |
| 2148 |
naRef keysVec = naNewVector(ctx); |
| 2149 |
naHash_keys(keysVec, a); |
| 2150 |
const auto aSz = naVec_size(keysVec); |
| 2151 |
|
| 2152 |
// first check key count, that's fast |
| 2153 |
if (aSz != naHash_size(b)) |
| 2154 |
return 0; |
| 2155 |
|
| 2156 |
for (int i = 0; i < aSz; i++) { |
| 2157 |
naRef key = naVec_get(keysVec, i); |
| 2158 |
naRef aValue, bValue; |
| 2159 |
if (!naHash_get(a, key, &aValue) || !naHash_get(b, key, &bValue)) { |
| 2160 |
return 0; |
| 2161 |
} |
| 2162 |
|
| 2163 |
int eq = nasalStructEqual(ctx, aValue, bValue); |
| 2164 |
if (!eq) { |
| 2165 |
return 0; |
| 2166 |
} |
| 2167 |
} |
| 2168 |
|
| 2169 |
// all values matched, we're good |
| 2170 |
return 1; |
| 2171 |
} |
| 2172 |
|
| 2173 |
return naEqual(a, b); |
| 2174 |
} |
| 2175 |
|
| 2176 |
simgear::BufferedLogCallback* FGNasalSys::log() const |
| 2177 |
{ |
| 2178 |
return d->_log.get(); |
| 2179 |
} |
| 2180 |
|
| 2181 |
naRef FGNasalSys::nasalGlobals() const |
| 2182 |
{ |
| 2183 |
return d->_globals; |
| 2184 |
} |
| 2185 |
|
| 2186 |
nasal::Hash FGNasalSys::getGlobals() const |
| 2187 |
{ |
| 2188 |
return nasal::Hash(d->_globals, d->_context); |
| 2189 |
} |