<commit_before>/***********************************************************************
filename:   CEGuiGLFWSharedBase.cpp
created:    12/2/2012
author:     Paul D Turner
*************************************************************************/
/***************************************************************************
*   Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team
*
*   Permission is hereby granted, free of charge, to any person obtaining
*   a copy of this software and associated documentation files (the
*   "Software"), to deal in the Software without restriction, including
*   without limitation the rights to use, copy, modify, merge, publish,
*   distribute, sublicense, and/or sell copies of the Software, and to
*   permit persons to whom the Software is furnished to do so, subject to
*   the following conditions:
*
*   The above copyright notice and this permission notice shall be
*   included in all copies or substantial portions of the Software.
*
*   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
*   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
*   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
*   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
*   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
*   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
*   OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#if defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__HAIKU__)
# include <unistd.h>
#endif

#include "CEGUISamplesConfig.h"
#include "CEGuiGLFWSharedBase.h"
#include "SamplesFrameworkBase.h"
#include "CEGUI/CEGUI.h"

#include <stdexcept>
#include <sstream>

//----------------------------------------------------------------------------//
CEGuiGLFWSharedBase* CEGuiGLFWSharedBase::d_appInstance = 0;
double  CEGuiGLFWSharedBase::d_frameTime = 0;
int CEGuiGLFWSharedBase::d_modifiers = 0;
bool CEGuiGLFWSharedBase::d_windowSized = false;
int CEGuiGLFWSharedBase::d_newWindowWidth;
int CEGuiGLFWSharedBase::d_newWindowHeight;

//----------------------------------------------------------------------------//
CEGuiGLFWSharedBase::CEGuiGLFWSharedBase()
{
    if (d_appInstance)
        throw CEGUI::InvalidRequestException(
        "CEGuiGLFWSharedBase instance already exists!");

    d_appInstance = this;
}

//----------------------------------------------------------------------------//
CEGuiGLFWSharedBase::~CEGuiGLFWSharedBase()
{
}

//----------------------------------------------------------------------------//
void CEGuiGLFWSharedBase::run()
{
    d_sampleApp->initialise();

    // Input callbacks of glfw for CEGUI
    glfwSetKeyCallback(glfwKeyCallback);
    glfwSetCharCallback(glfwCharCallback);
    glfwSetMouseButtonCallback(glfwMouseButtonCallback);
    glfwSetMouseWheelCallback(glfwMouseWheelCallback);
    glfwSetMousePosCallback(glfwMousePosCallback);

    //Window callbacks
    glfwSetWindowSizeCallback(glfwWindowResizeCallback);
    d_windowSized = false; //The resize callback is being called immediately after setting it in this version of glfw
    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

    // set starting time
    d_frameTime = glfwGetTime();

    while (!d_sampleApp->isQuitting() &&
        glfwGetWindowParam(GLFW_OPENED))
    {
        if (d_windowSized)
        {
            d_windowSized = false;
            CEGUI::System::getSingleton().
                notifyDisplaySizeChanged(
                CEGUI::Sizef(static_cast<float>(d_newWindowWidth),
                static_cast<float>(d_newWindowHeight)));
        }

        drawFrame();
    }

    d_sampleApp->deinitialise();
}
//----------------------------------------------------------------------------//
void CEGuiGLFWSharedBase::destroyWindow()
{
    glfwTerminate();
}

//----------------------------------------------------------------------------//
void CEGuiGLFWSharedBase::beginRendering(const float /*elapsed*/)
{
    glClear(GL_COLOR_BUFFER_BIT);
}

//----------------------------------------------------------------------------//
void CEGuiGLFWSharedBase::endRendering()
{
    glfwSwapBuffers();
}

//----------------------------------------------------------------------------//
void CEGuiGLFWSharedBase::drawFrame()
{
    // calculate time elapsed since last frame
    double time_now = glfwGetTime();
    const double elapsed = time_now - d_frameTime;
    d_frameTime = time_now;

    d_appInstance->renderSingleFrame(static_cast<float>(elapsed));
}

//----------------------------------------------------------------------------//
void CEGuiGLFWSharedBase::glfwWindowResizeCallback(int w, int h)
{
    // We cache this in order to minimise calls to notifyDisplaySizeChanged,
    // which happens in the main loop whenever d_windowSized is set to true.
    d_windowSized = true;
    d_newWindowWidth = w;
    d_newWindowHeight = h;
}

//----------------------------------------------------------------------------//
CEGUI::Key::Scan CEGuiGLFWSharedBase::GlfwToCeguiKey(int glfwKey)
{
    switch(glfwKey)
    {
    case GLFW_KEY_ESC       : return CEGUI::Key::Escape;
    case GLFW_KEY_F1        : return CEGUI::Key::F1;
    case GLFW_KEY_F2        : return CEGUI::Key::F2;
    case GLFW_KEY_F3        : return CEGUI::Key::F3;
    case GLFW_KEY_F4        : return CEGUI::Key::F4;
    case GLFW_KEY_F5        : return CEGUI::Key::F5;
    case GLFW_KEY_F6        : return CEGUI::Key::F6;
    case GLFW_KEY_F7        : return CEGUI::Key::F7;
    case GLFW_KEY_F8        : return CEGUI::Key::F8;
    case GLFW_KEY_F9        : return CEGUI::Key::F9;
    case GLFW_KEY_F10       : return CEGUI::Key::F10;
    case GLFW_KEY_F11       : return CEGUI::Key::F11;
    case GLFW_KEY_F12       : return CEGUI::Key::F12;
    case GLFW_KEY_F13       : return CEGUI::Key::F13;
    case GLFW_KEY_F14       : return CEGUI::Key::F14;
    case GLFW_KEY_F15       : return CEGUI::Key::F15;
    case GLFW_KEY_UP        : return CEGUI::Key::ArrowUp;
    case GLFW_KEY_DOWN      : return CEGUI::Key::ArrowDown;
    case GLFW_KEY_LEFT      : return CEGUI::Key::ArrowLeft;
    case GLFW_KEY_RIGHT     : return CEGUI::Key::ArrowRight;
    case GLFW_KEY_LSHIFT    : return CEGUI::Key::LeftShift;
    case GLFW_KEY_RSHIFT    : return CEGUI::Key::RightShift;
    case GLFW_KEY_LCTRL     : return CEGUI::Key::LeftControl;
    case GLFW_KEY_RCTRL     : return CEGUI::Key::RightControl;
    case GLFW_KEY_LALT      : return CEGUI::Key::LeftAlt;
    case GLFW_KEY_RALT      : return CEGUI::Key::RightAlt;
    case GLFW_KEY_TAB       : return CEGUI::Key::Tab;
    case GLFW_KEY_ENTER     : return CEGUI::Key::Return;
    case GLFW_KEY_BACKSPACE : return CEGUI::Key::Backspace;
    case GLFW_KEY_INSERT    : return CEGUI::Key::Insert;
    case GLFW_KEY_DEL       : return CEGUI::Key::Delete;
    case GLFW_KEY_PAGEUP    : return CEGUI::Key::PageUp;
    case GLFW_KEY_PAGEDOWN  : return CEGUI::Key::PageDown;
    case GLFW_KEY_HOME      : return CEGUI::Key::Home;
    case GLFW_KEY_END       : return CEGUI::Key::End;
    case GLFW_KEY_KP_ENTER  : return CEGUI::Key::NumpadEnter;
    case GLFW_KEY_SPACE     : return CEGUI::Key::Space;
    case 'A'                : return CEGUI::Key::A;
    case 'B'                : return CEGUI::Key::B;
    case 'C'                : return CEGUI::Key::C;
    case 'D'                : return CEGUI::Key::D;
    case 'E'                : return CEGUI::Key::E;
    case 'F'                : return CEGUI::Key::F;
    case 'G'                : return CEGUI::Key::G;
    case 'H'                : return CEGUI::Key::H;
    case 'I'                : return CEGUI::Key::I;
    case 'J'                : return CEGUI::Key::J;
    case 'K'                : return CEGUI::Key::K;
    case 'L'                : return CEGUI::Key::L;
    case 'M'                : return CEGUI::Key::M;
    case 'N'                : return CEGUI::Key::N;
    case 'O'                : return CEGUI::Key::O;
    case 'P'                : return CEGUI::Key::P;
    case 'Q'                : return CEGUI::Key::Q;
    case 'R'                : return CEGUI::Key::R;
    case 'S'                : return CEGUI::Key::S;
    case 'T'                : return CEGUI::Key::T;
    case 'U'                : return CEGUI::Key::U;
    case 'V'                : return CEGUI::Key::V;
    case 'W'                : return CEGUI::Key::W;
    case 'X'                : return CEGUI::Key::X;
    case 'Y'                : return CEGUI::Key::Y;
    case 'Z'                : return CEGUI::Key::Z;
    default                 : return CEGUI::Key::Unknown;
    }
}

//----------------------------------------------------------------------------//
CEGUI::MouseButton CEGuiGLFWSharedBase::GlfwToCeguiMouseButton(int glfwButton)
{
    switch(glfwButton)
    {
    case GLFW_MOUSE_BUTTON_LEFT     : return CEGUI::LeftButton;
    case GLFW_MOUSE_BUTTON_RIGHT    : return CEGUI::RightButton;
    case GLFW_MOUSE_BUTTON_MIDDLE   : return CEGUI::MiddleButton;
    default                         : return CEGUI::NoButton;
    }
}

//----------------------------------------------------------------------------//
void GLFWCALL CEGuiGLFWSharedBase::glfwKeyCallback(int key, int action)
{
    CEGUI::Key::Scan ceguiKey = GlfwToCeguiKey(key);

    if(action == GLFW_PRESS)
        d_sampleApp->injectKeyDown(ceguiKey);
    else if (action == GLFW_RELEASE)
        d_sampleApp->injectKeyUp(ceguiKey);
}

//----------------------------------------------------------------------------//
void GLFWCALL CEGuiGLFWSharedBase::glfwCharCallback(int character, int action)
{
    if(action == GLFW_PRESS)
        d_sampleApp->injectChar(character);
}

//----------------------------------------------------------------------------//
void GLFWCALL CEGuiGLFWSharedBase::glfwMouseButtonCallback(int key, int action)
{
    CEGUI::MouseButton ceguiMouseButton = GlfwToCeguiMouseButton(key);

    if(action == GLFW_PRESS)
        d_sampleApp->injectMouseButtonDown(ceguiMouseButton);
    else if (action == GLFW_RELEASE)
        d_sampleApp->injectMouseButtonUp(ceguiMouseButton);
}

//----------------------------------------------------------------------------//
void GLFWCALL CEGuiGLFWSharedBase::glfwMouseWheelCallback(int position)
{
    static int lastPosition = 0;
    d_sampleApp->injectMouseWheelChange(static_cast<float>(position - lastPosition));
    lastPosition = position;
}

