File: ScriptableObject.h

package info (click to toggle)
0ad 0~r11863-2
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 30,560 kB
  • sloc: cpp: 201,230; ansic: 28,387; sh: 10,593; perl: 4,847; python: 2,240; makefile: 658; java: 412; xml: 243; sql: 40
file content (487 lines) | stat: -rw-r--r-- 12,618 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
/* Copyright (C) 2009 Wildfire Games.
 * This file is part of 0 A.D.
 *
 * 0 A.D. is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * 0 A.D. is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with 0 A.D.  If not, see <http://www.gnu.org/licenses/>.
 */

// ScriptableObject.h
//
// A quick way to add (mostly) sensibly-behaving JavaScript interfaces to native classes.
//

#ifndef INCLUDED_SCRIPTABLEOBJECT
#define INCLUDED_SCRIPTABLEOBJECT

#include <boost/unordered_map.hpp>
#include "scripting/ScriptingHost.h"
#include "JSConversions.h"

#include "lib/sysdep/stl.h"

#define ALLOW_NONSHARED_NATIVES

class IJSObject;

class IJSProperty
{
public:
	virtual ~IJSProperty() {};
	virtual jsval Get( JSContext* cx, IJSObject* obj ) = 0;
	virtual void Set( JSContext* cx, IJSObject* obj, jsval value ) = 0;
};

class IJSObject
{
public:
	typedef boost::unordered_map<CStrW, IJSProperty*> PropertyTable;

	// Property getters and setters
	typedef jsval (IJSObject::*GetFn)( JSContext* cx );
	typedef void (IJSObject::*SetFn)( JSContext* cx, jsval value );

	// Return a pointer to a property, if it exists
	virtual IJSProperty* HasProperty( const CStrW& PropertyName ) = 0;

	// Retrieve the value of a property (returning false if that property is not defined)
	virtual bool GetProperty( JSContext* cx, const CStrW& PropertyName, jsval* vp ) = 0;
	
	// Add a property (with immediate value)
	virtual void AddProperty( const CStrW& PropertyName, jsval Value ) = 0;
	
	inline IJSObject() {}
	virtual ~IJSObject() {}
};

template<typename T, bool ReadOnly = false> class CJSObject;

template<typename T, bool ReadOnly> class CJSProperty : public IJSProperty
{
	T IJSObject::*m_Data;

public:
	CJSProperty( T IJSObject::*Data )
	{
		m_Data = Data;
	}
	jsval Get( JSContext* UNUSED(cx), IJSObject* owner )
	{
		return( ToJSVal( owner->*m_Data ) );
	}
	void Set( JSContext* cx, IJSObject* owner, jsval Value )
	{
		if( !ReadOnly )
			ToPrimitive( cx, Value, owner->*m_Data );
	}
};

#ifdef ALLOW_NONSHARED_NATIVES

template<typename T, bool ReadOnly> class CJSNonsharedProperty : public IJSProperty
{
	T* m_Data;

public:
	CJSNonsharedProperty( T* Data )
	{
		m_Data = Data;
	}
	jsval Get( JSContext* UNUSED(cx), IJSObject* UNUSED(owner) )
	{
		return( ToJSVal( *m_Data ) );
	}
	void Set( JSContext* cx, IJSObject* UNUSED(owner), jsval Value )
	{
		if( !ReadOnly )
			ToPrimitive( cx, Value, *m_Data );
	}
};

#endif /* ALLOW_NONSHARED_NATIVES */

class CJSFunctionProperty : public IJSProperty
{
	// Function on Owner to get the value
	IJSObject::GetFn m_Getter;
	
	// Function on Owner to set the value
	IJSObject::SetFn m_Setter;

public:
	CJSFunctionProperty( IJSObject::GetFn Getter, IJSObject::SetFn Setter )
	{
		m_Getter = Getter;
		m_Setter = Setter;
		// Must at least be able to read 
		ENSURE( m_Getter );
	}
	jsval Get( JSContext* cx, IJSObject* obj )
	{
		return( (obj->*m_Getter)(cx) );
	}
	void Set( JSContext* cx, IJSObject* obj, jsval value )
	{
		if( m_Setter )
			(obj->*m_Setter)( cx, value );
	}
};

