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 JSValue callback; // Owned.
82 uint32_t trackingID;
83 uint32_t _padding;
85
86/* SpiderMonkey needed each slot to be a GC root. With QuickJS, each occupied
87 slot simply owns a reference to its callback, which is freed when the
88 callback is removed. OOJavaScriptEngine calls OOJSFrameCallbacksRemoveAll()
89 before resetting or shutting down, so no reset observer is needed.
90*/
92static NSUInteger sCount; // Number of slots in use.
93static NSUInteger sSpace; // Number of slots allocated.
94static NSMutableArray* sDeferredOps; // Deferred adds/removes while running.
95static uint32_t sNextID;
96static BOOL sRunning;
97
98// Methods
102
103// Internals
104static BOOL AddCallback(JSContext* context, JSValueConst callback, uint32_t trackingID, NSString** errorString);
105static BOOL GrowCallbackList(JSContext* context, NSString** errorString);
106
107static BOOL GetIndexForTrackingID(uint32_t trackingID, NSUInteger* outIndex);
108
109static BOOL RemoveCallbackWithTrackingID(JSContext* context, uint32_t trackingID);
110static void RemoveCallbackAtIndex(JSContext* context, NSUInteger index);
111
112static void QueueDeferredOperation(NSString* opType, uint32_t trackingID, OOJSValue* value);
113static void RunDeferredOperations(JSContext* context);
114
115static const JSCFunctionListEntry sFrameCallbackMethods[] = {
116 // JS name Function min args
117 JS_CFUNC_DEF2("addFrameCallback", 1, GlobalAddFrameCallback, OOJS_METHOD_READONLY),
118 JS_CFUNC_DEF2("removeFrameCallback", 1, GlobalRemoveFrameCallback, OOJS_METHOD_READONLY),
119 JS_CFUNC_DEF2("isValidFrameCallback", 1, GlobalIsValidFrameCallback, OOJS_METHOD_READONLY),
120};
121
122// MARK: Public
123
124void InitOOJSFrameCallbacks(JSContext* context, JSValueConst global)
125{
126 JS_SetPropertyFunctionList(context, global, sFrameCallbackMethods, OOJS_COUNT(sFrameCallbackMethods));
127
128#if DEBUG_FCB_SIMPLE_TRACKING_IDS
129 sNextID = 1;
130#else
131 // Set randomish initial ID to catch bad habits.
132 sNextID = [[NSDate date] timeIntervalSinceReferenceDate];
133#endif
134}
135
137{
138 NSCAssert1(!sRunning, @"%s cannot be called while frame callbacks are running.", __PRETTY_FUNCTION__);
139
140 if (sCount != 0) {
141 const OOTimeDelta delta = inDeltaT * [UNIVERSE timeAccelerationFactor];
142 JSContext* context = OOJSAcquireContext();
143 JSValue deltaVal = JS_NewNumber(context, delta);
144 // As with JS_CallFunctionValue() with a NULL this, callbacks are called with the global object as this.
145 JSValue global = JS_GetGlobalObject(context);
146 NSUInteger i;
147
148 // Block mutations.
149 sRunning = YES;
150
151 /*
152 The watchdog timer only fires once per second in deployment builds,
153 but in testrelease builds at least we can keep them on a short leash.
154 (With QuickJS the limit is checked by the interrupt handler.)
155 */
157
158 for (i = 0; i < sCount; i++) {
159 // TODO: remove out of scope callbacks - post MNSR!
160 JSValue result = JS_Call(context, sCallbacks[i].callback, global, 1, (JSValueConst*)&deltaVal);
161 if (JS_IsException(result)) {
163 }
164 JS_FreeValue(context, result);
165 }
166
168 sRunning = NO;
169
170 JS_FreeValue(context, global);
171 JS_FreeValue(context, deltaVal);
172
173 if (EXPECT_NOT(sDeferredOps != NULL)) {
174 RunDeferredOperations(context);
176 }
177 OOJSRelinquishContext(context);
178 }
179}
180
182{
183 NSCAssert1(!sRunning, @"%s cannot be called while frame callbacks are running.", __PRETTY_FUNCTION__);
184
185 if (sCount != 0) {
186 JSContext* context = OOJSAcquireContext();
187 while (sCount != 0)
188 RemoveCallbackAtIndex(context, sCount - 1);
189 OOJSRelinquishContext(context);
190 }
191}
192
193// MARK: Methods
194
195// addFrameCallback(callback : Function) : Number
197{
198 OOJS_NATIVE_ENTER(context)
199
200 // Get callback argument and verify that it's a function.
201 JSValueConst callback = OOJS_ARGV[0];
202 if (EXPECT_NOT(argc < 1 || !OOJSValueIsFunction(context, callback))) {
203 OOJSReportBadArguments(context, nil, @"addFrameCallback", MIN(argc, 1), OOJS_ARGV, nil, @"function");
204 return JS_EXCEPTION;
205 }
206
207 // Assign a tracking ID.
208 uint32_t trackingID = sNextID ^ kIDScrambleMask;
210
211 if (EXPECT(!sRunning)) {
212 // Add to list immediately.
213 NSString* errorString = nil;
214 if (EXPECT_NOT(!AddCallback(context, callback, trackingID, &errorString))) {
215 OOJSReportError(context, @"%@", errorString);
216 return JS_EXCEPTION;
217 }
218 } else {
219 // Defer mutations during callback invocation.
220 FCBLog(@"script.frameCallback.debug.add.deferred", @"Deferring addition of frame callback with tracking ID %u.", trackingID);
221 QueueDeferredOperation(@"add", trackingID, [OOJSValue valueWithJSValue:callback inContext:context]);
222 }
223
224 OOJS_RETURN_INT(trackingID);
225
227}
228
229// removeFrameCallback(trackingID : Number)
231{
232 OOJS_NATIVE_ENTER(context)
233
234 // Get tracking ID argument.
235 uint32_t trackingID;
236 if (EXPECT_NOT(argc < 1 || JS_ToUint32(context, &trackingID, OOJS_ARGV[0]) < 0)) {
237 if (JS_HasException(context))
238 JS_FreeValue(context, JS_GetException(context));
239 OOJSReportBadArguments(context, nil, @"removeFrameCallback", MIN(argc, 1), OOJS_ARGV, nil, @"frame callback tracking ID");
240 return JS_EXCEPTION;
241 }
242
243 if (EXPECT(!sRunning)) {
244 // Remove it.
245 if (EXPECT_NOT(!RemoveCallbackWithTrackingID(context, trackingID))) {
246 OOJSReportWarning(context, @"removeFrameCallback(): invalid tracking ID.");
247 }
248 } else {
249 // Defer mutations during callback invocation.
250 FCBLog(@"script.frameCallback.debug.remove.deferred", @"Deferring removal of frame callback with tracking ID %u.", trackingID);
251 QueueDeferredOperation(@"remove", trackingID, nil);
252 }
253
255
257}
258
259// isValidFrameCallback(trackingID : Number)
261{
262 OOJS_NATIVE_ENTER(context)
263
264 if (EXPECT_NOT(argc < 1)) {
265 OOJSReportBadArguments(context, nil, @"isValidFrameCallback", 0, OOJS_ARGV, nil, @"frame callback tracking ID");
266 return JS_EXCEPTION;
267 }
268
269 // Get tracking ID argument.
270 uint32_t trackingID;
271 if (EXPECT_NOT(JS_ToUint32(context, &trackingID, OOJS_ARGV[0]) < 0)) {
272 JS_FreeValue(context, JS_GetException(context));
274 }
275
276 NSUInteger index;
277 OOJS_RETURN_BOOL(GetIndexForTrackingID(trackingID, &index));
278
280}
281
282// MARK: Internals
283
284static BOOL AddCallback(JSContext* context, JSValueConst callback, uint32_t trackingID, NSString** errorString)
285{
286 NSCParameterAssert(context != NULL);
287 NSCParameterAssert(errorString != NULL);
288 NSCAssert1(!sRunning, @"%s cannot be called while frame callbacks are running.", __PRETTY_FUNCTION__);
289
290 if (EXPECT_NOT(sCount == sSpace)) {
291 if (!GrowCallbackList(context, errorString))
292 return NO;
293 }
294
295 FCBLog(@"script.frameCallback.debug.add", @"Adding frame callback with tracking ID %u.", trackingID);
296
297 sCallbacks[sCount].callback = JS_DupValue(context, callback);
298 sCallbacks[sCount].trackingID = trackingID;
299 sCount++;
300
301 return YES;
302}
303
304static BOOL GrowCallbackList(JSContext* context, NSString** errorString)
305{
306 NSCParameterAssert(context != NULL);
307 NSCParameterAssert(errorString != NULL);
308
309 NSUInteger newSpace = MAX(sSpace * 2, (NSUInteger)kMinCount);
310
311 CallbackEntry* newCallbacks = calloc(sizeof(CallbackEntry), newSpace);
312 if (newCallbacks == NULL) {
313 *errorString = @"Failed to allocate space for frame callback.";
314 return NO;
315 }
316
317 // Move occupied slots; the references move with them.
318 if (sCount != 0)
319 memcpy(newCallbacks, sCallbacks, sizeof(CallbackEntry) * sCount);
320
321 // Replace array.
322 free(sCallbacks);
323 sCallbacks = newCallbacks;
324 sSpace = newSpace;
325
326 return YES;
327}
328
329static BOOL GetIndexForTrackingID(uint32_t trackingID, NSUInteger* outIndex)
330{
331 NSCParameterAssert(outIndex != NULL);
332
333 /* It is assumed that few frame callbacks will be active at once, so a
334 linear search is reasonable. If they become unexpectedly popular, we
335 can switch to a sorted list or a separate lookup table without changing
336 the API.
337 */
338 NSUInteger i;
339 for (i = 0; i < sCount; i++) {
340 if (sCallbacks[i].trackingID == trackingID) {
341 *outIndex = i;
342 return YES;
343 }
344 }
345
346 return NO;
347}
348
349static BOOL RemoveCallbackWithTrackingID(JSContext* context, uint32_t trackingID)
350{
351 NSCParameterAssert(context != NULL);
352 NSCAssert1(!sRunning, @"%s cannot be called while frame callbacks are running.", __PRETTY_FUNCTION__);
353
354 NSUInteger index = 0;
355 if (GetIndexForTrackingID(trackingID, &index)) {
356 RemoveCallbackAtIndex(context, index);
357 return YES;
358 }
359
360 return NO;
361}
362
363static void RemoveCallbackAtIndex(JSContext* context, NSUInteger index)
364{
365 NSCParameterAssert(context != NULL);
366 NSCParameterAssert(index < sCount && sCallbacks != NULL);
367 NSCAssert1(!sRunning, @"%s cannot be called while frame callbacks are running.", __PRETTY_FUNCTION__);
368
369 FCBLog(@"script.frameCallback.debug.remove", @"Removing frame callback with tracking ID %u.", sCallbacks[index].trackingID);
370
371 // Overwrite entry to be removed with last entry, and decrement count.
372 JSValue removed = sCallbacks[index].callback;
373 sCount--;
374 sCallbacks[index] = sCallbacks[sCount];
375 sCallbacks[sCount].callback = JS_NULL;
376 JS_FreeValue(context, removed);
377
378#if DEBUG_FCB_SIMPLE_TRACKING_IDS
379 if (sCount == 0) {
380 OOLog(@"script.frameCallback.debug.reset", @"All frame callbacks removed, resetting next ID to 1.");
381 sNextID = 1;
382 }
383#endif
384}
385
386static void QueueDeferredOperation(NSString* opType, uint32_t trackingID, OOJSValue* value)
387{
388 NSCAssert1(sRunning, @"%s can only be called while frame callbacks are running.", __PRETTY_FUNCTION__);
389
390 if (sDeferredOps == nil)
391 sDeferredOps = [[NSMutableArray alloc] init];
392 [sDeferredOps addObject:[NSDictionary dictionaryWithObjectsAndKeys:
393 opType, @"operation",
394 [NSNumber numberWithInt:trackingID], @"trackingID",
395 value, @"value",
396 nil]];
397}
398
399static void RunDeferredOperations(JSContext* context)
400{
401 NSDictionary* operation = nil;
402
403 FCBLog(@"script.frameCallback.debug.run-deferred", @"Running %zu deferred frame callback operations.", (long)[sDeferredOps count]);
404 FCBLogIndentIf(@"script.frameCallback.debug.run-deferred");
405
406 foreach (operation, sDeferredOps) {
407 NSString* opType = [operation objectForKey:@"operation"];
408 uint32_t trackingID = [operation oo_intForKey:@"trackingID"];
409
410 if ([opType isEqualToString:@"add"]) {
411 OOJSValue* callbackObj = [operation objectForKey:@"value"];
412 NSString* errorString = nil;
413
414 JSValue callback = OOJSValueFromNativeObject(context, callbackObj);
415 if (!AddCallback(context, callback, trackingID, &errorString)) {
416 OOLogWARN(@"script.frameCallback.deferredAdd.failed", @"Deferred frame callback insertion failed: %@", errorString);
417 }
418 JS_FreeValue(context, callback);
419 } else if ([opType isEqualToString:@"remove"]) {
420 RemoveCallbackWithTrackingID(context, trackingID);
421 }
422 }
423
424 FCBLogOutdentIf(@"script.frameCallback.debug.run-deferred");
425}
#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 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,...)
OOINLINE jsval OOJSValueFromNativeObject(JSContext *context, id object)
#define OOJS_RETURN_BOOL(v)
OOINLINE BOOL OOJSValueIsFunction(JSContext *context, jsval value)
OOINLINE JSContext * OOJSAcquireContext(void)
OOINLINE void OOJSReportPendingException(JSContext *context)
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 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
static const JSCFunctionListEntry sFrameCallbackMethods[]
#define OOJS_NATIVE_ARGS
#define OOJS_COUNT(array)