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 JSObject* sTimerPrototype;
34static JSClass sTimerClass;
35
36@interface OOJSTimer (Private)
37
38- (id)initWithDelay:(OOTimeAbsolute)delay
39 interval:(OOTimeDelta)interval
40 context:(JSContext*)context
41 function:(jsval)function
42 this:(JSObject*)jsThis;
43
44@end
45
46@implementation OOJSTimer
47
48- (id)initWithDelay:(OOTimeAbsolute)delay
49 interval:(OOTimeDelta)interval
50 context:(JSContext*)context
51 function:(jsval)function
52 this:(JSObject*)jsThis
53{
54 self = [super initWithNextTime:[UNIVERSE getTime] + delay interval:interval];
55 if (self != nil) {
56 NSAssert(OOJSValueIsFunction(context, function), @"Attempt to init OOJSTimer with a function that isn't.");
57
58 _jsThis = jsThis;
59 OOJSAddGCObjectRoot(context, &_jsThis, "OOJSTimer this");
60
61 _function = function;
62 OOJSAddGCValueRoot(context, &_function, "OOJSTimer function");
63
64 _jsSelf = JS_NewObject(context, &sTimerClass, sTimerPrototype, NULL);
65 if (_jsSelf != NULL) {
66 if (!JS_SetPrivate(context, _jsSelf, [self retain]))
67 _jsSelf = NULL;
68 }
69 if (_jsSelf == NULL) {
70 [self release];
71 return nil;
72 }
73
75
76 [[NSNotificationCenter defaultCenter] addObserver:self
77 selector:@selector(deleteJSPointers)
78 name:kOOJavaScriptEngineWillResetNotification
80 }
81
82 return self;
83}
84
86{
87 [self unscheduleTimer];
88
89 if (_jsThis != NULL) {
90 _jsThis = NULL;
91 _function = JSVAL_VOID;
92
93 JSContext* context = OOJSAcquireContext();
94 JS_RemoveObjectRoot(context, &_jsThis);
95 JS_RemoveValueRoot(context, &_function);
96 OOJSRelinquishContext(context);
97
98 [[NSNotificationCenter defaultCenter] removeObserver:self
99 name:kOOJavaScriptEngineWillResetNotification
101 }
102}
103
104- (void)dealloc
105{
106 [_owningScript release];
107
108 [self deleteJSPointers];
109
110 [super dealloc];
111}
112
114{
115 NSString* funcName = nil;
116 JSContext* context = NULL;
117
118 if (JSVAL_IS_VOID(_function) || JSVAL_IS_NULL(_function)) {
119 return @"invalid";
120 }
121
122 context = OOJSAcquireContext();
123 funcName = OOStringFromJSString(context, JS_GetFunctionId(JS_ValueToFunction(context, _function)));
124 OOJSRelinquishContext(context);
125
126 if (funcName == nil) {
127 funcName = @"anonymous";
128 }
129
130 return [NSString stringWithFormat:@"%@, function: %@", [super descriptionComponents], funcName];
131}
132
133- (NSString*)oo_jsClassName
134{
135 return @"Timer";
136}
137
139{
140 jsval rval = JSVAL_VOID;
141 NSString* description = nil;
142
144 JSContext* context = OOJSAcquireContext();
145
146 // stop and remove the timer if _jsThis (the first parameter in the constructor) dies.
147 id object = OOJSNativeObjectFromJSObject(context, _jsThis);
148 if (object != nil) {
149 description = [object oo_jsDescription];
150 if (description == nil)
151 description = [object description];
152 }
153
154 if (description == nil) {
155 [self unscheduleTimer];
156 OOJSRelinquishContext(context);
157 return;
158 }
159
160 [OOJSScript pushScript:_owningScript];
161 [engine callJSFunction:_function
162 forObject:_jsThis
163 argc:0
164 argv:NULL
165 result:&rval];
166 [OOJSScript popScript:_owningScript];
167
168 OOJSRelinquishContext(context);
169}
170
171- (jsval)oo_jsValueInContext:(JSContext*)context
172{
173 return OBJECT_TO_JSVAL(_jsSelf);
174}
175
176@end
177
178static JSBool TimerGetProperty(JSContext* context, JSObject* this, jsid propID, jsval* value);
179static JSBool TimerSetProperty(JSContext* context, JSObject* this, jsid propID, JSBool strict, jsval* value);
180static void TimerFinalize(JSContext* context, JSObject* this);
181static JSBool TimerConstruct(JSContext* context, uintN argc, jsval* vp);
182
183// Methods
184static JSBool TimerStart(JSContext* context, uintN argc, jsval* vp);
185static JSBool TimerStop(JSContext* context, uintN argc, jsval* vp);
186
187static JSClass sTimerClass = {
188 "Timer",
189 JSCLASS_HAS_PRIVATE,
190
191 JS_PropertyStub, // addProperty
192 JS_PropertyStub, // delProperty
193 TimerGetProperty, // getProperty
194 TimerSetProperty, // setProperty
195 JS_EnumerateStub, // enumerate
196 JS_ResolveStub, // resolve
197 JS_ConvertStub, // convert
198 TimerFinalize, // finalize
199 JSCLASS_NO_OPTIONAL_MEMBERS
200};
201
202enum {
203 // Property IDs
204 kTimer_nextTime, // next fire time, double, read/write
205 kTimer_interval, // interval, double, read/write
206 kTimer_isRunning // is scheduled, boolean, read-only
207};
208
209static JSPropertySpec sTimerProperties[] = {
210 // JS name ID flags
212 { "isRunning", kTimer_isRunning, OOJS_PROP_READONLY_CB },
214 { 0 }
215};
216
217static JSFunctionSpec sTimerMethods[] = {
218 // JS name Function min args
219 { "toString", OOJSObjectWrapperToString, 0 },
220 { "start", TimerStart, 0 },
221 { "stop", TimerStop, 0 },
222 { 0 }
223};
224
226
227void InitOOJSTimer(JSContext* context, JSObject* global)
228{
229 sTimerPrototype = JS_InitClass(context, global, NULL, &sTimerClass, TimerConstruct, 0, sTimerProperties, sTimerMethods, NULL, NULL);
231}
232
233static JSBool TimerGetProperty(JSContext* context, JSObject* this, jsid propID, jsval* value)
234{
235 if (!JSID_IS_INT(propID))
236 return YES;
237
238 OOJS_NATIVE_ENTER(context)
239
240 OOJSTimer* timer = nil;
241
242 if (EXPECT_NOT(!JSTimerGetTimer(context, this, &timer)))
243 return NO;
244
245 switch (JSID_TO_INT(propID)) {
246 case kTimer_nextTime:
247 return JS_NewNumberValue(context, [timer nextTime], value);
248
249 case kTimer_interval:
250 return JS_NewNumberValue(context, [timer interval], value);
251
252 case kTimer_isRunning:
253 *value = OOJSValueFromBOOL([timer isScheduled]);
254 return YES;
255
256 default:
257 OOJSReportBadPropertySelector(context, this, propID, sTimerProperties);
258 return NO;
259 }
260
262}
263
264static JSBool TimerSetProperty(JSContext* context, JSObject* this, jsid propID, JSBool strict, jsval* value)
265{
266 if (!JSID_IS_INT(propID))
267 return YES;
268
269 OOJS_NATIVE_ENTER(context)
270
271 OOJSTimer* timer = nil;
272 double fValue;
273
274 if (EXPECT_NOT(!JSTimerGetTimer(context, this, &timer)))
275 return NO;
276
277 switch (JSID_TO_INT(propID)) {
278 case kTimer_nextTime:
279 if (JS_ValueToNumber(context, *value, &fValue)) {
280 if (![timer setNextTime:fValue]) {
281 OOJSReportWarning(context, @"Ignoring attempt to change next fire time for running timer %@.", timer);
282 }
283 return YES;
284 }
285 break;
286
287 case kTimer_interval:
288 if (JS_ValueToNumber(context, *value, &fValue)) {
289 [timer setInterval:fValue];
290 return YES;
291 }
292 break;
293
294 default:
295 OOJSReportBadPropertySelector(context, this, propID, sTimerProperties);
296 return NO;
297 }
298
299 OOJSReportBadPropertyValue(context, this, propID, sTimerProperties, *value);
300 return NO;
301
303}
304
305static void TimerFinalize(JSContext* context, JSObject* this)
306{
308
309 // Can't use JSTimerGetTimer() here - potential chicken-and-egg problem manifesting as a crash.
310 OOJSTimer* timer = (OOJSTimer*)JS_GetPrivate(context, this);
311
312 if (timer != nil) {
313 if ([timer isScheduled]) {
314 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);
315 }
316 [timer release];
317 JS_SetPrivate(context, this, NULL);
318 }
319
321}
322
323// new Timer(this : Object, function : Function, delay : Number [, interval : Number]) : Timer
324static JSBool TimerConstruct(JSContext* context, uintN argc, jsval* vp)
325{
326 OOJS_NATIVE_ENTER(context)
327
328 jsval function = JSVAL_VOID;
329 double delay;
330 double interval = -1.0;
331 OOJSTimer* timer = nil;
332 JSObject* callbackThis = NULL;
333
334 if (EXPECT_NOT(!JS_IsConstructing(context, vp))) {
335 OOJSReportError(context, @"Timer() cannot be called as a function, it must be used as a constructor (as in new Timer(...)).");
336 return NO;
337 }
338
339 if (argc < 3) {
340 OOJSReportBadArguments(context, nil, @"Timer", argc, OOJS_ARGV, @"Invalid arguments in constructor", @"(object, function, number [, number])");
341 return NO;
342 }
343
344 if (!JSVAL_IS_NULL(OOJS_ARGV[0]) && !JSVAL_IS_VOID(OOJS_ARGV[0])) {
345 if (!JS_ValueToObject(context, OOJS_ARGV[0], &callbackThis)) {
346 OOJSReportBadArguments(context, nil, @"Timer", 1, OOJS_ARGV, @"Invalid argument in constructor", @"object");
347 return NO;
348 }
349 }
350
351 function = OOJS_ARGV[1];
352 if (JS_ValueToFunction(context, function) == NULL) {
353 OOJSReportBadArguments(context, nil, @"Timer", 1, OOJS_ARGV + 1, @"Invalid argument in constructor", @"function");
354 return NO;
355 }
356
357 if (!JS_ValueToNumber(context, OOJS_ARGV[2], &delay) || isnan(delay)) {
358 OOJSReportBadArguments(context, nil, @"Timer", 1, OOJS_ARGV + 2, @"Invalid argument in constructor", @"number");
359 return NO;
360 }
361
362 // Fourth argument is optional.
363 if (3 < argc && !JS_ValueToNumber(context, OOJS_ARGV[3], &interval))
364 interval = -1;
365
366 // Ensure interval is not too small.
367 if (0.0 < interval && interval < kMinInterval)
368 interval = kMinInterval;
369
370 timer = [[OOJSTimer alloc] initWithDelay:delay
371 interval:interval
372 context:context
373 function:function
374 this:callbackThis];
375 if (EXPECT_NOT(!timer))
376 return NO;
377
378 if (delay >= 0) // Leave in stopped state if delay is negative
379 {
380 [timer scheduleTimer];
381 }
382 [timer autorelease];
383 OOJS_RETURN_OBJECT(timer);
384
386}
387
388// *** Methods ***
389
390// start() : Boolean
391static JSBool TimerStart(JSContext* context, uintN argc, jsval* vp)
392{
393 OOJS_NATIVE_ENTER(context)
394
395 OOJSTimer* thisTimer = nil;
396
397 if (EXPECT_NOT(!JSTimerGetTimer(context, OOJS_THIS, &thisTimer)))
398 return NO;
399
400 OOJS_RETURN_BOOL([thisTimer scheduleTimer]);
401
403}
404
405// stop()
406static JSBool TimerStop(JSContext* context, uintN argc, jsval* vp)
407{
408 OOJS_NATIVE_ENTER(context)
409
410 OOJSTimer* thisTimer = nil;
411
412 if (EXPECT_NOT(!JSTimerGetTimer(context, OOJS_THIS, &thisTimer)))
413 return NO;
414
415 [thisTimer unscheduleTimer];
417
419}
#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 JSObject * sTimerPrototype
Definition OOJSTimer.m:33
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)
#define OOJS_PROP_READWRITE_CB
void OOJSRegisterObjectConverter(JSClass *theClass, OOJSClassConverterCallback converter)
id OOJSNativeObjectFromJSObject(JSContext *context, JSObject *object)
#define DEFINE_JS_OBJECT_GETTER(NAME, JSCLASS, JSPROTO, OBJCCLASSNAME)
#define OOJS_RETURN_OBJECT(o)
void OOJSReportBadPropertySelector(JSContext *context, JSObject *thisObj, jsid propID, JSPropertySpec *propertySpec)
#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 jsval OOJSValueFromBOOL(int b) INLINE_CONST_FUNC
#define OOJSAddGCObjectRoot(context, root, name)
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_PROP_READONLY_CB
#define OOJSAddGCValueRoot(context, root, name)
#define OOJS_RETURN_VOID
NSString * OOStringFromJSString(JSContext *context, JSString *string)
#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 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
static JSClassDef sTimerClass
Definition OOJSTimer.m:34
void pushScript:(OOJSScript *script)
Definition OOJSScript.m:480
OOJSScript * currentlyRunningScript()
Definition OOJSScript.m:101
void popScript:(OOJSScript *script)
Definition OOJSScript.m:493
jsval _function
Definition OOJSTimer.h:34
JSObject * _jsSelf
Definition OOJSTimer.h:39
void deleteJSPointers()
Definition OOJSTimer.m:85
void dealloc()
Definition OOJSTimer.m:104
void timerFired()
Definition OOJSTimer.m:138
JSObject * _jsThis
Definition OOJSTimer.h:35
NSString * descriptionComponents()
Definition OOJSTimer.m:113
NSString * oo_jsClassName()
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)
NSString * descriptionComponents()
id initWithNextTime:interval:(OOTimeAbsolute nextTime,[interval] OOTimeDelta interval)