Debian Codegraph @

Nasal/props.nas

raw
1 ##
2 # Node class definition. The class methods simply wrap the
3 # low level extension functions which work on a "ghost" handle to a
4 # SGPropertyNode object stored in the _g field.
5 #
6 # Not all of the features of SGPropertyNode are supported. There is
7 # no support for ties, obviously, as that wouldn't make much sense
8 # from a Nasal context. The various get/set methods work only on the
9 # local node, there is no equivalent of the "relative path" variants
10 # available in C++; just use node.getNode(path).whatever() instead.
11 #
12 var Node = {
13 getNode : func wrap(_getNode(me._g, arg)),
14 getParent : func wrap(_getParent(me._g, arg)),
15 getChild : func wrap(_getChild(me._g, arg)),
16 getChildren : func wrap(_getChildren(me._g, arg)),
17 setChildren : func wrap(_setChildren(me._g, arg)),
18 addChild : func wrap(_addChild(me._g, arg)),
19 addChildren : func wrap(_addChildren(me._g, arg)),
20 removeChild : func wrap(_removeChild(me._g, arg)),
21 removeChildren : func wrap(_removeChildren(me._g, arg)),
22 removeAllChildren: func wrap(_removeAllChildren(me._g, arg)),
23 getAliasTarget : func wrap(_getAliasTarget(me._g, arg)),
24
25 getName : func _getName(me._g, arg),
26 getIndex : func _getIndex(me._g, arg),
27 getType : func _getType(me._g, arg),
28 isNumeric : func _isNumeric(me._g, arg),
29 isInt : func _isInt(me._g, arg),
30 getAttribute : func _getAttribute(me._g, arg),
31 setAttribute : func _setAttribute(me._g, arg),
32 getValue : func _getValue(me._g, arg),
33 setValue : func _setValue(me._g, arg),
34 setValues : func _setValues(me._g, arg),
35 setIntValue : func _setIntValue(me._g, arg),
36 setBoolValue : func _setBoolValue(me._g, arg),
37 toggleBoolValue: func _toggleBoolValue(me._g, arg),
38 setDoubleValue : func _setDoubleValue(me._g, arg),
39 # adjustValue works like setDoubleValue but adds the argument to the
40 # current value of the node
41 adjustValue : func _adjustValue(me._g, arg),
42 unalias : func _unalias(me._g, arg),
43 alias : func(n, chainListener = 0) _alias(me._g, [isa(n, Node) ? n._g : n], chainListener),
44 equals : func(n) _equals(me._g, [isa(n, Node) ? n._g : n]),
45 clearValue : func _alias(me._g, [_globals()]) and me.unalias(),
46
47 getPath : func {
48 var (name, index, parent) = (me.getName(), me.getIndex(), me.getParent());
49 if(index != 0) { name ~= "[" ~ index ~ "]"; }
50 if(parent != nil) { name = parent.getPath() ~ "/" ~ name; }
51 return name;
52 },
53
54 getBoolValue : func {
55 var val = me.getValue();
56 var mytype = me.getType();
57 if((mytype == "STRING" or mytype == "UNSPECIFIED") and val == "false") return 0;
58 return !!val;
59 },
60
61 getIntValue : func (defaultValue = 0) {
62 var v = me.getValue();
63 if (!v) {
64 return defaultValue;
65 }
66
67 return math.round(v);
68 },
69
70 getDoubleValue : func (defaultValue = 0.0) {
71 var v = me.getValue();
72 if (!v) {
73 return defaultValue;
74 }
75
76 return num(v);
77 },
78
79 remove : func {
80 if((var p = me.getParent()) == nil) return nil;
81 p.removeChild(me.getName(), me.getIndex());
82 },
83
84 # follow alias links to "real" node (e.g. where the data is stored)
85 # optional argument: property node or prop path to resolve
86 # if no argument is given, operate on current obj ("me")
87 resolveAlias : func(p = nil) {
88 if (p == nil)
89 p = me;
90 elsif (isscalar(p))
91 p = globals.getNode(p);
92 if (isa(p, Node)) {
93 while (p.getAttribute("alias")) {
94 p = p.getAliasTarget();
95 }
96 }
97 return p;
98 },
99
100 # add to numeric property
101 # n: value to add
102 # optional:
103 # max: if not nil, clamp value to max
104 # range: if not nil, if exceeding max, wrap around
105 # example: headingProp.add(1, 360, 360)
106 add: func(n, max = nil, range = nil) {
107 if (me.isNumeric()) {
108 var v = me.getValue() + num(n);
109 if (max != nil and v > max) {
110 if (num(range) and range > 0) {
111 while (v > max) {
112 v -= range;
113 }
114 }
115 else v = max;
116 }
117 me.setValue(v);
118 # readback from prop as integer props removes decimals
119 return me.getValue();
120 }
121 else {
122 logprint(DEV_ALERT, "props.add() can be used only on numeric props "~
123 me.getPath()~" "~me.getType());
124 return nil;
125 }
126 },
127
128 # subtract from numeric property
129 # n: value to subtract
130 # optional:
131 # min: if not nil, clamp value to min
132 # range: if not nil, if reducing below min, wrap around
133 # example: headingProp.sub(1, 0, 360)
134 sub: func(n, min = nil, range = nil) {
135 if (me.isNumeric()) {
136 var v = me.getValue() - num(n);
137 if (min != nil and v < min) {
138 if (num(range) and range > 0) {
139 while (v < min) {
140 v += range;
141 }
142 }
143 else v = min;
144 }
145 me.setValue(v);
146 # readback from prop as integer props removes decimals
147 return me.getValue();
148 }
149 else {
150 logprint(DEV_ALERT, "props.sub() can be used only on numeric props"~
151 me.getPath()~" "~me.getType());
152 return nil;
153 }
154 },
155
156 # add n to int property, do nothing, if prop type is not int
157 # n shall be integer and defaults to 1
158 increment: func(n = 1) {
159 if (me.isInt()) {
160 var v = me.getValue() + int(n);
161 if (me.setIntValue(v)) return v;
162 }
163 else {
164 logprint(DEV_ALERT, "props.increment() can be used only on integer props "~
165 me.getPath()~" "~me.getType());
166 return nil;
167 }
168 },
169
170 # sub n from int property, do nothing, if prop type is not int
171 # n shall be integer and defaults to 1
172 decrement: func(n = 1) {
173 if (me.isInt()) {
174 var v = me.getValue() - int(n);
175 if (me.setIntValue(v)) return v;
176 }
177 else {
178 logprint(DEV_ALERT, "props.decrement() can be used only on integer props"~
179 me.getPath()~" "~me.getType());
180 return nil;
181 }
182 },
183
184 # checks if a string can be used as a prop name
185 # returns 0 (invalid) or 1 (valid)
186 # as string operations are expensive, use this only when necessary,
187 # especially do not use in update loops
188 isValidPropName: func(s) {
189 if (!size(s)) return 0;
190 var _ispropspecial = func(c) { c == `_` or c == `.` or c == `-`; }
191 var _ispropname = func(c) string.isalnum(c) or _ispropspecial(c);
192 if (!string.isalpha(s[0]) and s[0] != `_`) return 0;
193 for (var i=1; i < size(s); i += 1) {
194 if (!_ispropname(s[i])) return 0;
195 }
196 return 1;
197 },
198
199 # replaces any invalid char by "_"
200 # as string operations are expensive, use this only when necessary,
201 # especially do not use in update loops
202 makeValidPropName: func(s) {
203 if (!size(s)) return nil;
204 var _ispropspecial = func(c) { c == `_` or c == `.` or c == `-`; }
205 var _ispropname = func(c) string.isalnum(c) or _ispropspecial(c);
206 var rv = "";
207 rv ~= (!string.isalpha(s[0])) ? "_" : chr(s[0]);
208 for (var i=1; i < size(s); i += 1) {
209 rv ~= (_ispropname(s[i])) ? chr(s[i]) : "_";
210 }
211 return rv;
212 },
213 };
214
215 ##
216 # Static constructor for a Node object. Accepts a Nasal hash
217 # expression to initialize the object a-la setValues().
218 #
219 Node.new = func(values = nil) {
220 var result = wrapNode(_new());
221 if(ishash(values))
222 result.setValues(values);
223 return result;
224 }
225
226 ##
227 # Counter piece of setValues(). Returns a hash with all values
228 # in the subtree. Nodes with same name are returned as vector,
229 # where the original node indices are lost. The function should
230 # only be used if all or almost all values are needed, and never
231 # in performance-critical code paths. If it's called on a node
232 # without children, then the result is equivalent to getValue().
233 #
234 Node.getValues = func {
235 var children = me.getChildren();
236 if(!size(children)) return me.getValue();
237 var val = {};
238 var numchld = {};
239 foreach(var c; children) {
240 var name = c.getName();
241 if(contains(numchld, name)) { var nc = numchld[name]; }
242 else {
243 var nc = size(me.getChildren(name));
244 numchld[name] = nc;
245 if(nc > 1 and !contains(val, name)) val[name] = [];
246 }
247 if(nc > 1) append(val[name], c.getValues());
248 else val[name] = c.getValues();
249 }
250 return val;
251 }
252
253 ##
254 # Initializes property if it's still undefined. First argument
255 # is a property name/path. It can also be nil or an empty string,
256 # in which case the node itself gets initialized, rather than one
257 # of its children. Second argument is the default value. The third,
258 # optional argument is a property type (one of "STRING", "DOUBLE",
259 # "INT", or "BOOL"). If it is omitted, then "DOUBLE" is used for
260 # numbers, and STRING for everything else. Returns the property
261 # as props.Node. The fourth optional argument enforces a type if
262 # non-zero.
263 #
264 Node.initNode = func(path = nil, value = 0, type = nil, force = 0) {
265 var prop = me.getNode(path or "", 1);
266 if(prop.getType() != "NONE") value = prop.getValue();
267 if(force) prop.clearValue();
268 if(type == nil) prop.setValue(value);
269 elsif(type == "DOUBLE") prop.setDoubleValue(value);
270 elsif(type == "INT") prop.setIntValue(value);
271 elsif(type == "BOOL") prop.setBoolValue(value);
272 elsif(type == "STRING") prop.setValue("" ~ value);
273 else die("initNode(): unsupported type '" ~ type ~ "'");
274 return prop;
275 }
276
277 ##
278 # Useful debugging utility. Recursively dumps the full state of a
279 # Node object to the console. Try binding "props.dump(props.globals)"
280 # to a key for a fun hack.
281 #
282 var dump = func {
283 if(size(arg) == 1) { prefix = ""; node = arg[0]; }
284 else { prefix = arg[0]; node = arg[1]; }
285
286 index = node.getIndex();
287 type = node.getType();
288 name = node.getName();
289 val = node.getValue();
290
291 if(val == nil) { val = "nil"; }
292 name = prefix ~ name;
293 if(index > 0) { name = name ~ "[" ~ index ~ "]"; }
294 print(name, " {", type, "} = ", val);
295
296 # Don't recurse into aliases, lest we get stuck in a loop
297 if(type != "ALIAS") {
298 children = node.getChildren();
299 foreach(c; children) { dump(name ~ "/", c); }
300 }
301 }
302
303 ##
304 # Recursively copy property branch from source Node to
305 # destination Node. Doesn't copy aliases. Copies attributes
306 # if optional third argument is set and non-zero.
307 #
308 var copy = func(src, dest, attr = 0) {
309 var sp = src.getPath() or "";
310 var dp = dest.getPath() or "";
311
312 # sp and dp may be equal but on different trees!
313 # check if dest is sub node of source
314 sp = split("/", sp);
315 dp = split("/", dp);
316 while (size(sp) and size(dp) and (sp[0] == dp[0])) {
317 sp = subvec(sp, 1);
318 dp = subvec(dp, 1);
319 }
320
321 foreach(var c; src.getChildren()) {
322 var name = c.getName();
323 var i = c.getIndex();
324 if (i) name ~= "["~i~"]";
325 if (!(!size(sp) and size(dp) and name == dp[0]))
326 copy(src.getNode(name), dest.getNode(name, 1), attr);
327 else {
328 logprint(DEV_WARN, "props.copy() skipping "~name~" (recursion!)");
329 }
330 }
331 var type = src.getType();
332 var val = src.getValue();
333 if(type == "ALIAS" or type == "NONE") return;
334 elsif(type == "BOOL") dest.setBoolValue(val);
335 elsif(type == "INT" or type == "LONG") dest.setIntValue(val);
336 elsif(type == "FLOAT" or type == "DOUBLE") dest.setDoubleValue(val);
337 else dest.setValue(val);
338 if(attr) dest.setAttribute(src.getAttribute());
339 }
340
341 ##
342 # Utility. Turns any ghosts it finds (either solo, or in an
343 # array) into Node objects.
344 #
345 var wrap = func(node) {
346 if(isghost(node)) {
347 return wrapNode(node);
348 } elsif(isvec(node)) {
349 var v = node;
350 var n = size(v);
351 for(var i=0; i<n; i+=1) { v[i] = wrapNode(v[i]); }
352 return v;
353 }
354 return node;
355 }
356
357 ##
358 # Utility. Returns a new object with its superclass/parent set to the
359 # Node object and its _g (ghost) field set to the specified object.
360 # Nasal's literal syntax can be pleasingly terse. I like that. :)
361 #
362 var wrapNode = func(node) { { parents : [Node], _g : node } }
363
364 ##
365 # Global property tree. Set once at initialization. Is that OK?
366 # Does anything ever call globals.set_props() from C++? May need to
367 # turn this into a function if so.
368 #
369 var globals = wrapNode(_globals());
370
371 ##
372 # Shortcut for props.globals.getNode().
373 #
374 var getNode = func return call(props.globals.getNode, arg, props.globals);
375
376 ##
377 # Sets all indexed property children to a single value. arg[0]
378 # specifies a property name (e.g. /controls/engines/engine), arg[1] a
379 # path under each node of that name to set (e.g. "throttle"), arg[2]
380 # is the value.
381 #
382 var setAll = func(base, child, value) {
383 var node = props.globals.getNode(base);
384 if(node == nil) return;
385 var name = node.getName();
386 node = node.getParent();
387 if(node == nil) return;
388 var children = node.getChildren(name);
389 foreach(var c; children)
390 c.getNode(child, 1).setValue(value);
391 }
392
393 # createNodeObjectsFromHash - create nasal node objects from hash
394 # property_list: hash; where keys are variable names and values are
395 # property paths
396 # { foo: "/some/prop/foo", bar: "/some/other/prop", }
397 # namespace: optional; variables (objects) are created in this namespace
398 # defaults to namespace of caller, e.g. after calling this
399 # you can use foo.getValue() or bar.addChild()
400 #
401 var createNodeObjectsFromHash = func (property_list, namespace = nil) {
402 if (namespace == nil) {
403 namespace = caller(1)[0];
404 }
405 if (!ishash(namespace)) {
406 logprint(LOG_WARN, "createNodeObjectsFromHash: Error, namespace argument is not a hash.");
407 return nil;
408 }
409 if (!ishash(property_list)) {
410 logprint(LOG_WARN, "createNodeObjectsFromHash: Error, property_list argument is not a hash.");
411 return nil;
412 }
413 foreach (key; keys(property_list)) {
414 namespace[key] = props.getNode(property_list[key],1);
415 }
416 }
417
418 ##
419 # Turns about anything into a list of props.Nodes, including ghosts,
420 # path strings, vectors or hashes containing, as well as functions
421 # returning any of the former and in arbitrary nesting. This is meant
422 # to be used in functions whose main purpose is to handle collections
423 # of properties.
424 #
425 var nodeList = func {
426 var list = [];
427 foreach(var a; arg) {
428 if(isa(a, Node))
429 append(list, a);
430 elsif(isscalar(a))
431 append(list, props.globals.getNode(a, 1));
432 elsif(isvec(a))
433 foreach(var i; a)
434 list ~= nodeList(i);
435 elsif(ishash(a))
436 foreach(var i; keys(a))
437 list ~= nodeList(a[i]);
438 elsif(isfunc(a))
439 list ~= nodeList(a());
440 elsif(isghost(a) and ghosttype(a) == "prop")
441 append(list, wrapNode(a));
442 else
443 die("nodeList: invalid nil property");
444 }
445 return list;
446 }
447
448 ##
449 # Compiles a <condition> property branch according to the rules
450 # set out in $FG_ROOT/Docs/README.conditions into a Condition object.
451 # The 'test' method of the returend object can be used to evaluate
452 # the condition.
453 # The function returns nil on error.
454 #
455 var compileCondition = func(p) {
456 if(p == nil) return nil;
457 if(!isa(p, Node)) p = props.globals.getNode(p);
458 return _createCondition(p._g);
459 }
460
461 ##
462 # Evaluates a <condition> property branch according to the rules
463 # set out in $FG_ROOT/Docs/README.conditions. Undefined conditions
464 # and a nil argument are "true". The function dumps the condition
465 # branch and returns nil on error.
466 #
467 var condition = func(p) {
468 if(p == nil) return 1;
469 if(!isa(p, Node)) p = props.globals.getNode(p);
470 return _cond_and(p)
471 }
472
473 var _cond_and = func(p) {
474 foreach(var c; p.getChildren())
475 if(!_cond(c)) return 0;
476 return 1;
477 }
478
479 var _cond_or = func(p) {
480 foreach(var c; p.getChildren())
481 if(_cond(c)) return 1;
482 return 0;
483 }
484
485 var _cond = func(p) {
486 var n = p.getName();
487 if(n == "or") return _cond_or(p);
488 if(n == "and") return _cond_and(p);
489 if(n == "not") return !_cond_and(p);
490 if(n == "equals") return _cond_cmp(p, 0);
491 if(n == "not-equals") return !_cond_cmp(p, 0);
492 if(n == "less-than") return _cond_cmp(p, -1);
493 if(n == "greater-than") return _cond_cmp(p, 1);
494 if(n == "less-than-equals") return !_cond_cmp(p, 1);
495 if(n == "greater-than-equals") return !_cond_cmp(p, -1);
496 if(n == "property") return !!getprop(p.getValue());
497 logprint(LOG_ALERT, "condition: invalid operator ", n);
498 dump(p);
499 return nil;
500 }
501
502 var _cond_cmp = func(p, op) {
503 var left = p.getChild("property", 0, 0);
504 if(left != nil) { left = getprop(left.getValue()); }
505 else {
506 logprint(LOG_ALERT, "condition: no left value");
507 dump(p);
508 return nil;
509 }
510 var right = p.getChild("property", 1, 0);
511 if(right != nil) { right = getprop(right.getValue()); }
512 else {
513 right = p.getChild("value", 0, 0);
514 if(right != nil) { right = right.getValue(); }
515 else {
516 logprint(LOG_ALERT, "condition: no right value");
517 dump(p);
518 return nil;
519 }
520 }
521
522 if (left == nil) left = 0.0;
523 if (right == nil) right = 0.0;
524
525 if(op < 0) return left < right;
526 if(op > 0) return left > right;
527 return left == right;
528 }
529
530 ##
531 # Runs <binding> as described in $FG_ROOT/Docs/README.commands using
532 # a given module by default, and returns 1 if fgcommand() succeeded,
533 # or 0 otherwise. The module name won't override a <module> defined
534 # in the binding.
535 #
536 var runBinding = func(node, module = nil) {
537 if(module != nil and node.getNode("module") == nil)
538 node.getNode("module", 1).setValue(module);
539 var cmd = node.getNode("command", 1).getValue() or "null";
540 condition(node.getNode("condition")) ? fgcommand(cmd, node) : 0;
541 }
542
543 ##
544 # Swaps the value of two property nodes, like the property-swap command
545 #
546 var swapValues = func(left, right) {
547 if (!isa(left, Node)) {
548 left = props.globals.getNode(left);
549 }
550 if (!isa(right, Node)) {
551 right = props.globals.getNode(right);
552 }
553 var leftValue = left.getValue();
554 var rightValue = right.getValue();
555 left.setValue(rightValue);
556 right.setValue(leftValue);
557 }
558
559 #---------------------------------------------------------------------------
560 # Property / object update manager
561 #
562 # - Manage updates when a value has changed more than a predetermined amount.
563 # This class is designed to make updating displays (e.g. canvas), or
564 # performing actions based on a property (or value in a hash) changing
565 # by more than the preset amount.
566 # This can make a significant improvement to performance compared to simply
567 # redrawing a canvas in an update loop.
568 # - Author : Richard Harrison ([email protected])
569 #---------------------------------------------------------------------------*/
570
571 #example usage:
572 # this is using the hashlist (which works well with an Emesary notification)
573 # basically when the method is called it will call each section (in the lambda)
574 # when the value changes by more than the amount specified as the second parameter.
575 # It is possible to reference multiple elements from the hashlist in each FromHashList; if either
576 # one changes then it will result in the lambda being called.
577 #
578 # obj.update_items = [
579 # UpdateManager.FromHashList(["VV_x","VV_y"], 0.01, func(val)
580 # {
581 # obj.VV.setTranslation (val.VV_x, val.VV_y + pitch_offset);
582 # }),
583 # UpdateManager.FromHashList(["pitch","roll"], 0.025, func(hdp)
584 # {
585 # obj.ladder.setTranslation (0.0, hdp.pitch * pitch_factor+pitch_offset);
586 # obj.ladder.setCenter (118,830 - hdp.pitch * pitch_factor-pitch_offset);
587 # obj.ladder.setRotation (-hdp.roll_rad);
588 # obj.roll_pointer.setRotation (hdp.roll_rad);
589 # }),
590 # props.UpdateManager.FromProperty("velocities/airspeed-kt", 0.01, func(val)
591 # {
592 # obj.ias_range.setTranslation(0, val * ias_range_factor);
593 # }),
594 # props.UpdateManager.FromPropertyHashList(["orientation/alpha-indicated-deg", "orientation/side-slip-deg"], 0.1, func(val)
595 # {
596 # obj.VV_x = val.property["orientation/side-slip-deg"].getValue()*10; # adjust for view
597 # obj.VV_y = val.property["orientation/alpha-indicated-deg"].getValue()*10; # adjust for view
598 # obj.VV.setTranslation (obj.VV_x, obj.VV_y);
599 # }),
600 # ]
601 #
602 #==== the update loop then becomes ======
603 #
604 # foreach(var update_item; me.update_items)
605 # {
606 # # hdp is a data provider that can be used as the hashlist for the property
607 # # update from hash methods.
608 # update_item.update(hdp);
609 # }
610 #
611 var UpdateManager =
612 {
613 _updateProperty : func(_property)
614 {
615 },
616
617 #
618 # Monitor a property for a change more than the delta.
619 # - type of the property is used to determine if a delta change
620 # can be detected or whether to fire on every value change (strings)
621 FromProperty : func(_propname, _delta, _changed_method)
622 {
623 var obj = {parents : [UpdateManager] };
624 obj.propname = _propname;
625 obj.property = props.globals.getNode(_propname);
626 obj.delta = _delta;
627 obj.curval = obj.property.getValue();
628 obj.lastval = obj.curval;
629 obj.changed = _changed_method;
630 obj.update = func(obj)
631 {
632 me.curval = me.property.getValue();
633 if (me.curval != nil)
634 {
635 me.localType = me.property.getType();
636 if (me.localType == "INT" or me.localType == "LONG" or me.localType == "FLOAT" or me.localType == "DOUBLE")
637 {
638 if(me.lastval == nil or math.abs(me.lastval - me.curval) >= me.delta)
639 {
640 me.lastval = me.curval;
641 me.changed(me.curval);
642 }
643 }
644 else if(me.lastval == nil or me.lastval != me.curval)
645 {
646 me.lastval = me.curval;
647 me.changed(me.curval);
648 }
649 }
650 };
651 obj.update(obj);
652 return obj;
653 },
654
655 #
656 # Determine if specifc property is a numeric (false usually means a string)
657 IsNumeric : func(hashkey)
658 {
659 me.localType = me.property[hashkey].getType();
660 if (me.localType == "UNSPECIFIED") {
661 print("UpdateManager: warning ",hashkey," is ",ty, " excluding from update");
662 me.property[hashkey] = nil;
663 }
664 if (me.localType == "INT" or me.localType == "LONG" or me.localType == "FLOAT" or me.localType == "DOUBLE")
665 return 1;
666 else
667 return 0;
668 },
669
670 #
671 # Monitor list of properties for a change more than the delta.
672 # - type of the property is used to determine if a delta change
673 # can be detected or whether to fire on every value change (strings)
674 FromPropertyHashList : func(_keylist, _delta, _changed_method)
675 {
676 var obj = {parents : [UpdateManager] };
677 obj.hashkeylist = _keylist;
678 obj.delta = _delta;
679 obj.lastval = {};
680 obj.hashkey = nil;
681 obj.changed = _changed_method;
682 obj.needs_update = 0;
683 obj.property = {};
684 obj.is_numeric = {};
685 foreach (hashkey; obj.hashkeylist) {
686 obj.property[hashkey] = props.globals.getNode(hashkey);
687 obj.lastval[hashkey] = nil;
688 # var ty = obj.property[hashkey].getType();
689 # if (ty == "INT" or ty == "LONG" or ty == "FLOAT" or ty == "DOUBLE") {
690 # obj.is_numeric[hashkey] = 1;
691 # } else
692 # obj.is_numeric[hashkey] = 0;
693 #print("create: ", hashkey," ", ty, " isnum=",obj.is_numeric[hashkey]);
694 # if (ty == "UNSPECIFIED")
695 # print("UpdateManager: warning ",hashkey," is ",ty);
696 }
697 obj.update = func(obj)
698 {
699 if (me.lastval == nil)
700 me.needs_update = 1;
701 else {
702 me.needs_update = 0;
703
704 foreach (hashkey; me.hashkeylist) {
705 if (me.property[hashkey] != nil) {
706 me.valIsNumeric = me.IsNumeric(hashkey);
707
708 if (me.lastval[hashkey] == nil
709 or (me.valIsNumeric and (math.abs(me.lastval[hashkey] - me.property[hashkey].getValue()) >= me.delta))
710 or (!me.valIsNumeric and (me.lastval[hashkey] != me.property[hashkey].getValue()))) {
711 me.needs_update = 1;
712 break;
713 }
714 }
715 }
716 }
717 if (me.needs_update) {
718 me.changed(me);
719 foreach (hashkey; me.hashkeylist) {
720 me.lastval[hashkey] = me.property[hashkey].getValue();
721 }
722 }
723 }
724 ;
725 return obj;
726 },
727
728 # Monitor an individual hash value for a change more than the delta.
729 # - when the hash value is a string use nil as the delta to indicate that
730 # a simple value changed comparison is required.
731 # - can also use nil to detect any change; e.g. in
732 FromHashValue : func(_key, _delta, _changed_method)
733 {
734 var obj = {parents : [UpdateManager] };
735 obj.hashkey = _key;
736 obj.delta = _delta;
737 obj.isnum = _delta != nil;
738 obj.curval = nil;
739 obj.lastval = nil;
740 obj.changed = _changed_method;
741 obj.update = func(obj)
742 {
743 me.curval = obj[me.hashkey];
744 if (me.curval != nil) {
745 if (me.isnum) {
746 me.curval = num(me.curval);
747 if (me.lastval == nil or math.abs(me.lastval - me.curval) >= me.delta) {
748 me.lastval = me.curval;
749 me.changed(me.curval);
750 }
751 } else {
752 if (me.lastval == nil or me.lastval != me.curval) {
753 me.lastval = me.curval;
754 me.changed(me.curval);
755 }
756 }
757 }
758 }
759 ;
760 return obj;
761 },
762
763 #
764 # Monitor a list of hash values for a change more than the delta.
765 # - when the hash value is a string use nil as the delta to indicate that
766 # a simple value changed comparison is required.
767 # - can also use nil to detect any change; e.g. in
768 FromHashList : func(_keylist, _delta, _changed_method)
769 {
770 var obj = {parents : [UpdateManager] };
771 obj.hashkeylist = _keylist;
772 obj.delta = _delta;
773 obj.lastval = {};
774 obj.hashkey = nil;
775 obj.changed = _changed_method;
776 obj.needs_update = 0;
777 obj.isnum = _delta != nil;
778 obj.update = func(obj)
779 {
780 if (me.lastval == nil)
781 me.needs_update = 1;
782 else
783 me.needs_update = 0;
784
785 if (obj != nil or me.lastval == nil) {
786 foreach (hashkey; me.hashkeylist) {
787 if (me.isnum) {
788 if (me.lastval[hashkey] == nil or math.abs(me.lastval[hashkey] - obj[hashkey]) >= me.delta) {
789 me.needs_update = 1;
790 break;
791 }
792 } elsif (me.lastval[hashkey] == nil or me.lastval[hashkey] != obj[hashkey]) {
793 me.needs_update = 1;
794 break;
795 }
796 }
797 }
798 if (me.needs_update) {
799 me.changed(obj);
800 foreach (hashkey; me.hashkeylist) {
801 me.lastval[hashkey] = obj[hashkey];
802 }
803 }
804 };
805 return obj;
806 },
807 };