//----------------------------------------------------------------------------//
void GLFWCALL CEGuiGLFWSharedBase::glfwMousePosCallback(int x, int y)
{
    d_sampleApp->injectMousePosition(static_cast<float>(x), static_cast<float>(y));
}

//----------------------------------------------------------------------------//
void CEGuiGLFWSharedBase::initGLFW()
{
    if(!glfwInit())
        CEGUI_THROW(CEGUI::RendererException("Failed to initialise GLFW."));
}

//----------------------------------------------------------------------------//
void CEGuiGLFWSharedBase::createGLFWWindow()
{
    if (glfwOpenWindow(s_defaultWindowWidth, s_defaultWindowHeight, 0, 0, 0, 0, 24, 8, GLFW_WINDOW) != GL_TRUE)
    {
        CEGUI_THROW(CEGUI::RendererException("Failed to open GLFW window."));
        glfwTerminate();
    }
}

//----------------------------------------------------------------------------//
void CEGuiGLFWSharedBase::setGLFWAppConfiguration()
{
    glfwSetWindowTitle("Crazy Eddie's GUI Mk-2 - Sample Application");

    //Deactivate VSYNC
    glfwSwapInterval(0);

    // Disable the mouse position in Non_Debug mode
#ifndef DEBUG
    glfwDisable(GLFW_MOUSE_CURSOR);
#endif
    // Clear Errors by GLFW, even if Setup is correct.
    glGetError();
}

//----------------------------------------------------------------------------//

<commit_msg>MOD: Minor adjustment of glfw window creation params<commit_after>/***********************************************************************
filename:   CEGuiGLFWSharedBase.cpp
created:    12/2/2012
author:     Paul D Turner
*************************************************************************/
/***************************************************************************
*   Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team
*
*   Permission is hereby granted, free of charge, to any person obtaining
*   a copy of this software and associated documentation files (the
*   "Software"), to deal in the Software without restriction, including
*   without limitation the rights to use, copy, modify, merge, publish,
*   distribute, sublicense, and/or sell copies of the Software, and to
*   permit persons to whom the Software is furnished to do so, subject to
*   the following conditions:
*
*   The above copyright notice and this permission notice shall be
*   included in all copies or substantial portions of the Software.
*
*   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
*   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
*   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
*   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
*   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
*   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
*   OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#if defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__HAIKU__)
# include <unistd.h>
#endif

#include "CEGUISamplesConfig.h"
#include "CEGuiGLFWSharedBase.h"
#include "SamplesFrameworkBase.h"
#include "CEGUI/CEGUI.h"

#include <stdexcept>
#include <sstream>

//----------------------------------------------------------------------------//
CEGuiGLFWSharedBase* CEGuiGLFWSharedBase::d_appInstance = 0;
double  CEGuiGLFWSharedBase::d_frameTime = 0;
int CEGuiGLFWSharedBase::d_modifiers = 0;
bool CEGuiGLFWSharedBase::d_windowSized = false;
int CEGuiGLFWSharedBase::d_newWindowWidth;
int CEGuiGLFWSharedBase::d_newWindowHeight;

//----------------------------------------------------------------------------//
CEGuiGLFWSharedBase::CEGuiGLFWSharedBase()
{
    if (d_appInstance)
        throw CEGUI::InvalidRequestException(
        "CEGuiGLFWSharedBase instance already exists!");

    d_appInstance = this;
}

//----------------------------------------------------------------------------//
CEGuiGLFWSharedBase::~CEGuiGLFWSharedBase()
{
}

//----------------------------------------------------------------------------//
void CEGuiGLFWSharedBase::run()
{
    d_sampleApp->initialise();

    // Input callbacks of glfw for CEGUI
    glfwSetKeyCallback(glfwKeyCallback);
    glfwSetCharCallback(glfwCharCallback);
    glfwSetMouseButtonCallback(glfwMouseButtonCallback);
    glfwSetMouseWheelCallback(glfwMouseWheelCallback);
    glfwSetMousePosCallback(glfwMousePosCallback);

    //Window callbacks
    glfwSetWindowSizeCallback(glfwWindowResizeCallback);
    d_windowSized = false; //The resize callback is being called immediately after setting it in this version of glfw
    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

    // set starting time
    d_frameTime = glfwGetTime();

    while (!d_sampleApp->isQuitting() &&
        glfwGetWindowParam(GLFW_OPENED))
    {
        if (d_windowSized)
        {
            d_windowSized = false;
            CEGUI::System::getSingleton().
                notifyDisplaySizeChanged(
                CEGUI::Sizef(static_cast<float>(d_newWindowWidth),
                static_cast<float>(d_newWindowHeight)));
        }

        drawFrame();
    }

    d_sampleApp->deinitialise();
}
//----------------------------------------------------------------------------//
void CEGuiGLFWSharedBase::destroyWindow()
{
    glfwTerminate();
}

//----------------------------------------------------------------------------//
void CEGuiGLFWSharedBase::beginRendering(const float /*elapsed*/)
{
    glClear(GL_COLOR_BUFFER_BIT);
}

//----------------------------------------------------------------------------//
void CEGuiGLFWSharedBase::endRendering()
{
    glfwSwapBuffers();
}

//----------------------------------------------------------------------------//
void CEGuiGLFWSharedBase::drawFrame()
{
    // calculate time elapsed since last frame
    double time_now = glfwGetTime();
    const double elapsed = time_now - d_frameTime;
    d_frameTime = time_now;

    d_appInstance->renderSingleFrame(static_cast<float>(elapsed));
}

//----------------------------------------------------------------------------//
void CEGuiGLFWSharedBase::glfwWindowResizeCallback(int w, int h)
{
    // We cache this in order to minimise calls to notifyDisplaySizeChanged,
    // which happens in the main loop whenever d_windowSized is set to true.
    d_windowSized = true;
    d_newWindowWidth = w;
    d_newWindowHeight = h;
}

//----------------------------------------------------------------------------//
CEGUI::Key::Scan CEGuiGLFWSharedBase::GlfwToCeguiKey(int glfwKey)
{
    switch(glfwKey)
    {
    case GLFW_KEY_ESC       : return CEGUI::Key::Escape;
    case GLFW_KEY_F1        : return CEGUI::Key::F1;
    case GLFW_KEY_F2        : return CEGUI::Key::F2;
    case GLFW_KEY_F3        : return CEGUI::Key::F3;
    case GLFW_KEY_F4        : return CEGUI::Key::F4;
    case GLFW_KEY_F5        : return CEGUI::Key::F5;
    case GLFW_KEY_F6        : return CEGUI::Key::F6;
    case GLFW_KEY_F7        : return CEGUI::Key::F7;
    case GLFW_KEY_F8        : return CEGUI::Key::F8;
    case GLFW_KEY_F9        : return CEGUI::Key::F9;
    case GLFW_KEY_F10       : return CEGUI::Key::F10;
    case GLFW_KEY_F11       : return CEGUI::Key::F11;
    case GLFW_KEY_F12       : return CEGUI::Key::F12;
    case GLFW_KEY_F13       : return CEGUI::Key::F13;
    case GLFW_KEY_F14       : return CEGUI::Key::F14;
    case GLFW_KEY_F15       : return CEGUI::Key::F15;
    case GLFW_KEY_UP        : return CEGUI::Key::ArrowUp;
    case GLFW_KEY_DOWN      : return CEGUI::Key::ArrowDown;
    case GLFW_KEY_LEFT      : return CEGUI::Key::ArrowLeft;
    case GLFW_KEY_RIGHT     : return CEGUI::Key::ArrowRight;
    case GLFW_KEY_LSHIFT    : return CEGUI::Key::LeftShift;
    case GLFW_KEY_RSHIFT    : return CEGUI::Key::RightShift;
    case GLFW_KEY_LCTRL     : return CEGUI::Key::LeftControl;
    case GLFW_KEY_RCTRL     : return CEGUI::Key::RightControl;
    case GLFW_KEY_LALT      : return CEGUI::Key::LeftAlt;
    case GLFW_KEY_RALT      : return CEGUI::Key::RightAlt;
    case GLFW_KEY_TAB       : return CEGUI::Key::Tab;
    case GLFW_KEY_ENTER     : return CEGUI::Key::Return;
    case GLFW_KEY_BACKSPACE : return CEGUI::Key::Backspace;
    case GLFW_KEY_INSERT    : return CEGUI::Key::Insert;
    case GLFW_KEY_DEL       : return CEGUI::Key::Delete;
    case GLFW_KEY_PAGEUP    : return CEGUI::Key::PageUp;
    case GLFW_KEY_PAGEDOWN  : return CEGUI::Key::PageDown;
    case GLFW_KEY_HOME      : return CEGUI::Key::Home;
    case GLFW_KEY_END       : return CEGUI::Key::End;
    case GLFW_KEY_KP_ENTER  : return CEGUI::Key::NumpadEnter;
    case GLFW_KEY_SPACE     : return CEGUI::Key::Space;
    case 'A'                : return CEGUI::Key::A;
    case 'B'                : return CEGUI::Key::B;
    case 'C'                : return CEGUI::Key::C;
    case 'D'                : return CEGUI::Key::D;
    case 'E'                : return CEGUI::Key::E;
    case 'F'                : return CEGUI::Key::F;
    case 'G'                : return CEGUI::Key::G;
    case 'H'                : return CEGUI::Key::H;
    case 'I'                : return CEGUI::Key::I;
    case 'J'                : return CEGUI::Key::J;
    case 'K'                : return CEGUI::Key::K;
    case 'L'                : return CEGUI::Key::L;
    case 'M'                : return CEGUI::Key::M;
    case 'N'                : return CEGUI::Key::N;
    case 'O'                : return CEGUI::Key::O;
    case 'P'                : return CEGUI::Key::P;
    case 'Q'                : return CEGUI::Key::Q;
    case 'R'                : return CEGUI::Key::R;
    case 'S'                : return CEGUI::Key::S;
    case 'T'                : return CEGUI::Key::T;
    case 'U'                : return CEGUI::Key::U;
    case 'V'                : return CEGUI::Key::V;
    case 'W'                : return CEGUI::Key::W;
    case 'X'                : return CEGUI::Key::X;
    case 'Y'                : return CEGUI::Key::Y;
    case 'Z'                : return CEGUI::Key::Z;
    default                 : return CEGUI::Key::Unknown;
    }
}

//----------------------------------------------------------------------------//
CEGUI::MouseButton CEGuiGLFWSharedBase::GlfwToCeguiMouseButton(int glfwButton)
{
    switch(glfwButton)
    {
    case GLFW_MOUSE_BUTTON_LEFT     : return CEGUI::LeftButton;
    case GLFW_MOUSE_BUTTON_RIGHT    : return CEGUI::RightButton;
    case GLFW_MOUSE_BUTTON_MIDDLE   : return CEGUI::MiddleButton;
    default                         : return CEGUI::NoButton;
    }
}

