CHANGED: #1471 Moved the stuff I moved to NELGUI library, under the NLGUI namespace.

This commit is contained in:
dfighter1985 2012-05-23 19:40:41 +02:00
parent 731d1ced46
commit c817c68e83
21 changed files with 2318 additions and 2274 deletions

View file

@ -19,8 +19,9 @@
#include "nel/misc/types_nl.h" #include "nel/misc/types_nl.h"
#include "nel/gui/lua_helper.h" #include "nel/gui/lua_helper.h"
using namespace NLGUI;
#define IHM_LUA_METATABLE "__ui_metatable"
#define IHM_LUA_ENVTABLE "__ui_envtable"
namespace NLMISC namespace NLMISC
{ {
@ -29,133 +30,122 @@ namespace NLMISC
class CRGBA; class CRGBA;
} }
class CReflectable; namespace NLGUI
class CReflectedProperty;
// ***************************************************************************
/* Use this Exception for all LUA Error (eg: scripted passes bad number of paramters).
* Does not herit from Exception because avoid nlinfo, because sent twice (catch then resent)
* This is special to lua and IHM since it works with CLuaStackChecker, and also append to the error msg
* the FileName/LineNumber
*/
class ELuaIHMException : public ELuaWrappedFunctionException
{ {
private:
static CLuaState *getLuaState(); class CReflectable;
public: class CReflectedProperty;
ELuaIHMException() : ELuaWrappedFunctionException(getLuaState())
// ***************************************************************************
/* Use this Exception for all LUA Error (eg: scripted passes bad number of paramters).
* Does not herit from Exception because avoid nlinfo, because sent twice (catch then resent)
* This is special to lua and IHM since it works with CLuaStackChecker, and also append to the error msg
* the FileName/LineNumber
*/
class ELuaIHMException : public ELuaWrappedFunctionException
{ {
} private:
ELuaIHMException(const std::string &reason) : ELuaWrappedFunctionException(getLuaState(), reason) static CLuaState *getLuaState();
public:
ELuaIHMException() : ELuaWrappedFunctionException(getLuaState())
{
}
ELuaIHMException(const std::string &reason) : ELuaWrappedFunctionException(getLuaState(), reason)
{
}
ELuaIHMException(const char *format, ...) : ELuaWrappedFunctionException(getLuaState())
{
std::string reason;
NLMISC_CONVERT_VARGS (reason, format, NLMISC::MaxCStringSize);
init(getLuaState(), reason);
}
};
// ***************************************************************************
/**
* Define Functions to export from C to LUA
* \author Lionel Berenguier
* \author Nevrax France
* \date 2004
*/
class CLuaIHM
{ {
} public:
ELuaIHMException(const char *format, ...) : ELuaWrappedFunctionException(getLuaState()) static void registerAll(CLuaState &ls);
{
std::string reason; /** CReflectableInterfaceElement management on stack, stored by a CRefPtr.
NLMISC_CONVERT_VARGS (reason, format, NLMISC::MaxCStringSize); * May be called as well for ui element, because they derive from CReflectableRefPtrTarget
init(getLuaState(), reason); */
} static void pushReflectableOnStack(CLuaState &ls, class CReflectableRefPtrTarget *pRPT);
}; static bool isReflectableOnStack(CLuaState &ls, sint index);
static CReflectableRefPtrTarget *getReflectableOnStack(CLuaState &ls, sint index);
// *************************************************************************** // ucstring
#define IHM_LUA_METATABLE "__ui_metatable" static bool pop(CLuaState &ls, ucstring &dest);
#define IHM_LUA_ENVTABLE "__ui_envtable" static void push(CLuaState &ls, const ucstring &value);
static bool isUCStringOnStack(CLuaState &ls, sint index);
static bool getUCStringOnStack(CLuaState &ls, sint index, ucstring &dest);
// *************************************************************************** // RGBA
/** static bool pop(CLuaState &ls, NLMISC::CRGBA &dest);
* Define Functions to export from C to LUA
* \author Lionel Berenguier
* \author Nevrax France
* \date 2004
*/
class CLuaIHM
{
public:
static void registerAll(CLuaState &ls);
/** CReflectableInterfaceElement management on stack, stored by a CRefPtr. // CVector2f
* May be called as well for ui element, because they derive from CReflectableRefPtrTarget static bool pop(CLuaState &ls, NLMISC::CVector2f &dest);
*/
static void pushReflectableOnStack(CLuaState &ls, class CReflectableRefPtrTarget *pRPT);
static bool isReflectableOnStack(CLuaState &ls, sint index);
static CReflectableRefPtrTarget *getReflectableOnStack(CLuaState &ls, sint index);
// helper : get a 2D poly (a table of cvector2f) from a lua table (throw on fail)
static void getPoly2DOnStack(CLuaState &ls, sint index, NLMISC::CPolygon2D &dest);
// ucstring // argument checkin helpers
static bool pop(CLuaState &ls, ucstring &dest); static void checkArgCount(CLuaState &ls, const char* funcName, uint nArgs); // check that number of argument is exactly the one required
static void push(CLuaState &ls, const ucstring &value); static void checkArgMin(CLuaState &ls, const char* funcName, uint nArgs); // check that number of argument is at least the one required
static bool isUCStringOnStack(CLuaState &ls, sint index); static void checkArgMax(CLuaState &ls, const char* funcName, uint nArgs); // check that number of argument is at most the one required
static bool getUCStringOnStack(CLuaState &ls, sint index, ucstring &dest); static void check(CLuaState &ls, bool ok, const std::string &failReason);
static void checkArgType(CLuaState &ls, const char *funcName, uint index, int argType);
static void checkArgTypeRGBA(CLuaState &ls, const char *funcName, uint index);
static void checkArgTypeUCString(CLuaState &ls, const char *funcName, uint index);
/** throw a lua expection (inside a C function called from lua) with the given reason, and the current call stack
* The various check... function call this function when their test fails
*/
static void fails(CLuaState &ls, const char *format, ...);
// pop a sint32 from a lua stack, throw an exception on fail
static bool popSINT32(CLuaState &ls, sint32 & dest);
bool popString(CLuaState &ls, std::string & dest);
// RGBA /** read/write between values on a lua stack & a property exported from a 'CReflectable' derived object
static bool pop(CLuaState &ls, NLMISC::CRGBA &dest); * (throws on error)
*/
static void luaValueToReflectedProperty(CLuaState &ls, int stackIndex, CReflectable &target, const CReflectedProperty &property) throw(ELuaIHMException);
// CVector2f // push a reflected property on the stack
static bool pop(CLuaState &ls, NLMISC::CVector2f &dest); // NB : no check is done that 'property' is part of the class info of 'reflectedObject'
static void luaValueFromReflectedProperty(CLuaState &ls, CReflectable &reflectedObject, const CReflectedProperty &property);
// helper : get a 2D poly (a table of cvector2f) from a lua table (throw on fail)
static void getPoly2DOnStack(CLuaState &ls, sint index, NLMISC::CPolygon2D &dest);
// argument checkin helpers
static void checkArgCount(CLuaState &ls, const char* funcName, uint nArgs); // check that number of argument is exactly the one required
static void checkArgMin(CLuaState &ls, const char* funcName, uint nArgs); // check that number of argument is at least the one required
static void checkArgMax(CLuaState &ls, const char* funcName, uint nArgs); // check that number of argument is at most the one required
static void check(CLuaState &ls, bool ok, const std::string &failReason);
static void checkArgType(CLuaState &ls, const char *funcName, uint index, int argType);
static void checkArgTypeRGBA(CLuaState &ls, const char *funcName, uint index);
static void checkArgTypeUCString(CLuaState &ls, const char *funcName, uint index);
/** throw a lua expection (inside a C function called from lua) with the given reason, and the current call stack
* The various check... function call this function when their test fails
*/
static void fails(CLuaState &ls, const char *format, ...);
// pop a sint32 from a lua stack, throw an exception on fail
static bool popSINT32(CLuaState &ls, sint32 & dest);
bool popString(CLuaState &ls, std::string & dest);
/** read/write between values on a lua stack & a property exported from a 'CReflectable' derived object
* (throws on error)
*/
static void luaValueToReflectedProperty(CLuaState &ls, int stackIndex, CReflectable &target, const CReflectedProperty &property) throw(ELuaIHMException);
// push a reflected property on the stack
// NB : no check is done that 'property' is part of the class info of 'reflectedObject'
static void luaValueFromReflectedProperty(CLuaState &ls, CReflectable &reflectedObject, const CReflectedProperty &property);
private: private:
static void registerBasics(CLuaState &ls);
static void registerIHM(CLuaState &ls);
static void createLuaEnumTable(CLuaState &ls, const std::string &str);
//////////////////////////////////////////// Exported functions //////////////////////////////////////////////////////
static uint32 getLocalTime();
static double getPreciseLocalTime();
static std::string findReplaceAll(const std::string &str, const std::string &search, const std::string &replace);
static ucstring findReplaceAll(const ucstring &str, const ucstring &search, const ucstring &replace);
static ucstring findReplaceAll(const ucstring &str, const std::string &search, const std::string &replace);
static ucstring findReplaceAll(const ucstring &str, const std::string &search, const ucstring &replace);
static ucstring findReplaceAll(const ucstring &str, const ucstring &search, const std::string &replace);
static void registerBasics(CLuaState &ls); //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void registerIHM(CLuaState &ls);
static void createLuaEnumTable(CLuaState &ls, const std::string &str);
/// \name Exported Functions static int luaMethodCall(lua_State *ls);
// @{ };
// LUA exported Functions with luabind
static uint32 getLocalTime();
static double getPreciseLocalTime();
static std::string findReplaceAll(const std::string &str, const std::string &search, const std::string &replace);
static ucstring findReplaceAll(const ucstring &str, const ucstring &search, const ucstring &replace);
// just for ease of use
static ucstring findReplaceAll(const ucstring &str, const std::string &search, const std::string &replace);
static ucstring findReplaceAll(const ucstring &str, const std::string &search, const ucstring &replace);
static ucstring findReplaceAll(const ucstring &str, const ucstring &search, const std::string &replace);
// @}
// Function export tools
// Function to forward lua call to C++ to a 'lua method' exported from a reflected object
static int luaMethodCall(lua_State *ls);
};
}
#endif // NL_LUA_IHM_H #endif // NL_LUA_IHM_H

View file

@ -22,36 +22,36 @@
namespace NLGUI namespace NLGUI
{ {
class CLuaState; class CLuaState;
/// Provides a single global access point to the Lua state, and related stuff. :(
class CLuaManager
{
public:
~CLuaManager();
static CLuaManager& getInstance()
{
if( instance == NULL )
{
instance = new CLuaManager();
}
return *instance;
}
/// Enables attaching the Lua debugger in the CLuaState instance, only matters on startup.
static void enableLuaDebugging(){ debugLua = true; }
NLGUI::CLuaState* getLuaState() const{ return luaState; }
private:
CLuaManager();
static CLuaManager *instance;
static bool debugLua;
NLMISC::CSmartPtr< NLGUI::CLuaState > luaState;
};
} }
/// Provides a single global access point to the Lua state, and related stuff. :(
class CLuaManager
{
public:
~CLuaManager();
static CLuaManager& getInstance()
{
if( instance == NULL )
{
instance = new CLuaManager();
}
return *instance;
}
/// Enables attaching the Lua debugger in the CLuaState instance, only matters on startup.
static void enableLuaDebugging(){ debugLua = true; }
NLGUI::CLuaState* getLuaState() const{ return luaState; }
private:
CLuaManager();
static CLuaManager *instance;
static bool debugLua;
NLMISC::CSmartPtr< NLGUI::CLuaState > luaState;
};
#endif #endif

View file

@ -20,282 +20,284 @@
#include "nel/misc/smart_ptr.h" #include "nel/misc/smart_ptr.h"
#include "nel/misc/rgba.h" #include "nel/misc/rgba.h"
//
#include "nel/gui/lua_helper.h" #include "nel/gui/lua_helper.h"
using namespace NLGUI;
namespace NLGUI
class CLuaEnumeration;
/**
* Wrapper to a lua value
*
* Useful to navigate through lua tables without having to deal with the stack.
*
* The following types are tracked by reference :
* - lua table
* - lua user data
* - lua functions
*
* The following types are kept by value :
*
* - lua numbers
* - lua strings ?
* - lua boolean
* - lua light user datas
* - lua 'pointers'
*
* Each reference object has an id giving its path in order to track bugs more easily
*/
class CLuaObject
{ {
public:
CLuaObject() {}
~CLuaObject();
// Build this object by popping it from the given lua state
CLuaObject(CLuaState &state, const char *id ="");
CLuaObject(CLuaState &state, const std::string &id);
// Build this object from another object
CLuaObject(const CLuaObject &other);
// Copy refrence to another lua object
CLuaObject &operator=(const CLuaObject &other);
// Get id for that object
const std::string &getId() const { return _Id; }
// Set id for that object
void setId(const std::string &id) { _Id = id; }
// See if the obj
bool isValid() const;
// Pop a new value for this lua object from the top of the stack. The stack must not be empty
void pop(CLuaState &luaState, const char *id ="");
// Push the object that is being referenced on the stack
// An assertion is raised if 'pop' hasn't been called or
// if the lua state has been destroyed
void push() const;
// Get the lua state in which the object resides.
CLuaState *getLuaState() const;
// Release the object. 'pop' must be called to make the object valid again
void release();
// type queries
int type() const;
const char *getTypename() const;
bool isNil() const;
bool isNumber() const;
bool isBoolean() const;
bool isString() const;
bool isFunction() const;
bool isCFunction() const;
bool isTable() const;
bool isUserData() const;
bool isLightUserData() const;
bool isRGBA() const;
// equality
bool rawEqual(const CLuaObject &other) const;
// conversions (no throw) : the actual value of object is not modified!!
NLMISC::CRGBA toRGBA() const; // default to black if not a crgba
bool toBoolean() const;
lua_Number toNumber() const;
std::string toString() const;
lua_CFunction toCFunction() const;
void *toUserData() const;
const void *toPointer() const;
// implicit conversions (no throw)
operator bool() const;
operator float() const;
operator double() const;
operator std::string() const;
/** create a sub table for this object, with a string as a key
* This object must be a table or an exception if thrown
*/
CLuaObject newTable(const char *tableName) throw(ELuaNotATable);
class CLuaEnumeration;
/** Set a value in a table. /**
* If this object is not a table then an exception is thrown * Wrapper to a lua value
* NB : value should came from the same lua environment *
* \TODO other type of keys * Useful to navigate through lua tables without having to deal with the stack.
*
* The following types are tracked by reference :
* - lua table
* - lua user data
* - lua functions
*
* The following types are kept by value :
*
* - lua numbers
* - lua strings ?
* - lua boolean
* - lua light user datas
* - lua 'pointers'
*
* Each reference object has an id giving its path in order to track bugs more easily
*/ */
void setValue(const char *key, const CLuaObject &value) throw(ELuaNotATable); class CLuaObject
void setValue(const std::string &key, const CLuaObject &value) throw(ELuaNotATable) { setValue(key.c_str(), value); }
void setValue(const char *key, const std::string &value) throw(ELuaNotATable);
void setValue(const char *key, const char *value) throw(ELuaNotATable);
void setValue(const char *key, bool value) throw(ELuaNotATable);
void setValue(const char *key, TLuaWrappedFunction value) throw(ELuaNotATable);
void setValue(const char *key, double value) throw(ELuaNotATable);
void setValue(const std::string &key, const std::string &value) throw(ELuaNotATable) { setValue(key.c_str(), value); }
void setNil(const char *key) throw(ELuaNotATable);
void setNil(const std::string &key) throw(ELuaNotATable) { setNil(key.c_str()); }
/** Erase a value in a table by its key.
* If this object is not a table then an exception is thrown.
* \TODO other type of keys
*/
void eraseValue(const char *key) throw(ELuaNotATable);
void eraseValue(const std::string &key) throw(ELuaNotATable) { eraseValue(key.c_str()); }
// test is this object is enumerable
bool isEnumerable() const;
// Enumeration of a table. If the object is not a table, an exception is thrown.
CLuaEnumeration enumerate() throw(ELuaNotATable);
// retrieve metatable of an object (or nil if object has no metatable)
CLuaObject getMetaTable() const;
// set metatable for this object
bool setMetaTable(CLuaObject &metatable);
/** Access to a sub element of a table (no throw).
* if the element is not a table, then 'nil' is returned
* TODO nico : add other key types if needed
* TODO nico : version that takes destination object as a reference in its parameter to avoid an object copy
*/
CLuaObject operator[](double key) const;
CLuaObject operator[](const char *key) const;
CLuaObject operator[](const std::string &key) const { return operator[](key.c_str()); }
/** Checked access to a sub element of a table. An exception is thrown is the element is not a table.
*/
CLuaObject at(const char *key) const throw (ELuaNotATable);
CLuaObject at(const std::string &key) const { return at(key.c_str()); }
// Test is that table has the given key. The object must be a table or an exception is thrown
bool hasKey(const char *key) const;
/** debug : recursively get value (useful for table)
* \param maxDepth (0 for no limit)
* \param alreadySeen pointer to lua tables that have already been displayed by the command (to avoid infinite recursion when a cycluic graph is encountered)
*/
std::string toStringRecurse(uint depth = 0, uint maxDepth = 20, std::set<const void *> *alreadySeen = NULL) const;
/** dump the value in the log (includes tables)
* \param alreadySeen pointer to lua tables that have already been displayed by the command (to avoid infinite recursion when a cycluic graph is encountered)
*/
void dump(uint maxDepth = 20, std::set<const void *> *alreadySeen = NULL) const;
// concatenate identifiers, adding a dot between them if necessary. If right is a number then brackets are added
static std::string concatId(const std::string &left, const std::string &right);
// If this object is a function, then call it and return true on success
bool callNoThrow(int numArgs, int numRet);
// Call a method of this table by name (no throw version)
bool callMethodByNameNoThrow(const char *name, int numArgs, int numRet);
private:
NLMISC::CRefPtr<CLuaState> _LuaState;
std::string _Id;
};
/** enumeration of the content of a lua table
*
* Example of use :
*
*\code
CLuaObject table;
table.pop(luaState); // retrieve table from the top of a lua stack
CLuaEnumeration enueration = table.enumerate();
while (enumeration.hasNext())
{ {
nlinfo('key = %s", enumeration.nextKey().toString().c_str()); public:
nlinfo('value = %s", enumeration.nextValue().toString().c_str()); CLuaObject() {}
enumeration.next(); ~CLuaObject();
// Build this object by popping it from the given lua state
CLuaObject(CLuaState &state, const char *id ="");
CLuaObject(CLuaState &state, const std::string &id);
// Build this object from another object
CLuaObject(const CLuaObject &other);
// Copy refrence to another lua object
CLuaObject &operator=(const CLuaObject &other);
// Get id for that object
const std::string &getId() const { return _Id; }
// Set id for that object
void setId(const std::string &id) { _Id = id; }
// See if the obj
bool isValid() const;
// Pop a new value for this lua object from the top of the stack. The stack must not be empty
void pop(CLuaState &luaState, const char *id ="");
// Push the object that is being referenced on the stack
// An assertion is raised if 'pop' hasn't been called or
// if the lua state has been destroyed
void push() const;
// Get the lua state in which the object resides.
CLuaState *getLuaState() const;
// Release the object. 'pop' must be called to make the object valid again
void release();
// type queries
int type() const;
const char *getTypename() const;
bool isNil() const;
bool isNumber() const;
bool isBoolean() const;
bool isString() const;
bool isFunction() const;
bool isCFunction() const;
bool isTable() const;
bool isUserData() const;
bool isLightUserData() const;
bool isRGBA() const;
// equality
bool rawEqual(const CLuaObject &other) const;
// conversions (no throw) : the actual value of object is not modified!!
NLMISC::CRGBA toRGBA() const; // default to black if not a crgba
bool toBoolean() const;
lua_Number toNumber() const;
std::string toString() const;
lua_CFunction toCFunction() const;
void *toUserData() const;
const void *toPointer() const;
// implicit conversions (no throw)
operator bool() const;
operator float() const;
operator double() const;
operator std::string() const;
/** create a sub table for this object, with a string as a key
* This object must be a table or an exception if thrown
*/
CLuaObject newTable(const char *tableName) throw(ELuaNotATable);
/** Set a value in a table.
* If this object is not a table then an exception is thrown
* NB : value should came from the same lua environment
* \TODO other type of keys
*/
void setValue(const char *key, const CLuaObject &value) throw(ELuaNotATable);
void setValue(const std::string &key, const CLuaObject &value) throw(ELuaNotATable) { setValue(key.c_str(), value); }
void setValue(const char *key, const std::string &value) throw(ELuaNotATable);
void setValue(const char *key, const char *value) throw(ELuaNotATable);
void setValue(const char *key, bool value) throw(ELuaNotATable);
void setValue(const char *key, TLuaWrappedFunction value) throw(ELuaNotATable);
void setValue(const char *key, double value) throw(ELuaNotATable);
void setValue(const std::string &key, const std::string &value) throw(ELuaNotATable) { setValue(key.c_str(), value); }
void setNil(const char *key) throw(ELuaNotATable);
void setNil(const std::string &key) throw(ELuaNotATable) { setNil(key.c_str()); }
/** Erase a value in a table by its key.
* If this object is not a table then an exception is thrown.
* \TODO other type of keys
*/
void eraseValue(const char *key) throw(ELuaNotATable);
void eraseValue(const std::string &key) throw(ELuaNotATable) { eraseValue(key.c_str()); }
// test is this object is enumerable
bool isEnumerable() const;
// Enumeration of a table. If the object is not a table, an exception is thrown.
CLuaEnumeration enumerate() throw(ELuaNotATable);
// retrieve metatable of an object (or nil if object has no metatable)
CLuaObject getMetaTable() const;
// set metatable for this object
bool setMetaTable(CLuaObject &metatable);
/** Access to a sub element of a table (no throw).
* if the element is not a table, then 'nil' is returned
* TODO nico : add other key types if needed
* TODO nico : version that takes destination object as a reference in its parameter to avoid an object copy
*/
CLuaObject operator[](double key) const;
CLuaObject operator[](const char *key) const;
CLuaObject operator[](const std::string &key) const { return operator[](key.c_str()); }
/** Checked access to a sub element of a table. An exception is thrown is the element is not a table.
*/
CLuaObject at(const char *key) const throw (ELuaNotATable);
CLuaObject at(const std::string &key) const { return at(key.c_str()); }
// Test is that table has the given key. The object must be a table or an exception is thrown
bool hasKey(const char *key) const;
/** debug : recursively get value (useful for table)
* \param maxDepth (0 for no limit)
* \param alreadySeen pointer to lua tables that have already been displayed by the command (to avoid infinite recursion when a cycluic graph is encountered)
*/
std::string toStringRecurse(uint depth = 0, uint maxDepth = 20, std::set<const void *> *alreadySeen = NULL) const;
/** dump the value in the log (includes tables)
* \param alreadySeen pointer to lua tables that have already been displayed by the command (to avoid infinite recursion when a cycluic graph is encountered)
*/
void dump(uint maxDepth = 20, std::set<const void *> *alreadySeen = NULL) const;
// concatenate identifiers, adding a dot between them if necessary. If right is a number then brackets are added
static std::string concatId(const std::string &left, const std::string &right);
// If this object is a function, then call it and return true on success
bool callNoThrow(int numArgs, int numRet);
// Call a method of this table by name (no throw version)
bool callMethodByNameNoThrow(const char *name, int numArgs, int numRet);
private:
NLMISC::CRefPtr<CLuaState> _LuaState;
std::string _Id;
}; };
\endcode
*
* There is a macro called 'ENUM_LUA_TABLE' to automate that process. /** enumeration of the content of a lua table
* Previous code would then be written as follow : *
* * Example of use :
* *
*\code *\code
CLuaObject table; CLuaObject table;
table.pop(luaState); // retrieve table from the top of a lua stack table.pop(luaState); // retrieve table from the top of a lua stack
ENUM_LUA_TABLE(table, enumeration); CLuaEnumeration enueration = table.enumerate();
while (enumeration.hasNext())
{
nlinfo('key = %s", enumeration.nextKey().toString().c_str());
nlinfo('value = %s", enumeration.nextValue().toString().c_str());
enumeration.next();
};
\endcode
*
* There is a macro called 'ENUM_LUA_TABLE' to automate that process.
* Previous code would then be written as follow :
*
*
*\code
CLuaObject table;
table.pop(luaState); // retrieve table from the top of a lua stack
ENUM_LUA_TABLE(table, enumeration);
{
nlinfo('key = %s", enumeration.nextKey().toString().c_str());
nlinfo('value = %s", enumeration.nextValue().toString().c_str());
};
\endcode
*
*/
class CLuaEnumeration
{ {
nlinfo('key = %s", enumeration.nextKey().toString().c_str()); public:
nlinfo('value = %s", enumeration.nextValue().toString().c_str()); // is there a next key,value pair in the table
bool hasNext() { return _HasNext; }
// Return next key. Assertion if 'hasNext' is false
const CLuaObject &nextKey() const;
// Return next value. Assertion if 'hasNext' is false
CLuaObject &nextValue();
// Go to the next value. Assertion if there's no such value
void next();
private:
friend class CLuaObject;
// current value & key
CLuaObject _Table;
CLuaObject _Key;
CLuaObject _Value;
CLuaObject _NextFunction; // pointer to the global 'next' function
bool _HasNext;
// construction from a table on the stack
CLuaEnumeration(CLuaObject &table);
}; };
\endcode
*
*/
class CLuaEnumeration
{
public:
// is there a next key,value pair in the table
bool hasNext() { return _HasNext; }
// Return next key. Assertion if 'hasNext' is false
const CLuaObject &nextKey() const;
// Return next value. Assertion if 'hasNext' is false
CLuaObject &nextValue();
// Go to the next value. Assertion if there's no such value
void next();
private:
friend class CLuaObject;
// current value & key
CLuaObject _Table;
CLuaObject _Key;
CLuaObject _Value;
CLuaObject _NextFunction; // pointer to the global 'next' function
bool _HasNext;
// construction from a table on the stack
CLuaEnumeration(CLuaObject &table);
};
/** macro to ease lua table enumeration /** macro to ease lua table enumeration
* \param object A CLuaObject which must be a table, and on which enumeration is done. An exception will be thrown as 'CLuaObject::enumerate' is * \param object A CLuaObject which must be a table, and on which enumeration is done. An exception will be thrown as 'CLuaObject::enumerate' is
* called if this is not the case * called if this is not the case
* \param enumerator The enumerator object * \param enumerator The enumerator object
*/ */
#define ENUM_LUA_TABLE(object, enumerator) for(CLuaEnumeration enumerator = (object).enumerate(); enumerator.hasNext(); enumerator.next()) #define ENUM_LUA_TABLE(object, enumerator) for(CLuaEnumeration enumerator = (object).enumerate(); enumerator.hasNext(); enumerator.next())
//opitmized lua string for fast comparison //opitmized lua string for fast comparison
class CLuaString class CLuaString
{
public:
explicit CLuaString(const char *value = "")
{ {
nlassert( value != NULL ); public:
_Str = value; explicit CLuaString(const char *value = "")
{
nlassert( value != NULL );
_Str = value;
}
const std::string& getStr() const{ return _Str; }
private:
std::string _Str;
mutable CLuaState::TRefPtr _LuaState; // ref ptr so that statics get rebuilt on lua restart
mutable CLuaObject _InLua;
};
inline bool operator==(const char* lh, const CLuaString& rh)
{
return std::string(lh) == rh.getStr();
} }
const std::string& getStr() const{ return _Str; }
private:
std::string _Str;
mutable CLuaState::TRefPtr _LuaState; // ref ptr so that statics get rebuilt on lua restart
mutable CLuaObject _InLua;
};
inline bool operator==(const char* lh, const CLuaString& rh) inline bool operator==( const CLuaString& lh, const CLuaString& rh)
{ {
return std::string(lh) == rh.getStr(); return lh.getStr() == rh.getStr();
}
inline bool operator==(const CLuaString& lh, const char* rh)
{
return std::string(rh) == lh.getStr();
}
inline bool operator==( const CLuaString& lh, const std::string& rh)
{
return lh.getStr() == rh;
}
inline bool operator==(const std::string& lh, const CLuaString& rh)
{
return lh == rh.getStr();
}
class CLuaHashMapTraits
{
public:
static const size_t bucket_size = 4;
static const size_t min_buckets = 8;
CLuaHashMapTraits()
{}
// hasher for lua string -> they are unique pointers for each string, so just hash a pointer instead of a string...
size_t operator()(const char *value) const { return ((size_t) value) >> 3; }
// equality for lua string for hash_map -> they are unique pointer -> compare pointers instead of string content
bool operator()(const char *lhs, const char *rhs) const { return lhs < rhs; }
};
} }
inline bool operator==( const CLuaString& lh, const CLuaString& rh)
{
return lh.getStr() == rh.getStr();
}
inline bool operator==(const CLuaString& lh, const char* rh)
{
return std::string(rh) == lh.getStr();
}
inline bool operator==( const CLuaString& lh, const std::string& rh)
{
return lh.getStr() == rh;
}
inline bool operator==(const std::string& lh, const CLuaString& rh)
{
return lh == rh.getStr();
}
class CLuaHashMapTraits
{
public:
static const size_t bucket_size = 4;
static const size_t min_buckets = 8;
CLuaHashMapTraits()
{}
// hasher for lua string -> they are unique pointers for each string, so just hash a pointer instead of a string...
size_t operator()(const char *value) const { return ((size_t) value) >> 3; }
// equality for lua string for hash_map -> they are unique pointer -> compare pointers instead of string content
bool operator()(const char *lhs, const char *rhs) const { return lhs < rhs; }
};
#endif #endif

View file

@ -14,358 +14,355 @@
// You should have received a copy of the GNU Affero General Public License // You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>. // along with this program. If not, see <http://www.gnu.org/licenses/>.
#ifndef CL_REFLECT_H #ifndef CL_REFLECT_H
#define CL_REFLECT_H #define CL_REFLECT_H
#include "nel/misc/rgba.h" #include "nel/misc/rgba.h"
#include "nel/gui/lua_object.h" #include "nel/gui/lua_object.h"
//
#include <string> #include <string>
class CReflectable;
namespace NLGUI namespace NLGUI
{ {
class CReflectable;
class CLuaState; class CLuaState;
} struct CClassInfo;
struct CClassInfo;
/** A property of a reflectable object /** A property of a reflectable object
* NB: multiple inheritance not supported * NB: multiple inheritance not supported
*/
class CReflectedProperty
{
public:
enum TType { Boolean = 0,
SInt32,
UInt32,
Float,
String,
UCString,
RGBA,
LuaMethod
}; // other types will be added when needed
// define some pointer-to-member types
typedef bool (CReflectable::* TGetBool) () const;
typedef sint32 (CReflectable::* TGetSInt32) () const;
typedef uint32 (CReflectable::* TGetUInt32) () const;
typedef float (CReflectable::* TGetFloat) () const;
typedef std::string (CReflectable::* TGetString) () const;
typedef ucstring (CReflectable::* TGetUCString) () const;
typedef NLMISC::CRGBA (CReflectable::* TGetRGBA) () const;
//
typedef void (CReflectable::* TSetBool) (bool);
typedef void (CReflectable::* TSetSInt32) (sint32);
typedef void (CReflectable::* TSetUInt32) (uint32);
typedef void (CReflectable::* TSetFloat) (float);
typedef void (CReflectable::* TSetString) (const std::string &);
typedef void (CReflectable::* TSetUCString) (const ucstring &);
typedef void (CReflectable::* TSetRGBA) (NLMISC::CRGBA col);
//
typedef int (CReflectable:: *TLuaMethod) (CLuaState &luaState);
public:
TType Type;
// In each union we have method pointers to retrieve / set the data of the desired type (as told in 'Type')
union
{
TGetBool GetBool;
TGetSInt32 GetSInt32;
TGetUInt32 GetUInt32;
TGetFloat GetFloat;
TGetString GetString;
TGetUCString GetUCString;
TGetRGBA GetRGBA;
TLuaMethod GetLuaMethod; // lua method can only be obtained, not written ...
} GetMethod;
union
{
TSetBool SetBool;
TSetSInt32 SetSInt32;
TSetUInt32 SetUInt32;
TSetFloat SetFloat;
TSetString SetString;
TSetUCString SetUCString;
TSetRGBA SetRGBA;
} SetMethod;
// name of the property
std::string Name;
mutable CLuaObject LuaMethodRef; // cache pointer to function call if type == LuaMethod
const CClassInfo *ParentClass; // filled when 'registerClass' is called
};
// a vector of reflected properties
typedef std::vector<CReflectedProperty> TReflectedProperties;
struct CClassInfo;
/** Base class for a reflectable object
* NB: multiple inheritance not supported
*/
class CReflectable
{
public:
virtual ~CReflectable() {}
virtual const char *getReflectedClassName() const { return "CReflectable"; }
virtual const char *getRflectedParentClassName() const { return ""; }
/** When registering classes, the reflect system will call this function on each class
* to know which properties they exports.
* To defines which properties are exported use the REFLECT_EXPORT_** macros.
* By doing so, a new 'getReflectedProperties' function will be defined
*/ */
static void getReflectedProperties(TReflectedProperties &/* props */) class CReflectedProperty
{ {
public:
enum TType { Boolean = 0,
SInt32,
UInt32,
Float,
String,
UCString,
RGBA,
LuaMethod
}; // other types will be added when needed
// define some pointer-to-member types
typedef bool (CReflectable::* TGetBool) () const;
typedef sint32 (CReflectable::* TGetSInt32) () const;
typedef uint32 (CReflectable::* TGetUInt32) () const;
typedef float (CReflectable::* TGetFloat) () const;
typedef std::string (CReflectable::* TGetString) () const;
typedef ucstring (CReflectable::* TGetUCString) () const;
typedef NLMISC::CRGBA (CReflectable::* TGetRGBA) () const;
//
typedef void (CReflectable::* TSetBool) (bool);
typedef void (CReflectable::* TSetSInt32) (sint32);
typedef void (CReflectable::* TSetUInt32) (uint32);
typedef void (CReflectable::* TSetFloat) (float);
typedef void (CReflectable::* TSetString) (const std::string &);
typedef void (CReflectable::* TSetUCString) (const ucstring &);
typedef void (CReflectable::* TSetRGBA) (NLMISC::CRGBA col);
//
typedef int (CReflectable:: *TLuaMethod) (CLuaState &luaState);
public:
TType Type;
// In each union we have method pointers to retrieve / set the data of the desired type (as told in 'Type')
union
{
TGetBool GetBool;
TGetSInt32 GetSInt32;
TGetUInt32 GetUInt32;
TGetFloat GetFloat;
TGetString GetString;
TGetUCString GetUCString;
TGetRGBA GetRGBA;
TLuaMethod GetLuaMethod; // lua method can only be obtained, not written ...
} GetMethod;
union
{
TSetBool SetBool;
TSetSInt32 SetSInt32;
TSetUInt32 SetUInt32;
TSetFloat SetFloat;
TSetString SetString;
TSetUCString SetUCString;
TSetRGBA SetRGBA;
} SetMethod;
// name of the property
std::string Name;
mutable CLuaObject LuaMethodRef; // cache pointer to function call if type == LuaMethod
const CClassInfo *ParentClass; // filled when 'registerClass' is called
};
// a vector of reflected properties
typedef std::vector<CReflectedProperty> TReflectedProperties;
struct CClassInfo;
/** Base class for a reflectable object
* NB: multiple inheritance not supported
*/
class CReflectable
{
public:
virtual ~CReflectable() {}
virtual const char *getReflectedClassName() const { return "CReflectable"; }
virtual const char *getRflectedParentClassName() const { return ""; }
/** When registering classes, the reflect system will call this function on each class
* to know which properties they exports.
* To defines which properties are exported use the REFLECT_EXPORT_** macros.
* By doing so, a new 'getReflectedProperties' function will be defined
*/
static void getReflectedProperties(TReflectedProperties &/* props */)
{
}
// get class infos for this reflectable object
const CClassInfo *getClassInfo();
/** get a property from this object by name
* TODO nico : optimized version for lua string (found in CLuaIHM) would maybe fit better here ...
*/
const CReflectedProperty *getReflectedProperty(const std::string &propertyName, bool dspWarning= true) const;
};
struct CLuaIndexedProperty
{
const CReflectedProperty *Prop;
CLuaString Id; // must keep id here, so that we are sure the string is not gc in lua and its pointer remains valid
};
struct CClassInfo
{
TReflectedProperties Properties; // the properties exported by this class
const CClassInfo *ParentClass; // pointer to infos of the parent class, or NULL if it is a root class
std::string ClassName;
/** For lua speedup (used by CLuaIHM) : because lua string are unique, we can use them to access property directly.
*/
typedef CHashMap<const char *, CLuaIndexedProperty, CLuaHashMapTraits> TLuaStrToPropMap;
mutable TLuaStrToPropMap LuaStrToProp;
};
/** Simple reflection system.
* Used by the GUI and some other objects.
* It is used to export some properties so that we can easily manipulate them in the GUI scripts (either lua or with CInterfaceExpr).
* NB: multiple inheritance not supported
*
* Example of use : a class exporting a boolean
*
* class CTestClass : public CReflectable
* {
* public:
* void setValue(bool value) { _Value = value; }
* bool getValue() const { return _Value; }
* \\ export the bool value
* REFLECT_EXPORT_START(CTestClass, CReflectable)
* REFLECT_BOOL("myValue", setValue, getValue)
* REFLECT_EXPORT_END
* private:
* bool _Value;
* };
*
* The class must then be registered with :
*
* REGISTER_REFLECTABLE_CLASS(CTestClass, CReflectable)
*
* NB: It should be registered after its parents
*
*
* \author Nicolas Vizerie
* \author Nevrax France
* \date 2002
*/
class CReflectSystem
{
public:
typedef std::map<std::string, CClassInfo> TClassMap;
public:
// release memory
static void release();
/** register a class and its properties
* NB : class should be registered after their parent have been, or an assertion will be raised
*/
static void registerClass(const std::string &className, const std::string &parentName, const TReflectedProperties properties);
// retrieve a property of a reflectable class, or NULL if unknown
static const CReflectedProperty *getProperty(const std::string &className, const std::string &propertyName, bool dspWarning= true);
// get the list of class for debug or read purpose (NULL if no register has been called)
static const TClassMap *getClassMap() {return _ClassMap;}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
private:
static TClassMap *_ClassMap; // each class and its infos
};
/** Helper macros to export properties of a reflectable class
*/
/** Start a declaration of a reflectable class exports
* Should be placed inside the class
*/
#define REFLECT_EXPORT_START(className, parentName) \
virtual const char *getReflectedClassName() const { return #className; } \
virtual const char *getReflectedParentClassName() const { return #parentName; } \
static void getReflectedProperties(TReflectedProperties &props) \
{ \
typedef className A; \
typedef bool (className::* TGetBoola) () const; \
typedef sint32 (className::* TGetSInt32a) () const; \
typedef uint32 (className::* TGetUInt32a) () const; \
typedef float (className::* TGetFloata) () const; \
typedef std::string (className::* TGetStringa) () const; \
typedef ucstring (className::* TGetUCStringa) () const; \
typedef NLMISC::CRGBA (className::* TGetRGBAa) () const; \
typedef void (className::* TSetBoola) (bool); \
typedef void (className::* TSetSInt32a) (sint32); \
typedef void (className::* TSetUInt32a) (uint32); \
typedef void (className::* TSetFloata) (float); \
typedef void (className::* TSetStringa) (const std::string &); \
typedef void (className::* TSetUCStringa) (const ucstring &); \
typedef void (className::* TSetRGBAa) (NLMISC::CRGBA col); \
typedef int (className:: *TLuaMethoda) (CLuaState &luaState); \
nlunreferenced(props);
// export a boolean value, by giving the name of the get and the set method
#define REFLECT_BOOL(exportName, getMethod, setMethod) \
{ \
CReflectedProperty prop; \
prop.Name = exportName; \
prop.Type = CReflectedProperty::Boolean; \
prop.GetMethod.GetBool = (CReflectedProperty::TGetBool) (TGetBoola) &A::getMethod; \
prop.SetMethod.SetBool = (CReflectedProperty::TSetBool) (TSetBoola) &A::setMethod; \
props.push_back(prop); \
} }
// get class infos for this reflectable object
const CClassInfo *getClassInfo();
/** get a property from this object by name // export a sint32 value, by giving the name of the get and the set method
* TODO nico : optimized version for lua string (found in CLuaIHM) would maybe fit better here ... #define REFLECT_SINT32(exportName, getMethod, setMethod) \
{ \
CReflectedProperty prop; \
prop.Name = exportName; \
prop.Type = CReflectedProperty::SInt32; \
prop.GetMethod.GetSInt32 = (CReflectedProperty::TGetSInt32) (TGetSInt32a) &A::getMethod; \
prop.SetMethod.SetSInt32 = (CReflectedProperty::TSetSInt32) (TSetSInt32a) &A::setMethod; \
props.push_back(prop); \
}
// export a sint32 value, by giving the name of the get and the set method
#define REFLECT_UINT32(exportName, getMethod, setMethod) \
{ \
CReflectedProperty prop; \
prop.Name = exportName; \
prop.Type = CReflectedProperty::UInt32; \
prop.GetMethod.GetUInt32 = (CReflectedProperty::TGetUInt32) (TGetUInt32a) &A::getMethod; \
prop.SetMethod.SetUInt32 = (CReflectedProperty::TSetUInt32) (TSetUInt32a) &A::setMethod; \
props.push_back(prop); \
}
// export a float value, by giving the name of the get and the set method
#define REFLECT_FLOAT(exportName, getMethod, setMethod) \
{ \
CReflectedProperty prop; \
prop.Name = exportName; \
prop.Type = CReflectedProperty::Float; \
prop.GetMethod.GetFloat = (CReflectedProperty::TGetFloat) (TGetFloata) &A::getMethod; \
prop.SetMethod.SetFloat = (CReflectedProperty::TSetFloat) (TSetFloata) &A::setMethod; \
props.push_back(prop); \
}
// export a string value, by giving the name of the get and the set method
#define REFLECT_STRING(exportName, getMethod, setMethod) \
{ \
CReflectedProperty prop; \
prop.Name = exportName; \
prop.Type = CReflectedProperty::String; \
prop.GetMethod.GetString = (CReflectedProperty::TGetString) (TGetStringa) &A::getMethod; \
prop.SetMethod.SetString = (CReflectedProperty::TSetString) (TSetStringa) &A::setMethod; \
props.push_back(prop); \
}
// export a unicode string value, by giving the name of the get and the set method
#define REFLECT_UCSTRING(exportName, getMethod, setMethod) \
{ \
CReflectedProperty prop; \
prop.Name = exportName; \
prop.Type = CReflectedProperty::UCString; \
prop.GetMethod.GetUCString = (CReflectedProperty::TGetUCString) (TGetUCStringa) &A::getMethod; \
prop.SetMethod.SetUCString = (CReflectedProperty::TSetUCString) (TSetUCStringa) &A::setMethod; \
props.push_back(prop); \
}
// export a color value, by giving the name of the get and the set method
#define REFLECT_RGBA(exportName, getMethod, setMethod) \
{ \
CReflectedProperty prop; \
prop.Name = exportName; \
prop.Type = CReflectedProperty::RGBA; \
prop.GetMethod.GetRGBA = (CReflectedProperty::TGetRGBA) (TGetRGBAa) &A::getMethod; \
prop.SetMethod.SetRGBA = (CReflectedProperty::TSetRGBA) (TSetRGBAa) &A::setMethod; \
props.push_back(prop); \
}
// export a lua method
#define REFLECT_LUA_METHOD(exportName, method) \
{ \
CReflectedProperty prop; \
prop.Name = exportName; \
prop.Type = CReflectedProperty::LuaMethod; \
prop.GetMethod.GetLuaMethod = (CReflectedProperty::TLuaMethod) (TLuaMethoda) &A::method; \
props.push_back(prop); \
}
// ends an export declaration
#define REFLECT_EXPORT_END }
// This macro registers a reflectable class to the manager
#define REGISTER_REFLECTABLE_CLASS(className, parentName) \
{ \
TReflectedProperties props; \
className::getReflectedProperties(props); \
CReflectSystem::registerClass(#className, #parentName, props); \
}
/** Reflectable refcounted object
* NB nico : added this intermediate class so that the binding from lua to the reflection
* system that are found in CLuaIHM can be reused for other objects as well
* NOTE: The class is named 'CReflectableRefPtrTarget' and not 'CReflectableRefCount'
* because the refcount part is only used for ref pointing in the ui
*/ */
const CReflectedProperty *getReflectedProperty(const std::string &propertyName, bool dspWarning= true) const; class CReflectableRefPtrTarget : public CReflectable, public NLMISC::CRefCount
}; {
public:
struct CLuaIndexedProperty virtual ~CReflectableRefPtrTarget();
{ };
const CReflectedProperty *Prop;
CLuaString Id; // must keep id here, so that we are sure the string is not gc in lua and its pointer remains valid
};
struct CClassInfo class CReflectableLuaRef
{ {
TReflectedProperties Properties; // the properties exported by this class public:
const CClassInfo *ParentClass; // pointer to infos of the parent class, or NULL if it is a root class CReflectableLuaRef(CReflectableRefPtrTarget *ptr = NULL) : Ptr(ptr), _ClassInfo(NULL) {}
std::string ClassName; NLMISC::CRefPtr<CReflectableRefPtrTarget> Ptr;
/** For lua speedup (used by CLuaIHM) : because lua string are unique, we can use them to access property directly. const CClassInfo &getClassInfo() const;
*/ // IMPORTANT : luaStringPtr should have been obtained from lua, see remark in CClassInfo
typedef CHashMap<const char *, CLuaIndexedProperty, CLuaHashMapTraits> TLuaStrToPropMap; const CReflectedProperty *getProp(const char *luaStringPtr) const;
mutable TLuaStrToPropMap LuaStrToProp; private:
}; // cache to class definition of the pointee object (once a CReflectableLuaRef created in lua, it remains a *const* pointer)
mutable const CClassInfo *_ClassInfo;
/** Simple reflection system. };
* Used by the GUI and some other objects.
* It is used to export some properties so that we can easily manipulate them in the GUI scripts (either lua or with CInterfaceExpr).
* NB: multiple inheritance not supported
*
* Example of use : a class exporting a boolean
*
* class CTestClass : public CReflectable
* {
* public:
* void setValue(bool value) { _Value = value; }
* bool getValue() const { return _Value; }
* \\ export the bool value
* REFLECT_EXPORT_START(CTestClass, CReflectable)
* REFLECT_BOOL("myValue", setValue, getValue)
* REFLECT_EXPORT_END
* private:
* bool _Value;
* };
*
* The class must then be registered with :
*
* REGISTER_REFLECTABLE_CLASS(CTestClass, CReflectable)
*
* NB: It should be registered after its parents
*
*
* \author Nicolas Vizerie
* \author Nevrax France
* \date 2002
*/
class CReflectSystem
{
public:
typedef std::map<std::string, CClassInfo> TClassMap;
public:
// release memory
static void release();
/** register a class and its properties
* NB : class should be registered after their parent have been, or an assertion will be raised
*/
static void registerClass(const std::string &className, const std::string &parentName, const TReflectedProperties properties);
// retrieve a property of a reflectable class, or NULL if unknown
static const CReflectedProperty *getProperty(const std::string &className, const std::string &propertyName, bool dspWarning= true);
// get the list of class for debug or read purpose (NULL if no register has been called)
static const TClassMap *getClassMap() {return _ClassMap;}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
private:
static TClassMap *_ClassMap; // each class and its infos
};
/** Helper macros to export properties of a reflectable class
*/
/** Start a declaration of a reflectable class exports
* Should be placed inside the class
*/
#define REFLECT_EXPORT_START(className, parentName) \
virtual const char *getReflectedClassName() const { return #className; } \
virtual const char *getReflectedParentClassName() const { return #parentName; } \
static void getReflectedProperties(TReflectedProperties &props) \
{ \
typedef className A; \
typedef bool (className::* TGetBoola) () const; \
typedef sint32 (className::* TGetSInt32a) () const; \
typedef uint32 (className::* TGetUInt32a) () const; \
typedef float (className::* TGetFloata) () const; \
typedef std::string (className::* TGetStringa) () const; \
typedef ucstring (className::* TGetUCStringa) () const; \
typedef NLMISC::CRGBA (className::* TGetRGBAa) () const; \
typedef void (className::* TSetBoola) (bool); \
typedef void (className::* TSetSInt32a) (sint32); \
typedef void (className::* TSetUInt32a) (uint32); \
typedef void (className::* TSetFloata) (float); \
typedef void (className::* TSetStringa) (const std::string &); \
typedef void (className::* TSetUCStringa) (const ucstring &); \
typedef void (className::* TSetRGBAa) (NLMISC::CRGBA col); \
typedef int (className:: *TLuaMethoda) (CLuaState &luaState); \
nlunreferenced(props);
// export a boolean value, by giving the name of the get and the set method
#define REFLECT_BOOL(exportName, getMethod, setMethod) \
{ \
CReflectedProperty prop; \
prop.Name = exportName; \
prop.Type = CReflectedProperty::Boolean; \
prop.GetMethod.GetBool = (CReflectedProperty::TGetBool) (TGetBoola) &A::getMethod; \
prop.SetMethod.SetBool = (CReflectedProperty::TSetBool) (TSetBoola) &A::setMethod; \
props.push_back(prop); \
} }
// export a sint32 value, by giving the name of the get and the set method
#define REFLECT_SINT32(exportName, getMethod, setMethod) \
{ \
CReflectedProperty prop; \
prop.Name = exportName; \
prop.Type = CReflectedProperty::SInt32; \
prop.GetMethod.GetSInt32 = (CReflectedProperty::TGetSInt32) (TGetSInt32a) &A::getMethod; \
prop.SetMethod.SetSInt32 = (CReflectedProperty::TSetSInt32) (TSetSInt32a) &A::setMethod; \
props.push_back(prop); \
}
// export a sint32 value, by giving the name of the get and the set method
#define REFLECT_UINT32(exportName, getMethod, setMethod) \
{ \
CReflectedProperty prop; \
prop.Name = exportName; \
prop.Type = CReflectedProperty::UInt32; \
prop.GetMethod.GetUInt32 = (CReflectedProperty::TGetUInt32) (TGetUInt32a) &A::getMethod; \
prop.SetMethod.SetUInt32 = (CReflectedProperty::TSetUInt32) (TSetUInt32a) &A::setMethod; \
props.push_back(prop); \
}
// export a float value, by giving the name of the get and the set method
#define REFLECT_FLOAT(exportName, getMethod, setMethod) \
{ \
CReflectedProperty prop; \
prop.Name = exportName; \
prop.Type = CReflectedProperty::Float; \
prop.GetMethod.GetFloat = (CReflectedProperty::TGetFloat) (TGetFloata) &A::getMethod; \
prop.SetMethod.SetFloat = (CReflectedProperty::TSetFloat) (TSetFloata) &A::setMethod; \
props.push_back(prop); \
}
// export a string value, by giving the name of the get and the set method
#define REFLECT_STRING(exportName, getMethod, setMethod) \
{ \
CReflectedProperty prop; \
prop.Name = exportName; \
prop.Type = CReflectedProperty::String; \
prop.GetMethod.GetString = (CReflectedProperty::TGetString) (TGetStringa) &A::getMethod; \
prop.SetMethod.SetString = (CReflectedProperty::TSetString) (TSetStringa) &A::setMethod; \
props.push_back(prop); \
}
// export a unicode string value, by giving the name of the get and the set method
#define REFLECT_UCSTRING(exportName, getMethod, setMethod) \
{ \
CReflectedProperty prop; \
prop.Name = exportName; \
prop.Type = CReflectedProperty::UCString; \
prop.GetMethod.GetUCString = (CReflectedProperty::TGetUCString) (TGetUCStringa) &A::getMethod; \
prop.SetMethod.SetUCString = (CReflectedProperty::TSetUCString) (TSetUCStringa) &A::setMethod; \
props.push_back(prop); \
}
// export a color value, by giving the name of the get and the set method
#define REFLECT_RGBA(exportName, getMethod, setMethod) \
{ \
CReflectedProperty prop; \
prop.Name = exportName; \
prop.Type = CReflectedProperty::RGBA; \
prop.GetMethod.GetRGBA = (CReflectedProperty::TGetRGBA) (TGetRGBAa) &A::getMethod; \
prop.SetMethod.SetRGBA = (CReflectedProperty::TSetRGBA) (TSetRGBAa) &A::setMethod; \
props.push_back(prop); \
}
// export a lua method
#define REFLECT_LUA_METHOD(exportName, method) \
{ \
CReflectedProperty prop; \
prop.Name = exportName; \
prop.Type = CReflectedProperty::LuaMethod; \
prop.GetMethod.GetLuaMethod = (CReflectedProperty::TLuaMethod) (TLuaMethoda) &A::method; \
props.push_back(prop); \
}
// ends an export declaration
#define REFLECT_EXPORT_END }
// This macro registers a reflectable class to the manager
#define REGISTER_REFLECTABLE_CLASS(className, parentName) \
{ \
TReflectedProperties props; \
className::getReflectedProperties(props); \
CReflectSystem::registerClass(#className, #parentName, props); \
}
/** Reflectable refcounted object
* NB nico : added this intermediate class so that the binding from lua to the reflection
* system that are found in CLuaIHM can be reused for other objects as well
* NOTE: The class is named 'CReflectableRefPtrTarget' and not 'CReflectableRefCount'
* because the refcount part is only used for ref pointing in the ui
*/
class CReflectableRefPtrTarget : public CReflectable, public NLMISC::CRefCount
{
public:
virtual ~CReflectableRefPtrTarget();
};
class CReflectableLuaRef
{
public:
CReflectableLuaRef(CReflectableRefPtrTarget *ptr = NULL) : Ptr(ptr), _ClassInfo(NULL) {}
NLMISC::CRefPtr<CReflectableRefPtrTarget> Ptr;
const CClassInfo &getClassInfo() const;
// IMPORTANT : luaStringPtr should have been obtained from lua, see remark in CClassInfo
const CReflectedProperty *getProp(const char *luaStringPtr) const;
private:
// cache to class definition of the pointee object (once a CReflectableLuaRef created in lua, it remains a *const* pointer)
mutable const CClassInfo *_ClassInfo;
};
#endif #endif

File diff suppressed because it is too large Load diff

View file

@ -18,17 +18,22 @@
#include "nel/gui/lua_manager.h" #include "nel/gui/lua_manager.h"
#include "nel/gui/lua_helper.h" #include "nel/gui/lua_helper.h"
bool CLuaManager::debugLua = false; namespace NLGUI
CLuaManager* CLuaManager::instance = NULL;
CLuaManager::CLuaManager()
{ {
luaState = new NLGUI::CLuaState( debugLua );
bool CLuaManager::debugLua = false;
CLuaManager* CLuaManager::instance = NULL;
CLuaManager::CLuaManager()
{
luaState = new NLGUI::CLuaState( debugLua );
}
CLuaManager::~CLuaManager()
{
luaState = NULL;
}
} }
CLuaManager::~CLuaManager()
{
luaState = NULL;
}

File diff suppressed because it is too large Load diff

View file

@ -17,175 +17,182 @@
#include "nel/gui/reflect.h" #include "nel/gui/reflect.h"
// Yoyo: Act like a singleton, else registerClass may crash. namespace NLGUI
CReflectSystem::TClassMap *CReflectSystem::_ClassMap= NULL;
// hack to register the root class at startup
static const struct CRootReflectableClassRegister
{ {
CRootReflectableClassRegister() // Yoyo: Act like a singleton, else registerClass may crash.
CReflectSystem::TClassMap *CReflectSystem::_ClassMap= NULL;
// hack to register the root class at startup
static const struct CRootReflectableClassRegister
{ {
TReflectedProperties props; CRootReflectableClassRegister()
CReflectSystem::registerClass("CReflectable", "", props); {
} TReflectedProperties props;
} _RootReflectableClassRegisterInstance; CReflectSystem::registerClass("CReflectable", "", props);
}
} _RootReflectableClassRegisterInstance;
//=================================================================================== //===================================================================================
// release memory // release memory
void CReflectSystem::release() void CReflectSystem::release()
{ {
delete _ClassMap; delete _ClassMap;
_ClassMap = NULL; _ClassMap = NULL;
} }
//=================================================================================== //===================================================================================
void CReflectSystem::registerClass(const std::string &className, const std::string &parentName, const TReflectedProperties properties) void CReflectSystem::registerClass(const std::string &className, const std::string &parentName, const TReflectedProperties properties)
{ {
if(!_ClassMap) _ClassMap= new TClassMap; if(!_ClassMap) _ClassMap= new TClassMap;
TClassMap::const_iterator it = _ClassMap->find(className); TClassMap::const_iterator it = _ClassMap->find(className);
if (it != _ClassMap->end()) if (it != _ClassMap->end())
{ {
nlerror("CReflectSystem::registerClass : Class registered twice : %s!", className.c_str()); nlerror("CReflectSystem::registerClass : Class registered twice : %s!", className.c_str());
}
CClassInfo &ci = (*_ClassMap)[className];
ci.Properties = properties;
ci.ClassName = className;
for(uint k = 0; k < ci.Properties.size(); ++k)
{
ci.Properties[k].ParentClass = &ci;
}
if (parentName.empty())
{
ci.ParentClass = NULL;
}
else
{
it = _ClassMap->find(parentName);
if (it == _ClassMap->end())
{
nlerror("CReflectSystem::registerClass : Parent class %s not found", parentName.c_str());
}
ci.ParentClass = &(it->second);
}
} }
CClassInfo &ci = (*_ClassMap)[className];
ci.Properties = properties; //===================================================================================
ci.ClassName = className; const CReflectedProperty *CReflectSystem::getProperty(const std::string &className, const std::string &propertyName, bool dspWarning)
for(uint k = 0; k < ci.Properties.size(); ++k)
{ {
ci.Properties[k].ParentClass = &ci; if(!_ClassMap) _ClassMap= new TClassMap;
}
if (parentName.empty()) TClassMap::const_iterator it = _ClassMap->find(className);
{
ci.ParentClass = NULL;
}
else
{
it = _ClassMap->find(parentName);
if (it == _ClassMap->end()) if (it == _ClassMap->end())
{ {
nlerror("CReflectSystem::registerClass : Parent class %s not found", parentName.c_str()); nlwarning("CReflectSystem::getProperty : Unkwown class : %s", className.c_str());
return NULL;
} }
ci.ParentClass = &(it->second); const CClassInfo *ci = &it->second;
} while (ci)
}
//===================================================================================
const CReflectedProperty *CReflectSystem::getProperty(const std::string &className, const std::string &propertyName, bool dspWarning)
{
if(!_ClassMap) _ClassMap= new TClassMap;
TClassMap::const_iterator it = _ClassMap->find(className);
if (it == _ClassMap->end())
{
nlwarning("CReflectSystem::getProperty : Unkwown class : %s", className.c_str());
return NULL;
}
const CClassInfo *ci = &it->second;
while (ci)
{
// Linear search should suffice for now
for(uint k = 0; k < ci->Properties.size(); ++k)
{ {
if (ci->Properties[k].Name == propertyName) // Linear search should suffice for now
for(uint k = 0; k < ci->Properties.size(); ++k)
{ {
return &(ci->Properties[k]); if (ci->Properties[k].Name == propertyName)
{
return &(ci->Properties[k]);
}
} }
// search in parent
ci = ci->ParentClass;
} }
// search in parent //\ TODO nico : possible optimization : instead of going up in the parents when
ci = ci->ParentClass; // searching for a property, it would be simpler to concatenate properties
} // from parent class at registration.
//\ TODO nico : possible optimization : instead of going up in the parents when // All that would be left at the end would be a hash_map of properties ...
// searching for a property, it would be simpler to concatenate properties
// from parent class at registration.
// All that would be left at the end would be a hash_map of properties ...
if(dspWarning) if(dspWarning)
nlwarning("CReflectSystem::getProperty : %s is not a property of class : %s", propertyName.c_str(), className.c_str()); nlwarning("CReflectSystem::getProperty : %s is not a property of class : %s", propertyName.c_str(), className.c_str());
return NULL;
}
//===================================================================================
const CClassInfo *CReflectable::getClassInfo()
{
if (!CReflectSystem::getClassMap()) return NULL;
// TODO nico : a possible optimization would be to use the address of the static function
// 'getReflectedProperties' as a key into the CClassInfo map. This pointer uniquely identify
// classes that export properties
CReflectSystem::TClassMap::const_iterator it = CReflectSystem::getClassMap()->find(this->getReflectedClassName());
if (it == CReflectSystem::getClassMap()->end())
{
return NULL; return NULL;
} }
return &(it->second);
}
//===================================================================================
const CReflectedProperty *CReflectable::getReflectedProperty(const std::string &propertyName, bool dspWarning) const
{
return CReflectSystem::getProperty(this->getReflectedClassName(), propertyName, dspWarning);
}
//===================================================================================
const CClassInfo *CReflectable::getClassInfo()
{
if (!CReflectSystem::getClassMap()) return NULL;
// TODO nico : a possible optimization would be to use the address of the static function
// 'getReflectedProperties' as a key into the CClassInfo map. This pointer uniquely identify
// classes that export properties
CReflectSystem::TClassMap::const_iterator it = CReflectSystem::getClassMap()->find(this->getReflectedClassName());
if (it == CReflectSystem::getClassMap()->end())
{
return NULL;
}
return &(it->second);
}
//===================================================================================
const CReflectedProperty *CReflectable::getReflectedProperty(const std::string &propertyName, bool dspWarning) const
{
return CReflectSystem::getProperty(this->getReflectedClassName(), propertyName, dspWarning);
}
}
#include "nel/gui/lua_manager.h" #include "nel/gui/lua_manager.h"
CReflectableRefPtrTarget::~CReflectableRefPtrTarget() namespace NLGUI
{ {
CLuaState *lua= CLuaManager::getInstance().getLuaState(); CReflectableRefPtrTarget::~CReflectableRefPtrTarget()
if(!lua)
return;
CLuaStackChecker lsc(lua);
// remove from the lua registry if i'm in
lua->pushLightUserData((void *) this);
lua->getTable(LUA_REGISTRYINDEX);
if (!lua->isNil(-1))
{ {
lua->pop(); CLuaState *lua= CLuaManager::getInstance().getLuaState();
if(!lua)
return;
CLuaStackChecker lsc(lua);
// remove from the lua registry if i'm in
lua->pushLightUserData((void *) this); lua->pushLightUserData((void *) this);
lua->pushNil(); lua->getTable(LUA_REGISTRYINDEX);
lua->setTable(LUA_REGISTRYINDEX); if (!lua->isNil(-1))
{
lua->pop();
lua->pushLightUserData((void *) this);
lua->pushNil();
lua->setTable(LUA_REGISTRYINDEX);
}
else
{
lua->pop();
}
} }
else
/**
* Data structure pushed in lua (a userdata) to access CReflectableRefPtrTarget derived objects
* These includes element of the GUI.
* if holds a pointer to the reflectable object, and
* a cache to its CClassInfo for fast access to exported properties
* \see reflect.h
*/
//
inline const CClassInfo &CReflectableLuaRef::getClassInfo() const
{ {
lua->pop(); nlassert(Ptr); // class info should not be accessed for a null ptr
if (_ClassInfo) return *_ClassInfo;
_ClassInfo = Ptr->getClassInfo();
return *_ClassInfo;
} }
}
/** const CReflectedProperty *CReflectableLuaRef::getProp(const char *luaStringPtr) const
* Data structure pushed in lua (a userdata) to access CReflectableRefPtrTarget derived objects
* These includes element of the GUI.
* if holds a pointer to the reflectable object, and
* a cache to its CClassInfo for fast access to exported properties
* \see reflect.h
*/
//
inline const CClassInfo &CReflectableLuaRef::getClassInfo() const
{
nlassert(Ptr); // class info should not be accessed for a null ptr
if (_ClassInfo) return *_ClassInfo;
_ClassInfo = Ptr->getClassInfo();
return *_ClassInfo;
}
const CReflectedProperty *CReflectableLuaRef::getProp(const char *luaStringPtr) const
{
const CClassInfo &ci = getClassInfo();
CClassInfo::TLuaStrToPropMap::const_iterator it = ci.LuaStrToProp.find(luaStringPtr);
if (it != ci.LuaStrToProp.end())
{ {
return it->second.Prop; const CClassInfo &ci = getClassInfo();
CClassInfo::TLuaStrToPropMap::const_iterator it = ci.LuaStrToProp.find(luaStringPtr);
if (it != ci.LuaStrToProp.end())
{
return it->second.Prop;
}
// slowly retrieve property, and store in cache
// NB nico : this could also be done at startup...
const CReflectedProperty *prop = CReflectSystem::getProperty(ci.ClassName, luaStringPtr, false);
if (!prop) return NULL;
CLuaIndexedProperty lip;
lip.Id = CLuaString(luaStringPtr); // keep a ref on the lua string to ensure that its pointer always remains valid
lip.Prop = prop;
ci.LuaStrToProp[luaStringPtr] = lip;
return prop;
} }
// slowly retrieve property, and store in cache
// NB nico : this could also be done at startup...
const CReflectedProperty *prop = CReflectSystem::getProperty(ci.ClassName, luaStringPtr, false);
if (!prop) return NULL;
CLuaIndexedProperty lip;
lip.Id = CLuaString(luaStringPtr); // keep a ref on the lua string to ensure that its pointer always remains valid
lip.Prop = prop;
ci.LuaStrToProp[luaStringPtr] = lip;
return prop;
} }

View file

@ -23,7 +23,13 @@ namespace NLMISC
class CVector2f; class CVector2f;
} }
class CLuaObject; namespace NLGUI
{
class CLuaObject;
}
using namespace NLGUI;
class CDecal; class CDecal;
// TODO nico : this would fit nicely in the particle system animation system (would be more flexible) // TODO nico : this would fit nicely in the particle system animation system (would be more flexible)

View file

@ -25,6 +25,8 @@
#include "interface_property.h" #include "interface_property.h"
#include "nel/gui/reflect.h" #include "nel/gui/reflect.h"
using namespace NLGUI;
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
class CInterfaceGroup; class CInterfaceGroup;

View file

@ -22,12 +22,20 @@
#include "nel/misc/cdb_branch.h" #include "nel/misc/cdb_branch.h"
#include "nel/misc/cdb_branch_observing_handler.h" #include "nel/misc/cdb_branch_observing_handler.h"
namespace NLGUI
{
class CReflectedProperty;
}
class CInterfaceElement; class CInterfaceElement;
class CReflectedProperty;
class CInterfaceExprValue; class CInterfaceExprValue;
class CInterfaceGroup; class CInterfaceGroup;
class CInterfaceExprNode; class CInterfaceExprNode;
using namespace NLGUI;
/** A link in an interface. /** A link in an interface.
* A link is an object that can read one or several values from the database, that can evaluate an expression * A link is an object that can read one or several values from the database, that can evaluate an expression
* on these database entries (simple computation, using the CInterfaceExpr class), and that can affect the result to * on these database entries (simple computation, using the CInterfaceExpr class), and that can affect the result to

View file

@ -3,10 +3,12 @@
#include "nel/gui/lua_ihm.h" #include "nel/gui/lua_ihm.h"
using namespace NLGUI;
class CLuaIHMRyzom class CLuaIHMRyzom
{ {
public: public:
static void RegisterRyzomFunctions( NLGUI::CLuaState &ls ); static void RegisterRyzomFunctions( CLuaState &ls );
private: private:
static void createLuaEnumTable(CLuaState &ls, const std::string &str); static void createLuaEnumTable(CLuaState &ls, const std::string &str);

View file

@ -21,8 +21,10 @@
#include "nel/misc/class_registry.h" #include "nel/misc/class_registry.h"
#include "../interface_v3/interface_element.h" #include "../interface_v3/interface_element.h"
class CLuaObject; namespace NLGUI
{
class CLuaObject;
}
namespace R2 namespace R2
{ {

View file

@ -21,7 +21,12 @@
#include "nel/gui/lua_object.h" #include "nel/gui/lua_object.h"
#include <map> #include <map>
class CLuaObject; namespace NLGUI
{
class CLuaObject;
}
using namespace NLGUI;
namespace R2 namespace R2
{ {

View file

@ -20,8 +20,10 @@
namespace NLGUI namespace NLGUI
{ {
class CLuaState; class CLuaState;
class CLuaString;
} }
class CLuaString;
using namespace NLGUI;
namespace R2 namespace R2
{ {

View file

@ -24,8 +24,12 @@
#include "../interface_v3/group_map.h" #include "../interface_v3/group_map.h"
namespace NLGUI
{
class CLuaObject;
}
class CEntityCL; class CEntityCL;
class CLuaObject;
class CCtrlPolygon; class CCtrlPolygon;
namespace R2 namespace R2

View file

@ -29,8 +29,9 @@ class CInterfaceManager;
namespace NLGUI namespace NLGUI
{ {
class CEventDescriptor; class CEventDescriptor;
class CLuaObject;
} }
class CLuaObject;
class CGroupMap; class CGroupMap;
namespace NLMISC namespace NLMISC

View file

@ -25,8 +25,10 @@
class CEntity; class CEntity;
class CEntityCL; class CEntityCL;
class CLuaObject; namespace NLGUI
{
class CLuaObject;
}
namespace R2 namespace R2
{ {

View file

@ -22,8 +22,11 @@
#include "nel/gui/lua_object.h" #include "nel/gui/lua_object.h"
class CEntity; class CEntity;
class CLuaObject;
namespace NLGUI
{
class CLuaObject;
}
namespace R2 namespace R2
{ {

View file

@ -25,8 +25,10 @@
#include "displayer_visual_entity.h" #include "displayer_visual_entity.h"
class CEntity; class CEntity;
class CLuaObject; namespace NLGUI
{
class CLuaObject;
}
namespace R2 namespace R2
{ {

View file

@ -25,8 +25,10 @@
class CEntity; class CEntity;
class CLuaObject; namespace NLGUI
{
class CLuaObject;
}
namespace R2 namespace R2
{ {