Debian Codegraph @

src/Scripting/nasal-props.cxx

raw symbols SCIP
1 // SPDX-License-Identifier: GPL-2.0-or-later
2
3 #include "config.h"
4
5 #include <cstring>
6
7 #include <simgear/nasal/nasal.h>
8 #include <simgear/props/props.hxx>
9 #include <simgear/props/vectorPropTemplates.hxx>
10
11 #include <Main/globals.hxx>
12
13 #include "NasalSys.hxx"
14 #include "NasalSys_private.hxx"
15
16 using namespace std;
17
18 // Implementation of a Nasal wrapper for the SGPropertyNode class,
19 // using the Nasal "ghost" (er... Garbage collection Handle for
20 // OutSide Thingy) facility.
21 //
22 // Note that these functions appear in Nasal with prepended
23 // underscores. They work on the low-level "ghost" objects and aren't
24 // intended for use from user code, but from Nasal code you will find
25 // in props.nas. That is where the Nasal props.Node class is defined,
26 // which provides a saner interface along the lines of SGPropertyNode.
27
28 static void propNodeGhostDestroy(void* ghost)
29 {
30 SGPropertyNode* prop = static_cast<SGPropertyNode*>(ghost);
31 if (!SGPropertyNode::put(prop)) delete prop;
32 }
33
34 naGhostType PropNodeGhostType = { propNodeGhostDestroy, "prop", nullptr, nullptr };
35
36 naRef propNodeGhostCreate(naContext c, SGPropertyNode* ghost)
37 {
38 if(!ghost) return naNil();
39 SGPropertyNode::get(ghost);
40 return naNewGhost(c, &PropNodeGhostType, ghost);
41 }
42
43 naRef FGNasalSys::propNodeGhost(SGPropertyNode* handle)
44 {
45 return propNodeGhostCreate(d->_context, handle);
46 }
47
48 SGPropertyNode* ghostToPropNode(naRef ref)
49 {
50 if (!naIsGhost(ref) || (naGhost_type(ref) != &PropNodeGhostType))
51 return NULL;
52
53 return static_cast<SGPropertyNode*>(naGhost_ptr(ref));
54 }
55
56 #define NASTR(s) s ? naStr_fromdata(naNewString(c),(char*)(s),strlen(s)) : naNil()
57
58 //
59 // Standard header for the extension functions. It turns the "ghost"
60 // found in arg[0] into a SGPropertyNode_ptr, and then "unwraps" the
61 // vector found in the second argument into a normal-looking args
62 // array. This allows the Nasal handlers to do things like:
63 // Node.getChild = func { _getChild(me.ghost, arg) }
64 //
65 #define NODENOARG() \
66 if(argc < 2 || !naIsGhost(args[0]) || \
67 naGhost_type(args[0]) != &PropNodeGhostType) \
68 naRuntimeError(c, "bad argument to props function"); \
69 SGPropertyNode_ptr node = static_cast<SGPropertyNode*>(naGhost_ptr(args[0]));
70
71 #define NODEARG() \
72 NODENOARG(); \
73 naRef argv = args[1]
74
75 //
76 // Pops the first argument as a relative path if the first condition
77 // is true (e.g. argc > 1 for getAttribute) and if it is a string.
78 // If the second confition is true, then another is popped to specify
79 // if the node should be created (i.e. like the second argument to
80 // getNode())
81 //
82 // Note that this makes the function return nil if the node doesn't
83 // exist, so all functions with a relative_path parameter will
84 // return nil if the specified node does not exist.
85 //
86 #define MOVETARGET(cond1, create) \
87 if(cond1) { \
88 naRef name = naVec_get(argv, 0); \
89 if(naIsString(name)) { \
90 try { \
91 node = node->getNode(naStr_data(name), create); \
92 } catch(const string& err) { \
93 naRuntimeError(c, (char *)err.c_str()); \
94 return naNil(); \
95 } \
96 if(!node) return naNil(); \
97 naVec_removefirst(argv); /* pop only if we were successful */ \
98 } \
99 }
100
101
102 // Get the type of a property (returns a string).
103 // Forms:
104 // props.Node.getType(string relative_path);
105 // props.Node.getType();
106 static naRef f_getType(naContext c, naRef me, int argc, naRef* args)
107 {
108 using namespace simgear;
109 NODEARG();
110 MOVETARGET(naVec_size(argv) > 0, false);
111 const char* t = "unknown";
112 switch(node->getType()) {
113 case props::NONE: t = "NONE"; break;
114 case props::ALIAS: t = "ALIAS"; break;
115 case props::BOOL: t = "BOOL"; break;
116 case props::INT: t = "INT"; break;
117 case props::LONG: t = "LONG"; break;
118 case props::FLOAT: t = "FLOAT"; break;
119 case props::DOUBLE: t = "DOUBLE"; break;
120 case props::STRING: t = "STRING"; break;
121 case props::UNSPECIFIED: t = "UNSPECIFIED"; break;
122 case props::VEC3D: t = "VEC3D"; break;
123 case props::VEC4D: t = "VEC4D"; break;
124 case props::EXTENDED: t = "EXTENDED"; break; // shouldn't happen
125 }
126 return NASTR(t);
127 }
128
129 // Check if type of a property is numeric (returns 0 or 1).
130 // Forms:
131 // props.Node.isNumeric(string relative_path);
132 // props.Node.isNumeric();
133 static naRef f_isNumeric(naContext c, naRef me, int argc, naRef* args)
134 {
135 using namespace simgear;
136 NODEARG();
137 MOVETARGET(naVec_size(argv) > 0, false);
138 switch(node->getType()) {
139 case props::INT:
140 case props::LONG:
141 case props::FLOAT:
142 case props::DOUBLE: return naNum(true);
143 default:
144 break;
145 }
146 return naNum(false);
147 }
148
149 // Check if type of a property is integer (returns 0 or 1).
150 // Forms:
151 // props.Node.isInt(string relative_path);
152 // props.Node.isInt();
153 static naRef f_isInt(naContext c, naRef me, int argc, naRef* args)
154 {
155 using namespace simgear;
156 NODEARG();
157 MOVETARGET(naVec_size(argv) > 0, false);
158 if ((node->getType() == props::INT) || (node->getType() == props::LONG)) {
159 return naNum(true);
160 }
161 return naNum(false);
162 }
163
164
165 // Get an attribute of a property by name (returns true/false).
166 // Forms:
167 // props.Node.getType(string relative_path,
168 // string attribute_name);
169 // props.Node.getType(string attribute_name);
170 static naRef f_getAttribute(naContext c, naRef me, int argc, naRef* args)
171 {
172 NODEARG();
173 if(naVec_size(argv) == 0) return naNum(unsigned(node->getAttributes()));
174 MOVETARGET(naVec_size(argv) > 1, false);
175 naRef val = naVec_get(argv, 0);
176 const char *a = naStr_data(val);
177 SGPropertyNode::Attribute attr;
178 if(!a) a = "";
179 if(!strcmp(a, "last")) return naNum(SGPropertyNode::LAST_USED_ATTRIBUTE);
180 else if(!strcmp(a, "children")) return naNum(node->nChildren());
181 else if(!strcmp(a, "listeners")) return naNum(node->nListeners());
182 // Number of references without instance used in this function
183 else if(!strcmp(a, "references")) return naNum(node.getNumRefs() - 1);
184 else if(!strcmp(a, "tied")) return naNum(node->isTied());
185 else if(!strcmp(a, "alias")) return naNum(node->isAlias());
186 else if(!strcmp(a, "readable")) attr = SGPropertyNode::READ;
187 else if(!strcmp(a, "writable")) attr = SGPropertyNode::WRITE;
188 else if(!strcmp(a, "archive")) attr = SGPropertyNode::ARCHIVE;
189 else if(!strcmp(a, "trace-read")) attr = SGPropertyNode::TRACE_READ;
190 else if(!strcmp(a, "trace-write")) attr = SGPropertyNode::TRACE_WRITE;
191 else if(!strcmp(a, "userarchive")) attr = SGPropertyNode::USERARCHIVE;
192 else if(!strcmp(a, "preserve")) attr = SGPropertyNode::PRESERVE;
193 else if(!strcmp(a, "protected")) attr = SGPropertyNode::PROTECTED;
194 else if(!strcmp(a, "listener-safe")) attr = SGPropertyNode::LISTENER_SAFE;
195 else if(!strcmp(a, "value-changed-up")) attr = SGPropertyNode::VALUE_CHANGED_UP;
196 else if(!strcmp(a, "value-changed-down")) attr = SGPropertyNode::VALUE_CHANGED_DOWN;
197
198 else {
199 naRuntimeError(c, "props.getAttribute() with invalid attribute");
200 return naNil();
201 }
202 return naNum(node->getAttribute(attr));
203 }
204
205
206 // Set an attribute by name and boolean value or raw (bitmasked) number.
207 // Forms:
208 // props.Node.setAttribute(string relative_path,
209 // string attribute_name,
210 // bool value);
211 // props.Node.setAttribute(string attribute_name,
212 // bool value);
213 // props.Node.setArtribute(int attributes);
214 static naRef f_setAttribute(naContext c, naRef me, int argc, naRef* args)
215 {
216 NODEARG();
217 if (node->getAttribute(SGPropertyNode::PROTECTED)) {
218 naRuntimeError(c, "props.setAttribute() called on protected property %s",
219 node->getPath().c_str());
220 return naNil();
221 }
222
223 MOVETARGET(naVec_size(argv) > 2, false);
224 naRef val = naVec_get(argv, 0);
225 if(naVec_size(argv) == 1 && naIsNum(val)) {
226 naRef ret = naNum(node->getAttributes());
227 // prevent Nasal modifying PROTECTED
228 int attrs = static_cast<int>(val.num) & (~SGPropertyNode::PROTECTED);
229 node->setAttributes(attrs);
230 return ret;
231 }
232 SGPropertyNode::Attribute attr;
233 const char *a = naStr_data(val);
234 if(!a) a = "";
235 if(!strcmp(a, "readable")) attr = SGPropertyNode::READ;
236 else if(!strcmp(a, "writable")) attr = SGPropertyNode::WRITE;
237 else if(!strcmp(a, "archive")) attr = SGPropertyNode::ARCHIVE;
238 else if(!strcmp(a, "trace-read")) attr = SGPropertyNode::TRACE_READ;
239 else if(!strcmp(a, "trace-write")) attr = SGPropertyNode::TRACE_WRITE;
240 else if(!strcmp(a, "userarchive")) attr = SGPropertyNode::USERARCHIVE;
241 else if(!strcmp(a, "preserve")) attr = SGPropertyNode::PRESERVE;
242 // explicitly don't allow "protected" to be modified here
243 else {
244 naRuntimeError(c, "props.setAttribute() with invalid attribute");
245 return naNil();
246 }
247 naRef ret = naNum(node->getAttribute(attr));
248 node->setAttribute(attr, naTrue(naVec_get(argv, 1)) ? true : false);
249 return ret;
250 }
251
252
253 // Get the simple name of this node.
254 // Forms:
255 // props.Node.getName();
256 static naRef f_getName(naContext c, naRef me, int argc, naRef* args)
257 {
258 NODENOARG();
259 return NASTR(node->getNameString().c_str());
260 }
261
262
263 // Get the index of this node.
264 // Forms:
265 // props.Node.getIndex();
266 static naRef f_getIndex(naContext c, naRef me, int argc, naRef* args)
267 {
268 NODENOARG();
269 return naNum(node->getIndex());
270 }
271
272 // Check if other_node refers to the same as this node.
273 // Forms:
274 // props.Node.equals(other_node);
275 static naRef f_equals(naContext c, naRef me, int argc, naRef* args)
276 {
277 NODEARG();
278
279 naRef rhs = naVec_get(argv, 0);
280 if( !naIsGhost(rhs) || naGhost_type(rhs) != &PropNodeGhostType )
281 return naNum(false);
282
283 SGPropertyNode* node_rhs = static_cast<SGPropertyNode*>(naGhost_ptr(rhs));
284 return naNum(node.ptr() == node_rhs);
285 }
286
287 template<typename T>
288 naRef makeVectorFromVec(naContext c, const T& vec)
289 {
290 const int num_components
291 = sizeof(vec.data()) / sizeof(typename T::value_type);
292 naRef vector = naNewVector(c);
293 naVec_setsize(c, vector, num_components);
294 for (int i = 0; i < num_components; ++i)
295 naVec_set(vector, i, naNum(vec[i]));
296 return vector;
297 }
298
299
300 // Get the value of a node, with or without a relative path.
301 // Forms:
302 // props.Node.getValue(string relative_path);
303 // props.Node.getValue();
304 static naRef f_getValue(naContext c, naRef me, int argc, naRef* args)
305 {
306 using namespace simgear;
307 NODEARG();
308 MOVETARGET(naVec_size(argv) > 0, false);
309 return FGNasalSys::getPropertyValue(c, node);
310 }
311
312 template<typename T>
313 T makeVecFromVector(naRef vector)
314 {
315 T vec;
316 const int num_components
317 = sizeof(vec.data()) / sizeof(typename T::value_type);
318 int size = naVec_size(vector);
319
320 for (int i = 0; i < num_components && i < size; ++i) {
321 naRef element = naVec_get(vector, i);
322 naRef n = naNumValue(element);
323 if (!naIsNil(n))
324 vec[i] = n.num;
325 }
326 return vec;
327 }
328
329 static std::string s_val_description(naRef val)
330 {
331 std::ostringstream message;
332 if (naIsNil(val)) message << "nil";
333 else if (naIsNum(val)) message << "num:" << naNumValue(val).num;
334 else if (naIsString(val)) message << "string:" << naStr_data(val);
335 else if (naIsScalar(val)) message << "scalar";
336 else if (naIsVector(val)) message << "vector";
337 else if (naIsHash(val)) message << "hash";
338 else if (naIsFunc(val)) message << "func";
339 else if (naIsCode(val)) message << "code";
340 else if (naIsCCode(val)) message << "ccode";
341 else if (naIsGhost(val)) message << "ghost";
342 else message << "?";
343 return message.str();
344 }
345
346 // Helper function to set the value of a node; returns true if it succeeded or
347 // false if it failed. <val> can be a string, number, or a
348 // vector or numbers (for SGVec3D/4D types).
349 static naRef f_setValueHelper(naContext c, SGPropertyNode_ptr node, naRef val) {
350 bool result = false;
351 if(naIsString(val)) {
352 result = node->setStringValue(naStr_data(val));
353 } else if(naIsVector(val)) {
354 if(naVec_size(val) == 3)
355 result = node->setValue(makeVecFromVector<SGVec3d>(val));
356 else if(naVec_size(val) == 4)
357 result = node->setValue(makeVecFromVector<SGVec4d>(val));
358 else
359 naRuntimeError(c, "props.setValue() vector value has wrong size");
360 } else if(naIsNum(val)) {
361 double d = naNumValue(val).num;
362 if (SGMisc<double>::isNaN(d)) {
363 naRuntimeError(c, "props.setValue() passed a NaN");
364 }
365
366 result = node->setDoubleValue(d);
367 } else {
368 naRuntimeError(c, "props.setValue() called with unsupported value %s", s_val_description(val).c_str());
369 }
370 return naNum(result);
371 }
372
373
374 // Set the value of a node; returns true if it succeeded or
375 // false if it failed. <val> can be a string, number, or a
376 // vector or numbers (for SGVec3D/4D types).
377 // Forms:
378 // props.Node.setValue(string relative_path,
379 // val);
380 // props.Node.setValue(val);
381 static naRef f_setValue(naContext c, naRef me, int argc, naRef* args)
382 {
383 NODEARG();
384 MOVETARGET(naVec_size(argv) > 1, true);
385 naRef val = naVec_get(argv, 0);
386 return f_setValueHelper(c, node, val);
387 }
388
389 static naRef f_setIntValue(naContext c, naRef me, int argc, naRef* args)
390 {
391 NODEARG();
392 MOVETARGET(naVec_size(argv) > 1, true);
393 // Original code:
394 // int iv = (int)naNumValue(naVec_get(argv, 0)).num;
395
396 // Junk to pacify the gcc-2.95.3 optimizer:
397 naRef tmp0 = naVec_get(argv, 0);
398 naRef tmp1 = naNumValue(tmp0);
399 if(naIsNil(tmp1))
400 naRuntimeError(c, "props.setIntValue() with non-number");
401 double tmp2 = tmp1.num;
402 int iv = (int)tmp2;
403
404 return naNum(node->setIntValue(iv));
405 }
406
407 static naRef f_setBoolValue(naContext c, naRef me, int argc, naRef* args)
408 {
409 NODEARG();
410 MOVETARGET(naVec_size(argv) > 1, true);
411 naRef val = naVec_get(argv, 0);
412 return naNum(node->setBoolValue(naTrue(val) ? true : false));
413 }
414
415 static naRef f_toggleBoolValue(naContext c, naRef me, int argc, naRef* args)
416 {
417 using namespace simgear;
418
419 NODEARG();
420 MOVETARGET(naVec_size(argv) > 0, false);
421 if (node->getType() != props::BOOL) {
422 naRuntimeError(c, "props.toggleBoolValue() on non-bool prop");
423 }
424
425 const auto val = node->getBoolValue();
426 return naNum(node->setBoolValue(val ? false : true));
427 }
428
429 static naRef f_setDoubleValue(naContext c, naRef me, int argc, naRef* args)
430 {
431 NODEARG();
432 MOVETARGET(naVec_size(argv) > 1, true);
433 naRef r = naNumValue(naVec_get(argv, 0));
434 if (naIsNil(r))
435 naRuntimeError(c, "props.setDoubleValue() with non-number");
436
437 if (SGMisc<double>::isNaN(r.num)) {
438 naRuntimeError(c, "props.setDoubleValue() passed a NaN");
439 }
440
441 return naNum(node->setDoubleValue(r.num));
442 }
443
444 static naRef f_adjustValue(naContext c, naRef me, int argc, naRef* args)
445 {
446 using namespace simgear;
447
448 NODEARG();
449 MOVETARGET(naVec_size(argv) > 1, false);
450 naRef r = naNumValue(naVec_get(argv, 0));
451 if (naIsNil(r))
452 naRuntimeError(c, "props.adjustValue() with non-number");
453
454 if (SGMisc<double>::isNaN(r.num)) {
455 naRuntimeError(c, "props.adjustValue() passed a NaN");
456 }
457
458 switch(node->getType()) {
459 case props::BOOL:
460 case props::INT:
461 case props::LONG:
462 case props::FLOAT:
463 case props::DOUBLE:
464 // fall through
465 break;
466
467 default:
468 naRuntimeError(c, "props.adjustValue() called on non-numeric type");
469 return naNil();
470 }
471
472 const auto dv = node->getDoubleValue();
473 return naNum(node->setDoubleValue(dv + r.num));
474 }
475
476 // Forward declaration
477 static naRef f_setChildrenHelper(naContext c, SGPropertyNode_ptr node, char* name, naRef val);
478
479 static naRef f_setValuesHelper(naContext c, SGPropertyNode_ptr node, naRef hash)
480 {
481 if (!naIsHash(hash)) {
482 naRuntimeError(c, "props.setValues() with non-hash");
483 }
484
485 naRef keyvec = naNewVector(c);
486 naHash_keys(keyvec, hash);
487 naRef ret;
488
489 for (int i = 0; i < naVec_size(keyvec); i++) {
490 naRef key = naVec_get(keyvec, i);
491 if (! naIsScalar(key)) {
492 naRuntimeError(c, "props.setValues() with non-scalar key value");
493 }
494 char* keystr = naStr_data(naStringValue(c, key));
495 ret = f_setChildrenHelper(c, node, keystr, naHash_cget(hash, keystr));
496 }
497
498 return ret;
499 }
500
501 static naRef f_setValues(naContext c, naRef me, int argc, naRef* args)
502 {
503 NODEARG();
504 MOVETARGET(naVec_size(argv) > 1, true);
505 naRef val = naVec_get(argv, 0);
506 return f_setValuesHelper(c, node, val);
507 }
508
509 static naRef f_setChildrenHelper(naContext c, SGPropertyNode_ptr node, char* name, naRef val)
510 {
511 naRef ret;
512 try {
513 SGPropertyNode_ptr subnode = node->getNode(name, true);
514
515 if (naIsScalar(val)) {
516 ret = f_setValueHelper(c, subnode, val);
517 } else if (naIsHash(val)) {
518 ret = f_setValuesHelper(c, subnode, val);
519 } else if (naIsVector(val)) {
520 char nameBuf[1024];
521 for (int i = 0; i < naVec_size(val); i++) {
522 const auto len = ::snprintf(nameBuf, sizeof(nameBuf), "%s[%i]", name, i);
523 if ((len < 0) || (len >= (int) sizeof(nameBuf))) {
524 naRuntimeError(c, "Failed to create buffer for property name in setChildren");
525 }
526 ret = f_setChildrenHelper(c, node, nameBuf, naVec_get(val, i));
527 }
528 } else if (naIsNil(val)) {
529 // Nil value OK - no-op
530 } else {
531 // We have an error, but throwing a runtime error will prevent certain things from
532 // working (such as the pilot list)
533 // The nasal version would fail silently with invalid data - a runtime error will dump the stack and
534 // stop execution.
535 // Overall to be safer the new method should be functionally equivalent to keep compatibility.
536 //
537 //REMOVED: naRuntimeError(c, "props.setChildren() with unknown type");
538 }
539 } catch(const string& err) {
540 naRuntimeError(c, (char *)err.c_str());
541 return naNil();
542 }
543
544 return ret;
545 }
546
547 static naRef f_setChildren(naContext c, naRef me, int argc, naRef* args)
548 {
549 NODEARG();
550 if(! naIsString(naVec_get(argv, 0))) {
551 naRuntimeError(c, "props.setChildren() with non-string first argument");
552 }
553
554 char* name = naStr_data(naVec_get(argv, 0));
555 naRef val = naVec_get(argv, 1);
556 return f_setChildrenHelper(c, node, name, val);
557 }
558
559 // Get the parent of this node as a ghost.
560 // Forms:
561 // props.Node.getParent();
562 static naRef f_getParent(naContext c, naRef me, int argc, naRef* args)
563 {
564 NODENOARG();
565 SGPropertyNode* n = node->getParent();
566 if(!n) return naNil();
567 return propNodeGhostCreate(c, n);
568 }
569
570
571 // Get a child by name and optional index=0, creating if specified (by default it
572 // does not create it). If the node does not exist and create is false, then it
573 // returns nil, else it returns a (possibly new) property ghost.
574 // Forms:
575 // props.Node.getChild(string relative_path,
576 // int index=0,
577 // bool create=false);
578 static naRef f_getChild(naContext c, naRef me, int argc, naRef* args)
579 {
580 NODEARG();
581 naRef child = naVec_get(argv, 0);
582 if(!naIsString(child)) return naNil();
583 naRef idx = naNumValue(naVec_get(argv, 1));
584 bool create = naTrue(naVec_get(argv, 2)) != 0;
585 SGPropertyNode* n;
586 try {
587 if(naIsNil(idx)) {
588 n = node->getChild(naStr_data(child), create);
589 } else {
590 n = node->getChild(naStr_data(child), (int)idx.num, create);
591 }
592 } catch (const string& err) {
593 naRuntimeError(c, (char *)err.c_str());
594 return naNil();
595 }
596 if(!n) return naNil();
597 return propNodeGhostCreate(c, n);
598 }
599
600
601 // Get all children with a specified name as a vector of ghosts.
602 // Forms:
603 // props.Node.getChildren(string relative_path);
604 // props.Node.getChildren(); #get all children
605 static naRef f_getChildren(naContext c, naRef me, int argc, naRef* args)
606 {
607 NODEARG();
608 naRef result = naNewVector(c);
609 if(naIsNil(argv) || naVec_size(argv) == 0) {
610 // Get all children
611 for(int i=0; i<node->nChildren(); i++)
612 naVec_append(result, propNodeGhostCreate(c, node->getChild(i)));
613 } else {
614 // Get all children of a specified name
615 naRef name = naVec_get(argv, 0);
616 if(!naIsString(name)) return naNil();
617 try {
618 vector<SGPropertyNode_ptr> children
619 = node->getChildren(naStr_data(name));
620 for(unsigned int i=0; i<children.size(); i++)
621 naVec_append(result, propNodeGhostCreate(c, children[i]));
622 } catch (const string& err) {
623 naRuntimeError(c, (char *)err.c_str());
624 return naNil();
625 }
626 }
627 return result;
628 }
629
630
631 // Append a named child at the first unused index...
632 // Forms:
633 // props.Node.addChild(string name,
634 // int min_index=0,
635 // bool append=true);
636 static naRef f_addChild(naContext c, naRef me, int argc, naRef* args)
637 {
638 NODEARG();
639 naRef child = naVec_get(argv, 0);
640 if(!naIsString(child)) return naNil();
641 naRef ref_min_index = naNumValue(naVec_get(argv, 1));
642 naRef ref_append = naVec_get(argv, 2);
643 SGPropertyNode* n;
644 try
645 {
646 int min_index = 0;
647 if(!naIsNil(ref_min_index))
648 min_index = ref_min_index.num;
649
650 bool append = true;
651 if(!naIsNil(ref_append))
652 append = naTrue(ref_append) != 0;
653
654 n = node->addChild(naStr_data(child), min_index, append);
655 }
656 catch (const string& err)
657 {
658 naRuntimeError(c, (char *)err.c_str());
659 return naNil();
660 }
661
662 return propNodeGhostCreate(c, n);
663 }
664
665 static naRef f_addChildren(naContext c, naRef me, int argc, naRef* args)
666 {
667 NODEARG();
668 naRef child = naVec_get(argv, 0);
669 if(!naIsString(child)) return naNil();
670 naRef ref_count = naNumValue(naVec_get(argv, 1));
671 naRef ref_min_index = naNumValue(naVec_get(argv, 2));
672 naRef ref_append = naVec_get(argv, 3);
673 try
674 {
675 size_t count = 0;
676 if( !naIsNum(ref_count) )
677 throw string("props.addChildren() missing number of children");
678 count = ref_count.num;
679
680 int min_index = 0;
681 if(!naIsNil(ref_min_index))
682 min_index = ref_min_index.num;
683
684 bool append = true;
685 if(!naIsNil(ref_append))
686 append = naTrue(ref_append) != 0;
687
688 const simgear::PropertyList& nodes =
689 node->addChildren(naStr_data(child), count, min_index, append);
690
691 naRef result = naNewVector(c);
692 for( size_t i = 0; i < nodes.size(); ++i )
693 naVec_append(result, propNodeGhostCreate(c, nodes[i]));
694 return result;
695 }
696 catch (const string& err)
697 {
698 naRuntimeError(c, (char *)err.c_str());
699 }
700
701 return naNil();
702 }
703
704
705 // Remove a child by name and index. Returns it as a ghost.
706 // Forms:
707 // props.Node.removeChild(string relative_path,
708 // int index);
709 static naRef f_removeChild(naContext c, naRef me, int argc, naRef* args)
710 {
711 NODEARG();
712 naRef child = naVec_get(argv, 0);
713 naRef index = naVec_get(argv, 1);
714 if(!naIsString(child) || !naIsNum(index)) return naNil();
715 SGPropertyNode_ptr n;
716 try {
717 n = node->getChild(naStr_data(child), (int)index.num);
718 if (n && n->getAttribute(SGPropertyNode::PROTECTED)) {
719 naRuntimeError(c, "props.Node.removeChild() called on protected child %s of %s",
720 naStr_data(child), node->getPath().c_str());
721 return naNil();
722 }
723 n = node->removeChild(naStr_data(child), (int)index.num);
724 } catch (const string& err) {
725 naRuntimeError(c, (char *)err.c_str());
726 }
727 return propNodeGhostCreate(c, n);
728 }
729
730
731 // Remove all children with specified name. Returns a vector of all the nodes
732 // removed as ghosts.
733 // Forms:
734 // props.Node.removeChildren(string relative_path);
735 // props.Node.removeChildren(); #remove all children
736 static naRef f_removeChildren(naContext c, naRef me, int argc, naRef* args)
737 {
738 NODEARG();
739 naRef result = naNewVector(c);
740 if(naIsNil(argv) || naVec_size(argv) == 0) {
741 // Remove all children
742 for(int i = node->nChildren() - 1; i >=0; i--) {
743 SGPropertyNode_ptr n = node->getChild(i);
744 if (n->getAttribute(SGPropertyNode::PROTECTED)) {
745 SG_LOG(SG_NASAL, SG_ALERT, "props.Node.removeChildren: node " <<
746 n->getPath() << " is protected");
747 continue;
748 }
749
750 node->removeChild(i);
751 naVec_append(result, propNodeGhostCreate(c, n));
752 }
753 } else {
754 // Remove all children of a specified name
755 naRef name = naVec_get(argv, 0);
756 if(!naIsString(name)) return naNil();
757 try {
758 auto children = node->getChildren(naStr_data(name));
759 for (auto cn : children) {
760 if (cn->getAttribute(SGPropertyNode::PROTECTED)) {
761 SG_LOG(SG_NASAL, SG_ALERT, "props.Node.removeChildren: node " <<
762 cn->getPath() << " is protected");
763 continue;
764 }
765 node->removeChild(cn);
766 naVec_append(result, propNodeGhostCreate(c, cn));
767 }
768 } catch (const string& err) {
769 naRuntimeError(c, (char *)err.c_str());
770 return naNil();
771 }
772 }
773 return result;
774 }
775
776 // Remove all children of a property node.
777 // Forms:
778 // props.Node.removeAllChildren();
779 static naRef f_removeAllChildren(naContext c, naRef me, int argc, naRef* args)
780 {
781 NODENOARG();
782 node->removeAllChildren();
783 return propNodeGhostCreate(c, node);
784 }
785
786 // Alias this property to another one; returns 1 on success or 0 on failure
787 // (only applicable to tied properties).
788 // Forms:
789 // props.Node.alias(string global_path);
790 // props.Node.alias(prop_ghost node);
791 // props.Node.alias(props.Node node); #added by props.nas
792 static naRef f_alias(naContext c, naRef me, int argc, naRef* args)
793 {
794 NODEARG();
795 if (node->getAttribute(SGPropertyNode::PROTECTED)) {
796 naRuntimeError(c, "props.Node.alias() called on protected property %s",
797 node->getPath().c_str());
798 return naNil();
799 }
800 SGPropertyNode* al;
801 naRef prop = naVec_get(argv, 0);
802 try {
803 if(naIsString(prop)) al = globals->get_props()->getNode(naStr_data(prop), true);
804 else if(naIsGhost(prop)) al = static_cast<SGPropertyNode*>(naGhost_ptr(prop));
805 else
806 throw sg_exception("props.alias() with bad argument");
807 } catch (sg_exception& err) {
808 naRuntimeError(c, err.what());
809 return naNil();
810 }
811
812 bool withListeners = false;
813 if (naVec_size(argv) > 1) {
814 withListeners = static_cast<int>(naVec_get(argv, 1).num) != 0;
815 }
816 return naNum(node->alias(al, withListeners));
817 }
818
819
820 // Un-alias this property. Returns 1 on success or 0 on failure (only
821 // applicable to tied properties).
822 // Forms:
823 // props.Node.unalias();
824 static naRef f_unalias(naContext c, naRef me, int argc, naRef* args)
825 {
826 NODENOARG();
827 return naNum(node->unalias());
828 }
829
830
831 // Get the alias of this node as a ghost.
832 // Forms:
833 // props.Node.getAliasTarget();
834 static naRef f_getAliasTarget(naContext c, naRef me, int argc, naRef* args)
835 {
836 NODENOARG();
837 return propNodeGhostCreate(c, node->getAliasTarget());
838 }
839
840
841 // Get a relative node. Returns nil if it does not exist and create is false,
842 // or a ghost object otherwise (wrapped into a props.Node object by props.nas).
843 // Forms:
844 // props.Node.getNode(string relative_path,
845 // bool create=false);
846 static naRef f_getNode(naContext c, naRef me, int argc, naRef* args)
847 {
848 NODEARG();
849 naRef path = naVec_get(argv, 0);
850 bool create = naTrue(naVec_get(argv, 1)) != 0;
851 if(!naIsString(path)) return naNil();
852 SGPropertyNode* n;
853 try {
854 n = node->getNode(naStr_data(path), create);
855 } catch (const string& err) {
856 naRuntimeError(c, (char *)err.c_str());
857 return naNil();
858 }
859 return propNodeGhostCreate(c, n);
860 }
861
862
863 // Create a new property node.
864 // Forms:
865 // props.Node.new();
866 static naRef f_new(naContext c, naRef me, int argc, naRef* args)
867 {
868 return propNodeGhostCreate(c, new SGPropertyNode());
869 }
870
871
872 // Get the global root node (cached by props.nas so that it does
873 // not require a function call).
874 // Forms:
875 // props._globals()
876 // props.globals
877 static naRef f_globals(naContext c, naRef me, int argc, naRef* args)
878 {
879 return propNodeGhostCreate(c, globals->get_props());
880 }
881
882 static struct {
883 naCFunction func;
884 const char* name;
885 } propfuncs[] = {
886 { f_getType, "_getType" },
887 { f_getAttribute, "_getAttribute" },
888 { f_setAttribute, "_setAttribute" },
889 { f_getName, "_getName" },
890 { f_getIndex, "_getIndex" },
891 { f_equals, "_equals" },
892 { f_getValue, "_getValue" },
893 { f_setValue, "_setValue" },
894 { f_setValues, "_setValues" },
895 { f_setIntValue, "_setIntValue" },
896 { f_setBoolValue, "_setBoolValue" },
897 { f_toggleBoolValue, "_toggleBoolValue" },
898 { f_setDoubleValue, "_setDoubleValue" },
899 { f_getParent, "_getParent" },
900 { f_getChild, "_getChild" },
901 { f_getChildren, "_getChildren" },
902 { f_addChild, "_addChild" },
903 { f_addChildren, "_addChildren" },
904 { f_removeChild, "_removeChild" },
905 { f_removeChildren, "_removeChildren" },
906 { f_removeAllChildren, "_removeAllChildren" },
907 { f_setChildren, "_setChildren" },
908 { f_alias, "_alias" },
909 { f_unalias, "_unalias" },
910 { f_getAliasTarget, "_getAliasTarget" },
911 { f_getNode, "_getNode" },
912 { f_new, "_new" },
913 { f_globals, "_globals" },
914 { f_isNumeric, "_isNumeric" },
915 { f_isInt, "_isInt" },
916 { f_adjustValue, "_adjustValue" },
917 { 0, 0 }
918 };
919
920 naRef FGNasalSys::genPropsModule()
921 {
922 naRef namespc = naNewHash(d->_context);
923 for(int i=0; propfuncs[i].name; i++)
924 hashset(namespc, propfuncs[i].name,
925 naNewFunc(d->_context, naNewCCode(d->_context, propfuncs[i].func)));
926 return namespc;
927 }
928
929 naRef FGNasalSys::getPropertyValue(naContext c, SGPropertyNode* node)
930 {
931 using namespace simgear;
932 if (!node)
933 return naNil();
934
935 switch(node->getType()) {
936 case props::BOOL: case props::INT:
937 case props::LONG: case props::FLOAT:
938 case props::DOUBLE:
939 {
940 double dv = node->getDoubleValue();
941 if (SGMisc<double>::isNaN(dv)) {
942 SG_LOG(SG_NASAL, SG_ALERT, "Nasal getValue: property " << node->getPath() << " is NaN");
943 return naNil();
944 }
945
946 return naNum(dv);
947 }
948
949 case props::STRING:
950 case props::UNSPECIFIED:
951 return NASTR(node->getStringValue().c_str());
952 case props::VEC3D:
953 return makeVectorFromVec(c, node->getValue<SGVec3d>());
954 case props::VEC4D:
955 return makeVectorFromVec(c, node->getValue<SGVec4d>());
956 default:
957 return naNil();
958 }
959 }