//----------------------------------------------------------------------------//
void GLFWCALL CEGuiGLFWSharedBase::glfwKeyCallback(int key, int action)
{
    CEGUI::Key::Scan ceguiKey = GlfwToCeguiKey(key);

    if(action == GLFW_PRESS)
        d_sampleApp->injectKeyDown(ceguiKey);
    else if (action == GLFW_RELEASE)
        d_sampleApp->injectKeyUp(ceguiKey);
}

//----------------------------------------------------------------------------//
void GLFWCALL CEGuiGLFWSharedBase::glfwCharCallback(int character, int action)
{
    if(action == GLFW_PRESS)
        d_sampleApp->injectChar(character);
}

//----------------------------------------------------------------------------//
void GLFWCALL CEGuiGLFWSharedBase::glfwMouseButtonCallback(int key, int action)
{
    CEGUI::MouseButton ceguiMouseButton = GlfwToCeguiMouseButton(key);

    if(action == GLFW_PRESS)
        d_sampleApp->injectMouseButtonDown(ceguiMouseButton);
    else if (action == GLFW_RELEASE)
        d_sampleApp->injectMouseButtonUp(ceguiMouseButton);
}

//----------------------------------------------------------------------------//
void GLFWCALL CEGuiGLFWSharedBase::glfwMouseWheelCallback(int position)
{
    static int lastPosition = 0;
    d_sampleApp->injectMouseWheelChange(static_cast<float>(position - lastPosition));
    lastPosition = position;
}

//----------------------------------------------------------------------------//
void GLFWCALL CEGuiGLFWSharedBase::glfwMousePosCallback(int x, int y)
{
    d_sampleApp->injectMousePosition(static_cast<float>(x), static_cast<float>(y));
}

//----------------------------------------------------------------------------//
void CEGuiGLFWSharedBase::initGLFW()
{
    if(!glfwInit())
        CEGUI_THROW(CEGUI::RendererException("Failed to initialise GLFW."));
}

//----------------------------------------------------------------------------//
void CEGuiGLFWSharedBase::createGLFWWindow()
{
    if (glfwOpenWindow(s_defaultWindowWidth, s_defaultWindowHeight, 8, 8, 8, 0, 24, 0, GLFW_WINDOW) != GL_TRUE)
    {
        CEGUI_THROW(CEGUI::RendererException("Failed to open GLFW window."));
        glfwTerminate();
    }
}

//----------------------------------------------------------------------------//
void CEGuiGLFWSharedBase::setGLFWAppConfiguration()
{
    glfwSetWindowTitle("Crazy Eddie's GUI Mk-2 - Sample Application");

    //Deactivate VSYNC
    glfwSwapInterval(0);

    // Disable the mouse position in Non_Debug mode
#ifndef DEBUG
    glfwDisable(GLFW_MOUSE_CURSOR);
#endif
    // Clear Errors by GLFW, even if Setup is correct.
    glGetError();
}

//----------------------------------------------------------------------------//

<|endoftext|>


<commit_before>/**
 * \file
 * \brief SignalsCatcherControlBlock class header
 *
 * \author Copyright (C) 2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
 *
 * \par License
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
 * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * \date 2015-04-10
 */

#ifndef INCLUDE_DISTORTOS_SYNCHRONIZATION_SIGNALSCATCHERCONTROLBLOCK_HPP_
#define INCLUDE_DISTORTOS_SYNCHRONIZATION_SIGNALSCATCHERCONTROLBLOCK_HPP_

namespace distortos
{

namespace synchronization
{

/// SignalsCatcherControlBlock class is a structure required by threads for "catching" and "handling" of signals
class SignalsCatcherControlBlock
{

};

}	// namespace synchronization

}	// namespace distortos

#endif	// INCLUDE_DISTORTOS_SYNCHRONIZATION_SIGNALSCATCHERCONTROLBLOCK_HPP_
<commit_msg>SignalsCatcherControlBlock: add constexpr constructor<commit_after>/**
 * \file
 * \brief SignalsCatcherControlBlock class header
 *
 * \author Copyright (C) 2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
 *
 * \par License
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
 * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * \date 2015-04-16
 */

#ifndef INCLUDE_DISTORTOS_SYNCHRONIZATION_SIGNALSCATCHERCONTROLBLOCK_HPP_
#define INCLUDE_DISTORTOS_SYNCHRONIZATION_SIGNALSCATCHERCONTROLBLOCK_HPP_

namespace distortos
{

namespace synchronization
{

/// SignalsCatcherControlBlock class is a structure required by threads for "catching" and "handling" of signals
class SignalsCatcherControlBlock
{
public:

	/**
	 * \brief SignalsCatcherControlBlock's constructor
	 */

	constexpr SignalsCatcherControlBlock()
	{

	}
};

}	// namespace synchronization

}	// namespace distortos

#endif	// INCLUDE_DISTORTOS_SYNCHRONIZATION_SIGNALSCATCHERCONTROLBLOCK_HPP_
<|endoftext|>


<commit_before>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.

#include <ctime>
#include <iostream>
#include <iterator>

#include <nix/util/util.hpp>
#include "BaseTestEntity.hpp"

#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/CompilerOutputter.h>
#include <cppunit/TestResult.h>
#include <cppunit/TestResultCollector.h>
#include <cppunit/TestRunner.h>
#include <cppunit/BriefTestProgressListener.h>

using namespace std;
using namespace nix;

void BaseTestEntity::testId() {
    CPPUNIT_ASSERT(block.id().size() == 36);
    CPPUNIT_ASSERT(util::toId(block).compare(block.id()) == 0);
}

void BaseTestEntity::testName() {
    CPPUNIT_ASSERT(block.name() == "block_one");
    CPPUNIT_ASSERT(util::toName(block).compare(block.name()) == 0);
}

void BaseTestEntity::testType() {
    CPPUNIT_ASSERT(block.type() == "dataset");
    string typ = util::createId();
    block.type(typ);
    CPPUNIT_ASSERT(block.type() == typ);
}

void BaseTestEntity::testDefinition() {
    string def = util::createId();
    block.definition(def);
    CPPUNIT_ASSERT(*block.definition() == def);
    block.definition(nix::none);
    CPPUNIT_ASSERT(block.definition() == nix::none);
}

void BaseTestEntity::testCreatedAt() {
    CPPUNIT_ASSERT(block.createdAt() >= startup_time);
    time_t past_time = time(NULL) - 10000000;
    block.forceCreatedAt(past_time);
    CPPUNIT_ASSERT(block.createdAt() == past_time);
}

void BaseTestEntity::testUpdatedAt() {
    CPPUNIT_ASSERT(block.updatedAt() >= startup_time);
}

void BaseTestEntity::testIsValidEntity() {
    CPPUNIT_ASSERT(block.isValidEntity());
    Source s  = block.createSource("test", "test");
    CPPUNIT_ASSERT(s.isValidEntity());
    block.deleteSource(s.name());
    CPPUNIT_ASSERT(!s.isValidEntity());
}

<commit_msg>[file_backend/TestEntity] enable file_backend tests for Entity<commit_after>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.

#include <ctime>
#include <iostream>
#include <iterator>

#include <nix/util/util.hpp>
#include "BaseTestEntity.hpp"

#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/CompilerOutputter.h>
#include <cppunit/TestResult.h>
#include <cppunit/TestResultCollector.h>
#include <cppunit/TestRunner.h>
#include <cppunit/BriefTestProgressListener.h>

using namespace std;
using namespace nix;

void BaseTestEntity::testId() {
    CPPUNIT_ASSERT(block.id().size() == 36);
    CPPUNIT_ASSERT(util::toId(block).compare(block.id()) == 0);
}

void BaseTestEntity::testName() {
    CPPUNIT_ASSERT(block.name() == "block_one");
    CPPUNIT_ASSERT(util::toName(block).compare(block.name()) == 0);
}

void BaseTestEntity::testType() {
    CPPUNIT_ASSERT(block.type() == "dataset");
    string typ = util::createId();
    block.type(typ);
    CPPUNIT_ASSERT(block.type() == typ);
}

void BaseTestEntity::testDefinition() {
    string def = util::createId();
    block.definition(def);
    CPPUNIT_ASSERT(*block.definition() == def);
    block.definition(nix::none);
    CPPUNIT_ASSERT(block.definition() == nix::none);
}

void BaseTestEntity::testCreatedAt() {
    CPPUNIT_ASSERT(block.createdAt() >= startup_time);
    time_t past_time = time(NULL) - 10000000;
    block.forceCreatedAt(past_time);
    CPPUNIT_ASSERT(block.createdAt() == past_time);
}

void BaseTestEntity::testUpdatedAt() {
    CPPUNIT_ASSERT(block.updatedAt() >= startup_time);
    CPPUNIT_ASSERT(block_fs.updatedAt() >= startup_time);
}

void BaseTestEntity::testIsValidEntity() {
    CPPUNIT_ASSERT(block.isValidEntity());
    Source s  = block.createSource("test", "test");
    CPPUNIT_ASSERT(s.isValidEntity());
    block.deleteSource(s.name());
    CPPUNIT_ASSERT(!s.isValidEntity());
}

void TestEntity::testOperators() {
    CPPUNIT_ASSERT(null == false);
    CPPUNIT_ASSERT(null == none);

    CPPUNIT_ASSERT(block != false);
    CPPUNIT_ASSERT(block != none);

    CPPUNIT_ASSERT(block == block);
    CPPUNIT_ASSERT(block != block_other);

    block_other = block;
    CPPUNIT_ASSERT(block_other == block);
}
<|endoftext|>


<commit_before>#include "ValueViewerTable.h"
#include "CCAPI/Common.h"
#include "CCAPI/Helpers.h"
#include <iostream>
#include <fstream>
#include <FL/fl_draw.H>
#include <FL/Fl_Widget.H>
#include "ui_main.h"

using namespace std;

#define ADDRESS_COL		0
#define VALUE_COL		1
#define HEX_COL			2

#define VALUE_COLS		3

ValueViewerTable::ValueViewerTable(int X, int Y, int W, int H, const char *l) : Fl_Table_Row(X,Y,W,H,l) {

	m_operator = 0;
	m_selectedType = SEARCH_VALUE_TYPE_1BYTE;
	rkWindow::addObject(this);

	rows(DEFAULT_ROWS);
	row_header(0);
	row_height_all(25);
	row_resize(0);

	cols(VALUE_COLS);
	col_header(1);
	col_width_all(110);
	col_width(VALUE_COL, 250);
	col_resize(1);

	viewer = 0;
	m_codeTable = 0;
	m_startAddress = m_focusAddress = 0;
	m_signed = false;

	type(SELECT_MULTI);
	end();
	callback(tableClickedCB);

	Fl::add_timeout(0.5, redraw, this);
}

void ValueViewerTable::redraw(void *v)
{
	ValueViewerTable *t = (ValueViewerTable *)v;
	t->damage(FL_DAMAGE_ALL);
	Fl::repeat_timeout(1.0, ValueViewerTable::redraw, v);
}