class CJSValProperty : public IJSProperty
{
	template<typename Q, bool ReadOnly> friend class CJSObject;

	jsval m_Data;

public:
	CJSValProperty( jsval Data )
	{
		m_Data = Data;
		Root();
	}
	~CJSValProperty()
	{
		Uproot();
	}
	void Root()
	{
		if( JSVAL_IS_GCTHING( m_Data ) )
			JS_AddNamedValueRoot( g_ScriptingHost.GetContext(), &m_Data, "ScriptableObjectProperty" );
	}
	void Uproot()
	{
		if( JSVAL_IS_GCTHING( m_Data ))
			JS_RemoveValueRoot( g_ScriptingHost.GetContext(), &m_Data );
	}
	jsval Get( JSContext* UNUSED(cx), IJSObject* UNUSED(object))
	{
		return( m_Data );
	}
	void Set( JSContext* UNUSED(cx), IJSObject* UNUSED(owner), jsval value )
	{
		Uproot();
		m_Data = value;
		Root();
	}
};

// Wrapper around native functions that are attached to CJSObjects

template<typename T, bool ReadOnly, typename RType, RType (T::*NativeFunction)( JSContext* cx, uintN argc, jsval* argv )> class CNativeFunction
{
public:
	static JSBool JSFunction( JSContext* cx, uintN argc, jsval* vp )
	{
		T* Native = ToNative<T>( cx, JS_THIS_OBJECT( cx, vp ) );
		if( !Native )
			return( JS_FALSE );

		jsval rval = ToJSVal<RType>( (Native->*NativeFunction)( cx, argc, JS_ARGV(cx, vp) ) );
		JS_SET_RVAL( cx, vp, rval );
		return( JS_TRUE );
	}
};

// Special case for void functions
template<typename T, bool ReadOnly, void (T::*NativeFunction)( JSContext* cx, uintN argc, jsval* argv )>
class CNativeFunction<T, ReadOnly, void, NativeFunction>
{
public:
	static JSBool JSFunction( JSContext* cx, uintN argc, jsval* vp )
	{
		T* Native = ToNative<T>( cx, JS_THIS_OBJECT( cx, vp ) );
		if( !Native )
			return( JS_FALSE );

		(Native->*NativeFunction)( cx, argc, JS_ARGV(cx, vp) );

		JS_SET_RVAL( cx, vp, JSVAL_VOID );
		return( JS_TRUE );
	}
};

