Oolite
Loading...
Searching...
No Matches
OOJSTimer.m
Go to the documentation of this file.
1/*
2
3OOJSTimer.m
4
5
6Oolite
7Copyright (C) 2004-2013 Giles C Williams and contributors
8
9This program is free software; you can redistribute it and/or
10modify it under the terms of the GNU General Public License
11as published by the Free Software Foundation; either version 2
12of the License, or (at your option) any later version.
13
14This program is distributed in the hope that it will be useful,
15but WITHOUT ANY WARRANTY; without even the implied warranty of
16MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17GNU General Public License for more details.
18
19You should have received a copy of the GNU General Public License
20along with this program; if not, write to the Free Software
21Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
22MA 02110-1301, USA.
23
24*/
25
26#import "OOJSTimer.h"
28#import "Universe.h"
29
30// Minimum allowable interval for repeating timers.
31#define kMinInterval 0.25
32
33static JSClassID sTimerClassID;
34static JSClassDef sTimerClass;
35
36/* Ownership
37
38 The JS Timer object owns a retain on its OOJSTimer (its opaque value).
39 The OOJSTimer owns references to its function and this, as the
40 SpiderMonkey version rooted them, and holds a non-owning reference to
41 its JS Timer object, cleared when that object is finalized.
42
43 The function and this references are deliberately not reported through
44 a gc_mark hook. A scheduled timer outlives its JS object (the scheduler
45 retains it), and QuickJS's cycle collector would free any object marked
46 from a garbage JS Timer even though the OOJSTimer still holds it. As in
47 SpiderMonkey, where they were GC roots, they keep their targets (and any
48 cycle through them back to the Timer object) alive until the timer is
49 deallocated or the engine is reset.
50*/
51
52@interface OOJSTimer (Private)
53
54- (id)initWithDelay:(OOTimeAbsolute)delay
55 interval:(OOTimeDelta)interval
56 context:(JSContext*)context
57 function:(JSValueConst)function
58 this:(JSValueConst)jsThis;
59
60- (void)clearJSSelf;
61- (BOOL)willNotFireAgain;
62- (JSValue)transferJSSelf;
63- (void)releaseJSValues;
64
65@end
66
67@implementation OOJSTimer
68
69- (id)initWithDelay:(OOTimeAbsolute)delay
70 interval:(OOTimeDelta)interval
71 context:(JSContext*)context
72 function:(JSValueConst)function
73 this:(JSValueConst)jsThis
74{
75 self = [super initWithNextTime:[UNIVERSE getTime] + delay interval:interval];
76 if (self != nil) {
77 NSAssert(OOJSValueIsFunction(context, function), @"Attempt to init OOJSTimer with a function that isn't.");
78
79 _jsThis = JS_DupValue(context, jsThis);
80 _function = JS_DupValue(context, function);
81
82 /* QuickJS has no JS_GetFunctionId(); use the function's name property.
83 It's cached because -descriptionComponents is used by the
84 finalizer, which must not run JS code (the property could be a
85 getter, or the function a Proxy).
86 */
87 JSValue nameValue = JS_GetPropertyStr(context, function, "name");
88 if (JS_IsException(nameValue)) {
89 JS_FreeValue(context, JS_GetException(context));
90 } else {
91 NSString* name = OOStringFromJSValue(context, nameValue);
92 if ([name length] != 0)
93 _functionName = [name copy];
94 }
95 JS_FreeValue(context, nameValue);
96
97 _jsSelf = JS_NewObjectClass(context, sTimerClassID);
98 if (!JS_IsException(_jsSelf)) {
99 if (JS_SetOpaque(_jsSelf, [self retain]) < 0) {
100 [self release];
101 JS_FreeValue(context, _jsSelf);
102 _jsSelf = JS_EXCEPTION;
103 }
104 }
105 if (JS_IsException(_jsSelf)) {
106 _jsSelf = JS_UNDEFINED;
107 [self releaseJSValues];
108 [self release];
109 return nil;
110 }
111
113
114 [[NSNotificationCenter defaultCenter] addObserver:self
115 selector:@selector(deleteJSPointers)
116 name:kOOJavaScriptEngineWillResetNotification
118 }
119
120 return self;
121}
122
123// Notification handler: engine reset.
124- (void)deleteJSPointers
125{
126 /* Freeing _jsThis may free the JS Timer object, whose finalizer releases
127 us, so stay alive until we're done.
128 */
129 [[self retain] autorelease];
130 [self releaseJSValues];
131}
132
134{
135 [self unscheduleTimer];
136
137 // Ivars are zero-filled (not objects) before they are set.
138 if (JS_IsObject(_function)) {
139 // Don't touch the ivars after freeing (see -deleteJSPointers).
140 JSValue function = _function;
141 JSValue jsThis = _jsThis;
142 _function = JS_UNDEFINED;
143 _jsThis = JS_UNDEFINED;
144
145 [[NSNotificationCenter defaultCenter] removeObserver:self
146 name:kOOJavaScriptEngineWillResetNotification
148
149 JSContext* context = OOJSAcquireContext();
150 JS_FreeValue(context, function);
151 JS_FreeValue(context, jsThis);
152 OOJSRelinquishContext(context);
153 }
154}
155
156- (void)dealloc
157{
158 [_owningScript release];
159 [_functionName release];
160
161 /* Not -deleteJSPointers: we can't be retained during dealloc. Freeing
162 _jsThis can't re-enter, since the JS Timer object, which held our
163 retain, has already been finalized.
164 */
165 [self releaseJSValues];
166
167 [super dealloc];
168}
169
170- (NSString*)descriptionComponents
171{
172 NSString* funcName = nil;
173
174 if (!JS_IsObject(_function)) {
175 return @"invalid";
176 }
177
178 funcName = _functionName;
179 if (funcName == nil) {
180 funcName = @"anonymous";
181 }
182
183 return [NSString stringWithFormat:@"%@, function: %@", [super descriptionComponents], funcName];
184}
185
186- (NSString*)oo_jsClassName
187{
188 return @"Timer";
189}
190
191- (void)timerFired
192{
193 JSValue rval = JS_UNDEFINED;
194 NSString* description = nil;
195
196 OOJavaScriptEngine* engine = [OOJavaScriptEngine sharedEngine];
197 JSContext* context = OOJSAcquireContext();
198
199 // stop and remove the timer if _jsThis (the first parameter in the constructor) dies.
200 id object = OOJSNativeObjectFromJSObject(context, _jsThis);
201 if (object != nil) {
202 description = [object oo_jsDescription];
203 if (description == nil)
204 description = [object description];
205 }
206
207 if (description == nil || !JS_IsObject(_function)) {
208 [self unscheduleTimer];
209 OOJSRelinquishContext(context);
210 return;
211 }
212
213 // The callback may stop the timer and drop the last references to it.
214 [[self retain] autorelease];
215 JSValue function = JS_DupValue(context, _function);
216 JSValue jsThis = JS_DupValue(context, _jsThis);
217
218 [OOJSScript pushScript:_owningScript];
219 _firing = YES;
220 [engine callJSFunction:function
221 forObject:jsThis
222 argc:0
223 argv:NULL
224 result:&rval];
225 _firing = NO;
226 [OOJSScript popScript:_owningScript];
227
228 JS_FreeValue(context, rval);
229 JS_FreeValue(context, function);
230 JS_FreeValue(context, jsThis);
231
232 OOJSRelinquishContext(context);
233}
234
235- (JSValue)oo_jsValueInContext:(JSContext*)context
236{
237 /* _jsSelf is cleared when the JS object is finalized (which, as before,
238 can happen while the timer is still scheduled). SpiderMonkey returned
239 the dangling object; return null instead.
240 */
241 if (JS_IsObject(_jsSelf))
242 return JS_DupValue(context, _jsSelf);
243 return JS_NULL;
244}
245
247{
248 _jsSelf = JS_UNDEFINED;
249}
250
251/* A one-shot timer stays scheduled while its callback runs, and is dropped
252 afterwards. A callback that replaces the only reference to its own timer
253 (e.g. with a new timer) frees the JS object at once under QuickJS's
254 reference counting, which SpiderMonkey's GC almost never did.
255*/
257{
258 return _firing && [self interval] <= 0.0;
259}
260
261/* The reference created with the JS object in -initWithDelay:... belongs to
262 whoever calls this, once (the constructor, which returns it).
263 SpiderMonkey's unrooted _jsSelf pointer added no reference, so this is
264 what lets the JS object be collected (and finalized) as before.
265*/
267{
268 return _jsSelf;
269}
270
271@end
272
273static JSValue TimerGetProperty(OOJS_GETTER_ARGS);
274static JSValue TimerSetProperty(OOJS_SETTER_ARGS);
275static void TimerFinalize(JSRuntime* runtime, JSValueConst this);
276static JSValue TimerConstruct(OOJS_NATIVE_ARGS);
277
278// Methods
279static JSValue TimerStart(OOJS_NATIVE_ARGS);
280static JSValue TimerStop(OOJS_NATIVE_ARGS);
281
282static JSClassDef sTimerClass = {
283 .class_name = "Timer",
284 .finalizer = TimerFinalize,
285};
286
287enum {
288 // Property IDs
289 kTimer_nextTime, // next fire time, double, read/write
290 kTimer_interval, // interval, double, read/write
291 kTimer_isRunning // is scheduled, boolean, read-only
292};
293
294static const JSCFunctionListEntry sTimerProperties[] = {
295 // JS name Getter Setter ID
299};
300
301static const JSCFunctionListEntry sTimerMethods[] = {
302 // JS name Function min args
303 JS_CFUNC_DEF("toString", 0, OOJSObjectWrapperToString),
304 JS_CFUNC_DEF("start", 0, TimerStart),
305 JS_CFUNC_DEF("stop", 0, TimerStop),
306};
307
309
317
319{
320 OOJS_NATIVE_ENTER(context)
321
322 OOJSTimer* timer = nil;
323
324 if (EXPECT_NOT(!JSTimerGetTimer(context, this, &timer)))
325 return OOJSNativeFailure(context);
326
327 switch (magic) {
328 case kTimer_nextTime:
329 return JS_NewNumber(context, [timer nextTime]);
330
331 case kTimer_interval:
332 return JS_NewNumber(context, [timer interval]);
333
334 case kTimer_isRunning:
335 return OOJSValueFromBOOL([timer isScheduled]);
336
337 default:
339 return JS_EXCEPTION;
340 }
341
343}
344
346{
347 OOJS_NATIVE_ENTER(context)
348
349 OOJSTimer* timer = nil;
350 double fValue;
351
352 if (EXPECT_NOT(!JSTimerGetTimer(context, this, &timer)))
353 return OOJSNativeFailure(context);
354
355 switch (magic) {
356 case kTimer_nextTime:
357 if (JS_ToFloat64(context, &fValue, value) == 0) {
358 if (![timer setNextTime:fValue]) {
359 OOJSReportWarning(context, @"Ignoring attempt to change next fire time for running timer %@.", timer);
360 }
361 return JS_UNDEFINED;
362 }
363 JS_FreeValue(context, JS_GetException(context));
364 break;
365
366 case kTimer_interval:
367 if (JS_ToFloat64(context, &fValue, value) == 0) {
368 [timer setInterval:fValue];
369 return JS_UNDEFINED;
370 }
371 JS_FreeValue(context, JS_GetException(context));
372 break;
373
374 default:
376 return JS_EXCEPTION;
377 }
378
380 return JS_EXCEPTION;
381
383}
384
385static void TimerFinalize(JSRuntime* runtime, JSValueConst this)
386{
388
389 // Can't use JSTimerGetTimer() here - potential chicken-and-egg problem manifesting as a crash.
390 OOJSTimer* timer = (OOJSTimer*)JS_GetOpaque(this, sTimerClassID);
391
392 if (timer != nil) {
393 if ([timer isScheduled] && ![timer willNotFireAgain]) {
394 OOLogWARN(@"script.javaScript.unrootedTimer", @"Timer %@ is being garbage-collected while still running. You must keep a reference to all running timers, or they will stop unpredictably!", timer);
395 }
396 [timer clearJSSelf];
397 [timer release];
398 JS_SetOpaque(this, NULL);
399 }
400
402}
403
404// new Timer(this : Object, function : Function, delay : Number [, interval : Number]) : Timer
406{
407 OOJS_NATIVE_ENTER(context)
408
409 JSValueConst function = JS_UNDEFINED;
410 double delay;
411 double interval = -1.0;
412 OOJSTimer* timer = nil;
413 JSValue callbackThis = JS_NULL;
414
416 OOJSReportError(context, @"Timer() cannot be called as a function, it must be used as a constructor (as in new Timer(...)).");
417 return JS_EXCEPTION;
418 }
419
420 if (argc < 3) {
421 OOJSReportBadArguments(context, nil, @"Timer", argc, OOJS_ARGV, @"Invalid arguments in constructor", @"(object, function, number [, number])");
422 return JS_EXCEPTION;
423 }
424
425 if (!JS_IsNull(OOJS_ARGV[0]) && !JS_IsUndefined(OOJS_ARGV[0])) {
426 callbackThis = JS_ToObject(context, OOJS_ARGV[0]);
427 if (JS_IsException(callbackThis)) {
428 JS_FreeValue(context, JS_GetException(context));
429 OOJSReportBadArguments(context, nil, @"Timer", 1, OOJS_ARGV, @"Invalid argument in constructor", @"object");
430 return JS_EXCEPTION;
431 }
432 }
433
434 function = OOJS_ARGV[1];
435 if (!JS_IsFunction(context, function)) {
436 JS_FreeValue(context, callbackThis);
437 OOJSReportBadArguments(context, nil, @"Timer", 1, OOJS_ARGV + 1, @"Invalid argument in constructor", @"function");
438 return JS_EXCEPTION;
439 }
440
441 if (JS_ToFloat64(context, &delay, OOJS_ARGV[2]) < 0 || isnan(delay)) {
442 if (JS_HasException(context))
443 JS_FreeValue(context, JS_GetException(context));
444 JS_FreeValue(context, callbackThis);
445 OOJSReportBadArguments(context, nil, @"Timer", 1, OOJS_ARGV + 2, @"Invalid argument in constructor", @"number");
446 return JS_EXCEPTION;
447 }
448
449 // Fourth argument is optional.
450 if (3 < argc && JS_ToFloat64(context, &interval, OOJS_ARGV[3]) < 0) {
451 JS_FreeValue(context, JS_GetException(context));
452 interval = -1;
453 }
454
455 // Ensure interval is not too small.
456 if (0.0 < interval && interval < kMinInterval)
457 interval = kMinInterval;
458
459 timer = [[OOJSTimer alloc] initWithDelay:delay
460 interval:interval
461 context:context
462 function:function
463 this:callbackThis];
464 JS_FreeValue(context, callbackThis);
465 if (EXPECT_NOT(!timer))
466 return OOJSNativeFailure(context);
467
468 if (delay >= 0) // Leave in stopped state if delay is negative
469 {
470 [timer scheduleTimer];
471 }
472 JSValue result = [timer transferJSSelf];
473 [timer autorelease];
474 return result;
475
477}
478
479// *** Methods ***
480
481// start() : Boolean
483{
484 OOJS_NATIVE_ENTER(context)
485
486 OOJSTimer* thisTimer = nil;
487
488 if (EXPECT_NOT(!JSTimerGetTimer(context, OOJS_THIS, &thisTimer)))
489 return OOJSNativeFailure(context);
490
491 OOJS_RETURN_BOOL([thisTimer scheduleTimer]);
492
494}
495
496// stop()
498{
499 OOJS_NATIVE_ENTER(context)
500
501 OOJSTimer* thisTimer = nil;
502
503 if (EXPECT_NOT(!JSTimerGetTimer(context, OOJS_THIS, &thisTimer)))
504 return OOJSNativeFailure(context);
505
506 [thisTimer unscheduleTimer];
508
510}
#define EXPECT_NOT(x)
#define OOJS_PROFILE_EXIT_VOID
#define OOJS_NATIVE_ENTER(cx)
#define OOJS_NATIVE_EXIT
#define OOJS_PROFILE_ENTER
@ kTimer_isRunning
Definition OOJSTimer.m:206
@ kTimer_nextTime
Definition OOJSTimer.m:204
@ kTimer_interval
Definition OOJSTimer.m:205
static JSBool TimerSetProperty(JSContext *context, JSObject *this, jsid propID, JSBool strict, jsval *value)
Definition OOJSTimer.m:264
static JSBool TimerGetProperty(JSContext *context, JSObject *this, jsid propID, jsval *value)
Definition OOJSTimer.m:233
static JSPropertySpec sTimerProperties[]
Definition OOJSTimer.m:209
static JSClass sTimerClass
Definition OOJSTimer.m:34
static JSBool TimerConstruct(JSContext *context, uintN argc, jsval *vp)
Definition OOJSTimer.m:324
static JSBool TimerStart(JSContext *context, uintN argc, jsval *vp)
Definition OOJSTimer.m:391
static void TimerFinalize(JSContext *context, JSObject *this)
Definition OOJSTimer.m:305
static JSFunctionSpec sTimerMethods[]
Definition OOJSTimer.m:217
#define kMinInterval
Definition OOJSTimer.m:31
static JSBool TimerStop(JSContext *context, uintN argc, jsval *vp)
Definition OOJSTimer.m:406
void OOJSReportWarning(JSContext *context, NSString *format,...)
#define OOJS_THIS
JSBool OOJSObjectWrapperToString(JSContext *context, uintN argc, jsval *vp)
void OOJSRegisterObjectConverter(JSClass *theClass, OOJSClassConverterCallback converter)
id OOJSNativeObjectFromJSObject(JSContext *context, JSObject *object)
#define DEFINE_JS_OBJECT_GETTER(NAME, JSCLASS, JSPROTO, OBJCCLASSNAME)
void OOJSReportBadPropertySelector(JSContext *context, JSObject *thisObj, jsid propID, JSPropertySpec *propertySpec)
#define OOJS_RETURN_BOOL(v)
NSString * OOStringFromJSValue(JSContext *context, jsval value)
OOINLINE BOOL OOJSValueIsFunction(JSContext *context, jsval value)
OOINLINE JSContext * OOJSAcquireContext(void)
void OOJSReportError(JSContext *context, NSString *format,...)
#define OOJS_ARGV
OOINLINE jsval OOJSValueFromBOOL(int b) INLINE_CONST_FUNC
OOINLINE void OOJSRelinquishContext(JSContext *context)
void OOJSReportBadPropertyValue(JSContext *context, JSObject *thisObj, jsid propID, JSPropertySpec *propertySpec, jsval value)
id OOJSBasicPrivateObjectConverter(JSContext *context, JSObject *object)
void OOJSReportBadArguments(JSContext *context, NSString *scriptClass, NSString *function, uintN argc, jsval *argv, NSString *message, NSString *expectedArgsDescription)
#define OOJS_RETURN_VOID
#define OOLogWARN(class, format,...)
Definition OOLogging.h:126
return nil
double OOTimeDelta
Definition OOTypes.h:193
double OOTimeAbsolute
Definition OOTypes.h:192
static JSValue TimerStart(OOJS_NATIVE_ARGS)
Definition OOJSTimer.m:482
static JSValue TimerGetProperty(OOJS_GETTER_ARGS)
Definition OOJSTimer.m:318
void InitOOJSTimer(JSContext *context, JSValueConst global)
Definition OOJSTimer.m:310
static JSValue TimerSetProperty(OOJS_SETTER_ARGS)
Definition OOJSTimer.m:345
static JSClassID sTimerClassID
Definition OOJSTimer.m:33
static JSValue TimerStop(OOJS_NATIVE_ARGS)
Definition OOJSTimer.m:497
static void TimerFinalize(JSRuntime *runtime, JSValueConst this)
Definition OOJSTimer.m:385
static JSValue TimerConstruct(OOJS_NATIVE_ARGS)
Definition OOJSTimer.m:405
#define OOJS_PROPERTY_RW(name, getter, setter, magic)
#define OOJS_IS_CONSTRUCTING
JSValue OOJSNativeFailure(JSContext *context)
JSClassID OOJSRegisterClass(JSClassID *ioClassID, const JSClassDef *classDef)
Definition OOJSClasses.m:61
#define OOJS_SETTER_ARGS
#define OOJS_PROPERTY_RO(name, getter, magic)
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)
JSValue transferJSSelf()
Definition OOJSTimer.m:266
void pushScript:(OOJSScript *script)
Definition OOJSScript.m:480
OOJSScript * currentlyRunningScript()
Definition OOJSScript.m:101
void popScript:(OOJSScript *script)
Definition OOJSScript.m:493
OOJSScript * _owningScript
Definition OOJSTimer.h:37
jsval _function
Definition OOJSTimer.h:34
JSValue transferJSSelf()
Definition OOJSTimer.m:266
JSObject * _jsSelf
Definition OOJSTimer.h:39
JSObject * _jsThis
Definition OOJSTimer.h:35
NSString * _functionName
Definition OOJSTimer.h:38
void releaseJSValues()
Definition OOJSTimer.m:133
BOOL callJSFunction:forObject:argc:argv:result:(jsval function,[forObject] JSObject *jsThis,[argc] uintN argc,[argv] jsval *argv,[result] jsval *outResult)
OOJavaScriptEngine * sharedEngine()
void setInterval:(OOTimeDelta interval)
OOTimeDelta interval()
id initWithNextTime:interval:(OOTimeAbsolute nextTime,[interval] OOTimeDelta interval)