void ValueViewerTable::addSelectedAddresses()
{
	if (m_codeTable == 0 || !hasSelection())
		return;
	for (int i=0; i<rows(); ++i)
	{
		if (i > DEFAULT_ROWS)
			break;
		if (row_selected(i))
			m_codeTable->addEntry("Value Viewer Entry", m_startAddress+i, 0, m_selectedType);
	}
}

bool ValueViewerTable::hasSelection()
{
	int t,b,l,r;
	get_selection(t,l,b,r);
	return (t > -1 && b > -1);
}

void ValueViewerTable::draw_cell(TableContext context, int ROW, int COL, int X, int Y, int W, int H){
    static char s[40];
	int x,y,w,h;
    switch ( context ) {
      case CONTEXT_STARTPAGE:                   // before page is drawn..
        fl_font(FL_HELVETICA, 14);              // set the font for our drawing operations
        return;
	case CONTEXT_RC_RESIZE:
	{
	    int X, Y, W, H;
	    int index = 0;
	    for ( int r = 0; r<rows(); r++ )
	    {
			for ( int c = 0; c<cols(); c++ )
			{
				if ( index >= children() ) break;
				find_cell(CONTEXT_TABLE, r, c, X, Y, W, H);
				child(index)->resize(X,Y,W,H);
				index++;
			}
	    }
	    init_sizes();			// tell group children resized
	    return;
	}

      case CONTEXT_COL_HEADER:                  // Draw column headers
		switch (COL)
		{
		case ADDRESS_COL:	DrawHeader("Address",X,Y,W,H); break;
		case VALUE_COL:		DrawHeader("Value",X,Y,W,H); break;
		case HEX_COL:		DrawHeader("Hex",X,Y,W,H); break;
		default: break;
		}
        return;
      case CONTEXT_ROW_HEADER:                  // Draw row headers
		fl_font(FL_HELVETICA, 14);              // set the font for our drawing operations
        sprintf(s,"%03d:",COL);                 // "001:", "002:", etc
        DrawHeader(s,X,Y,W,H);
        return;
      case CONTEXT_CELL:    // Draw data in cells
		if (ROW > DEFAULT_ROWS)
			break;
		fl_font(FL_HELVETICA, 14);              // set the font for our drawing operations
	    fl_push_clip(X, Y, W, H);
	    {
	        // BG COLOR
		if (ROW == (m_focusAddress - m_startAddress) )
			fl_color( row_selected(ROW) ? selection_color() : FL_GREEN);
		else
			fl_color( row_selected(ROW) ? selection_color() : FL_WHITE);
		fl_rectf(X, Y, W, H);

		// TEXT
		fl_color(FL_BLACK);
		if ((unsigned int)ROW < DEFAULT_ROWS)
		{
			unsigned long tmpLong = BSWAP32(*(unsigned long*)(&m_memory[ROW]));
			unsigned short tmpShort = BSWAP16(*(unsigned short*)(&m_memory[ROW]));
			switch(COL)
			{
			case ADDRESS_COL: sprintf(s,"0x%08X",m_startAddress+ROW); break;
			case VALUE_COL:
				switch (m_selectedType)
				{
				case SEARCH_VALUE_TYPE_FLOAT:
					sprintf(s,"%f", *(float*)(&tmpLong) ); break;
				case SEARCH_VALUE_TYPE_1BYTE:
					if (m_signed)
						sprintf(s,"%hd", (char)m_memory[ROW]);
					else
						sprintf(s,"%hu", (unsigned char)m_memory[ROW]);
					break;
				case SEARCH_VALUE_TYPE_2BYTE:
					if (m_signed)
						 sprintf(s,"%hd", (short) tmpShort);
					 else
						 sprintf(s,"%hu", (unsigned short) tmpShort);
					 break;
				default:
					if (m_signed)
						sprintf(s,"%d", (long) tmpLong);
					else
						sprintf(s,"%u", (unsigned long) tmpLong);
					break;
				} break;
			case HEX_COL:
				switch (m_selectedType)
				{
				case SEARCH_VALUE_TYPE_FLOAT:
					sprintf(s,"%X", tmpLong); break;
				case SEARCH_VALUE_TYPE_1BYTE:
						 sprintf(s,"%X", m_memory[ROW]);
						 break;
				case SEARCH_VALUE_TYPE_2BYTE:
						 sprintf(s,"%X", tmpShort);
						 break;
				default:
						 sprintf(s,"%X", tmpLong);
						 break;
				} break;
			default: break;
			}
			DrawData(s,X,Y,W,H);
		}
		// BORDER
		fl_color(FL_LIGHT2);
		fl_rect(X, Y, W, H);
	    }
	    fl_pop_clip();
        return;
      default:
        return;
    }
}

int ValueViewerTable::handle(int evt)
{
	int res = 0;
	when(FL_WHEN_NEVER);
	res = Fl_Table_Row::handle(evt);
	return res;
}
void ValueViewerTable::DrawData(const char *s, int X, int Y, int W, int H) {
fl_push_clip(X,Y,W,H);
    // Draw cell bg
    //fl_color(FL_WHITE); fl_rectf(X,Y,W,H);
    // Draw cell data
    fl_color(FL_GRAY0); fl_draw(s, X,Y,W,H, FL_ALIGN_CENTER);
    // Draw box border
    fl_color(color()); fl_rect(X,Y,W,H);
fl_pop_clip();
}

void ValueViewerTable::DrawHeader(const char *s, int X, int Y, int W, int H) {
fl_push_clip(X,Y,W,H);
    fl_draw_box(FL_THIN_UP_BOX, X,Y,W,H, row_header_color());
    fl_color(FL_BLACK);
    fl_draw(s, X,Y,W,H, FL_ALIGN_CENTER);
fl_pop_clip();
}

void ValueViewerTable::onCellDoubleClicked(int row, int col)
{
#if 0
	long long int_val;
	if (data[row].sign)
		int_val = (signed long)data[row]->value;
	else
		int_val = (unsigned long) data[row]->value;
	unsigned long address = data[row]->address;
	char hex[50];
	float float_val = *(float*)&data[row]->value;
	switch (col)
	{
	case DESC_COL:
		current_cell_widget = data[row]->widget->description;
		if (current_cell_widget != last_cell_widget) //click on a new widget
		{
			if (last_cell_widget) last_cell_widget->hide();
			data[row]->widget->description->show();
			data[row]->widget->description->value(data[row]->description.c_str());
			data[row]->widget->description->take_focus();
		}
		last_cell_widget = current_cell_widget;
		break;
	case ADDRESS_COL: //address
		current_cell_widget = data[row]->widget->address_input;
		if (current_cell_widget != last_cell_widget) //click on a new widget
		{
			if (last_cell_widget) last_cell_widget->hide();
			data[row]->widget->address_input->show();
			sprintf(hex, "%.8X", address);
			data[row]->widget->address_input->value(hex);
			data[row]->widget->address_input->take_focus();
		}
		last_cell_widget = current_cell_widget;
		break;
	case VALUE_COL: //input
		current_cell_widget = data[row]->widget->value_input;
		if (current_cell_widget != last_cell_widget) //click on a new widget
		{
			if (last_cell_widget) last_cell_widget->hide();
			data[row]->widget->value_input->show();
			data[row]->widget->value_input->take_focus();
			if (data[row]->type == SEARCH_VALUE_TYPE_FLOAT)
				data[row]->widget->value_input->value(to_string(float_val).c_str());
			else
			{
				switch (data[row]->type)
				{
				case SEARCH_VALUE_TYPE_1BYTE:
					data[row]->widget->value_input->value(data[row]->sign ? to_string((char)int_val).c_str() : to_string((unsigned char)int_val).c_str());
					break;
				case SEARCH_VALUE_TYPE_2BYTE:
					data[row]->widget->value_input->value(data[row]->sign ? to_string((short)int_val).c_str() : to_string((unsigned short)int_val).c_str());
					break;
				default:
					data[row]->widget->value_input->value(data[row]->sign ? to_string((long)int_val).c_str() : to_string((unsigned long)int_val).c_str());
					break;
				}
			}
		}
		last_cell_widget = current_cell_widget;
		break;
	case TYPE_COL: //type
		current_cell_widget = data[row]->widget->type;
		if (current_cell_widget != last_cell_widget) //click on a new widget
		{
			if (last_cell_widget) last_cell_widget->hide();
			data[row]->widget->type->show();
			data[row]->widget->type->take_focus();
		}
		last_cell_widget = current_cell_widget;
		break;
	case FREEZE_COL: //freeze
		current_cell_widget = data[row]->widget->freeze;
		if (current_cell_widget != last_cell_widget) //click on a new widget
		{
			if (last_cell_widget) last_cell_widget->hide();
			data[row]->widget->freeze->take_focus();
		}
		last_cell_widget = 0;
		break;
	}
#endif
}

void ValueViewerTable::onCellRightClicked(int row, int col)
{
#if 0
	const Fl_Menu_Item *m = 0;
	if (col == ADDRESS_COL)
	{
		Fl_Menu_Item rclick_menu[] = {
			{ "View Nearby...",   0, viewer,  (void*)this },
            { 0 }
            };
            m = rclick_menu->popup(Fl::event_x(), Fl::event_y(), 0, 0, 0);
			//if ( m ) m->do_callback(0, m->user_data());
            if ( m ) m->do_callback(0, data[row].get());
	}
#endif
}

void ValueViewerTable::onTableClicked()
{
}

void ValueViewerTable::doDeactivate()
{
	 //if (!Fl::event_inside(this->parent()))
//		select_all_rows(0);
}

void ValueViewerTable::setMemoryOperator(MemoryOperator *op)
{
	m_operator = op;
}

void ValueViewerTable::startMemoryRead()
{
	if (m_operator == 0)
		return;
	m_startAddress = 0;
	if ((long long)m_focusAddress - (DEFAULT_ROWS/2) < 0)
		m_startAddress = 0;
	else if ((long long)m_focusAddress + (DEFAULT_ROWS/2) > 0xFFFFFFFF)
		m_startAddress = 0xFFFFFFFF - (DEFAULT_ROWS/2);
	else
		m_startAddress = m_focusAddress - (DEFAULT_ROWS/2);
	m_operator->setChunkReadMemoryOperation(m_startAddress, DEFAULT_ROWS+3, m_memory, true);
	row_position(m_focusAddress - m_startAddress);
}

void ValueViewerTable::stopMemoryRead()
{
	if (m_operator == 0)
		return;
	m_operator->removeMemoryOperation(MEMORY_COMMAND_READCHUNK, m_startAddress);
}
<commit_msg>fixed issue with 1 byte hex values.<commit_after>#include "ValueViewerTable.h"
#include "CCAPI/Common.h"
#include "CCAPI/Helpers.h"
#include <iostream>
#include <fstream>
#include <FL/fl_draw.H>
#include <FL/Fl_Widget.H>
#include "ui_main.h"

