Oolite
Loading...
Searching...
No Matches
OOJSSystemInfo.m
Go to the documentation of this file.
1/*
2
3OOJSSystemInfo.m (QuickJS-ng)
4
5Oolite
6Copyright (C) 2004-2013 Giles C Williams and contributors
7
8This program is free software; you can redistribute it and/or
9modify it under the terms of the GNU General Public License
10as published by the Free Software Foundation; either version 2
11of the License, or (at your option) any later version.
12
13This program is distributed in the hope that it will be useful,
14but WITHOUT ANY WARRANTY; without even the implied warranty of
15MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16GNU General Public License for more details.
17
18You should have received a copy of the GNU General Public License
19along with this program; if not, write to the Free Software
20Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
21MA 02110-1301, USA.
22
23*/
24
25#import "OOJSSystemInfo.h"
26#import "OOConstToString.h"
27#import "OOIsNumberLiteral.h"
28#import "OOJSScript.h"
29#import "OOJSVector.h"
33#import "Universe.h"
34
35/* SpiderMonkey implemented SystemInfo's dynamic per-system properties with
36 class getProperty/setProperty/delProperty hooks and a JSCLASS_NEW_ENUMERATE
37 enumerate hook. QuickJS equivalents are exotic methods on the class:
38
39 * get_property: properties on the prototype chain (methods, the four
40 fixed properties, Object.prototype) are found first, as SpiderMonkey
41 only consulted the hook for names it could not otherwise find;
42 anything else is looked up in the system data.
43 * get_own_property / get_own_property_names: the system data keys are
44 enumerable, so for..in, Object.keys(), Object.getOwnPropertyNames()
45 and JSON.stringify() list exactly the system data keys, as the
46 SpiderMonkey enumerate hook did; but, as in SpiderMonkey,
47 hasOwnProperty() and the in operator report false for them. The fixed
48 properties are own properties (OOJSGetSharedPermanentOwnProperty()),
49 as in SpiderMonkey, but are not listed by any enumeration.
50 * set_property: assignments to names that are not read-only or
51 accessors on the prototype chain are stored (as strings) in the
52 system data, like the SpiderMonkey setProperty hook. SpiderMonkey also
53 added a shadowing own slot property; reads go to the system data
54 instead, except that a key assigned null reads back as null.
55 * delete_property: removes the key from the system data, like the
56 SpiderMonkey delProperty hook.
57
58 The fixed properties (coordinates etc.) are not enumerable, because the
59 SpiderMonkey enumerate hook never listed them.
60*/
61
62static JSClassID sSystemInfoClassID;
63
64/* The most recently created SystemInfo object. SpiderMonkey's cache was a
65 weak reference, but its lazy garbage collector kept the object alive for
66 a while, so successive system.info reads in a script usually got the same
67 object. With reference counting the object would die at the end of each
68 statement, so the cache holds a reference, released when another system
69 is requested and when the JavaScript engine is reset. Zero-filled until
70 first use, so always test with JS_IsObject().
71*/
72static JSValue sCachedSystemInfo;
75
77static void SystemInfoFinalize(JSRuntime* runtime, JSValueConst this);
78
79static int SystemInfoExoticGetOwnProperty(JSContext* context, JSPropertyDescriptor* desc, JSValueConst obj, JSAtom prop);
80static int SystemInfoExoticGetOwnPropertyNames(JSContext* context, JSPropertyEnum** ptab, uint32_t* plen, JSValueConst obj);
81static int SystemInfoExoticDeleteProperty(JSContext* context, JSValueConst obj, JSAtom prop);
82static JSValue SystemInfoExoticGetProperty(JSContext* context, JSValueConst obj, JSAtom prop, JSValueConst receiver);
83static int SystemInfoExoticSetProperty(JSContext* context, JSValueConst obj, JSAtom prop, JSValueConst value, JSValueConst receiver, int flags);
84
89
92
93static JSClassExoticMethods sSystemInfoExoticMethods = {
94 .get_own_property = SystemInfoExoticGetOwnProperty,
95 .get_own_property_names = SystemInfoExoticGetOwnPropertyNames,
96 .delete_property = SystemInfoExoticDeleteProperty,
97 .get_property = SystemInfoExoticGetProperty,
98 .set_property = SystemInfoExoticSetProperty,
99};
100
101static JSClassDef sSystemInfoClass = {
102 .class_name = "SystemInfo",
103 .finalizer = SystemInfoFinalize,
104 .exotic = &sSystemInfoExoticMethods,
105};
106
107enum {
108 // Property IDs
109 kSystemInfo_coordinates, // system coordinates (in LY), Vector3D (with z = 0), read-only
110 kSystemInfo_internalCoordinates, // system coordinates (unscaled), Vector3D (with z = 0), read-only
111 kSystemInfo_galaxyID, // galaxy number, integer, read-only
112 kSystemInfo_systemID // system number, integer, read-only
113};
114
115static const JSCFunctionListEntry sSystemInfoProperties[] = {
116 // JS name, getter, setter, ID, flags (hidden: see comment at top of file)
117 JS_CGETSET_MAGIC_DEF2("coordinates", SystemInfoGetProperty, NULL, kSystemInfo_coordinates, OOJS_PROP_HIDDEN_READONLY_CB),
118 JS_CGETSET_MAGIC_DEF2("internalCoordinates", SystemInfoGetProperty, NULL, kSystemInfo_internalCoordinates, OOJS_PROP_HIDDEN_READONLY_CB),
119 JS_CGETSET_MAGIC_DEF2("galaxyID", SystemInfoGetProperty, NULL, kSystemInfo_galaxyID, OOJS_PROP_HIDDEN_READONLY_CB),
120 JS_CGETSET_MAGIC_DEF2("systemID", SystemInfoGetProperty, NULL, kSystemInfo_systemID, OOJS_PROP_HIDDEN_READONLY_CB),
121};
122
123static const JSCFunctionListEntry sSystemInfoMethods[] = {
124 // JS name, min args, function
125 JS_CFUNC_DEF("toString", 0, OOJSObjectWrapperToString),
126 JS_CFUNC_DEF("distanceToSystem", 1, SystemInfoDistanceToSystem),
127 JS_CFUNC_DEF("routeToSystem", 1, SystemInfoRouteToSystem),
128 JS_CFUNC_DEF("samplePrice", 1, SystemInfoSamplePrice),
129 JS_CFUNC_DEF("setProperty", 3, SystemInfoSetPropertyMethod),
130};
131
132static const JSCFunctionListEntry sSystemInfoStaticMethods[] = {
133 // JS name, min args, function
134 JS_CFUNC_DEF("filteredSystems", 2, SystemInfoStaticFilteredSystems),
135 JS_CFUNC_DEF("setInterstellarProperty", 4, SystemInfoStaticSetInterstellarProperty),
136};
137
138// Helper class wrapped by JS SystemInfo objects
139@interface OOSystemInfo : NSObject {
140@private
143 NSString* _planetKey;
144 NSMutableSet* _nullAssignedKeys; // See SystemInfoExoticSetProperty().
145}
146
147- (id)initWithGalaxy:(OOGalaxyID)galaxy system:(OOSystemID)system;
148
149- (id)valueForKey:(NSString*)key;
150- (void)setValue:(id)value forKey:(NSString*)key;
151
152- (NSArray*)allKeys;
153
154- (void)setNullAssigned:(BOOL)flag forKey:(NSString*)key;
155- (BOOL)isNullAssignedForKey:(NSString*)key;
156
159//- (Random_Seed) systemSeed;
160
161@end
162
164
165@implementation OOSystemInfo
166
167- (id)init
168{
169 [self release];
170 return nil;
171}
172
173- (id)initWithGalaxy:(OOGalaxyID)galaxy system:(OOSystemID)system
174{
176 [self release];
177 return nil;
178 }
179
180 if ((self = [super init])) {
181 _galaxy = galaxy;
182 _system = system;
183 _planetKey = [[NSString stringWithFormat:@"%u %i", galaxy, system] retain];
184 }
185 return self;
186}
187
188- (void)dealloc
189{
190 [_planetKey release];
191 [_nullAssignedKeys release];
192
193 [super dealloc];
194}
195
196- (void)setNullAssigned:(BOOL)flag forKey:(NSString*)key
197{
198 if (flag) {
199 if (_nullAssignedKeys == nil)
200 _nullAssignedKeys = [[NSMutableSet alloc] init];
201 [_nullAssignedKeys addObject:key];
202 } else {
203 [_nullAssignedKeys removeObject:key];
204 }
205}
206
207- (BOOL)isNullAssignedForKey:(NSString*)key
208{
209 return [_nullAssignedKeys containsObject:key];
210}
211
212- (NSString*)descriptionComponents
213{
214 return [NSString stringWithFormat:@"galaxy %u, system %i", _galaxy, _system];
215}
216
218{
219 return _planetKey;
220}
221
222- (NSString*)oo_jsClassName
223{
224 return @"SystemInfo";
225}
226
227- (BOOL)isEqual:(id)other
228{
229 return other == self || ([other isKindOfClass:[OOSystemInfo class]] && [other galaxy] == _galaxy && [other system] == _system);
230}
231
232- (NSUInteger)hash
233{
234 NSUInteger hash = _galaxy;
235 hash <<= 16;
236 hash |= (uint16_t)_system;
237 return hash;
238}
239
240- (id)valueForKey:(NSString*)key
241{
242 if ([UNIVERSE inInterstellarSpace] && _system == -1) {
243 return [[UNIVERSE currentSystemData] objectForKey:key];
244 }
245 return [UNIVERSE systemDataForGalaxy:_galaxy planet:_system key:key];
246}
247
248- (void)setValue:(id)value forKey:(NSString*)key
249{
250 NSString* manifest = [[OOJSScript currentlyRunningScript] propertyNamed:kLocalManifestProperty];
251
252 [UNIVERSE setSystemDataForGalaxy:_galaxy planet:_system key:key value:value fromManifest:manifest forLayer:OO_LAYER_OXP_DYNAMIC];
253}
254
255- (NSArray*)allKeys
256{
257 if ([UNIVERSE inInterstellarSpace] && _system == -1) {
258 return [[UNIVERSE currentSystemData] allKeys];
259 }
260 return [UNIVERSE systemDataKeysForGalaxy:_galaxy planet:_system];
261}
262
264{
265 return _galaxy;
266}
267
269{
270 return _system;
271}
272
273/*- (Random_Seed) systemSeed
274{
275 NSAssert([PLAYER currentGalaxyID] == _galaxy, @"Attempt to use -[OOSystemInfo systemSeed] from a different galaxy.");
276 return [UNIVERSE systemSeedForSystemNumber:_system];
277 }*/
278
279- (NSPoint)coordinates
280{
281 if ([UNIVERSE inInterstellarSpace] && _system == -1) {
282 return [PLAYER galaxy_coordinates];
283 }
284 return [UNIVERSE coordinatesForSystem:_system];
285}
286
287- (JSValue)oo_jsValueInContext:(JSContext*)context
288{
289 JSValue result = JS_NewObjectClass(context, (int)sSystemInfoClassID);
290 if (JS_IsException(result)) {
291 JS_FreeValue(context, JS_GetException(context));
292 return JS_NULL;
293 }
294 JS_SetOpaque(result, [self retain]);
295
296 return result;
297}
298
299+ (void)oo_javaScriptEngineWillReset:(NSNotification*)notification
300{
301 JSValue oldCache = sCachedSystemInfo;
302 sCachedSystemInfo = JS_UNDEFINED;
303 if (JS_IsObject(oldCache))
304 JS_FreeValue(OOJSAcquireContext(), oldCache);
305}
306
307@end
308
309void InitOOJSSystemInfo(JSContext* context, JSValueConst global)
310{
311 static BOOL observing = NO;
312 if (!observing) {
313 [[NSNotificationCenter defaultCenter] addObserver:[OOSystemInfo class]
314 selector:@selector(oo_javaScriptEngineWillReset:)
315 name:kOOJavaScriptEngineWillResetNotification
316 object:nil];
317 observing = YES;
318 }
319 sCachedSystemInfo = JS_UNDEFINED;
320
322 OOJSInitClass(context, global, sSystemInfoClassID, JS_UNDEFINED, OOJSUnconstructableConstruct, 0,
326}
327
329{
331
332 // Use cached object if possible.
333 if (JS_IsObject(sCachedSystemInfo) && sCachedGalaxy == galaxy && sCachedSystem == system) {
334 return JS_DupValue(context, sCachedSystemInfo);
335 }
336
337 // If not, create a new one.
338 OOSystemInfo* info = nil;
339 JSValue result;
341 info = [[[OOSystemInfo alloc] initWithGalaxy:galaxy system:system] autorelease];
343
344 if (EXPECT_NOT(info == nil)) {
345 OOJSReportWarning(context, @"Could not create system info object for galaxy %u, system %i.", galaxy, system);
346 }
347
348 result = OOJSValueFromNativeObject(context, info);
349
350 // Replace the cached object. (Freeing it may run SystemInfoFinalize(), which clears the cache.)
351 JSValue oldCache = sCachedSystemInfo;
352 sCachedSystemInfo = JS_UNDEFINED;
353 if (JS_IsObject(oldCache))
354 JS_FreeValue(context, oldCache);
355 sCachedSystemInfo = JS_IsObject(result) ? JS_DupValue(context, result) : JS_UNDEFINED;
358
359 return result;
360
362}
363
364static void SystemInfoFinalize(JSRuntime* runtime, JSValueConst this)
365{
367
368 // Clear now-stale cache entry if appropriate.
369 if (JS_IsObject(sCachedSystemInfo) && JS_VALUE_GET_PTR(sCachedSystemInfo) == JS_VALUE_GET_PTR(this)) {
370 sCachedSystemInfo = JS_UNDEFINED;
371 }
372
373 // Releases the OOSystemInfo.
374 OOJSObjectWrapperFinalize(runtime, this);
375
377}
378
379// *** Exotic property behaviour (replaces SpiderMonkey class hooks) ***
380
381/* Exotic methods are called from inside QuickJS, so Objective-C exceptions
382 must not escape them. These bracket the body of each one, converting an
383 exception into a JS error.
384*/
385#define OOJS_EXOTIC_ENTER \
386 @try {
387#define OOJS_EXOTIC_EXIT(context, failure) \
388 } \
389 @catch (id exception) \
390 { \
391 OOJSReportWrappedException(context, exception); \
392 return (failure); \
393 }
394
395// The OOSystemInfo of an instance, or nil for the prototype.
396static OOSystemInfo* SystemInfoForObject(JSValueConst obj)
397{
398 return (OOSystemInfo*)JS_GetOpaque(obj, sSystemInfoClassID);
399}
400
401// The key for a string property, or nil for symbols.
402static NSString* SystemInfoKeyForAtom(JSContext* context, JSAtom prop)
403{
404 NSString* key = nil;
405 JSValue propValue = JS_AtomToValue(context, prop);
406 if (JS_IsString(propValue)) {
407 key = OOStringFromJSValue(context, propValue);
408 }
409 JS_FreeValue(context, propValue);
410 return key;
411}
412
413/* Look up a system data value, as the string-ID branch of the SpiderMonkey
414 SystemInfoGetProperty() did. Returns YES and an owned *outValue if the key
415 exists, NO otherwise (or on exception, which is then pending and
416 *outValue is JS_EXCEPTION).
417*/
418static BOOL SystemInfoGetSystemDataValue(JSContext* context, OOSystemInfo* info, NSString* key, JSValue* outValue)
419{
420 *outValue = JS_UNDEFINED;
421
422 OOSystemDescriptionManager* systemManager = [UNIVERSE systemManager];
423 id propValue = nil;
424 // interstellar space needs more work at this stage
425 if ([info system] != -1) {
426 propValue = [systemManager getProperty:key forSystem:[info system] inGalaxy:[info galaxy]];
427 } else {
428 propValue = [info valueForKey:key];
429 }
430
431 if (propValue == nil)
432 return NO;
433
434 if ([propValue isKindOfClass:[NSNumber class]] || OOIsNumberLiteral([propValue description], YES)) {
435 *outValue = JS_NewNumber(context, [propValue doubleValue]);
436 } else {
437 *outValue = [propValue oo_jsValueInContext:context];
438 }
439 return YES;
440}
441
442/* Ordinary [[Set]] on the prototype chain of obj (whose own properties have
443 already been checked by QuickJS). If an accessor or read-only property is
444 found, it is handled and *outHandled is set; the return value is then the
445 set_property result. Otherwise *outHandled is NO and the caller decides
446 where the value goes.
447*/
448static int SystemInfoSetOnPrototypeChain(JSContext* context, JSValueConst obj, JSAtom prop, JSValueConst value, JSValueConst receiver, int flags, BOOL* outHandled)
449{
450 JSValue proto = JS_GetPrototype(context, obj);
451 *outHandled = YES;
452
453 while (JS_IsObject(proto)) {
454 JSPropertyDescriptor desc;
455 int found = JS_GetOwnProperty(context, &desc, proto, prop);
456 if (found < 0) {
457 JS_FreeValue(context, proto);
458 return -1;
459 }
460 if (found) {
461 JS_FreeValue(context, proto);
462 if (desc.flags & JS_PROP_GETSET) {
463 JS_FreeValue(context, desc.getter);
464 if (JS_IsUndefined(desc.setter))
465 goto readOnly;
466 JSValue result = JS_Call(context, desc.setter, receiver, 1, &value);
467 JS_FreeValue(context, desc.setter);
468 if (JS_IsException(result))
469 return -1;
470 JS_FreeValue(context, result);
471 return true;
472 }
473 JS_FreeValue(context, desc.value);
474 if (!(desc.flags & JS_PROP_WRITABLE))
475 goto readOnly;
476 *outHandled = NO;
477 return true;
478 }
479
480 JSValue next = JS_GetPrototype(context, proto);
481 JS_FreeValue(context, proto);
482 proto = next;
483 }
484
485 if (JS_IsException(proto))
486 return -1;
487 JS_FreeValue(context, proto);
488 *outHandled = NO;
489 return true;
490
491readOnly:
492 /* QuickJS does not expose whether the calling code is strict, so
493 assignments to read-only properties are ignored except when the
494 caller explicitly asks for an exception (JS_PROP_THROW).
495 */
496 if (flags & JS_PROP_THROW) {
497 JSValue propName = JS_AtomToString(context, prop);
498 const char* name = JS_ToCString(context, propName);
499 JS_ThrowTypeError(context, "'%s' is read-only", name ? name : "?");
500 JS_FreeCString(context, name);
501 JS_FreeValue(context, propName);
502 return -1;
503 }
504 return false;
505}
506
507static int SystemInfoExoticGetOwnProperty(JSContext* context, JSPropertyDescriptor* desc, JSValueConst obj, JSAtom prop)
508{
510
512
514 NSString* key = (info != nil) ? SystemInfoKeyForAtom(context, prop) : nil;
515 JSValue value;
516
517 /* SpiderMonkey reported the fixed (shared permanent) properties as own
518 properties, so they win over system data keys of the same name
519 (notably "coordinates"). They are hidden, but a name that is also a
520 system data key is reported as enumerable, since the SpiderMonkey
521 enumerate hook listed every system data key.
522 */
523 int shared = OOJSGetSharedPermanentOwnProperty(context, desc, obj, prop);
524 if (shared != 0) {
525 if (shared > 0 && desc != NULL && key != nil) {
526 if (SystemInfoGetSystemDataValue(context, info, key, &value)) {
527 if (JS_IsException(value)) {
528 JS_FreeValue(context, desc->getter);
529 JS_FreeValue(context, desc->setter);
530 JS_FreeValue(context, desc->value);
531 return -1;
532 }
533 JS_FreeValue(context, value);
534 desc->flags |= JS_PROP_ENUMERABLE;
535 }
536 }
537 return shared;
538 }
539
540 if (key == nil)
541 return false; // Prototype (no dynamic properties) or symbol.
542
543 /* SpiderMonkey's resolve hook made system data keys enumerable (for..in and
544 Object.keys() list them) but not own properties: hasOwnProperty() and
545 the in operator returned false. QuickJS asks this hook without a
546 descriptor for hasOwnProperty() and in, and with one when collecting
547 enumerable keys, so answer accordingly. (QuickJS-ng 0.17 behaviour;
548 tools/js-parity checks it.)
549 */
550 if (desc == NULL)
551 return false;
552
553 if (!SystemInfoGetSystemDataValue(context, info, key, &value)) {
554 return false;
555 }
556 if (JS_IsException(value))
557 return -1;
558
559 if (desc != NULL) {
560 desc->flags = JS_PROP_C_W_E;
561 desc->value = value;
562 desc->getter = JS_UNDEFINED;
563 desc->setter = JS_UNDEFINED;
564 } else {
565 JS_FreeValue(context, value);
566 }
567 return true;
568
569 OOJS_EXOTIC_EXIT(context, -1)
570
572}
573
574static int SystemInfoExoticGetOwnPropertyNames(JSContext* context, JSPropertyEnum** ptab, uint32_t* plen, JSValueConst obj)
575{
577
579
580 *ptab = NULL;
581 *plen = 0;
582
584 NSArray* keys = [info allKeys];
585 NSUInteger count = [keys count];
586 assert(count <= INT32_MAX);
587
588 JSPropertyEnum* tab = js_mallocz(context, sizeof *tab * (count + 1));
589 if (tab == NULL)
590 return -1;
591
592 // System data keys (all enumerable; the SpiderMonkey enumerate hook listed exactly these).
593 uint32_t i = 0;
594 for (NSString* key in keys) {
595 JSAtom atom = JS_NewAtom(context, [[key description] UTF8String]);
596 if (atom == JS_ATOM_NULL) {
597 JS_FreePropertyEnum(context, tab, i);
598 return -1;
599 }
600 tab[i].atom = atom;
601 tab[i].is_enumerable = true;
602 i++;
603 }
604
605 /* Only the system data keys, as SpiderMonkey's JSCLASS_NEW_ENUMERATE hook
606 listed: the fixed properties (galaxyID...) are not named, although
607 hasOwnProperty() reports them, as before.
608 */
609 *ptab = tab;
610 *plen = i;
611 return 0;
612
613 OOJS_EXOTIC_EXIT(context, -1)
614
616}
617
618static int SystemInfoExoticDeleteProperty(JSContext* context, JSValueConst obj, JSAtom prop)
619{
621
623
624 // SpiderMonkey version: set the property to undefined (which removes it).
626 NSString* key = SystemInfoKeyForAtom(context, prop);
627 if (info != nil && key != nil) {
628 [info setValue:nil forKey:key];
629 }
630 return true;
631
632 OOJS_EXOTIC_EXIT(context, -1)
633
635}
636
637static JSValue SystemInfoExoticGetProperty(JSContext* context, JSValueConst obj, JSAtom prop, JSValueConst receiver)
638{
640
642
643 // Prototype chain first: SpiderMonkey only used the hook for otherwise unknown names.
644 JSValue proto = JS_GetPrototype(context, obj);
645 while (JS_IsObject(proto)) {
646 JSPropertyDescriptor desc;
647 int found = JS_GetOwnProperty(context, &desc, proto, prop);
648 if (found < 0) {
649 JS_FreeValue(context, proto);
650 return JS_EXCEPTION;
651 }
652 if (found) {
653 JS_FreeValue(context, proto);
654 if (desc.flags & JS_PROP_GETSET) {
655 JSValue result = JS_UNDEFINED;
656 JS_FreeValue(context, desc.setter);
657 if (JS_IsFunction(context, desc.getter)) {
658 result = JS_Call(context, desc.getter, receiver, 0, NULL);
659 }
660 JS_FreeValue(context, desc.getter);
661 return result;
662 }
663 return desc.value;
664 }
665
666 JSValue next = JS_GetPrototype(context, proto);
667 JS_FreeValue(context, proto);
668 proto = next;
669 }
670 if (JS_IsException(proto))
671 return JS_EXCEPTION;
672 JS_FreeValue(context, proto);
673
675 if (info == nil) {
676 // Let QuickJS behave normally for the prototype object (where info will be nil).
677 return JS_UNDEFINED;
678 }
679
680 NSString* key = SystemInfoKeyForAtom(context, prop);
681 if (key == nil)
682 return JS_UNDEFINED;
683
684 JSValue value;
685 if (!SystemInfoGetSystemDataValue(context, info, key, &value) && [info isNullAssignedForKey:key])
686 return JS_NULL;
687 return value;
688
689 OOJS_EXOTIC_EXIT(context, JS_EXCEPTION)
690
692}
693
694static int SystemInfoExoticSetProperty(JSContext* context, JSValueConst obj, JSAtom prop, JSValueConst value, JSValueConst receiver, int flags)
695{
697
699
700 BOOL handled;
701 int result = SystemInfoSetOnPrototypeChain(context, obj, prop, value, receiver, flags, &handled);
702 if (handled)
703 return result;
704
706 NSString* key = SystemInfoKeyForAtom(context, prop);
707 if (info == nil || key == nil || !JS_IsObject(receiver) || JS_VALUE_GET_PTR(receiver) != JS_VALUE_GET_PTR(obj)) {
708 // Ordinary property (prototype object, symbol, or inherited by another object).
709 return JS_DefinePropertyValue(context, receiver, prop, JS_DupValue(context, value), JS_PROP_C_W_E);
710 }
711
712 /* Assigning null removes the system data key. SpiderMonkey also stored the
713 value in the object's own slot, so reading the key back gave null;
714 remember such keys to do the same.
715 */
716 [info setValue:OOStringFromJSValue(context, value) forKey:key];
717 [info setNullAssigned:JS_IsNull(value) forKey:key];
718 return true;
719
720 OOJS_EXOTIC_EXIT(context, -1)
721
723}
724
725// *** Fixed properties ***
726
728{
729 OOJS_NATIVE_ENTER(context)
730
731 OOSystemInfo* info = OOJSNativeObjectOfClassFromJSObject(context, this, [OOSystemInfo class]);
732 if (info == nil) {
733 // Let QuickJS handle access to the prototype object (where info will be nil).
734 return JS_UNDEFINED;
735 }
736
737 // What if we're trying to access a saved witchspace systemInfo object?
738 BOOL savedInterstellarInfo = ![UNIVERSE inInterstellarSpace] && [info system] == -1;
739 BOOL sameGalaxy = [PLAYER currentGalaxyID] == [info galaxy];
740
741 switch (magic) {
743 if (sameGalaxy && !savedInterstellarInfo) {
745 } else {
746 OOJSReportError(context, @"Cannot read systemInfo values for %@.", savedInterstellarInfo ? @"invalid interstellar space reference" : @"other galaxies");
747 return OOJSNativeFailure(context);
748 }
749 break;
750
752 if (sameGalaxy && !savedInterstellarInfo) {
754 } else {
755 OOJSReportError(context, @"Cannot read systemInfo values for %@.", savedInterstellarInfo ? @"invalid interstellar space reference" : @"other galaxies");
756 return OOJSNativeFailure(context);
757 }
758 break;
759
761 return JS_NewInt32(context, [info galaxy]);
762
764 return JS_NewInt32(context, [info system]);
765
766 default:
768 return OOJSNativeFailure(context);
769 }
770
772}
773
774// *** Methods ***
775
776// distanceToSystem(sys : SystemInfo) : Number
778{
779 OOJS_NATIVE_ENTER(context)
780
781 OOSystemInfo* thisInfo = nil;
782 OOSystemInfo* otherInfo = nil;
783
784 if (!JSSystemInfoGetSystemInfo(context, OOJS_THIS, &thisInfo))
785 return OOJSNativeFailure(context);
786 // SpiderMonkey version used JS_ValueToObject(); a primitive can't be a SystemInfo anyway.
787 if (argc < 1 || !JS_IsObject(OOJS_ARGV[0]) || !JSSystemInfoGetSystemInfo(context, OOJS_ARGV[0], &otherInfo)) {
788 OOJSReportBadArguments(context, @"SystemInfo", @"distanceToSystem", MIN(argc, 1), OOJS_ARGV, nil, @"system info");
789 return OOJSNativeFailure(context);
790 }
791
792 BOOL sameGalaxy = ([thisInfo galaxy] == [otherInfo galaxy]);
793 if (!sameGalaxy) {
794 OOJSReportErrorForCaller(context, @"SystemInfo", @"distanceToSystem", @"Cannot calculate distance for systems in other galaxies.");
795 return OOJSNativeFailure(context);
796 }
797
798 NSPoint thisCoord = [thisInfo coordinates];
799 NSPoint otherCoord = [otherInfo coordinates];
800
801 OOJS_RETURN_DOUBLE(distanceBetweenPlanetPositions(thisCoord.x, thisCoord.y, otherCoord.x, otherCoord.y));
802
804}
805
806// routeToSystem(sys : SystemInfo [, optimizedBy : String]) : Object
808{
809 OOJS_NATIVE_ENTER(context)
810
811 OOSystemInfo* thisInfo = nil;
812 OOSystemInfo* otherInfo = nil;
813 NSDictionary* result = nil;
815
816 if (!JSSystemInfoGetSystemInfo(context, OOJS_THIS, &thisInfo))
817 return OOJSNativeFailure(context);
818 if (argc < 1 || !JS_IsObject(OOJS_ARGV[0]) || !JSSystemInfoGetSystemInfo(context, OOJS_ARGV[0], &otherInfo)) {
819 OOJSReportBadArguments(context, @"SystemInfo", @"routeToSystem", MIN(argc, 1), OOJS_ARGV, nil, @"system info");
820 return OOJSNativeFailure(context);
821 }
822
823 BOOL sameGalaxy = ([thisInfo galaxy] == [otherInfo galaxy]);
824 if (!sameGalaxy) {
825 OOJSReportErrorForCaller(context, @"SystemInfo", @"routeToSystem", @"Cannot calculate route for destinations in other galaxies.");
826 return OOJSNativeFailure(context);
827 }
828
829 if (argc >= 2) {
830 routeType = StringToRouteType(OOStringFromJSValue(context, OOJS_ARGV[1]));
831 }
832
834 result = [UNIVERSE routeFromSystem:[thisInfo system] toSystem:[otherInfo system] optimizedBy:routeType];
836
837 OOJS_RETURN_OBJECT(result);
838
840}
841
842// samplePrice(commodity)
844{
845 OOJS_NATIVE_ENTER(context)
846
847 OOSystemInfo* thisInfo = nil;
848
849 if (!JSSystemInfoGetSystemInfo(context, OOJS_THIS, &thisInfo))
850 return OOJSNativeFailure(context);
851 OOCommodityType commodity = OOStringFromJSValue(context, OOJS_ARGV[0]);
852 if (EXPECT_NOT(![[UNIVERSE commodities] goodDefined:commodity])) {
853 OOJSReportBadArguments(context, @"SystemInfo", @"samplePrice", MIN(argc, 1), OOJS_ARGV, NULL, @"Unrecognised commodity type");
854 return OOJSNativeFailure(context);
855 }
856
857 BOOL sameGalaxy = ([thisInfo galaxy] == [PLAYER galaxyNumber]);
858 if (!sameGalaxy) {
859 OOJSReportErrorForCaller(context, @"SystemInfo", @"samplePrice", @"Cannot calculate sample price for destinations in other galaxies.");
860 return OOJSNativeFailure(context);
861 }
862
863 OOCreditsQuantity price = [[UNIVERSE commodities] samplePriceForCommodity:commodity inEconomy:[[thisInfo valueForKey:@"economy"] intValue] withScript:[thisInfo valueForKey:@"commodity_script"] inSystem:[thisInfo system]];
864
865 return JS_NewNumber(context, price);
866
868}
869
871{
872 OOJS_NATIVE_ENTER(context)
873
874 OOSystemInfo* thisInfo = nil;
875
876 if (!JSSystemInfoGetSystemInfo(context, OOJS_THIS, &thisInfo))
877 return OOJSNativeFailure(context);
878
879 NSString* property = nil;
880 id value = nil;
881 NSString* manifest = nil;
882
883 int32_t iValue;
884
885 if (argc < 3) {
886 OOJSReportBadArguments(context, @"SystemInfo", @"setProperty", MIN(argc, 3), OOJS_ARGV, NULL, @"setProperty(layer, property, value [,manifest])");
887 return OOJSNativeFailure(context);
888 }
889 if (!OOJSValueToInt32(context, OOJS_ARGV[0], &iValue)) {
890 OOJSReportBadArguments(context, @"SystemInfo", @"setProperty", MIN(argc, 3), OOJS_ARGV, NULL, @"setProperty(layer, property, value [,manifest])");
891 return OOJSNativeFailure(context);
892 }
893 if (iValue < 0 || iValue >= OO_SYSTEM_LAYERS) {
894 OOJSReportBadArguments(context, @"SystemInfo", @"setProperty", MIN(argc, 3), OOJS_ARGV, NULL, @"layer must be 0, 1, 2 or 3");
895 return OOJSNativeFailure(context);
896 }
897 OOSystemLayer layer = (OOSystemLayer)iValue;
898
899 property = OOStringFromJSValue(context, OOJS_ARGV[1]);
900 if (!JS_IsNull(OOJS_ARGV[2])) {
901 value = OOJSNativeObjectFromJSValue(context, OOJS_ARGV[2]);
902 }
903 if (argc >= 4) {
904 manifest = OOStringFromJSValue(context, OOJS_ARGV[3]);
905 } else {
906 manifest = [[OOJSScript currentlyRunningScript] propertyNamed:kLocalManifestProperty];
907 }
908
909 [UNIVERSE setSystemDataForGalaxy:[thisInfo galaxy] planet:[thisInfo system] key:property value:value fromManifest:manifest forLayer:layer];
910
912
914}
915
916// filteredSystems(this : Object, predicate : Function) : Array
918{
919 OOJS_NATIVE_ENTER(context)
920
921 /* SpiderMonkey version converted the this argument with
922 JS_ValueToObject(). QuickJS performs the same conversion (and
923 null/undefined -> global object) when calling a non-strict
924 function, so it is passed through unchanged.
925 */
926 // Get this and predicate arguments
927 if (argc < 2 || !OOJSValueIsFunction(context, OOJS_ARGV[1])) {
928 OOJSReportBadArguments(context, @"SystemInfo", @"filteredSystems", argc, OOJS_ARGV, nil, @"this and predicate function");
929 return OOJSNativeFailure(context);
930 }
931 JSValueConst jsThis = OOJS_ARGV[0];
932 JSValueConst predicate = OOJS_ARGV[1];
933
934 NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
935 NSMutableArray* result = [NSMutableArray arrayWithCapacity:256];
936 JSValue rval = JS_UNDEFINED;
937
938 // Not OOJS_BEGIN_FULL_NATIVE() - we use JSAPI while paused.
940
941 // Iterate over systems.
942 BOOL OK = result != nil;
943 OOGalaxyID galaxy = [PLAYER currentGalaxyID];
945 for (system = 0; system <= kOOMaximumSystemID; system++) {
946 // NOTE: this deliberately bypasses the cache, since iteration is inherently unfriendly to a single-item cache.
947 OOSystemInfo* info = [[[OOSystemInfo alloc] initWithGalaxy:galaxy system:system] autorelease];
948 JSValue args[1] = { OOJSValueFromNativeObject(context, info) };
949
951 JSValue callResult = JS_Call(context, predicate, jsThis, 1, (JSValueConst*)args);
953 JS_FreeValue(context, args[0]);
954
955 // On exception, it is left pending and propagated to our caller, as before.
956 OK = !JS_IsException(callResult);
957
958 if (OK) {
959 int boolVal = JS_ToBool(context, callResult);
960 if (boolVal > 0) {
961 [result addObject:info];
962 } else if (boolVal < 0) {
963 JS_FreeValue(context, JS_GetException(context));
964 }
965 }
966 JS_FreeValue(context, callResult);
967
968 if (!OK)
969 break;
970 }
971
972 if (OK) {
973 rval = [result oo_jsValueInContext:context];
974 } else {
975 rval = OOJSNativeFailure(context);
976 }
977
978 [pool release];
979
981 return rval;
982
984}
985
987{
988 OOJS_NATIVE_ENTER(context)
989
990 NSString* property = nil;
991 id value = nil;
992 NSString* manifest = nil;
993
994 int32_t iValue;
995 OOGalaxyID g;
996 OOSystemID s1, s2;
997
998 if (argc < 6) {
999 OOJSReportBadArguments(context, @"SystemInfo", @"setInterstellarProperty", MIN(argc, 3), OOJS_ARGV, NULL, @"setProperty(galaxy, fromsystem, tosystem, layer, property, value [,manifest])");
1000 return OOJSNativeFailure(context);
1001 }
1002 if (!OOJSValueToInt32(context, OOJS_ARGV[0], &iValue)) {
1003 OOJSReportBadArguments(context, @"SystemInfo", @"setInterstellarProperty", MIN(argc, 3), OOJS_ARGV, NULL, @"setProperty(galaxy, fromsystem, tosystem, layer, property, value [,manifest])");
1004 return OOJSNativeFailure(context);
1005 }
1006 if (iValue < 0 || iValue > kOOMaximumGalaxyID) {
1007 OOJSReportBadArguments(context, @"SystemInfo", @"setInterstellarProperty", MIN(argc, 3), OOJS_ARGV, NULL, @"galaxy out of range");
1008 return OOJSNativeFailure(context);
1009 } else {
1010 g = (OOGalaxyID)iValue;
1011 }
1012
1013 if (!OOJSValueToInt32(context, OOJS_ARGV[1], &iValue)) {
1014 OOJSReportBadArguments(context, @"SystemInfo", @"setInterstellarProperty", MIN(argc, 3), OOJS_ARGV, NULL, @"setProperty(galaxy, fromsystem, tosystem, layer, property, value [,manifest])");
1015 return OOJSNativeFailure(context);
1016 }
1017 if (iValue < 0 || iValue > kOOMaximumSystemID) {
1018 OOJSReportBadArguments(context, @"SystemInfo", @"setInterstellarProperty", MIN(argc, 3), OOJS_ARGV, NULL, @"fromsystem out of range");
1019 return OOJSNativeFailure(context);
1020 } else {
1021 s1 = (OOSystemID)iValue;
1022 }
1023
1024 if (!OOJSValueToInt32(context, OOJS_ARGV[2], &iValue)) {
1025 OOJSReportBadArguments(context, @"SystemInfo", @"setInterstellarProperty", MIN(argc, 3), OOJS_ARGV, NULL, @"setProperty(galaxy, fromsystem, tosystem, layer, property, value [,manifest])");
1026 return OOJSNativeFailure(context);
1027 }
1028 if (iValue < 0 || iValue > kOOMaximumSystemID) {
1029 OOJSReportBadArguments(context, @"SystemInfo", @"setInterstellarProperty", MIN(argc, 3), OOJS_ARGV, NULL, @"tosystem out of range");
1030 return OOJSNativeFailure(context);
1031 } else {
1032 s2 = (OOSystemID)iValue;
1033 }
1034
1035 if (!OOJSValueToInt32(context, OOJS_ARGV[3], &iValue)) {
1036 OOJSReportBadArguments(context, @"SystemInfo", @"setInterstellarProperty", MIN(argc, 3), OOJS_ARGV, NULL, @"setProperty(galaxy, fromsystem, tosystem, layer, property, value [,manifest])");
1037 return OOJSNativeFailure(context);
1038 }
1039 if (iValue < 0 || iValue >= OO_SYSTEM_LAYERS) {
1040 OOJSReportBadArguments(context, @"SystemInfo", @"setInterstellarProperty", MIN(argc, 3), OOJS_ARGV, NULL, @"layer must be 0, 1, 2 or 3");
1041 return OOJSNativeFailure(context);
1042 }
1043 OOSystemLayer layer = (OOSystemLayer)iValue;
1044
1045 property = OOStringFromJSValue(context, OOJS_ARGV[4]);
1046 if (!JS_IsNull(OOJS_ARGV[5])) {
1047 value = OOJSNativeObjectFromJSValue(context, OOJS_ARGV[5]);
1048 }
1049 if (argc >= 7) {
1050 manifest = OOStringFromJSValue(context, OOJS_ARGV[6]);
1051 } else {
1052 manifest = [[OOJSScript currentlyRunningScript] propertyNamed:kLocalManifestProperty];
1053 }
1054
1055 NSString* key = [NSString stringWithFormat:@"interstellar: %u %u %u", g, s1, s2];
1056
1057 [[UNIVERSE systemManager] setProperty:property forSystemKey:key andLayer:layer toValue:value fromManifest:manifest];
1058
1060
1062}
OORouteType StringToRouteType(NSString *string)
#define EXPECT_NOT(x)
BOOL OOIsNumberLiteral(NSString *string, BOOL allowSpaces)
#define OOJS_PROFILE_EXIT
#define OOJS_PROFILE_EXIT_VOID
#define OOJS_END_FULL_NATIVE
#define OOJS_BEGIN_FULL_NATIVE(context)
#define OOJS_NATIVE_ENTER(cx)
#define OOJS_NATIVE_EXIT
#define OOJS_PROFILE_ENTER
void InitOOJSSystemInfo(JSContext *context, JSObject *global)
jsval GetJSSystemInfoForSystem(JSContext *context, OOGalaxyID galaxy, OOSystemID system)
static JSBool SystemInfoDistanceToSystem(JSContext *context, uintN argc, jsval *vp)
static OOSystemID sCachedSystem
static JSBool SystemInfoStaticFilteredSystems(JSContext *context, uintN argc, jsval *vp)
static JSBool SystemInfoRouteToSystem(JSContext *context, uintN argc, jsval *vp)
static JSPropertySpec sSystemInfoProperties[]
static JSObject * sCachedSystemInfo
static JSFunctionSpec sSystemInfoStaticMethods[]
static JSBool SystemInfoStaticSetInterstellarProperty(JSContext *context, uintN argc, jsval *vp)
static JSBool SystemInfoSetPropertyMethod(JSContext *context, uintN argc, jsval *vp)
@ kSystemInfo_systemID
@ kSystemInfo_coordinates
@ kSystemInfo_internalCoordinates
@ kSystemInfo_galaxyID
static JSBool SystemInfoGetProperty(JSContext *context, JSObject *this, jsid propID, jsval *value)
static JSClass sSystemInfoClass
static void SystemInfoFinalize(JSContext *context, JSObject *this)
static OOGalaxyID sCachedGalaxy
static JSFunctionSpec sSystemInfoMethods[]
static JSBool SystemInfoSamplePrice(JSContext *context, uintN argc, jsval *vp)
BOOL NSPointToVectorJSValue(JSContext *context, NSPoint point, jsval *outValue) NONNULL_FUNC
Definition OOJSVector.m:328
void OOJSPauseTimeLimiter(void)
id OOJSNativeObjectFromJSValue(JSContext *context, jsval value)
void OOJSReportWarning(JSContext *context, NSString *format,...)
#define OOJS_THIS
#define OOJS_RETURN_WITH_HELPER(helper, value)
JSBool OOJSObjectWrapperToString(JSContext *context, uintN argc, jsval *vp)
#define OOJS_PROP_HIDDEN_READONLY_CB
void OOJSRegisterObjectConverter(JSClass *theClass, OOJSClassConverterCallback converter)
#define OOJS_RETURN_DOUBLE(value)
OOINLINE jsval OOJSValueFromNativeObject(JSContext *context, id object)
#define DEFINE_JS_OBJECT_GETTER(NAME, JSCLASS, JSPROTO, OBJCCLASSNAME)
void OOJSObjectWrapperFinalize(JSContext *context, JSObject *this)
#define OOJS_RETURN_OBJECT(o)
void OOJSReportBadPropertySelector(JSContext *context, JSObject *thisObj, jsid propID, JSPropertySpec *propertySpec)
void OOJSReportErrorForCaller(JSContext *context, NSString *scriptClass, NSString *function, NSString *format,...)
OOINLINE BOOL OOJSValueToInt32(JSContext *context, jsval value, int32_t *outValue)
NSString * OOStringFromJSValue(JSContext *context, jsval value)
JSBool OOJSUnconstructableConstruct(JSContext *context, uintN argc, jsval *vp)
OOINLINE BOOL OOJSValueIsFunction(JSContext *context, jsval value)
OOINLINE JSContext * OOJSAcquireContext(void)
void OOJSReportError(JSContext *context, NSString *format,...)
#define OOJS_ARGV
id OOJSBasicPrivateObjectConverter(JSContext *context, JSObject *object)
void OOJSReportBadArguments(JSContext *context, NSString *scriptClass, NSString *function, uintN argc, jsval *argv, NSString *message, NSString *expectedArgsDescription)
void OOJSResumeTimeLimiter(void)
#define OOJS_RETURN_VOID
id OOJSNativeObjectOfClassFromJSObject(JSContext *context, JSObject *object, Class requiredClass)
#define OOJS_RETURN_VECTOR(value)
#define MIN(A, B)
Definition OOMaths.h:91
unsigned count
return nil
#define OO_SYSTEM_LAYERS
@ kOOMaximumSystemID
Definition OOTypes.h:187
@ kOOMaximumGalaxyID
Definition OOTypes.h:186
@ kOOMinimumSystemID
Definition OOTypes.h:188
NSString * OOCommodityType
Definition OOTypes.h:97
OORouteType
Definition OOTypes.h:31
@ OPTIMIZED_BY_JUMPS
Definition OOTypes.h:33
uint64_t OOCreditsQuantity
Definition OOTypes.h:160
int16_t OOSystemID
Definition OOTypes.h:183
uint8_t OOGalaxyID
Definition OOTypes.h:182
Vector OOGalacticCoordinatesFromInternal(NSPoint internalCoordinates)
#define OOJS_EXOTIC_EXIT(context, failure)
static int SystemInfoExoticGetOwnPropertyNames(JSContext *context, JSPropertyEnum **ptab, uint32_t *plen, JSValueConst obj)
static JSClassID sSystemInfoClassID
#define OOJS_EXOTIC_ENTER
static int SystemInfoExoticDeleteProperty(JSContext *context, JSValueConst obj, JSAtom prop)
static NSString * SystemInfoKeyForAtom(JSContext *context, JSAtom prop)
static int SystemInfoSetOnPrototypeChain(JSContext *context, JSValueConst obj, JSAtom prop, JSValueConst value, JSValueConst receiver, int flags, BOOL *outHandled)
static JSValue SystemInfoExoticGetProperty(JSContext *context, JSValueConst obj, JSAtom prop, JSValueConst receiver)
static JSValue sCachedSystemInfo
static int SystemInfoExoticSetProperty(JSContext *context, JSValueConst obj, JSAtom prop, JSValueConst value, JSValueConst receiver, int flags)
static int SystemInfoExoticGetOwnProperty(JSContext *context, JSPropertyDescriptor *desc, JSValueConst obj, JSAtom prop)
static JSClassExoticMethods sSystemInfoExoticMethods
static BOOL SystemInfoGetSystemDataValue(JSContext *context, OOSystemInfo *info, NSString *key, JSValue *outValue)
static OOSystemInfo * SystemInfoForObject(JSValueConst obj)
JSValue OOJSNativeFailure(JSContext *context)
JSClassID OOJSRegisterClass(JSClassID *ioClassID, const JSClassDef *classDef)
Definition OOJSClasses.m:61
int OOJSGetSharedPermanentOwnProperty(JSContext *context, JSPropertyDescriptor *desc, JSValueConst object, JSAtom prop)
JSValueConst OOJSInitClass(JSContext *context, JSValueConst global, JSClassID classID, JSValueConst parentPrototype, JSCFunction *constructor, int constructorArgCount, const JSCFunctionListEntry *properties, size_t propertyCount, const JSCFunctionListEntry *methods, size_t methodCount, const JSCFunctionListEntry *staticMethods, size_t staticMethodCount)
#define OOJS_GETTER_ARGS
#define OOJS_NATIVE_ARGS
#define OOJS_COUNT(array)
#define UNIVERSE
Definition Universe.h:827
OOCreditsQuantity samplePriceForCommodity:inEconomy:withScript:inSystem:(OOCommodityType commodity,[inEconomy] OOEconomyID economy,[withScript] NSString *scriptName,[inSystem] OOSystemID system)
id propertyNamed:(NSString *name)
Definition OOJSScript.m:431
OOJSScript * currentlyRunningScript()
Definition OOJSScript.m:101
id getProperty:forSystem:inGalaxy:(NSString *property,[forSystem] OOSystemID s,[inGalaxy] OOGalaxyID g)
NSString * _planetKey
id valueForKey:(NSString *key)
OOSystemID system()
NSPoint coordinates()
OOSystemID _system
OOGalaxyID _galaxy
NSMutableSet * _nullAssignedKeys
OOGalaxyID galaxy()
NSArray * allKeys()
NSString * oo_jsClassName()
NSString * descriptionComponents()
NSUInteger hash()
void setNullAssigned:forKey:(BOOL flag,[forKey] NSString *key)
void setValue:forKey:(id value,[forKey] NSString *key)
NSString * shortDescriptionComponents()
OOINLINE double distanceBetweenPlanetPositions(int x1, int y1, int x2, int y2) INLINE_CONST_FUNC