template<typename T, bool ReadOnly> class CJSObject : public IJSObject
{
	// This object
	JSObject* m_JS;

protected:
	// The properties defined by the engine
	static PropertyTable m_NativeProperties;
#ifdef ALLOW_NONSHARED_NATIVES
	PropertyTable m_NonsharedProperties;
#endif
	// Properties added by script
	PropertyTable m_ScriptProperties;

	// Whether native code is responsible for managing this object.
	// Script constructors should clear this *BEFORE* creating a JS
	// mirror (otherwise it'll be rooted).

	bool m_EngineOwned;

public:
	// Property getters and setters
	typedef jsval (T::*TGetFn)( JSContext* );
	typedef void (T::*TSetFn)( JSContext*, jsval value );

	static JSClass JSI_class;

	static void ScriptingInit( const char* ClassName, JSNative Constructor = NULL, uintN ConstructorMinArgs = 0 )
	{
		JSFunctionSpec* JSI_methods = new JSFunctionSpec[ m_Methods.size() + 1 ];
		size_t MethodID;
		for( MethodID = 0; MethodID < m_Methods.size(); ++MethodID )
			JSI_methods[MethodID] = m_Methods[MethodID];

		JSI_methods[MethodID].name = 0;

		JSI_class.name = ClassName;
		g_ScriptingHost.DefineCustomObjectType( &JSI_class, Constructor, ConstructorMinArgs, JSI_props, JSI_methods, NULL, NULL );

		delete[]( JSI_methods );

		atexit( ScriptingShutdown );
	}
	static void ScriptingShutdown()
	{
		PropertyTable::iterator it;
		for( it = m_NativeProperties.begin(); it != m_NativeProperties.end(); ++it )
			delete( it->second );
		m_NativeProperties.clear();
	}

	// JS Property access
	bool GetProperty( JSContext* cx, const CStrW& PropertyName, jsval* vp )
	{
		IJSProperty* Property = HasProperty( PropertyName );
		if( Property )
			*vp = Property->Get( cx, this );

		return( true );
	}
	void SetProperty( JSContext* cx, const CStrW& PropertyName, jsval* vp )
	{
		if( !ReadOnly )
		{
			IJSProperty* prop = HasProperty( PropertyName );
			
			if( prop )
			{
				// Already exists
				prop->Set( cx, this, *vp );
			}
			else
			{
				// Need to add it
				AddProperty( PropertyName, *vp );
			}
		}
	}

	IJSProperty* HasProperty( const CStrW& PropertyName )
	{
		PropertyTable::iterator it;

		// Engine-defined properties take precedence
		it = m_NativeProperties.find( PropertyName );
		if( it != m_NativeProperties.end() )
			return( it->second );
		// Next are the object-local engine-defined properties
		// (if they're compiled in)
#ifdef ALLOW_NONSHARED_NATIVES
		it = m_NonsharedProperties.find( PropertyName );
		if( it != m_NonsharedProperties.end() )
			return( it->second );
#endif
		// Then check in script properties
		it = m_ScriptProperties.find( PropertyName );
		if( it != m_ScriptProperties.end() )
			return( it->second );

		// Otherwise not found
		return( NULL );
	}

	void AddProperty( const CStrW& PropertyName, jsval Value )
	{
		ENSURE( !HasProperty( PropertyName ) );
		CJSValProperty* newProp = new CJSValProperty( Value ); 
		m_ScriptProperties[PropertyName] = newProp;
	}
	static void AddProperty( const CStrW& PropertyName, TGetFn Getter, TSetFn Setter = NULL )
	{
		m_NativeProperties[PropertyName] = new CJSFunctionProperty( (GetFn)Getter, (SetFn)Setter );
	}
	template<typename ReturnType, ReturnType (T::*NativeFunction)( JSContext* cx, uintN argc, jsval* argv )> 
		static void AddMethod( const char* Name, uintN MinArgs )
	{
		JSFunctionSpec FnInfo = { Name, CNativeFunction<T, ReadOnly, ReturnType, NativeFunction>::JSFunction, (uint8)MinArgs, 0 };
		m_Methods.push_back( FnInfo );
	}
	template<typename PropType> static void AddProperty( const CStrW& PropertyName, PropType T::*Native, bool PropReadOnly = ReadOnly )
	{
		IJSProperty* prop;
		if( PropReadOnly )
		{
			prop = new CJSProperty<PropType, true>( (PropType IJSObject::*)Native );
		}
		else
		{
			prop = new CJSProperty<PropType, ReadOnly>( (PropType IJSObject::*)Native );
		}
		m_NativeProperties[PropertyName] = prop;
	}
#ifdef ALLOW_NONSHARED_NATIVES
	template<typename PropType> void AddLocalProperty( const CStrW& PropertyName, PropType* Native, bool PropReadOnly = ReadOnly )
	{
		IJSProperty* prop;
		if( PropReadOnly )
		{
			prop = new CJSNonsharedProperty<PropType, true>( Native );
		}
		else
			prop = new CJSNonsharedProperty<PropType, ReadOnly>( Native );
		m_NonsharedProperties[PropertyName] = prop;
	}
#endif

	// Object operations
	JSObject* GetScript() 
	{
		if( !m_JS )
			CreateScriptObject();
		return( m_JS );
	}
	// Creating and releasing script objects is done automatically most of the time, but you
	// can do it explicitly. 
	void CreateScriptObject()
	{
		if( !m_JS )
		{
			m_JS = JS_NewObject( g_ScriptingHost.GetContext(), &JSI_class, NULL, NULL );
			if( m_EngineOwned )
				JS_AddNamedObjectRoot( g_ScriptingHost.GetContext(), &m_JS, JSI_class.name );
	
			JS_SetPrivate( g_ScriptingHost.GetContext(), m_JS, (T*)this );
		}
	}
	void ReleaseScriptObject()
	{
		if( m_JS )
		{
			JS_SetPrivate( g_ScriptingHost.GetContext(), m_JS, NULL );
			if( m_EngineOwned )
				JS_RemoveObjectRoot( g_ScriptingHost.GetContext(), &m_JS );
			m_JS = NULL;
		}
	}

	// 
	// Functions and data that must be provided to JavaScript
	// 
private:
	static JSBool JSGetProperty( JSContext* cx, JSObject* obj, jsid id, jsval* vp )
	{
		T* Instance = ToNative<T>( cx, obj );
		if( !Instance )
			return( JS_TRUE );

		jsval idval;
		if( !JS_IdToValue( cx, id, &idval ) )
			return( JS_FALSE );

		CStrW PropName = g_ScriptingHost.ValueToUCString( idval );

		if( !Instance->GetProperty( cx, PropName, vp ) )
			return( JS_TRUE );
		
		return( JS_TRUE );
	}
	static JSBool JSSetProperty( JSContext* cx, JSObject* obj, jsid id, JSBool UNUSED(strict), jsval* vp )
	{
		T* Instance = ToNative<T>( cx, obj );
		if( !Instance )
			return( JS_TRUE );

		jsval idval;
		if( !JS_IdToValue( cx, id, &idval ) )
			return( JS_FALSE );

		CStrW PropName = g_ScriptingHost.ValueToUCString( idval );

		Instance->SetProperty( cx, PropName, vp );

		return( JS_TRUE );
	}
	static void DefaultFinalize( JSContext *cx, JSObject *obj )
	{
		T* Instance = ToNative<T>( cx, obj );
		if( !Instance || Instance->m_EngineOwned )
			return;
		
		delete( Instance );
		JS_SetPrivate( cx, obj, NULL );
	}

	
	static JSPropertySpec JSI_props[];
	static std::vector<JSFunctionSpec> m_Methods;
	
public:
	// Standard constructors/destructors
	CJSObject()
	{
		m_JS = NULL;
		m_EngineOwned = true;
	}
	virtual ~CJSObject()
	{
		Shutdown();
	}
	void Shutdown()
	{
		PropertyTable::iterator it;
		for( it = m_ScriptProperties.begin(); it != m_ScriptProperties.end(); ++it )
			delete( it->second );
		m_ScriptProperties.clear();
		ReleaseScriptObject();
#ifdef ALLOW_NONSHARED_NATIVES
		for( it = m_NonsharedProperties.begin(); it != m_NonsharedProperties.end(); ++it )
			delete( it->second );
		m_NonsharedProperties.clear();
#endif
	}
};

template<typename T, bool ReadOnly> JSClass CJSObject<T, ReadOnly>::JSI_class = {
	NULL, JSCLASS_HAS_PRIVATE,
	JS_PropertyStub, JS_PropertyStub,
	JSGetProperty, JSSetProperty,
	JS_EnumerateStub, JS_ResolveStub,
	JS_ConvertStub, DefaultFinalize,
	NULL, NULL, NULL, NULL,
	NULL, NULL, NULL, NULL
};

template<typename T, bool ReadOnly> JSPropertySpec CJSObject<T, ReadOnly>::JSI_props[] = {
	{ NULL, 0, 0, NULL, NULL },
};

template<typename T, bool ReadOnly> std::vector<JSFunctionSpec> CJSObject<T, ReadOnly>::m_Methods;

template<typename T, bool ReadOnly> typename CJSObject<T, ReadOnly>::PropertyTable CJSObject<T, ReadOnly>::m_NativeProperties;

#endif