using namespace std;

#define ADDRESS_COL		0
#define VALUE_COL		1
#define HEX_COL			2

#define VALUE_COLS		3

ValueViewerTable::ValueViewerTable(int X, int Y, int W, int H, const char *l) : Fl_Table_Row(X,Y,W,H,l) {

	m_operator = 0;
	m_selectedType = SEARCH_VALUE_TYPE_1BYTE;
	rkWindow::addObject(this);

	rows(DEFAULT_ROWS);
	row_header(0);
	row_height_all(25);
	row_resize(0);

	cols(VALUE_COLS);
	col_header(1);
	col_width_all(110);
	col_width(VALUE_COL, 250);
	col_resize(1);

	viewer = 0;
	m_codeTable = 0;
	m_startAddress = m_focusAddress = 0;
	m_signed = false;

	type(SELECT_MULTI);
	end();
	callback(tableClickedCB);

	Fl::add_timeout(0.5, redraw, this);
}

void ValueViewerTable::redraw(void *v)
{
	ValueViewerTable *t = (ValueViewerTable *)v;
	t->damage(FL_DAMAGE_ALL);
	Fl::repeat_timeout(1.0, ValueViewerTable::redraw, v);
}

void ValueViewerTable::addSelectedAddresses()
{
	if (m_codeTable == 0 || !hasSelection())
		return;
	for (int i=0; i<rows(); ++i)
	{
		if (i > DEFAULT_ROWS)
			break;
		if (row_selected(i))
			m_codeTable->addEntry("Value Viewer Entry", m_startAddress+i, 0, m_selectedType);
	}
}

bool ValueViewerTable::hasSelection()
{
	int t,b,l,r;
	get_selection(t,l,b,r);
	return (t > -1 && b > -1);
}

void ValueViewerTable::draw_cell(TableContext context, int ROW, int COL, int X, int Y, int W, int H){
    static char s[40];
	int x,y,w,h;
    switch ( context ) {
      case CONTEXT_STARTPAGE:                   // before page is drawn..
        fl_font(FL_HELVETICA, 14);              // set the font for our drawing operations
        return;
	case CONTEXT_RC_RESIZE:
	{
	    int X, Y, W, H;
	    int index = 0;
	    for ( int r = 0; r<rows(); r++ )
	    {
			for ( int c = 0; c<cols(); c++ )
			{
				if ( index >= children() ) break;
				find_cell(CONTEXT_TABLE, r, c, X, Y, W, H);
				child(index)->resize(X,Y,W,H);
				index++;
			}
	    }
	    init_sizes();			// tell group children resized
	    return;
	}

      case CONTEXT_COL_HEADER:                  // Draw column headers
		switch (COL)
		{
		case ADDRESS_COL:	DrawHeader("Address",X,Y,W,H); break;
		case VALUE_COL:		DrawHeader("Value",X,Y,W,H); break;
		case HEX_COL:		DrawHeader("Hex",X,Y,W,H); break;
		default: break;
		}
        return;
      case CONTEXT_ROW_HEADER:                  // Draw row headers
		fl_font(FL_HELVETICA, 14);              // set the font for our drawing operations
        sprintf(s,"%03d:",COL);                 // "001:", "002:", etc
        DrawHeader(s,X,Y,W,H);
        return;
      case CONTEXT_CELL:    // Draw data in cells
		if (ROW > DEFAULT_ROWS)
			break;
		fl_font(FL_HELVETICA, 14);              // set the font for our drawing operations
	    fl_push_clip(X, Y, W, H);
	    {
	        // BG COLOR
		if (ROW == (m_focusAddress - m_startAddress) )
			fl_color( row_selected(ROW) ? selection_color() : FL_GREEN);
		else
			fl_color( row_selected(ROW) ? selection_color() : FL_WHITE);
		fl_rectf(X, Y, W, H);

		// TEXT
		fl_color(FL_BLACK);
		if ((unsigned int)ROW < DEFAULT_ROWS)
		{
			unsigned long tmpLong = BSWAP32(*(unsigned long*)(&m_memory[ROW]));
			unsigned short tmpShort = BSWAP16(*(unsigned short*)(&m_memory[ROW]));
			switch(COL)
			{
			case ADDRESS_COL: sprintf(s,"0x%08X",m_startAddress+ROW); break;
			case VALUE_COL:
				switch (m_selectedType)
				{
				case SEARCH_VALUE_TYPE_FLOAT:
					sprintf(s,"%f", *(float*)(&tmpLong) ); break;
				case SEARCH_VALUE_TYPE_1BYTE:
					if (m_signed)
						sprintf(s,"%hd", (char)m_memory[ROW]);
					else
						sprintf(s,"%hu", (unsigned char)m_memory[ROW]);
					break;
				case SEARCH_VALUE_TYPE_2BYTE:
					if (m_signed)
						 sprintf(s,"%hd", (short) tmpShort);
					 else
						 sprintf(s,"%hu", (unsigned short) tmpShort);
					 break;
				default:
					if (m_signed)
						sprintf(s,"%d", (long) tmpLong);
					else
						sprintf(s,"%u", (unsigned long) tmpLong);
					break;
				} break;
			case HEX_COL:
				switch (m_selectedType)
				{
				case SEARCH_VALUE_TYPE_FLOAT:
					sprintf(s,"%X", tmpLong); break;
				case SEARCH_VALUE_TYPE_1BYTE:
						 sprintf(s,"%X", (unsigned char)m_memory[ROW]);
						 break;
				case SEARCH_VALUE_TYPE_2BYTE:
						 sprintf(s,"%X", tmpShort);
						 break;
				default:
						 sprintf(s,"%X", tmpLong);
						 break;
				} break;
			default: break;
			}
			DrawData(s,X,Y,W,H);
		}
		// BORDER
		fl_color(FL_LIGHT2);
		fl_rect(X, Y, W, H);
	    }
	    fl_pop_clip();
        return;
      default:
        return;
    }
}

int ValueViewerTable::handle(int evt)
{
	int res = 0;
	when(FL_WHEN_NEVER);
	res = Fl_Table_Row::handle(evt);
	return res;
}
void ValueViewerTable::DrawData(const char *s, int X, int Y, int W, int H) {
fl_push_clip(X,Y,W,H);
    // Draw cell bg
    //fl_color(FL_WHITE); fl_rectf(X,Y,W,H);
    // Draw cell data
    fl_color(FL_GRAY0); fl_draw(s, X,Y,W,H, FL_ALIGN_CENTER);
    // Draw box border
    fl_color(color()); fl_rect(X,Y,W,H);
fl_pop_clip();
}

void ValueViewerTable::DrawHeader(const char *s, int X, int Y, int W, int H) {
fl_push_clip(X,Y,W,H);
    fl_draw_box(FL_THIN_UP_BOX, X,Y,W,H, row_header_color());
    fl_color(FL_BLACK);
    fl_draw(s, X,Y,W,H, FL_ALIGN_CENTER);
fl_pop_clip();
}

void ValueViewerTable::onCellDoubleClicked(int row, int col)
{
#if 0
	long long int_val;
	if (data[row].sign)
		int_val = (signed long)data[row]->value;
	else
		int_val = (unsigned long) data[row]->value;
	unsigned long address = data[row]->address;
	char hex[50];
	float float_val = *(float*)&data[row]->value;
	switch (col)
	{
	case DESC_COL:
		current_cell_widget = data[row]->widget->description;
		if (current_cell_widget != last_cell_widget) //click on a new widget
		{
			if (last_cell_widget) last_cell_widget->hide();
			data[row]->widget->description->show();
			data[row]->widget->description->value(data[row]->description.c_str());
			data[row]->widget->description->take_focus();
		}
		last_cell_widget = current_cell_widget;
		break;
	case ADDRESS_COL: //address
		current_cell_widget = data[row]->widget->address_input;
		if (current_cell_widget != last_cell_widget) //click on a new widget
		{
			if (last_cell_widget) last_cell_widget->hide();
			data[row]->widget->address_input->show();
			sprintf(hex, "%.8X", address);
			data[row]->widget->address_input->value(hex);
			data[row]->widget->address_input->take_focus();
		}
		last_cell_widget = current_cell_widget;
		break;
	case VALUE_COL: //input
		current_cell_widget = data[row]->widget->value_input;
		if (current_cell_widget != last_cell_widget) //click on a new widget
		{
			if (last_cell_widget) last_cell_widget->hide();
			data[row]->widget->value_input->show();
			data[row]->widget->value_input->take_focus();
			if (data[row]->type == SEARCH_VALUE_TYPE_FLOAT)
				data[row]->widget->value_input->value(to_string(float_val).c_str());
			else
			{
				switch (data[row]->type)
				{
				case SEARCH_VALUE_TYPE_1BYTE:
					data[row]->widget->value_input->value(data[row]->sign ? to_string((char)int_val).c_str() : to_string((unsigned char)int_val).c_str());
					break;
				case SEARCH_VALUE_TYPE_2BYTE:
					data[row]->widget->value_input->value(data[row]->sign ? to_string((short)int_val).c_str() : to_string((unsigned short)int_val).c_str());
					break;
				default:
					data[row]->widget->value_input->value(data[row]->sign ? to_string((long)int_val).c_str() : to_string((unsigned long)int_val).c_str());
					break;
				}
			}
		}
		last_cell_widget = current_cell_widget;
		break;
	case TYPE_COL: //type
		current_cell_widget = data[row]->widget->type;
		if (current_cell_widget != last_cell_widget) //click on a new widget
		{
			if (last_cell_widget) last_cell_widget->hide();
			data[row]->widget->type->show();
			data[row]->widget->type->take_focus();
		}
		last_cell_widget = current_cell_widget;
		break;
	case FREEZE_COL: //freeze
		current_cell_widget = data[row]->widget->freeze;
		if (current_cell_widget != last_cell_widget) //click on a new widget
		{
			if (last_cell_widget) last_cell_widget->hide();
			data[row]->widget->freeze->take_focus();
		}
		last_cell_widget = 0;
		break;
	}
#endif
}

void ValueViewerTable::onCellRightClicked(int row, int col)
{
#if 0
	const Fl_Menu_Item *m = 0;
	if (col == ADDRESS_COL)
	{
		Fl_Menu_Item rclick_menu[] = {
			{ "View Nearby...",   0, viewer,  (void*)this },
            { 0 }
            };
            m = rclick_menu->popup(Fl::event_x(), Fl::event_y(), 0, 0, 0);
			//if ( m ) m->do_callback(0, m->user_data());
            if ( m ) m->do_callback(0, data[row].get());
	}
#endif
}

void ValueViewerTable::onTableClicked()
{
}

void ValueViewerTable::doDeactivate()
{
	 //if (!Fl::event_inside(this->parent()))
//		select_all_rows(0);
}

void ValueViewerTable::setMemoryOperator(MemoryOperator *op)
{
	m_operator = op;
}

