Oolite
Loading...
Searching...
No Matches
OOJSFrameCallbacks.m
Go to the documentation of this file.
1/*
2
3OOJSFrameCallbacks.m
4
5
6Copyright (C) 2011-2013 Jens Ayton
7
8Permission is hereby granted, free of charge, to any person obtaining a copy
9of this software and associated documentation files (the "Software"), to deal
10in the Software without restriction, including without limitation the rights
11to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12copies of the Software, and to permit persons to whom the Software is
13furnished to do so, subject to the following conditions:
14
15The above copyright notice and this permission notice shall be included in all
16copies or substantial portions of the Software.
17
18THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24SOFTWARE.
25
26*/
27
31
32/*
33 By default, tracking IDs are scrambled to discourage people from trying to
34 be clever or making assumptions about them. If DEBUG_FCB_SIMPLE_TRACKING_IDS
35 is non-zero, tracking IDs starting from 1 and rising monotonously are used
36 instead. Additionally, the next ID is reset to 1 when all frame callbacks
37 are removed.
38*/
39#ifndef DEBUG_FCB_SIMPLE_TRACKING_IDS
40#define DEBUG_FCB_SIMPLE_TRACKING_IDS 0
41#endif
42
43#ifndef DEBUG_FCB_VERBOSE_LOGGING
44#define DEBUG_FCB_VERBOSE_LOGGING 0
45#endif
46
47#if defined(NDEBUG) && DEBUG_FCB_SIMPLE_TRACKING_IDS
48#error Deployment builds may not be built with DEBUG_FCB_SIMPLE_TRACKING_IDS.
49#endif
50
51#if DEBUG_FCB_VERBOSE_LOGGING
52#define FCBLog OOLog
53#define FCBLogIndentIf OOLogIndentIf
54#define FCBLogOutdentIf OOLogOutdentIf
55#else
56#define FCBLog(...) \
57 do { \
58 } while (0)
59#define FCBLogIndentIf(key) \
60 do { \
61 } while (0)
62#define FCBLogOutdentIf(key) \
63 do { \
64 } while (0)
65#endif
66
67enum {
69
70#if DEBUG_FCB_SIMPLE_TRACKING_IDS
72 kIDIncrement = 1
73#else
74 kIDScrambleMask = 0x2315EB16, // Just a random number.
75 kIDIncrement = 992699 // A large prime number, to produce a non-obvious sequence which still uses all 2^32 values.
76#endif
77};
78
79typedef struct
80{
81 jsval callback;
82 uint32 trackingID;
83 uint32 _padding;
85
87static NSUInteger sCount; // Number of slots in use.
88static NSUInteger sSpace; // Number of slots allocated.
89static NSUInteger sHighWaterMark; // Number of slots which are GC roots.
90static NSMutableArray* sDeferredOps; // Deferred adds/removes while running.
91static uint32 sNextID;
92static BOOL sRunning;
93
94// Methods
95static JSBool GlobalAddFrameCallback(JSContext* context, uintN argc, jsval* vp);
96static JSBool GlobalRemoveFrameCallback(JSContext* context, uintN argc, jsval* vp);
97static JSBool GlobalIsValidFrameCallback(JSContext* context, uintN argc, jsval* vp);
98
99// Internals
100static BOOL AddCallback(JSContext* context, jsval callback, uint32 trackingID, NSString** errorString);
101static BOOL GrowCallbackList(JSContext* context, NSString** errorString);
102
103static BOOL GetIndexForTrackingID(uint32 trackingID, NSUInteger* outIndex);
104
105static BOOL RemoveCallbackWithTrackingID(JSContext* context, uint32 trackingID);
106static void RemoveCallbackAtIndex(JSContext* context, NSUInteger index);
107
108static void QueueDeferredOperation(NSString* opType, uint32 trackingID, OOJSValue* value);
109static void RunDeferredOperations(JSContext* context);
110
111// MARK: Public
112
113void InitOOJSFrameCallbacks(JSContext* context, JSObject* global)
114{
115 JS_DefineFunction(context, global, "addFrameCallback", GlobalAddFrameCallback, 1, OOJS_METHOD_READONLY);
116 JS_DefineFunction(context, global, "removeFrameCallback", GlobalRemoveFrameCallback, 1, OOJS_METHOD_READONLY);
117 JS_DefineFunction(context, global, "isValidFrameCallback", GlobalIsValidFrameCallback, 1, OOJS_METHOD_READONLY);
118
119#if DEBUG_FCB_SIMPLE_TRACKING_IDS
120 sNextID = 1;
121#else
122 // Set randomish initial ID to catch bad habits.
123 sNextID = [[NSDate date] timeIntervalSinceReferenceDate];
124#endif
125}
126
128{
129 NSCAssert1(!sRunning, @"%s cannot be called while frame callbacks are running.", __PRETTY_FUNCTION__);
130
131 if (sCount != 0) {
132 const OOTimeDelta delta = inDeltaT * [UNIVERSE timeAccelerationFactor];
133 JSContext* context = OOJSAcquireContext();
134 jsval deltaVal, result;
135 NSUInteger i;
136
137 if (EXPECT(JS_NewNumberValue(context, delta, &deltaVal))) {
138 // Block mutations.
139 sRunning = YES;
140
141 /*
142 The watchdog timer only fires once per second in deployment builds,
143 but in testrelease builds at least we can keep them on a short leash.
144 */
146
147 for (i = 0; i < sCount; i++) {
148 // TODO: remove out of scope callbacks - post MNSR!
149 JS_CallFunctionValue(context, NULL, sCallbacks[i].callback, 1, &deltaVal, &result);
150 JS_ReportPendingException(context);
151 }
152
154 sRunning = NO;
155
156 if (EXPECT_NOT(sDeferredOps != NULL)) {
157 RunDeferredOperations(context);
159 }
160 }
161 OOJSRelinquishContext(context);
162 }
163}
164
166{
167 NSCAssert1(!sRunning, @"%s cannot be called while frame callbacks are running.", __PRETTY_FUNCTION__);
168
169 if (sCount != 0) {
170 JSContext* context = OOJSAcquireContext();
171 while (sCount != 0)
172 RemoveCallbackAtIndex(context, sCount - 1);
173 OOJSRelinquishContext(context);
174 }
175}
176
177// MARK: Methods
178
179// addFrameCallback(callback : Function) : Number
180static JSBool GlobalAddFrameCallback(JSContext* context, uintN argc, jsval* vp)
181{
182 OOJS_NATIVE_ENTER(context)
183
184 // Get callback argument and verify that it's a function.
185 jsval callback = OOJS_ARGV[0];
186 if (EXPECT_NOT(argc < 1 || !OOJSValueIsFunction(context, callback))) {
187 OOJSReportBadArguments(context, nil, @"addFrameCallback", MIN(argc, 1U), OOJS_ARGV, nil, @"function");
188 return NO;
189 }
190
191 // Assign a tracking ID.
192 uint32 trackingID = sNextID ^ kIDScrambleMask;
194
195 if (EXPECT(!sRunning)) {
196 // Add to list immediately.
197 NSString* errorString = nil;
198 if (EXPECT_NOT(!AddCallback(context, callback, trackingID, &errorString))) {
199 OOJSReportError(context, @"%@", errorString);
200 return NO;
201 }
202 } else {
203 // Defer mutations during callback invocation.
204 FCBLog(@"script.frameCallback.debug.add.deferred", @"Deferring addition of frame callback with tracking ID %u.", trackingID);
205 QueueDeferredOperation(@"add", trackingID, [OOJSValue valueWithJSValue:callback inContext:context]);
206 }
207
208 OOJS_RETURN_INT(trackingID);
209
211}
212
213// removeFrameCallback(trackingID : Number)
214static JSBool GlobalRemoveFrameCallback(JSContext* context, uintN argc, jsval* vp)
215{
216 OOJS_NATIVE_ENTER(context)
217
218 // Get tracking ID argument.
219 uint32 trackingID;
220 if (EXPECT_NOT(argc < 1 || !JS_ValueToECMAUint32(context, OOJS_ARGV[0], &trackingID))) {
221 OOJSReportBadArguments(context, nil, @"removeFrameCallback", MIN(argc, 1U), OOJS_ARGV, nil, @"frame callback tracking ID");
222 return NO;
223 }
224
225 if (EXPECT(!sRunning)) {
226 // Remove it.
227 if (EXPECT_NOT(!RemoveCallbackWithTrackingID(context, trackingID))) {
228 OOJSReportWarning(context, @"removeFrameCallback(): invalid tracking ID.");
229 }
230 } else {
231 // Defer mutations during callback invocation.
232 FCBLog(@"script.frameCallback.debug.remove.deferred", @"Deferring removal of frame callback with tracking ID %u.", trackingID);
233 QueueDeferredOperation(@"remove", trackingID, nil);
234 }
235
237
239}
240
241// isValidFrameCallback(trackingID : Number)
242static JSBool GlobalIsValidFrameCallback(JSContext* context, uintN argc, jsval* vp)
243{
244 OOJS_NATIVE_ENTER(context)
245
246 if (EXPECT_NOT(argc < 1)) {
247 OOJSReportBadArguments(context, nil, @"isValidFrameCallback", 0, OOJS_ARGV, nil, @"frame callback tracking ID");
248 return NO;
249 }
250
251 // Get tracking ID argument.
252 uint32 trackingID;
253 if (EXPECT_NOT(!JS_ValueToECMAUint32(context, OOJS_ARGV[0], &trackingID))) {
255 }
256
257 NSUInteger index;
258 OOJS_RETURN_BOOL(GetIndexForTrackingID(trackingID, &index));
259
261}
262
263// MARK: Internals
264
265static BOOL AddCallback(JSContext* context, jsval callback, uint32 trackingID, NSString** errorString)
266{
267 NSCParameterAssert(context != NULL && JS_IsInRequest(context));
268 NSCParameterAssert(errorString != NULL);
269 NSCAssert1(!sRunning, @"%s cannot be called while frame callbacks are running.", __PRETTY_FUNCTION__);
270
271 if (EXPECT_NOT(sCount == sSpace)) {
272 if (!GrowCallbackList(context, errorString))
273 return NO;
274 }
275
276 FCBLog(@"script.frameCallback.debug.add", @"Adding frame callback with tracking ID %u.", trackingID);
277
278 sCallbacks[sCount].callback = callback;
279 if (sCount >= sHighWaterMark) {
280 // If we haven't used this slot before, root it.
281
282 if (EXPECT_NOT(!OOJSAddGCValueRoot(context, &sCallbacks[sCount].callback, "frame callback"))) {
283 *errorString = @"Failed to add GC root for frame callback.";
284 return NO;
285 }
286
288 }
289
290 sCallbacks[sCount].trackingID = trackingID;
291 sCount++;
292
293 return YES;
294}
295
296static BOOL GrowCallbackList(JSContext* context, NSString** errorString)
297{
298 NSCParameterAssert(context != NULL && JS_IsInRequest(context));
299 NSCParameterAssert(errorString != NULL);
300
301 NSUInteger newSpace = MAX(sSpace * 2, (NSUInteger)kMinCount);
302
303 CallbackEntry* newCallbacks = calloc(sizeof(CallbackEntry), newSpace);
304 if (newCallbacks == NULL)
305 return NO;
306
307 CallbackEntry* oldCallbacks = sCallbacks;
308
309 // Root and copy occupied slots.
310 NSUInteger newHighWaterMark = sCount;
311 NSUInteger i;
312 for (i = 0; i < newHighWaterMark; i++) {
313 if (EXPECT_NOT(!OOJSAddGCValueRoot(context, &newCallbacks[i].callback, "frame callback"))) {
314 // If we can't root them all, we fail; unroot all entries to date, free the buffer and return NO.
315 NSUInteger j;
316 for (j = 0; j < i; j++) {
317 JS_RemoveValueRoot(context, &newCallbacks[j].callback);
318 }
319 free(newCallbacks);
320
321 *errorString = @"Failed to add GC root for frame callback.";
322 return NO;
323 }
324 newCallbacks[i] = oldCallbacks[i];
325 }
326
327 // Unroot old array's slots.
328 for (i = 0; i < sHighWaterMark; i++) {
329 JS_RemoveValueRoot(context, &oldCallbacks[i].callback);
330 }
331
332 // We only rooted the occupied slots, so reset high water mark.
333 sHighWaterMark = newHighWaterMark;
334
335 // Replace array.
336 sCallbacks = newCallbacks;
337 free(oldCallbacks);
338 sSpace = newSpace;
339
340 return YES;
341}
342
343static BOOL GetIndexForTrackingID(uint32 trackingID, NSUInteger* outIndex)
344{
345 NSCParameterAssert(outIndex != NULL);
346
347 /* It is assumed that few frame callbacks will be active at once, so a
348 linear search is reasonable. If they become unexpectedly popular, we
349 can switch to a sorted list or a separate lookup table without changing
350 the API.
351 */
352 NSUInteger i;
353 for (i = 0; i < sCount; i++) {
354 if (sCallbacks[i].trackingID == trackingID) {
355 *outIndex = i;
356 return YES;
357 }
358 }
359
360 return NO;
361}
362
363static BOOL RemoveCallbackWithTrackingID(JSContext* context, uint32 trackingID)
364{
365 NSCParameterAssert(context != NULL && JS_IsInRequest(context));
366 NSCAssert1(!sRunning, @"%s cannot be called while frame callbacks are running.", __PRETTY_FUNCTION__);
367
368 NSUInteger index = 0;
369 if (GetIndexForTrackingID(trackingID, &index)) {
370 RemoveCallbackAtIndex(context, index);
371 return YES;
372 }
373
374 return NO;
375}
376
377static void RemoveCallbackAtIndex(JSContext* context, NSUInteger index)
378{
379 NSCParameterAssert(context != NULL && JS_IsInRequest(context));
380 NSCParameterAssert(index < sCount && sCallbacks != NULL);
381 NSCAssert1(!sRunning, @"%s cannot be called while frame callbacks are running.", __PRETTY_FUNCTION__);
382
383 FCBLog(@"script.frameCallback.debug.remove", @"Removing frame callback with tracking ID %u.", sCallbacks[index].trackingID);
384
385 // Overwrite entry to be removed with last entry, and decrement count.
386 sCount--;
387 sCallbacks[index] = sCallbacks[sCount];
388 sCallbacks[sCount].callback = JSVAL_NULL;
389
390#if DEBUG_FCB_SIMPLE_TRACKING_IDS
391 if (sCount == 0) {
392 OOLog(@"script.frameCallback.debug.reset", @"All frame callbacks removed, resetting next ID to 1.");
393 sNextID = 1;
394 }
395#endif
396}
397
398static void QueueDeferredOperation(NSString* opType, uint32 trackingID, OOJSValue* value)
399{
400 NSCAssert1(sRunning, @"%s can only be called while frame callbacks are running.", __PRETTY_FUNCTION__);
401
402 if (sDeferredOps == nil)
403 sDeferredOps = [[NSMutableArray alloc] init];
404 [sDeferredOps addObject:[NSDictionary dictionaryWithObjectsAndKeys:
405 opType, @"operation",
406 [NSNumber numberWithInt:trackingID], @"trackingID",
407 value, @"value",
408 nil]];
409}
410
411static void RunDeferredOperations(JSContext* context)
412{
413 NSDictionary* operation = nil;
414
415 FCBLog(@"script.frameCallback.debug.run-deferred", @"Running %zu deferred frame callback operations.", (long)[sDeferredOps count]);
416 FCBLogIndentIf(@"script.frameCallback.debug.run-deferred");
417
418 foreach (operation, sDeferredOps) {
419 NSString* opType = [operation objectForKey:@"operation"];
420 uint32 trackingID = [operation oo_intForKey:@"trackingID"];
421
422 if ([opType isEqualToString:@"add"]) {
423 OOJSValue* callbackObj = [operation objectForKey:@"value"];
424 NSString* errorString = nil;
425
426 if (!AddCallback(context, OOJSValueFromNativeObject(context, callbackObj), trackingID, &errorString)) {
427 OOLogWARN(@"script.frameCallback.deferredAdd.failed", @"Deferred frame callback insertion failed: %@", errorString);
428 }
429 } else if ([opType isEqualToString:@"remove"]) {
430 RemoveCallbackWithTrackingID(context, trackingID);
431 }
432 }
433
434 FCBLogOutdentIf(@"script.frameCallback.debug.run-deferred");
435}
#define DESTROY(x)
#define EXPECT_NOT(x)
#define EXPECT(x)
#define OOJS_NATIVE_ENTER(cx)
#define OOJS_NATIVE_EXIT
#define OOJSStopTimeLimiter()
#define OOJSStartTimeLimiterWithTimeLimit(limit)
void InitOOJSFrameCallbacks(JSContext *context, JSObject *global)
static JSBool GlobalAddFrameCallback(JSContext *context, uintN argc, jsval *vp)
static void RemoveCallbackAtIndex(JSContext *context, NSUInteger index)
#define FCBLog(...)
#define FCBLogOutdentIf(key)
static uint32 sNextID
static BOOL RemoveCallbackWithTrackingID(JSContext *context, uint32 trackingID)
static BOOL GetIndexForTrackingID(uint32 trackingID, NSUInteger *outIndex)
static NSUInteger sCount
@ kIDIncrement
@ kMinCount
@ kIDScrambleMask
void OOJSFrameCallbacksRemoveAll(void)
static NSUInteger sHighWaterMark
static void QueueDeferredOperation(NSString *opType, uint32 trackingID, OOJSValue *value)
#define FCBLogIndentIf(key)
static BOOL sRunning
void OOJSFrameCallbacksInvoke(OOTimeDelta inDeltaT)
static CallbackEntry * sCallbacks
static BOOL AddCallback(JSContext *context, jsval callback, uint32 trackingID, NSString **errorString)
static NSUInteger sSpace
static JSBool GlobalRemoveFrameCallback(JSContext *context, uintN argc, jsval *vp)
static BOOL GrowCallbackList(JSContext *context, NSString **errorString)
static void RunDeferredOperations(JSContext *context)
static NSMutableArray * sDeferredOps
static JSBool GlobalIsValidFrameCallback(JSContext *context, uintN argc, jsval *vp)
void OOJSReportWarning(JSContext *context, NSString *format,...)
#define JS_IsInRequest(context)
OOINLINE jsval OOJSValueFromNativeObject(JSContext *context, id object)
#define OOJS_RETURN_BOOL(v)
OOINLINE BOOL OOJSValueIsFunction(JSContext *context, jsval value)
OOINLINE JSContext * OOJSAcquireContext(void)
void OOJSReportError(JSContext *context, NSString *format,...)
#define OOJS_ARGV
OOINLINE void OOJSRelinquishContext(JSContext *context)
void OOJSReportBadArguments(JSContext *context, NSString *scriptClass, NSString *function, uintN argc, jsval *argv, NSString *message, NSString *expectedArgsDescription)
#define OOJSAddGCValueRoot(context, root, name)
#define OOJS_RETURN_VOID
#define OOJS_RETURN_INT(v)
#define OOJS_METHOD_READONLY
#define OOLogWARN(class, format,...)
Definition OOLogging.h:126
#define OOLog(class, format,...)
Definition OOLogging.h:84
#define MAX(A, B)
Definition OOMaths.h:94
#define MIN(A, B)
Definition OOMaths.h:91
unsigned count
return nil
double OOTimeDelta
Definition OOTypes.h:193