0ad/source/ps/scripting/JSMap.h
olsner 7bcc12373b - Created JSMap
- Changed player colour JS interface: setColour(...) instead of a colour
property
- Introduced a network log and replaced most network LOG() calls with
NET_LOG()
- Moved to a slot-based system for Pre-Game and extended a lot of the JS
APIs to networking stuff
- A bit of cleanup in the low-level network code (Unix parts)
- Clients now keep track of all other connected clients on the server
(And exposes this info to JS)
- Split out GameAttributes to its own file
- Removed unused class AttributeMap
- Changed CJSObject to use T* pointers in JS_SetPrivate (needed to make
ToScript work with multiple inheritance)

This was SVN commit r1929.
2005-02-21 17:13:31 +00:00

99 lines
2.2 KiB
C++

#ifndef _ps_scripting_JSMap_H
#define _ps_scripting_JSMap_H
/*
A simple read-only JS wrapper for map types (STL associative containers).
Has been tested with integer keys. Writeability shouldn't be all that hard
to add, it's just not needed by the current users of the class.
*/
template <typename T, typename KeyType = typename T::key_type>
class CJSMap
{
T *m_pInstance;
JSObject *m_JSObject;
typedef typename T::iterator iterator;
static JSBool GetProperty( JSContext* cx, JSObject* obj, jsval id, jsval* vp )
{
CJSMap<T, KeyType> *object=ToNative<CJSMap<T, KeyType> >(cx, obj);
T *pInstance = object->m_pInstance;
KeyType key=ToPrimitive<KeyType>(id);
iterator it;
it=pInstance->find(key);
if (it == pInstance->end())
return JS_FALSE;
*vp=OBJECT_TO_JSVAL(ToScript(it->second));
return JS_TRUE;
}
static JSBool SetProperty( JSContext* cx, JSObject* obj, jsval id, jsval* vp )
{
return JS_FALSE;
}
void CreateScriptObject()
{
if( !m_JSObject )
{
m_JSObject = JS_NewObject( g_ScriptingHost.GetContext(), &JSI_class, NULL, NULL );
JS_AddRoot( g_ScriptingHost.GetContext(), (void*)&m_JSObject );
JS_SetPrivate( g_ScriptingHost.GetContext(), m_JSObject, this );
}
}
void ReleaseScriptObject()
{
if( m_JSObject )
{
JS_SetPrivate( g_ScriptingHost.GetContext(), m_JSObject, NULL );
JS_RemoveRoot( g_ScriptingHost.GetContext(), &m_JSObject );
m_JSObject = NULL;
}
}
public:
CJSMap(T* pInstance):
m_pInstance(pInstance),
m_JSObject(NULL)
{
}
~CJSMap()
{
ReleaseScriptObject();
}
JSObject *GetScript()
{
if (!m_JSObject)
CreateScriptObject();
return m_JSObject;
}
static void ScriptingInit(const char *className)
{
JSI_class.name=className;
g_ScriptingHost.DefineCustomObjectType(&JSI_class,
NULL, 0, NULL, NULL, NULL, NULL);
}
// Needs to be public for ToScript/ToNative
static JSClass JSI_class;
};
template<typename T, typename KeyType>
JSClass CJSMap<T, KeyType>::JSI_class =
{
NULL, JSCLASS_HAS_PRIVATE,
JS_PropertyStub, JS_PropertyStub,
GetProperty, SetProperty,
JS_EnumerateStub, JS_ResolveStub,
JS_ConvertStub, JS_FinalizeStub,
NULL, NULL, NULL, NULL
};
#endif // _ps_scripting_JSMap_H