void ValueViewerTable::startMemoryRead()
{
	if (m_operator == 0)
		return;
	m_startAddress = 0;
	if ((long long)m_focusAddress - (DEFAULT_ROWS/2) < 0)
		m_startAddress = 0;
	else if ((long long)m_focusAddress + (DEFAULT_ROWS/2) > 0xFFFFFFFF)
		m_startAddress = 0xFFFFFFFF - (DEFAULT_ROWS/2);
	else
		m_startAddress = m_focusAddress - (DEFAULT_ROWS/2);
	m_operator->setChunkReadMemoryOperation(m_startAddress, DEFAULT_ROWS+3, m_memory, true);
	row_position(m_focusAddress - m_startAddress);
}

void ValueViewerTable::stopMemoryRead()
{
	if (m_operator == 0)
		return;
	m_operator->removeMemoryOperation(MEMORY_COMMAND_READCHUNK, m_startAddress);
}
<|endoftext|>


<commit_before>/***********************************************************************************************************************
 **
 ** Copyright (c) 2011, 2016 ETH Zurich
 ** All rights reserved.
 **
 ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
 ** following conditions are met:
 **
 **    * Redistributions of source code must retain the above copyright notice, this list of conditions and the
 **      following disclaimer.
 **    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
 **      following disclaimer in the documentation and/or other materials provided with the distribution.
 **    * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products
 **      derived from this software without specific prior written permission.
 **
 **
 ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 **
 **********************************************************************************************************************/

#include "SpecialCases.h"

#include "ExportHelpers.h"
#include "CodeComposite.h"
#include "visitors/CppPrintContext.h"
#include "visitors/DeclarationVisitor.h"
#include "visitors/ExpressionVisitor.h"
#include "visitors/ElementVisitor.h"
#include "visitors/StatementVisitor.h"

#include "Export/src/tree/CompositeFragment.h"
#include "OOModel/src/declarations/Class.h"
#include "OOModel/src/declarations/TypeAlias.h"
#include "OOModel/src/declarations/Method.h"
#include "OOModel/src/declarations/MetaDefinition.h"
#include "OOModel/src/expressions/MetaCallExpression.h"
#include "OOModel/src/expressions/BooleanLiteral.h"
#include "OOModel/src/expressions/ReferenceExpression.h"

namespace CppExport {

void SpecialCases::handleQT_Flags(OOModel::Class* classs, Export::CompositeFragment* fragment)
{
	auto specialCaseFragment = fragment->append(new Export::CompositeFragment{classs});
	for (auto subDeclaration : *classs->subDeclarations())
		if (auto typeAlias = DCast<OOModel::TypeAlias>(subDeclaration))
			if (auto reference = DCast<OOModel::ReferenceExpression>(typeAlias->typeExpression()))
				if (reference->name() == "QFlags")
					*specialCaseFragment << "Q_DECLARE_OPERATORS_FOR_FLAGS(" << classs->name() << "::"
												<< typeAlias->name() << ")";
}

bool SpecialCases::isTestClass(OOModel::Class* classs)
{
	if (!classs) return false;
	return classs->methods()->size() == 1 &&
			(classs->methods()->first()->name() == "test" || classs->methods()->first()->name() == "init");
}

void SpecialCases::overrideFlag(OOModel::Method* method, Export::CompositeFragment* fragment)
{
	for (auto expression : *method->metaCalls())
		if (auto metaCall = DCast<OOModel::MetaCallExpression>(expression))
			if (auto reference = DCast<OOModel::ReferenceExpression>(metaCall->callee()))
				if (reference->name() == "SET_OVERRIDE_FLAG")
				{
					*fragment << " OVERRIDE";
					return;
				}
}

Export::CompositeFragment* SpecialCases::overrideFlagArgumentTransformation(OOModel::MetaCallExpression* metaCall)
{
	Export::CompositeFragment* fragment{};
	if (auto metaDefinition = metaCall->metaDefinition())
		if (metaDefinition->arguments()->size() == 1 && metaCall->arguments()->size() == 1)
			if (metaDefinition->arguments()->first()->name() == "OVERRIDE")
					if (auto booleanLiteral = DCast<OOModel::BooleanLiteral>(metaCall->arguments()->first()))
					{
						fragment = new Export::CompositeFragment{metaCall->arguments(), "argsList"};
						*fragment << (booleanLiteral->value() ? "override" : "");
					}
	return fragment;
}

bool SpecialCases::hasTemplatePrefixArgument(OOModel::MetaDefinition* metaDefinition)
{
	for (auto argument : *metaDefinition->arguments())
		if (argument->name() == "templatePrefix")
			return true;
	return false;
}

bool SpecialCases::isMainMethod(OOModel::Method* method)
{
	return method && method->symbolName() == "main";
}

bool SpecialCases::isTemplateArgumentNameOnlyDependency(OOModel::ReferenceExpression* parentReference,
																		  OOModel::ReferenceExpression*)
{
	return parentReference->name() == "unique_ptr" || parentReference->name() == "shared_ptr";
}

Export::SourceFragment* SpecialCases::printXMacroDataBlock(OOModel::MetaCallExpression* metaCall)
{
	auto reference = DCast<OOModel::ReferenceExpression>(metaCall->callee());
	Q_ASSERT(reference->name().startsWith("BEGIN_"));

	auto fragment = new Export::CompositeFragment{metaCall, "sections"};
	auto beginCallFragment = fragment->append(new Export::CompositeFragment{metaCall});
	*beginCallFragment << reference->name();
	auto argumentsFragment =
			beginCallFragment->append(new Export::CompositeFragment{metaCall->arguments(), "argsList"});

	CppPrintContext printContext{nullptr};
	for (auto i = 0; i < metaCall->arguments()->size() - 1; i++)
		if (auto expression = DCast<OOModel::Expression>(metaCall->arguments()->at(i)))
			*argumentsFragment << ExpressionVisitor{printContext}.visit(expression);
		else
			Q_ASSERT(false);

	Q_ASSERT(metaCall->arguments()->size() > 0);
	auto childMetaCallsList = DCast<Model::List>(metaCall->arguments()->last());
	auto childMetaCallsFragment = fragment->append(new Export::CompositeFragment{childMetaCallsList, "bodyNoBraces"});
	Q_ASSERT(childMetaCallsList);
	for (auto childMetaCallCandidate : *childMetaCallsList)
	{
		auto childMetaCall = DCast<OOModel::MetaCallExpression>(childMetaCallCandidate);
		Q_ASSERT(childMetaCall);
		*childMetaCallsFragment << ExpressionVisitor{printContext}.visit(childMetaCall);
	}

	*fragment << "END_STANDARD_EXPRESSION_VISUALIZATION";

	return fragment;
}

Export::CompositeFragment* SpecialCases::printPartialBeginMacroSpecialization(OOModel::MetaDefinition* metaDefinition,
																										bool isHeaderFile)
{
	Q_ASSERT(metaDefinition->name().startsWith("BEGIN_") && metaDefinition->metaBindings()->isEmpty());

	auto macro = new Export::CompositeFragment{metaDefinition, "macro"};
	auto fragment = macro->append(new Export::CompositeFragment{metaDefinition, "sections"});
	auto metaDefinitionFragment = fragment->append(new Export::CompositeFragment{metaDefinition});
	*metaDefinitionFragment << "#define " << metaDefinition->name();
	auto argumentsFragment = metaDefinitionFragment->append(new Export::CompositeFragment{metaDefinition->arguments(),
																													  "argsList"});
	CppPrintContext printContext{nullptr};
	for (auto i = 0; i < metaDefinition->arguments()->size() - 1; i++)
		*argumentsFragment << ElementVisitor{printContext}.visit(metaDefinition->arguments()->at(i));

	if (auto metaCall = DCast<OOModel::MetaCallExpression>(metaDefinition->context()->metaCalls()->first()))
	{
		auto metaCallFragment = fragment->append(new Export::CompositeFragment{metaCall});
		*metaCallFragment << ExpressionVisitor{printContext}.visit(metaCall->callee());
		auto argumentsFragment =
				metaCallFragment->append(new Export::CompositeFragment{metaCall->arguments(), "argsList"});
		for (auto i = 0; i < metaCall->arguments()->size() - (isHeaderFile ? 2 : 3); i++)
			if (auto argument = DCast<OOModel::Expression>(metaCall->arguments()->at(i)))
				*argumentsFragment << ExpressionVisitor{printContext}.visit(argument);

		if (!isHeaderFile)
		{
			Q_ASSERT(metaCall->arguments()->size() > 0);
			auto statementList = DCast<Model::List>(metaCall->arguments()->at(metaCall->arguments()->size() - 2));
			Q_ASSERT(statementList);
			auto statementListFragment = fragment->append(new Export::CompositeFragment{statementList, "bodyNoBraces"});
			for (auto statementCandidate : *statementList)
				if (auto statement = DCast<OOModel::StatementItem>(statementCandidate))
					*statementListFragment << StatementVisitor{printContext}.visit(statement);
				else
					Q_ASSERT(false);
		}
	}
	else
		Q_ASSERT(false);

	return macro;
}

Export::CompositeFragment* SpecialCases::printPartialBeginMacroBase(OOModel::MetaDefinition* metaDefinition,
																						  bool isHeaderFile)
{
	Q_ASSERT(metaDefinition->name().startsWith("BEGIN_") && !metaDefinition->metaBindings()->isEmpty());

	auto fragment = new Export::CompositeFragment{metaDefinition, "macro"};
	auto context = DCast<OOModel::Module>(metaDefinition->context());
	auto classs = context->classes()->first();
	CppPrintContext printContext{isHeaderFile ? classs : nullptr, isHeaderFile ? CppPrintContext::IsHeaderPart :
																										  CppPrintContext::None
																					  | CppPrintContext::XMacro};
	auto metaDefinitionFragment = fragment->append(new Export::CompositeFragment{metaDefinition});
	*metaDefinitionFragment << "#define " << metaDefinition->name();
	auto argumentsFragment = metaDefinitionFragment->append(new Export::CompositeFragment{metaDefinition->arguments(),
																													  "argsList"});
	for (auto i = 0; i < metaDefinition->arguments()->size() - (isHeaderFile ? 2 : 3); i++)
		*argumentsFragment << ElementVisitor{printContext}.visit(metaDefinition->arguments()->at(i));
	*metaDefinitionFragment << "\n";
	*fragment << DeclarationVisitor{printContext}.visit(classs);

	return fragment;
}

Export::SourceFragment* SpecialCases::includeXMacroData(CodeComposite* codeComposite,
																					Export::SourceFragment* baseFragment,
																					bool isSourceFile)
{
	auto fragment = new Export::CompositeFragment{baseFragment->node(), "sections"};
	*fragment << baseFragment
				 << "\n"
				 << "namespace OOVisualization {"
				 << "#include \"" + XMACRO_DATA_FILENAME + ".h\""
				 << "}";
	for (auto unit : codeComposite->units())
		if (auto metaDefinition = DCast<OOModel::MetaDefinition>(unit->node()))
			if (metaDefinition->name().startsWith("BEGIN_") || (metaDefinition->name().endsWith("_CPP") == isSourceFile))
				*fragment << "#undef " + ExportHelpers::strip_CPPFromName(metaDefinition);
	return fragment;
}

}
<commit_msg>use additional formatting fragments to avoid manual newline printing<commit_after>/***********************************************************************************************************************
 **
 ** Copyright (c) 2011, 2016 ETH Zurich
 ** All rights reserved.
 **
 ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
 ** following conditions are met:
 **
 **    * Redistributions of source code must retain the above copyright notice, this list of conditions and the
 **      following disclaimer.
 **    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
 **      following disclaimer in the documentation and/or other materials provided with the distribution.
 **    * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products
 **      derived from this software without specific prior written permission.
 **
 **
 ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 **
 **********************************************************************************************************************/

