From 96e0b1e90960c0e13a12da1614642fb55c214ab3 Mon Sep 17 00:00:00 2001 From: Eduardo Bart Date: Fri, 22 Apr 2011 15:48:02 -0300 Subject: [PATCH] new logger scripts are now more error prone --- CMakeLists.txt | 2 +- data/modules/mainmenu/mainmenu.lua | 2 +- src/framework/core/configs.cpp | 10 ++-- src/framework/core/dispatcher.cpp | 4 +- src/framework/core/dispatcher.h | 10 ++-- src/framework/core/engine.cpp | 2 +- src/framework/core/engine.h | 4 +- src/framework/core/resources.cpp | 8 +-- src/framework/graphics/font.cpp | 6 +- src/framework/graphics/fonts.cpp | 4 +- src/framework/graphics/graphics.cpp | 4 +- src/framework/graphics/textures.cpp | 6 +- src/framework/net/connection.cpp | 2 +- src/framework/net/connection.h | 4 +- src/framework/net/protocol.cpp | 4 +- src/framework/net/protocol.h | 2 +- src/framework/platform/win32platform.cpp | 26 ++++----- src/framework/platform/x11platform.cpp | 22 ++++---- src/framework/prerequisites.h | 3 +- src/framework/script/luafunctions.cpp | 37 +++++++----- src/framework/script/luascript.cpp | 72 ++++++++++++++++-------- src/framework/script/luascript.h | 5 +- src/framework/ui/uilayout.cpp | 6 +- src/framework/ui/uiloader.cpp | 4 +- src/framework/ui/uiskins.cpp | 6 +- src/framework/util/logger.cpp | 12 +--- src/framework/util/logger.h | 50 ++++++++-------- src/framework/util/util.cpp | 27 --------- src/framework/util/util.h | 13 ++--- src/main.cpp | 2 +- 30 files changed, 181 insertions(+), 178 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index cae11dbc..7b3cb730 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -6,7 +6,7 @@ SET(CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake;${CMAKE_MODULE_PATH}") # find needed packages SET(Boost_USE_STATIC_LIBS ON) SET(Boost_USE_MULTITHREADED ON) -FIND_PACKAGE(Boost COMPONENTS system regex signals REQUIRED) +FIND_PACKAGE(Boost COMPONENTS system signals REQUIRED) FIND_PACKAGE(OpenGL REQUIRED) FIND_PACKAGE(Lua51 REQUIRED) FIND_PACKAGE(YamlCpp REQUIRED) diff --git a/data/modules/mainmenu/mainmenu.lua b/data/modules/mainmenu/mainmenu.lua index bbbf4d26..d1355ffa 100644 --- a/data/modules/mainmenu/mainmenu.lua +++ b/data/modules/mainmenu/mainmenu.lua @@ -9,7 +9,7 @@ end function MainMenu_enterGameClicked() enterGameWindow = loadUI("modules/mainmenu/entergamewindow.yml") - enterGameWindow:getParent():lock(enterGameWindow) + button = enterGameWindow:getChildByID("okButton") end function MainMenu_optionsClicked() diff --git a/src/framework/core/configs.cpp b/src/framework/core/configs.cpp index c1f39dc9..f595fcae 100644 --- a/src/framework/core/configs.cpp +++ b/src/framework/core/configs.cpp @@ -54,7 +54,7 @@ bool Configs::load(const std::string& fileName) m_confsMap[key] = value; } } catch (YAML::Exception& e) { - logError("Malformed config file: %s", e.what()); + flogError("ERROR: Malformed config file: %s", e.what()); return false; } @@ -102,7 +102,7 @@ const std::string &Configs::getString(const std::string &key) const { auto it = m_confsMap.find(key); if(it == m_confsMap.end()) { - logWarning("Config value %s not found", key.c_str()); + flogWarning("WARNING: Config value %s not found", key.c_str()); static std::string emptystr; return emptystr; } @@ -113,7 +113,7 @@ float Configs::getFloat(const std::string &key) const { auto it = m_confsMap.find(key); if(it == m_confsMap.end()) { - logWarning("Config value %s not found", key.c_str()); + flogWarning("WARNING: Config value %s not found", key.c_str()); return 0; } return convertType(it->second); @@ -123,7 +123,7 @@ bool Configs::getBoolean(const std::string &key) const { auto it = m_confsMap.find(key); if(it == m_confsMap.end()) { - logWarning("Config value %s not found", key.c_str()); + flogWarning("WARNING: Config value %s not found", key.c_str()); return 0; } return (it->second == "true"); @@ -133,7 +133,7 @@ int Configs::getInteger(const std::string &key) const { auto it = m_confsMap.find(key); if(it == m_confsMap.end()) { - logWarning("Config value %s not found", key.c_str()); + flogWarning("WARNING: Config value %s not found", key.c_str()); return 0; } return convertType(it->second); diff --git a/src/framework/core/dispatcher.cpp b/src/framework/core/dispatcher.cpp index b43eca1a..04ae315b 100644 --- a/src/framework/core/dispatcher.cpp +++ b/src/framework/core/dispatcher.cpp @@ -41,12 +41,12 @@ void Dispatcher::poll() } } -void Dispatcher::scheduleTask(const Callback& callback, int delay) +void Dispatcher::scheduleTask(const SimpleCallback& callback, int delay) { m_taskList.push(new Task(g_engine.getCurrentFrameTicks() + delay, callback)); } -void Dispatcher::addTask(const Callback& callback) +void Dispatcher::addTask(const SimpleCallback& callback) { m_taskList.push(new Task(callback)); } diff --git a/src/framework/core/dispatcher.h b/src/framework/core/dispatcher.h index 933ee5a9..5287860c 100644 --- a/src/framework/core/dispatcher.h +++ b/src/framework/core/dispatcher.h @@ -29,11 +29,11 @@ class Task { public: - inline Task(const Callback& _callback) : ticks(0), callback(_callback) { } - inline Task(int _ticks, const Callback& _callback) : ticks(_ticks), callback(_callback) { } + inline Task(const SimpleCallback& _callback) : ticks(0), callback(_callback) { } + inline Task(int _ticks, const SimpleCallback& _callback) : ticks(_ticks), callback(_callback) { } inline bool operator<(const Task& other) const { return ticks > other.ticks; } int ticks; - Callback callback; + SimpleCallback callback; }; class lessTask : public std::binary_function { @@ -50,10 +50,10 @@ public: void poll(); /// Add an event - void addTask(const Callback& callback); + void addTask(const SimpleCallback& callback); /// Schedula an event - void scheduleTask(const Callback& callback, int delay); + void scheduleTask(const SimpleCallback& callback, int delay); private: std::priority_queue, lessTask> m_taskList; diff --git a/src/framework/core/engine.cpp b/src/framework/core/engine.cpp index 19255cc5..d5bb3b4b 100644 --- a/src/framework/core/engine.cpp +++ b/src/framework/core/engine.cpp @@ -87,7 +87,7 @@ void Engine::run() frameCount = 0; // update fps text - fpsText = format("FPS: %d", fps); + fpsText = f("FPS: %d", fps); fpsTextSize = defaultFont->calculateTextRectSize(fpsText); } } diff --git a/src/framework/core/engine.h b/src/framework/core/engine.h index dad4b388..0b3ff78e 100644 --- a/src/framework/core/engine.h +++ b/src/framework/core/engine.h @@ -63,7 +63,7 @@ public: /// Return the current ticks on this frame int getCurrentFrameTicks() const { return m_lastFrameTicks; } - void setOnClose(Callback onCloseCallback) { m_onCloseCallback = onCloseCallback; } + void setOnClose(SimpleCallback onCloseCallback) { m_onCloseCallback = onCloseCallback; } private: bool m_stopping; @@ -72,7 +72,7 @@ private: int m_lastFrameTicks; - Callback m_onCloseCallback; + SimpleCallback m_onCloseCallback; }; extern Engine g_engine; diff --git a/src/framework/core/resources.cpp b/src/framework/core/resources.cpp index b9b253c2..554b1a48 100644 --- a/src/framework/core/resources.cpp +++ b/src/framework/core/resources.cpp @@ -44,14 +44,14 @@ bool Resources::setWriteDir(const std::string& path) bool ret = (bool)PHYSFS_setWriteDir(path.c_str()); if(!ret) - logError("Could not set the path \"%s\" as write directory, file write will not work correctly.", path.c_str()); + flogError("ERROR: Could not set the path \"%s\" as write directory, file write will not work correctly.", path.c_str()); return ret; } bool Resources::addToSearchPath(const std::string& path, bool insertInFront /*= true*/) { if(!PHYSFS_addToSearchPath(path.c_str(), insertInFront ? 0 : 1)) { - logError("Error while adding \"%s\" to resources search path: %s", path.c_str(), PHYSFS_getLastError()); + flogError("ERROR: Error while adding \"%s\" to resources search path: %s", path.c_str() % PHYSFS_getLastError()); return false; } return true; @@ -66,7 +66,7 @@ uchar *Resources::loadFile(const std::string& fileName, uint *fileSize) { PHYSFS_file *file = PHYSFS_openRead(fileName.c_str()); if(!file) { - logError("Failed to load file \"%s\": %s", fileName.c_str(), PHYSFS_getLastError()); + flogError("ERROR: Failed to load file \"%s\": %s", fileName.c_str() % PHYSFS_getLastError()); *fileSize = 0; return NULL; } @@ -95,7 +95,7 @@ bool Resources::saveFile(const std::string &fileName, const uchar *data, uint si { PHYSFS_file *file = PHYSFS_openWrite(fileName.c_str()); if(!file) { - logError("Failed to save file \"%s\": %s", fileName.c_str(), PHYSFS_getLastError()); + flogError("ERROR: Failed to save file \"%s\": %s", fileName.c_str() % PHYSFS_getLastError()); return false; } diff --git a/src/framework/graphics/font.cpp b/src/framework/graphics/font.cpp index 6e2aa06e..504c95c2 100644 --- a/src/framework/graphics/font.cpp +++ b/src/framework/graphics/font.cpp @@ -68,7 +68,7 @@ bool Font::load(const std::string& file) { std::string fileContents = g_resources.loadTextFile(file); if(!fileContents.size()) { - logError("Coult not load font file \"%s", file.c_str()); + flogError("ERROR: Coult not load font file \"%s", file.c_str()); return false; } @@ -96,7 +96,7 @@ bool Font::load(const std::string& file) // load texture m_texture = g_textures.get("fonts/" + textureName); if(!m_texture) { - logError("Failed to load image for font file \"%s\"", file.c_str()); + flogError("ERROR: Failed to load image for font file \"%s\"", file.c_str()); return false; } @@ -123,7 +123,7 @@ bool Font::load(const std::string& file) m_glyphHeight); } } catch (YAML::Exception& e) { - logError("Malformed font file \"%s\":\n %s", file.c_str(), e.what()); + flogError("ERROR: Malformed font file \"%s\":\n %s", file.c_str() % e.what()); return false; } diff --git a/src/framework/graphics/fonts.cpp b/src/framework/graphics/fonts.cpp index 79ee5c2e..1b1c0811 100644 --- a/src/framework/graphics/fonts.cpp +++ b/src/framework/graphics/fonts.cpp @@ -47,7 +47,7 @@ void Fonts::init(const std::string& defaultFontName) } if(!m_defaultFont) - logFatal("Could not load the default font \"%s\"\n", defaultFontName.c_str()); + flogFatal("FATAL ERROR: Could not load the default font \"%s\"\n", defaultFontName.c_str()); } Font* Fonts::get(const std::string& fontName) @@ -58,6 +58,6 @@ Font* Fonts::get(const std::string& fontName) return (*it).get(); } - logError("Font \"%s\" not found, returing the default one", fontName.c_str()); + flogError("ERROR: Font \"%s\" not found, returing the default one", fontName.c_str()); return m_defaultFont.get(); } diff --git a/src/framework/graphics/graphics.cpp b/src/framework/graphics/graphics.cpp index 230e4444..bf066c6b 100644 --- a/src/framework/graphics/graphics.cpp +++ b/src/framework/graphics/graphics.cpp @@ -43,8 +43,8 @@ void Graphics::init() glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glClearColor(0.0f, 0.0f, 0.0f, 1.0f); - logInfo("GPU %s", (const char*)glGetString(GL_RENDERER)); - logInfo("OpenGL %s", (const char*)glGetString(GL_VERSION)); + flogInfo("GPU %s", (const char*)glGetString(GL_RENDERER)); + flogInfo("OpenGL %s", (const char*)glGetString(GL_VERSION)); } void Graphics::terminate() diff --git a/src/framework/graphics/textures.cpp b/src/framework/graphics/textures.cpp index e8aecad1..4b1b81d4 100644 --- a/src/framework/graphics/textures.cpp +++ b/src/framework/graphics/textures.cpp @@ -46,18 +46,18 @@ TexturePtr Textures::get(const std::string& textureFile) if(!texture) { // currently only png textures are supported if(!boost::ends_with(textureFile, ".png")) - logFatal("Unable to load texture %s, file format no supported.", textureFile.c_str()); + flogFatal("FATAL ERROR: Unable to load texture %s, file format no supported.", textureFile.c_str()); // load texture file data uint fileSize; uchar *textureFileData = g_resources.loadFile(textureFile, &fileSize); if(!textureFileData) - logFatal("Unable to load texture %s, file could not be read.", textureFile.c_str()); + flogFatal("FATAL ERROR: Unable to load texture %s, file could not be read.", textureFile.c_str()); // load the texture texture = TexturePtr(TextureLoader::loadPNG(textureFileData)); if(!texture) - logFatal("Unable to load texture %s", textureFile.c_str()); + flogFatal("FATAL ERROR: Unable to load texture %s", textureFile.c_str()); delete[] textureFileData; } diff --git a/src/framework/net/connection.cpp b/src/framework/net/connection.cpp index 38a012a7..1a483068 100644 --- a/src/framework/net/connection.cpp +++ b/src/framework/net/connection.cpp @@ -40,7 +40,7 @@ void Connection::poll() ioService.reset(); } -void Connection::connect(const std::string& host, uint16 port, const Callback& callback) +void Connection::connect(const std::string& host, uint16 port, const SimpleCallback& callback) { m_connectCallback = callback; m_connectionState = CONNECTION_STATE_RESOLVING; diff --git a/src/framework/net/connection.h b/src/framework/net/connection.h index 7a044cc0..356f7613 100644 --- a/src/framework/net/connection.h +++ b/src/framework/net/connection.h @@ -37,7 +37,7 @@ public: static void poll(); - void connect(const std::string& host, uint16 port, const Callback& callback); + void connect(const std::string& host, uint16 port, const SimpleCallback& callback); void setErrorCallback(const ErrorCallback& errorCallback) { m_errorCallback = errorCallback; } void onTimeout(const boost::system::error_code& error); @@ -53,7 +53,7 @@ public: private: ErrorCallback m_errorCallback; - Callback m_connectCallback; + SimpleCallback m_connectCallback; ConnectionState_t m_connectionState; boost::asio::deadline_timer m_timer; diff --git a/src/framework/net/protocol.cpp b/src/framework/net/protocol.cpp index 01ee8596..01ab5764 100644 --- a/src/framework/net/protocol.cpp +++ b/src/framework/net/protocol.cpp @@ -30,14 +30,14 @@ Protocol::Protocol() : m_connection->setErrorCallback(boost::bind(&Protocol::onError, this, _1)); } -void Protocol::connect(const std::string& host, uint16 port, const Callback& callback) +void Protocol::connect(const std::string& host, uint16 port, const SimpleCallback& callback) { m_connection->connect(host, port, callback); } void Protocol::onError(const boost::system::error_code& error) { - logError(error.message().c_str()); + flogError("PROTOCOL ERROR: ", error.message()); // invalid hostname // connection timeouted diff --git a/src/framework/net/protocol.h b/src/framework/net/protocol.h index 47643e71..45727a9f 100644 --- a/src/framework/net/protocol.h +++ b/src/framework/net/protocol.h @@ -32,7 +32,7 @@ class Protocol public: Protocol(); - void connect(const std::string& host, uint16 port, const Callback& callback); + void connect(const std::string& host, uint16 port, const SimpleCallback& callback); virtual void onError(const boost::system::error_code& error); diff --git a/src/framework/platform/win32platform.cpp b/src/framework/platform/win32platform.cpp index 520a6a72..4e438523 100644 --- a/src/framework/platform/win32platform.cpp +++ b/src/framework/platform/win32platform.cpp @@ -211,7 +211,7 @@ void Platform::init(const char *appName) wc.lpszClassName = win32.appName.c_str(); // Set The Class Name if(!RegisterClassA(&wc)) - logFatal("Failed to register the window class."); + logFatal("FATAL ERROR: Failed to register the window class."); // force first tick Platform::getTicks(); @@ -226,7 +226,7 @@ void Platform::terminate() if(win32.instance) { if(!UnregisterClassA(win32.appName.c_str(), win32.instance)) - logError("Unregister class failed."); + logError("ERROR: Unregister class failed."); win32.instance = NULL; } @@ -286,7 +286,7 @@ bool Platform::createWindow(int x, int y, int width, int height, int minWidth, i if(!win32.window) { terminate(); - logFatal("Window creation error."); + logFatal("FATAL ERROR: Window creation error."); return false; } @@ -315,31 +315,31 @@ bool Platform::createWindow(int x, int y, int width, int height, int minWidth, i if(!(win32.hdc = GetDC(win32.window))) { terminate(); - logFatal("Can't Create A GL Device Context."); + logFatal("FATAL ERROR: Can't Create A GL Device Context."); return false; } if(!(pixelFormat = ChoosePixelFormat(win32.hdc, &pfd))) { terminate(); - logFatal("Can't Find A Suitable PixelFormat."); + logFatal("FATAL ERROR: Can't Find A Suitable PixelFormat."); return false; } if(!SetPixelFormat(win32.hdc, pixelFormat, &pfd)) { terminate(); - logFatal("Can't Set The PixelFormat."); + logFatal("FATAL ERROR: Can't Set The PixelFormat."); return false; } if(!(win32.hrc = wglCreateContext(win32.hdc))) { terminate(); - logFatal("Can't Create A GL Rendering Context."); + logFatal("FATAL ERROR: Can't Create A GL Rendering Context."); return false; } if(!wglMakeCurrent(win32.hdc, win32.hrc)) { terminate(); - logFatal("Can't Activate The GL Rendering Context."); + logFatal("FATAL ERROR: Can't Activate The GL Rendering Context."); return false; } @@ -350,24 +350,24 @@ void Platform::destroyWindow() { if(win32.hrc) { if(!wglMakeCurrent(NULL, NULL)) - logError("Release Of DC And RC Failed."); + logError("ERROR: Release Of DC And RC Failed."); if(!wglDeleteContext(win32.hrc)) - logError("Release Rendering Context Failed."); + logError("ERROR: Release Rendering Context Failed."); win32.hrc = NULL; } if(win32.hdc) { if(!ReleaseDC(win32.window, win32.hdc)) - logError("Release Device Context Failed."); + logError("ERROR: Release Device Context Failed."); win32.hdc = NULL; } if(win32.window) { if(!DestroyWindow(win32.window)) - logError("Destroy window failed."); + logError("ERROR: Destroy window failed."); win32.window = NULL; } @@ -502,7 +502,7 @@ std::string Platform::getAppUserDir() std::stringstream sdir; sdir << PHYSFS_getUserDir() << "/." << win32.appName << "/"; if((mkdir(sdir.str().c_str()) != 0) && (errno != EEXIST)) - logError("Couldn't create directory for saving configuration file. (%s)", sdir.str().c_str()); + logError("ERROR: Couldn't create directory for saving configuration file. (%s)", sdir.str().c_str()); return sdir.str(); } diff --git a/src/framework/platform/x11platform.cpp b/src/framework/platform/x11platform.cpp index 1cb13966..a377bea6 100644 --- a/src/framework/platform/x11platform.cpp +++ b/src/framework/platform/x11platform.cpp @@ -234,18 +234,18 @@ void Platform::init(const char *appName) // open display x11.display = XOpenDisplay(0); if(!x11.display) - logFatal("Failed to open X display"); + logFatal("FATAL ERROR: Failed to open X display"); // check if GLX is supported on this display if(!glXQueryExtension(x11.display, 0, 0)) - logFatal("GLX not supported"); + logFatal("FATAL ERROR: GLX not supported"); // retrieve GLX version int glxMajor; int glxMinor; if(!glXQueryVersion(x11.display, &glxMajor, &glxMinor)) - logFatal("Unable to query GLX version"); - logInfo("GLX version %d.%d", glxMajor, glxMinor); + logFatal("FATAL ERROR: Unable to query GLX version"); + flogInfo("GLX version %d.%d", glxMajor % glxMinor); // clipboard related atoms x11.atomClipboard = XInternAtom(x11.display, "CLIPBOARD", False); @@ -497,12 +497,12 @@ bool Platform::createWindow(int x, int y, int width, int height, int minWidth, i // choose OpenGL, RGBA, double buffered, visual x11.visual = glXChooseVisual(x11.display, DefaultScreen(x11.display), attrList); if(!x11.visual) - logFatal("RGBA/Double buffered visual not supported"); + logFatal("FATAL ERROR: RGBA/Double buffered visual not supported"); // create GLX context x11.glxContext = glXCreateContext(x11.display, x11.visual, 0, GL_TRUE); if(!x11.glxContext) - logFatal("Unable to create GLX context"); + logFatal("FATAL ERROR: Unable to create GLX context"); // color map x11.colormap = XCreateColormap(x11.display, @@ -535,7 +535,7 @@ bool Platform::createWindow(int x, int y, int width, int height, int minWidth, i &wa); if(!x11.window) - logFatal("Unable to create X window"); + logFatal("FATAL ERROR: Unable to create X window"); // create input context (to have better key input handling) if(XSupportsLocale()) { @@ -547,11 +547,11 @@ bool Platform::createWindow(int x, int y, int width, int height, int minWidth, i XIMPreeditNothing | XIMStatusNothing, XNClientWindow, x11.window, NULL); if(!x11.xic) - logError("Unable to create the input context"); + logError("ERROR: Unable to create the input context"); } else - logError("Failed to open an input method"); + logError("ERROR: Failed to open an input method"); } else - logError("X11 does not support the current locale"); + logError("ERROR: X11 does not support the current locale"); if(!x11.xic) logWarning("Input of special keys maybe messed up because we couldn't create an input context"); @@ -836,6 +836,6 @@ std::string Platform::getAppUserDir() std::stringstream sdir; sdir << PHYSFS_getUserDir() << "/." << x11.appName << "/"; if((mkdir(sdir.str().c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) != 0) && (errno != EEXIST)) - logError("Couldn't create directory for saving configuration file. (%s)", sdir.str().c_str()); + flogError("ERROR: Couldn't create directory for saving configuration file. (%s)", sdir.str().c_str()); return sdir.str(); } diff --git a/src/framework/prerequisites.h b/src/framework/prerequisites.h index af132389..738e5042 100644 --- a/src/framework/prerequisites.h +++ b/src/framework/prerequisites.h @@ -62,7 +62,6 @@ typedef int8_t int8; // boost utilities #include -#include #include #include #include @@ -72,7 +71,7 @@ typedef int8_t int8; #include #define foreach BOOST_FOREACH -typedef boost::function Callback; +typedef boost::function SimpleCallback; // yaml #include diff --git a/src/framework/script/luafunctions.cpp b/src/framework/script/luafunctions.cpp index 645c3183..e07dff7b 100644 --- a/src/framework/script/luafunctions.cpp +++ b/src/framework/script/luafunctions.cpp @@ -61,12 +61,19 @@ int LuaScript::lua_loadUI() { UIContainerPtr parent; if(getStackSize() > 1) { - parent = boost::static_pointer_cast(popClassInstance()); + parent = boost::dynamic_pointer_cast(popClassInstance()); } else { parent = UIContainer::getRootContainer(); } + std::string uiFile = popString(); - UIElementPtr element = UILoader::loadFile(uiFile.c_str(), parent); + + UIElementPtr element; + if(parent) + element = UILoader::loadFile(uiFile.c_str(), parent); + else + reportErrorWithTraceback("invalid parent container"); + pushClassInstance(element); return 1; } @@ -78,7 +85,6 @@ int LuaScript::lua_getUIRootContainer() return 1; } - int LuaScript::lua_setOnApplicationClose() { int funcRef = popFunction(); @@ -91,7 +97,7 @@ int LuaScript::lua_setOnApplicationClose() int LuaScript::lua_UIElement_destroy() { - UIElementPtr element = boost::static_pointer_cast(popClassInstance()); + UIElementPtr element = boost::dynamic_pointer_cast(popClassInstance()); if(element) element->destroy(); else @@ -101,7 +107,7 @@ int LuaScript::lua_UIElement_destroy() int LuaScript::lua_UIElement_getParent() { - UIElementPtr element = boost::static_pointer_cast(popClassInstance()); + UIElementPtr element = boost::dynamic_pointer_cast(popClassInstance()); if(element) pushClassInstance(element->getParent()); else @@ -111,13 +117,13 @@ int LuaScript::lua_UIElement_getParent() int LuaScript::lua_UIButton_setOnClick() { - lua_insert(L, -2); - UIButtonPtr button = boost::static_pointer_cast(popClassInstance()); + moveTop(-2); + UIButtonPtr button = boost::dynamic_pointer_cast(popClassInstance()); if(button) { int funcRef = popFunction(); button->setOnClick([this, funcRef](UIButtonPtr button) { pushFunction(funcRef); - setSelf(button); + setLocal(button, "self"); callFunction(); }); } else { @@ -129,7 +135,7 @@ int LuaScript::lua_UIButton_setOnClick() int LuaScript::lua_UIContainer_getChildByID() { std::string id = popString(); - UIContainerPtr container = boost::static_pointer_cast(popClassInstance()); + UIContainerPtr container = boost::dynamic_pointer_cast(popClassInstance()); if(container) pushClassInstance(container->getChildById(id)); else @@ -139,9 +145,14 @@ int LuaScript::lua_UIContainer_getChildByID() int LuaScript::lua_UIContainer_lock() { - UIElementPtr element = boost::static_pointer_cast(popClassInstance()); - UIContainerPtr container = boost::static_pointer_cast(popClassInstance()); - if(container && element) { + UIElementPtr element = boost::dynamic_pointer_cast(popClassInstance()); + UIContainerPtr container = boost::dynamic_pointer_cast(popClassInstance()); + if(!element) { + reportFuncErrorWithTraceback("invalid lock element"); + return 1; + } + + if(container) { container->lockElement(element); } return 1; @@ -149,7 +160,7 @@ int LuaScript::lua_UIContainer_lock() int LuaScript::lua_UIContainer_unlock() { - UIContainerPtr container = boost::static_pointer_cast(popClassInstance()); + UIContainerPtr container = boost::dynamic_pointer_cast(popClassInstance()); if(container) { container->unlockElement(); } diff --git a/src/framework/script/luascript.cpp b/src/framework/script/luascript.cpp index 6b7ead6f..2ef3bd1d 100644 --- a/src/framework/script/luascript.cpp +++ b/src/framework/script/luascript.cpp @@ -32,7 +32,7 @@ LuaScript::LuaScript() { L = luaL_newstate(); if(!L) - logFatal("could not create lua context"); + logFatal("FATAL ERROR: could not create lua context"); // load lua standard libraries luaL_openlibs(L); @@ -64,7 +64,7 @@ void LuaScript::loadAllModules() bool LuaScript::loadFile(const std::string& fileName) { if(!g_resources.fileExists(fileName)) { - logError("script file '%s' doesn't exist", fileName.c_str()); + flogError("ERROR: script file '%s' doesn't exist", fileName.c_str()); return false; } std::string fileContents = g_resources.loadTextFile(fileName); @@ -114,11 +114,18 @@ int LuaScript::loadBufferAsFunction(const std::string& text, const std::string& void LuaScript::reportError(const std::string& errorDesc, const char *funcName) { std::stringstream ss; - ss << "LUA script error"; + ss << "LUA Script ERROR: "; if(funcName) - ss << " in " << funcName << "()"; - ss << ": " << errorDesc << std::endl; - logError(ss.str().c_str()); + ss << " in " << funcName << "(): "; + ss << errorDesc << std::endl; + logError(ss.str()); +} + +void LuaScript::reportErrorWithTraceback(const std::string& errorDesc, const char* funcName) +{ + pushString(errorDesc); + luaErrorHandler(L); + reportError(popString(), funcName); } int LuaScript::getStackSize() @@ -126,6 +133,11 @@ int LuaScript::getStackSize() return lua_gettop(L); } +void LuaScript::moveTop(int index) +{ + lua_insert(L, index); +} + void LuaScript::pop(int n) { lua_pop(L, n); @@ -141,15 +153,15 @@ bool LuaScript::popBoolean() int32_t LuaScript::popInteger() { double d = lua_tonumber(L, -1); - pop(1); + pop(); return (int)d; } std::string LuaScript::popString() { - size_t len; - const char *cstr = lua_tolstring(L, -1, &len); - std::string str(cstr, len); + std::string str; + if(lua_isstring(L, -1)) + str = lua_tostring(L, -1); pop(); return str; } @@ -181,8 +193,10 @@ void LuaScript::pushUserdata(void* ptr) void LuaScript::pushClassInstance(const ScriptablePtr& object) { - if(object && object->getScriptableName()) { + if(object) { + // create weak_ptr to the scriptable object stored as userdata new(lua_newuserdata(L, sizeof(ScriptableWeakPtr))) ScriptableWeakPtr(object); + // set object metatable lua_getfield(L, LUA_REGISTRYINDEX, (std::string(object->getScriptableName()) + "_mt").c_str()); lua_setmetatable(L, -2); } else { @@ -192,18 +206,14 @@ void LuaScript::pushClassInstance(const ScriptablePtr& object) ScriptablePtr LuaScript::popClassInstance() { - if(!lua_isuserdata(L, -1)) { - reportError(format("couldn't pop a class instance, top objet is not a valid type (%s)", luaL_typename(L, -1))); - lua_pop(L, 1); - return ScriptablePtr(); - } - - ScriptableWeakPtr *objectRef = (ScriptableWeakPtr *)lua_touserdata(L, -1); + ScriptablePtr object; + if(lua_isuserdata(L, -1)) { // instances are store as userdata + object = ((ScriptableWeakPtr *)lua_touserdata(L, -1))->lock(); + if(!object) + reportErrorWithTraceback("attempt to retrive class instance from a object that is already expired"); + } else if(!lua_isnil(L, -1)) // we accept nil values + reportErrorWithTraceback("couldn't retrive class instance, the value is not a scriptable type"); lua_pop(L, 1); - - ScriptablePtr object = objectRef->lock(); - if(!object) - reportError(format("attempt to retrive class instance from a object that is already expired")); return object; } @@ -240,11 +250,11 @@ void LuaScript::callFunction(int numArgs) reportError("stack size changed!"); } -void LuaScript::setSelf(const ScriptablePtr& scriptable, int envIndex) +void LuaScript::setLocal(const ScriptablePtr& scriptable, const char *varName, int envIndex) { lua_getfenv(L, envIndex); pushClassInstance(scriptable); - lua_setfield(L, -2, "self"); + lua_setfield(L, -2, varName); lua_pop(L, 1); } @@ -382,24 +392,36 @@ int LuaScript::luaCompareClassInstances(lua_State* L) int LuaScript::luaFunctionCallback(lua_State* L) { + // look for function id int id = lua_tonumber(L, lua_upvalueindex(1)); + // call the function return (g_lua.*(g_lua.m_functions[id]))(); } int LuaScript::luaErrorHandler(lua_State *L) { + // push debug lua_getfield(L, LUA_GLOBALSINDEX, "debug"); if(!lua_istable(L, -1)) { lua_pop(L, 1); return 1; } + // push debug.traceback lua_getfield(L, -1, "traceback"); if(!lua_isfunction(L, -1)) { lua_pop(L, 2); return 1; } - lua_pushvalue(L, 1); + // remove debug + lua_remove(L, -2); + // push additional error message + lua_pushvalue(L, -2); + // push level lua_pushinteger(L, 2); + // call debug.traceback lua_call(L, 2, 1); + // remove additional error message + lua_remove(L, -2); + // return, the complete error message is on the stack return 1; } diff --git a/src/framework/script/luascript.h b/src/framework/script/luascript.h index cdd4a415..fe54b99e 100644 --- a/src/framework/script/luascript.h +++ b/src/framework/script/luascript.h @@ -30,6 +30,7 @@ #include #define reportFuncError(a) reportError(a, __FUNCTION__) +#define reportFuncErrorWithTraceback(a) reportErrorWithTraceback(a, __FUNCTION__) class LuaScript { @@ -42,8 +43,10 @@ public: bool loadBuffer(const std::string& text, const std::string& what = "luaBuffer"); int loadBufferAsFunction(const std::string& text, const std::string& what = "luaBuffer"); void reportError(const std::string& errorDesc, const char *funcName = NULL); + void reportErrorWithTraceback(const std::string& errorDesc, const char *funcName = NULL); int getStackSize(); + void moveTop(int index); void pushNil(); void pushBoolean(bool b); @@ -61,7 +64,7 @@ public: void releaseFunction(int functionRef); void callFunction(int numArgs = 0); - void setSelf(const ScriptablePtr& scriptable, int envIndex = -1); + void setLocal(const ScriptablePtr& scriptable, const char *varName, int envIndex = -1); void pushClassInstance(const ScriptablePtr& object); ScriptablePtr popClassInstance(); diff --git a/src/framework/ui/uilayout.cpp b/src/framework/ui/uilayout.cpp index cadb7ca8..a350d0eb 100644 --- a/src/framework/ui/uilayout.cpp +++ b/src/framework/ui/uilayout.cpp @@ -47,7 +47,7 @@ int AnchorLine::getPos() const return 0; } } - logError("anchor line of an element has expired, your UI is missconfigured"); + logError("ERROR: anchor line of an element has expired, your UI is missconfigured"); return 0; } @@ -74,7 +74,7 @@ bool UILayout::addAnchor(EAnchorType type, const AnchorLine& anchorLine) { // we can never anchor with itself if(anchorLine.getRelativeElement() == asUILayout()) { - logError("anchoring with itself is not possible"); + logError("ERROR: anchoring with itself is not possible"); return false; } @@ -82,7 +82,7 @@ bool UILayout::addAnchor(EAnchorType type, const AnchorLine& anchorLine) // this only happens in missconfigurations for(auto it = m_anchoredElements.begin(); it != m_anchoredElements.end(); ++it) { if((*it).lock() == anchorLine.getRelativeElement()) { - logError("anchoring elements with each other is not possible"); + logError("ERROR: anchoring elements with each other is not possible"); return false; } } diff --git a/src/framework/ui/uiloader.cpp b/src/framework/ui/uiloader.cpp index 05c0eb48..c9a5a1ac 100644 --- a/src/framework/ui/uiloader.cpp +++ b/src/framework/ui/uiloader.cpp @@ -67,7 +67,7 @@ UIElementPtr UILoader::loadFile(const std::string& file, const UIContainerPtr& p { std::string fileContents = g_resources.loadTextFile(file); if(!fileContents.size()) { - logError("Could not load ui file \"%s", file.c_str()); + flogError("ERROR: Could not load ui file \"%s", file.c_str()); return UIElementPtr(); } @@ -101,7 +101,7 @@ UIElementPtr UILoader::loadFile(const std::string& file, const UIContainerPtr& p return element; } catch (YAML::Exception& e) { - logError("Failed to load ui file \"%s\":\n %s", file.c_str(), e.what()); + flogError("ERROR: Failed to load ui file \"%s\":\n %s", file.c_str() % e.what()); } return UIElementPtr(); diff --git a/src/framework/ui/uiskins.cpp b/src/framework/ui/uiskins.cpp index e74453cd..84d9ca33 100644 --- a/src/framework/ui/uiskins.cpp +++ b/src/framework/ui/uiskins.cpp @@ -38,7 +38,7 @@ void UISkins::load(const std::string& skinsFile) { std::string fileContents = g_resources.loadTextFile(skinsFile); if(!fileContents.size()) - logFatal("Could not load skin file \"%s", skinsFile.c_str()); + flogFatal("FATAL ERROR: Could not load skin file \"%s", skinsFile.c_str()); std::istringstream fin(fileContents); @@ -126,7 +126,7 @@ void UISkins::load(const std::string& skinsFile) } } } catch (YAML::Exception& e) { - logFatal("Malformed skin file \"%s\":\n %s", skinsFile.c_str(), e.what()); + flogFatal("FATAL ERROR: Malformed skin file \"%s\":\n %s", skinsFile.c_str() % e.what()); } } @@ -143,6 +143,6 @@ UIElementSkinPtr UISkins::getElementSkin(UI::EElementType elementType, const std if(elementType == skin->getElementType() && name == skin->getName()) return skin; } - logWarning("Element skin '%s' not found", name.c_str()); + flogWarning("Element skin '%s' not found", name.c_str()); return UIElementSkinPtr(); } diff --git a/src/framework/util/logger.cpp b/src/framework/util/logger.cpp index 8fbfb8af..fcc1beb2 100644 --- a/src/framework/util/logger.cpp +++ b/src/framework/util/logger.cpp @@ -26,17 +26,10 @@ #include #include -#include -void Logger::_log(int level, const char *trace, const char *format, ...) +void Logger::log(int level, const std::string& text, const char *trace) { - va_list args; std::string strace; - - va_start(args, format); - std::string text = vformat(format, args); - va_end(args); - if(trace) { strace = trace; strace = strace.substr(0, strace.find_first_of('(')); @@ -54,8 +47,6 @@ void Logger::_log(int level, const char *trace, const char *format, ...) if(!strace.empty()) std::cout << "[" << strace << "] "; - static char const *prefixes[] = { "FATAL ERROR: ", "ERROR: ", "WARNING: ", "", "", "" }; - std::cout << prefixes[level]; std::cout << text; #ifdef linux @@ -68,3 +59,4 @@ void Logger::_log(int level, const char *trace, const char *format, ...) if(level == LFATAL) exit(-1); } + diff --git a/src/framework/util/logger.h b/src/framework/util/logger.h index c4db46bd..7ec1e7ac 100644 --- a/src/framework/util/logger.h +++ b/src/framework/util/logger.h @@ -26,33 +26,39 @@ #define LOGGER_H #include +#include -namespace Logger { +class Logger { +public: + enum ELogLevel { + LFATAL = 0, + LERROR, + LWARNING, + LINFO, + LDEBUG + }; -enum ELogLevel { - LFATAL = 0, - LERROR, - LWARNING, - LINFO, - LDEBUG + static void log(int level, const std::string& text = "", const char *trace = NULL); }; -void _log(int level, const char *trace, const char *format, ...); - -} +#define logFatal(a) Logger::log(Logger::LFATAL, a) +#define logError(a) Logger::log(Logger::LERROR, a) +#define logWarning(a) Logger::log(Logger::LWARNING, a) +#define logDebug(a) Logger::log(Logger::LDEBUG, a) +#define logInfo(a) Logger::log(Logger::LINFO, a) -#define logFatal(...) Logger::_log(Logger::LFATAL, NULL, __VA_ARGS__) -#define logError(...) Logger::_log(Logger::LERROR, NULL, __VA_ARGS__) -#define logWarning(...) Logger::_log(Logger::LWARNING, NULL, __VA_ARGS__) -#define logDebug(...) Logger::_log(Logger::LDEBUG, NULL, __VA_ARGS__) -#define logInfo(...) Logger::_log(Logger::LINFO, NULL, __VA_ARGS__) +#define flogFatal(a,b) Logger::log(Logger::LFATAL, (boost::format(a) % b).str()) +#define flogError(a,b) Logger::log(Logger::LERROR, (boost::format(a) % b).str()) +#define flogWarning(a,b) Logger::log(Logger::LWARNING, (boost::format(a) % b).str()) +#define flogDebug(a,b) Logger::log(Logger::LDEBUG, (boost::format(a) % b).str()) +#define flogInfo(a,b) Logger::log(Logger::LINFO, (boost::format(a) % b).str()) -#define logTrace() Logger::_log(Logger::LDEBUG, __PRETTY_FUNCTION__, "") -#define logTraceFatal(...) Logger::_log(Logger::LFATAL, __PRETTY_FUNCTION__, __VA_ARGS__) -#define logTraceError(...) Logger::_log(Logger::LERROR, __PRETTY_FUNCTION__, __VA_ARGS__) -#define logTraceWarning(...) Logger::_log(Logger::LWARNING, __PRETTY_FUNCTION__, __VA_ARGS__) -#define logTraceDebug(...) Logger::_log(Logger::LDEBUG, __PRETTY_FUNCTION__, __VA_ARGS__) -#define logTraceInfo(...) Logger::_log(Logger::LINFO, __PRETTY_FUNCTION__, __VA_ARGS__) +#define logTrace() Logger::log(Logger::LDEBUG, "", __PRETTY_FUNCTION__) +#define logTraceFatal(a) Logger::log(Logger::LFATAL, a, __PRETTY_FUNCTION__) +#define logTraceError(a) Logger::log(Logger::LERROR, a, __PRETTY_FUNCTION__) +#define logTraceWarning(a) Logger::log(Logger::LWARNING, a, __PRETTY_FUNCTION__) +#define logTraceDebug(a) Logger::log(Logger::LDEBUG, a, __PRETTY_FUNCTION__) +#define logTraceInfo(a) Logger::log(Logger::LINFO, a, __PRETTY_FUNCTION__) struct Dump { public: @@ -65,4 +71,4 @@ private: #define dump Dump() -#endif +#endif // LOGGER_H diff --git a/src/framework/util/util.cpp b/src/framework/util/util.cpp index 467193b5..0c29664c 100644 --- a/src/framework/util/util.cpp +++ b/src/framework/util/util.cpp @@ -23,30 +23,3 @@ #include #include - -std::string vformat(const char *format, va_list args) -{ - if(!format) - return ""; - int result = -1, length = 256; - char *buffer = 0; - while(result == -1) { - if(buffer) - delete [] buffer; - buffer = new char [length + 1]; - result = vsnprintf(buffer, length, format, args); - length *= 2; - } - std::string s(buffer); - delete [] buffer; - return s; -} - -std::string format(const char *format, ...) -{ - va_list args; - va_start(args, format); - std::string s = vformat(format, args); - va_end(args); - return s; -} diff --git a/src/framework/util/util.h b/src/framework/util/util.h index b21a25f9..40319007 100644 --- a/src/framework/util/util.h +++ b/src/framework/util/util.h @@ -26,14 +26,11 @@ #define UTIL_H #include -#include #include +#include -/// Formatting like printf for std::string, va_list input version -std::string vformat(const char *format, va_list args); - -/// Formatting like printf for std::string -std::string format(const char *format, ...); +/// Easy/fast writting formater +#define f(a, b) (boost::format(a) % b).str() /// Convert any data type through boost::lexical_cast template @@ -43,9 +40,9 @@ R convertType(T t) try { ret = boost::lexical_cast(t); } catch(boost::bad_lexical_cast bad) { - logError("Error converting type: %s", bad.what()); + flogError("Error converting type: %s", bad.what()); } return ret; } -#endif \ No newline at end of file +#endif // UTIL_H diff --git a/src/main.cpp b/src/main.cpp index dcb8230a..6048d221 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -121,7 +121,7 @@ int main(int argc, const char *argv[]) g_lua.loadAllModules(); if(!UIContainer::getRootContainer()->getChildCount()) - logFatal("no ui loaded at all, no reason to continue running"); + logFatal("FATAL ERROR: no ui loaded at all, no reason to continue running"); Platform::showWindow(); //Platform::hideMouseCursor();