#include "SpecialCases.h"

#include "ExportHelpers.h"
#include "CodeComposite.h"
#include "visitors/CppPrintContext.h"
#include "visitors/DeclarationVisitor.h"
#include "visitors/ExpressionVisitor.h"
#include "visitors/ElementVisitor.h"
#include "visitors/StatementVisitor.h"

#include "Export/src/tree/CompositeFragment.h"
#include "OOModel/src/declarations/Class.h"
#include "OOModel/src/declarations/TypeAlias.h"
#include "OOModel/src/declarations/Method.h"
#include "OOModel/src/declarations/MetaDefinition.h"
#include "OOModel/src/expressions/MetaCallExpression.h"
#include "OOModel/src/expressions/BooleanLiteral.h"
#include "OOModel/src/expressions/ReferenceExpression.h"

namespace CppExport {

void SpecialCases::handleQT_Flags(OOModel::Class* classs, Export::CompositeFragment* fragment)
{
	auto specialCaseFragment = fragment->append(new Export::CompositeFragment{classs});
	for (auto subDeclaration : *classs->subDeclarations())
		if (auto typeAlias = DCast<OOModel::TypeAlias>(subDeclaration))
			if (auto reference = DCast<OOModel::ReferenceExpression>(typeAlias->typeExpression()))
				if (reference->name() == "QFlags")
					*specialCaseFragment << "Q_DECLARE_OPERATORS_FOR_FLAGS(" << classs->name() << "::"
												<< typeAlias->name() << ")";
}

bool SpecialCases::isTestClass(OOModel::Class* classs)
{
	if (!classs) return false;
	return classs->methods()->size() == 1 &&
			(classs->methods()->first()->name() == "test" || classs->methods()->first()->name() == "init");
}

void SpecialCases::overrideFlag(OOModel::Method* method, Export::CompositeFragment* fragment)
{
	for (auto expression : *method->metaCalls())
		if (auto metaCall = DCast<OOModel::MetaCallExpression>(expression))
			if (auto reference = DCast<OOModel::ReferenceExpression>(metaCall->callee()))
				if (reference->name() == "SET_OVERRIDE_FLAG")
				{
					*fragment << " OVERRIDE";
					return;
				}
}

Export::CompositeFragment* SpecialCases::overrideFlagArgumentTransformation(OOModel::MetaCallExpression* metaCall)
{
	Export::CompositeFragment* fragment{};
	if (auto metaDefinition = metaCall->metaDefinition())
		if (metaDefinition->arguments()->size() == 1 && metaCall->arguments()->size() == 1)
			if (metaDefinition->arguments()->first()->name() == "OVERRIDE")
					if (auto booleanLiteral = DCast<OOModel::BooleanLiteral>(metaCall->arguments()->first()))
					{
						fragment = new Export::CompositeFragment{metaCall->arguments(), "argsList"};
						*fragment << (booleanLiteral->value() ? "override" : "");
					}
	return fragment;
}

bool SpecialCases::hasTemplatePrefixArgument(OOModel::MetaDefinition* metaDefinition)
{
	for (auto argument : *metaDefinition->arguments())
		if (argument->name() == "templatePrefix")
			return true;
	return false;
}

bool SpecialCases::isMainMethod(OOModel::Method* method)
{
	return method && method->symbolName() == "main";
}

bool SpecialCases::isTemplateArgumentNameOnlyDependency(OOModel::ReferenceExpression* parentReference,
																		  OOModel::ReferenceExpression*)
{
	return parentReference->name() == "unique_ptr" || parentReference->name() == "shared_ptr";
}

Export::SourceFragment* SpecialCases::printXMacroDataBlock(OOModel::MetaCallExpression* metaCall)
{
	auto reference = DCast<OOModel::ReferenceExpression>(metaCall->callee());
	Q_ASSERT(reference->name().startsWith("BEGIN_"));

	auto fragment = new Export::CompositeFragment{metaCall, "sections"};
	auto beginCallFragment = fragment->append(new Export::CompositeFragment{metaCall});
	*beginCallFragment << reference->name();
	auto argumentsFragment =
			beginCallFragment->append(new Export::CompositeFragment{metaCall->arguments(), "argsList"});

	CppPrintContext printContext{nullptr};
	for (auto i = 0; i < metaCall->arguments()->size() - 1; i++)
		if (auto expression = DCast<OOModel::Expression>(metaCall->arguments()->at(i)))
			*argumentsFragment << ExpressionVisitor{printContext}.visit(expression);
		else
			Q_ASSERT(false);

	Q_ASSERT(metaCall->arguments()->size() > 0);
	auto childMetaCallsList = DCast<Model::List>(metaCall->arguments()->last());
	auto childMetaCallsFragment = fragment->append(new Export::CompositeFragment{childMetaCallsList, "bodyNoBraces"});
	Q_ASSERT(childMetaCallsList);
	for (auto childMetaCallCandidate : *childMetaCallsList)
	{
		auto childMetaCall = DCast<OOModel::MetaCallExpression>(childMetaCallCandidate);
		Q_ASSERT(childMetaCall);
		*childMetaCallsFragment << ExpressionVisitor{printContext}.visit(childMetaCall);
	}

	*fragment << "END_STANDARD_EXPRESSION_VISUALIZATION";

	return fragment;
}

Export::CompositeFragment* SpecialCases::printPartialBeginMacroSpecialization(OOModel::MetaDefinition* metaDefinition,
																										bool isHeaderFile)
{
	Q_ASSERT(metaDefinition->name().startsWith("BEGIN_") && metaDefinition->metaBindings()->isEmpty());

	auto macro = new Export::CompositeFragment{metaDefinition, "macro"};
	auto fragment = macro->append(new Export::CompositeFragment{metaDefinition, "sections"});
	auto metaDefinitionFragment = fragment->append(new Export::CompositeFragment{metaDefinition});
	*metaDefinitionFragment << "#define " << metaDefinition->name();
	auto argumentsFragment = metaDefinitionFragment->append(new Export::CompositeFragment{metaDefinition->arguments(),
																													  "argsList"});
	CppPrintContext printContext{nullptr};
	for (auto i = 0; i < metaDefinition->arguments()->size() - 1; i++)
		*argumentsFragment << ElementVisitor{printContext}.visit(metaDefinition->arguments()->at(i));

	if (auto metaCall = DCast<OOModel::MetaCallExpression>(metaDefinition->context()->metaCalls()->first()))
	{
		auto metaCallFragment = fragment->append(new Export::CompositeFragment{metaCall});
		*metaCallFragment << ExpressionVisitor{printContext}.visit(metaCall->callee());
		auto argumentsFragment =
				metaCallFragment->append(new Export::CompositeFragment{metaCall->arguments(), "argsList"});
		for (auto i = 0; i < metaCall->arguments()->size() - (isHeaderFile ? 2 : 3); i++)
			if (auto argument = DCast<OOModel::Expression>(metaCall->arguments()->at(i)))
				*argumentsFragment << ExpressionVisitor{printContext}.visit(argument);

		if (!isHeaderFile)
		{
			Q_ASSERT(metaCall->arguments()->size() > 0);
			auto statementList = DCast<Model::List>(metaCall->arguments()->at(metaCall->arguments()->size() - 2));
			Q_ASSERT(statementList);
			auto statementListFragment = fragment->append(new Export::CompositeFragment{statementList, "bodyNoBraces"});
			for (auto statementCandidate : *statementList)
				if (auto statement = DCast<OOModel::StatementItem>(statementCandidate))
					*statementListFragment << StatementVisitor{printContext}.visit(statement);
				else
					Q_ASSERT(false);
		}
	}
	else
		Q_ASSERT(false);

	return macro;
}

Export::CompositeFragment* SpecialCases::printPartialBeginMacroBase(OOModel::MetaDefinition* metaDefinition,
																						  bool isHeaderFile)
{
	Q_ASSERT(metaDefinition->name().startsWith("BEGIN_") && !metaDefinition->metaBindings()->isEmpty());

	auto fragment = new Export::CompositeFragment{metaDefinition, "macro"};
	auto macroFragment = fragment->append(new Export::CompositeFragment{metaDefinition, "sections"});
	auto context = DCast<OOModel::Module>(metaDefinition->context());
	auto classs = context->classes()->first();
	CppPrintContext printContext{isHeaderFile ? classs : nullptr, isHeaderFile ? CppPrintContext::IsHeaderPart :
																										  CppPrintContext::None
																					  | CppPrintContext::XMacro};
	auto metaDefinitionFragment = macroFragment->append(new Export::CompositeFragment{metaDefinition});
	*metaDefinitionFragment << "#define " << metaDefinition->name();
	auto argumentsFragment = metaDefinitionFragment->append(new Export::CompositeFragment{metaDefinition->arguments(),
																													  "argsList"});
	for (auto i = 0; i < metaDefinition->arguments()->size() - (isHeaderFile ? 2 : 3); i++)
		*argumentsFragment << ElementVisitor{printContext}.visit(metaDefinition->arguments()->at(i));
	*macroFragment << DeclarationVisitor{printContext}.visit(classs);

	return fragment;
}

Export::SourceFragment* SpecialCases::includeXMacroData(CodeComposite* codeComposite,
																					Export::SourceFragment* baseFragment,
																					bool isSourceFile)
{
	auto dataInclusionFragment = new Export::CompositeFragment{baseFragment->node(), "sections"};
	*dataInclusionFragment << "namespace OOVisualization {"
								  << "#include \"" + XMACRO_DATA_FILENAME + ".h\""
								  << "}";
	auto fragment = new Export::CompositeFragment{baseFragment->node(), "spacedSections"};
	*fragment << baseFragment
				 << dataInclusionFragment;
	for (auto unit : codeComposite->units())
		if (auto metaDefinition = DCast<OOModel::MetaDefinition>(unit->node()))
			if (metaDefinition->name().startsWith("BEGIN_") || (metaDefinition->name().endsWith("_CPP") == isSourceFile))
				*fragment << "#undef " + ExportHelpers::strip_CPPFromName(metaDefinition);
	return fragment;
}

}
<|endoftext|>


<commit_before>// MsOfficeDocumentInformation.h: Schnittstelle f�r die Klasse MsOfficeDocumentInformation.
//
//////////////////////////////////////////////////////////////////////

#ifndef _REGISTRATIONCONTEXTINFORMATION_HXX_
#define _REGISTRATIONCONTEXTINFORMATION_HXX_

#pragma warning(push, 1) /* disable warnings within system headers */
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <msi.h>
#pragma warning(pop)

#include <string>

/** A simple implementation class that returns the
    appropriate display names for the Microsoft
    Office document types.
    Under Windows 9x this class checks if the
    document display name is convertable to an ANSI
    string and if not returns an english default.
    So we avoid garbage if soemone for instance
    installs an japanese StarOffice/OpenOffice
    under a German Windows 98 for instance.
*/
class RegistrationContextInformation
{
public:

    enum SHELL_COMMAND {New, Open, Print, Printto};
    enum OFFICE_APPLICATION {Office, Writer, Calc, Impress};

    RegistrationContextInformation(MSIHANDLE hMsi, const std::wstring& OpenOfficeExecutablePath);

    /** Word document information
        The icon index is the index of the icon
        in soffice.exe to be associated with
        word document files
    */
    std::wstring GetWordDocumentDisplayName() const;
    std::wstring GetWordDocumentFileExtension() const;
    std::wstring GetWordDocumentDefaultIconEntry() const;
    std::wstring GetWordDocumentDefaultShellCommand() const;

    /** Word template information
        The icon index is the index of the icon
        in soffice.exe to be associated with
        word template files
    */
    std::wstring GetWordTemplateDisplayName() const;
    std::wstring GetWordTemplateFileExtension() const;
    std::wstring GetWordTemplateDefaultIconEntry() const;
    std::wstring GetWordTemplateDefaultShellCommand() const;

    /** Rtf document information
        The icon index is the index of the icon
        in soffice.exe to be associated with
        rtf document files
    */
    std::wstring GetRtfDocumentDisplayName() const;
    std::wstring GetRtfDocumentFileExtension() const;
    std::wstring GetRtfDocumentDefaultIconEntry() const;
    std::wstring GetRtfDocumentDefaultShellCommand() const;

    /** Excel sheet information
        The icon index is the index of the icon
        in soffice.exe to be associated with
        Excel sheets
    */
    std::wstring GetExcelSheetDisplayName() const;
    std::wstring GetExcelSheetFileExtension() const;
    std::wstring GetExcelSheetDefaultIconEntry() const;
    std::wstring GetExcelSheetDefaultShellCommand() const;

    /** Excel template information
        The icon index is the index of the icon
        in soffice.exe to be associated with
        Excel template files
    */
    std::wstring GetExcelTemplateDisplayName() const;
    std::wstring GetExcelTemplateFileExtension() const;
    std::wstring GetExcelTemplateDefaultIconEntry() const;
    std::wstring GetExcelTemplateDefaultShellCommand() const;

    /** PowerPoint document information
        The icon index is the index of the icon
        in soffice.exe to be associated with
        PowerPoint document files
    */
    std::wstring GetPowerPointDocumentDisplayName() const;
    std::wstring GetPowerPointDocumentFileExtension() const;
    std::wstring GetPowerPointDocumentDefaultIconEntry() const;
    std::wstring GetPowerPointDocumentDefaultShellCommand() const;

    /** PowerPoint template information
        The icon index is the index of the icon
        in soffice.exe to be associated with
        PowerPoint template files
    */
    std::wstring GetPowerPointTemplateDisplayName() const;
    std::wstring GetPowerPointTemplateFileExtension() const;
    std::wstring GetPowerPointTemplateDefaultIconEntry() const;
    std::wstring GetPowerPointTemplateDefaultShellCommand() const;

    /** PowerPoint Show information
    */
    std::wstring GetPowerPointShowDisplayName() const;
    std::wstring GetPowerPointShowFileExtension() const;
    std::wstring GetPowerPointShowDefaultIconEntry() const;
    std::wstring GetPowerPointShowDefaultShellCommand() const;

    /** The string for the "New" command that should appear
        in the Explorer context menu when someone right
        clicks a Microsoft document
    */
    std::wstring ShellNewCommandDisplayName() const;

    /** The string for the "Edit" command that should
        appear in the Explorer context menu when someone
        right clicks a document
    */
    std::wstring ShellEditCommandDisplayName() const;

    /** A friendly name for the application
    */
    std::wstring GetOpenOfficeFriendlyAppName() const;

    /** The path to the StarOffice/OpenOffice executable
    */
    std::wstring GetOpenOfficeExecutablePath() const;

    /** The name of the executable (currently "soffice.exe"
        but may change in the future, who knows)
    */
    std::wstring GetOpenOfficeExecutableName() const;

    /** A command line for the specified shell command
    */
    std::wstring GetOpenOfficeCommandline(SHELL_COMMAND ShellCommand,
                                          OFFICE_APPLICATION OfficeApp) const;

private:
    bool IsConvertableToAnsi(const std::wstring& String)  const;

    void ExtractOpenOfficeExecNameFromPath();

private:
    MSIHANDLE    msihandle_;
    bool         m_IsWin9x;
    std::wstring m_OOExecPath;
    std::wstring m_OOExecName;
};

#endif
<commit_msg>INTEGRATION: CWS mingwport06 (1.3.44); FILE MERGED 2007/08/24 13:12:57 vg 1.3.44.1: #i75499# pragma is for MSVC<commit_after>// MsOfficeDocumentInformation.h: Schnittstelle f�r die Klasse MsOfficeDocumentInformation.
//
//////////////////////////////////////////////////////////////////////

#ifndef _REGISTRATIONCONTEXTINFORMATION_HXX_
#define _REGISTRATIONCONTEXTINFORMATION_HXX_

#ifdef _MSC_VER
#pragma warning(push, 1) /* disable warnings within system headers */
#endif
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <msi.h>
#ifdef _MSC_VER
#pragma warning(pop)
#endif

#include <string>

/** A simple implementation class that returns the
    appropriate display names for the Microsoft
    Office document types.
    Under Windows 9x this class checks if the
    document display name is convertable to an ANSI
    string and if not returns an english default.
    So we avoid garbage if soemone for instance
    installs an japanese StarOffice/OpenOffice
    under a German Windows 98 for instance.
*/
class RegistrationContextInformation
{
public:

    enum SHELL_COMMAND {New, Open, Print, Printto};
    enum OFFICE_APPLICATION {Office, Writer, Calc, Impress};

    RegistrationContextInformation(MSIHANDLE hMsi, const std::wstring& OpenOfficeExecutablePath);

    /** Word document information
        The icon index is the index of the icon
        in soffice.exe to be associated with
        word document files
    */
    std::wstring GetWordDocumentDisplayName() const;
    std::wstring GetWordDocumentFileExtension() const;
    std::wstring GetWordDocumentDefaultIconEntry() const;
    std::wstring GetWordDocumentDefaultShellCommand() const;

    /** Word template information
        The icon index is the index of the icon
        in soffice.exe to be associated with
        word template files
    */
    std::wstring GetWordTemplateDisplayName() const;
    std::wstring GetWordTemplateFileExtension() const;
    std::wstring GetWordTemplateDefaultIconEntry() const;
    std::wstring GetWordTemplateDefaultShellCommand() const;

    /** Rtf document information
        The icon index is the index of the icon
        in soffice.exe to be associated with
        rtf document files
    */
    std::wstring GetRtfDocumentDisplayName() const;
    std::wstring GetRtfDocumentFileExtension() const;
    std::wstring GetRtfDocumentDefaultIconEntry() const;
    std::wstring GetRtfDocumentDefaultShellCommand() const;

    /** Excel sheet information
        The icon index is the index of the icon
        in soffice.exe to be associated with
        Excel sheets
    */
    std::wstring GetExcelSheetDisplayName() const;
    std::wstring GetExcelSheetFileExtension() const;
    std::wstring GetExcelSheetDefaultIconEntry() const;
    std::wstring GetExcelSheetDefaultShellCommand() const;

    /** Excel template information
        The icon index is the index of the icon
        in soffice.exe to be associated with
        Excel template files
    */
    std::wstring GetExcelTemplateDisplayName() const;
    std::wstring GetExcelTemplateFileExtension() const;
    std::wstring GetExcelTemplateDefaultIconEntry() const;
    std::wstring GetExcelTemplateDefaultShellCommand() const;

    /** PowerPoint document information
        The icon index is the index of the icon
        in soffice.exe to be associated with
        PowerPoint document files
    */
    std::wstring GetPowerPointDocumentDisplayName() const;
    std::wstring GetPowerPointDocumentFileExtension() const;
    std::wstring GetPowerPointDocumentDefaultIconEntry() const;
    std::wstring GetPowerPointDocumentDefaultShellCommand() const;

    /** PowerPoint template information
        The icon index is the index of the icon
        in soffice.exe to be associated with
        PowerPoint template files
    */
    std::wstring GetPowerPointTemplateDisplayName() const;
    std::wstring GetPowerPointTemplateFileExtension() const;
    std::wstring GetPowerPointTemplateDefaultIconEntry() const;
    std::wstring GetPowerPointTemplateDefaultShellCommand() const;

    /** PowerPoint Show information
    */
    std::wstring GetPowerPointShowDisplayName() const;
    std::wstring GetPowerPointShowFileExtension() const;
    std::wstring GetPowerPointShowDefaultIconEntry() const;
    std::wstring GetPowerPointShowDefaultShellCommand() const;

    /** The string for the "New" command that should appear
        in the Explorer context menu when someone right
        clicks a Microsoft document
    */
    std::wstring ShellNewCommandDisplayName() const;

    /** The string for the "Edit" command that should
        appear in the Explorer context menu when someone
        right clicks a document
    */
    std::wstring ShellEditCommandDisplayName() const;

    /** A friendly name for the application
    */
    std::wstring GetOpenOfficeFriendlyAppName() const;

    /** The path to the StarOffice/OpenOffice executable
    */
    std::wstring GetOpenOfficeExecutablePath() const;

    /** The name of the executable (currently "soffice.exe"
        but may change in the future, who knows)
    */
    std::wstring GetOpenOfficeExecutableName() const;

    /** A command line for the specified shell command
    */
    std::wstring GetOpenOfficeCommandline(SHELL_COMMAND ShellCommand,
                                          OFFICE_APPLICATION OfficeApp) const;

private:
    bool IsConvertableToAnsi(const std::wstring& String)  const;

    void ExtractOpenOfficeExecNameFromPath();

private:
    MSIHANDLE    msihandle_;
    bool         m_IsWin9x;
    std::wstring m_OOExecPath;
    std::wstring m_OOExecName;
};

#endif
<|endoftext|>