<commit_before>//****************************************************************************
// Copyright © 2015 Jan Erik Breimo. All rights reserved.
// Created by Jan Erik Breimo on 2015-06-03
//
// This file is distributed under the Simplified BSD License.
// License text is included with the source distribution.
//****************************************************************************
#pragma once

#include <cstdint>
#include <utility>

namespace Ystring { namespace EncodedString
{
    template <typename Decoder, typename UnaryPred>
    bool advanceIf(Decoder& str, UnaryPred pred)
    {
        auto pos = str.getLogicalBegin();
        char32_t ch;
        if (!str.next(ch) || !pred(ch))
        {
            str.setLogicalBegin(pos);
            return false;
        }
        return true;
    }

    template <typename Decoder, typename UnaryPred>
    bool advanceIfNot(Decoder& str, UnaryPred pred)
    {
        auto pos = str.getLogicalBegin();
        char32_t ch;
        if (!str.next(ch) || pred(ch))
        {
            str.setLogicalBegin(pos);
            return false;
        }
        return true;
    }

    template <typename Decoder1, typename Decoder2, typename BinaryPred>
    bool advanceIfEqual(Decoder1& a, Decoder2& b, BinaryPred compare)
    {
        auto aPos = a.getLogicalBegin();
        auto bPos = b.getLogicalBegin();
        char32_t aCh, bCh;
        bool aNext = a.next(aCh);
        bool bNext = b.next(bCh);
        if (!aNext && !bNext)
            return false;
        if (!aNext || !bNext || !compare(aCh, bCh))
        {
            a.setLogicalBegin(aPos);
            b.setLogicalBegin(bPos);
            return false;
        }
        return true;
    }

    template <typename Decoder, typename UnaryPred>
    bool advanceUntil(Decoder& str, UnaryPred pred)
    {
        while (advanceIfNot(str, pred))
        {}
        return str.begin() != str.end();
    }

    template <typename Decoder, typename UnaryPred>
    bool advanceWhile(Decoder& str, UnaryPred pred)
    {
        while (advanceIf(str, pred))
        {}
        return str.begin() == str.end();
    }

    template <typename Decoder1, typename Decoder2, typename BinaryPred>
    bool advanceWhileEqual(Decoder1& str, Decoder2& cmp, BinaryPred compare)
    {
        while (advanceIfEqual(str, cmp, compare))
        {}
        return cmp.begin() == cmp.end();
    }

    template <typename Decoder1, typename Decoder2>
    bool advanceWhileEqual(Decoder1& str, Decoder2& cmp)
    {
        return advanceWhileEqual(str, cmp,
                                 [](char32_t a, char32_t b){return a == b;});
    }

    template <typename Decoder1, typename Decoder2, typename BinaryPred>
    Decoder1 search(Decoder1& str, Decoder2& cmp, BinaryPred compare)
    {
        while (true)
        {
            auto copyOfStr = str;
            auto copyOfCmp = cmp;
            if (advanceWhileEqual(copyOfStr, copyOfCmp, compare))
            {
                str.setLogicalEnd(copyOfStr.getLogicalBegin());
                std::swap(str, copyOfStr);
                return copyOfStr;
            }
            if (!str.skip())
                break;
        }
        return str;
    }

    template <typename Decoder1, typename Decoder2>
    Decoder1 search(Decoder1& str, Decoder2& cmp)
    {
        return search(str, cmp, [](char32_t a, char32_t b){return a == b;});
    }
}}
<commit_msg>MSVC 2019 requires this namespace prefix for some reason.<commit_after>//****************************************************************************
// Copyright © 2015 Jan Erik Breimo. All rights reserved.
// Created by Jan Erik Breimo on 2015-06-03
//
// This file is distributed under the Simplified BSD License.
// License text is included with the source distribution.
//****************************************************************************
#pragma once

#include <cstdint>
#include <utility>

namespace Ystring { namespace EncodedString
{
    template <typename Decoder, typename UnaryPred>
    bool advanceIf(Decoder& str, UnaryPred pred)
    {
        auto pos = str.getLogicalBegin();
        char32_t ch;
        if (!str.next(ch) || !pred(ch))
        {
            str.setLogicalBegin(pos);
            return false;
        }
        return true;
    }

    template <typename Decoder, typename UnaryPred>
    bool advanceIfNot(Decoder& str, UnaryPred pred)
    {
        auto pos = str.getLogicalBegin();
        char32_t ch;
        if (!str.next(ch) || pred(ch))
        {
            str.setLogicalBegin(pos);
            return false;
        }
        return true;
    }

    template <typename Decoder1, typename Decoder2, typename BinaryPred>
    bool advanceIfEqual(Decoder1& a, Decoder2& b, BinaryPred compare)
    {
        auto aPos = a.getLogicalBegin();
        auto bPos = b.getLogicalBegin();
        char32_t aCh, bCh;
        bool aNext = a.next(aCh);
        bool bNext = b.next(bCh);
        if (!aNext && !bNext)
            return false;
        if (!aNext || !bNext || !compare(aCh, bCh))
        {
            a.setLogicalBegin(aPos);
            b.setLogicalBegin(bPos);
            return false;
        }
        return true;
    }

    template <typename Decoder, typename UnaryPred>
    bool advanceUntil(Decoder& str, UnaryPred pred)
    {
        while (advanceIfNot(str, pred))
        {}
        return str.begin() != str.end();
    }

    template <typename Decoder, typename UnaryPred>
    bool advanceWhile(Decoder& str, UnaryPred pred)
    {
        while (advanceIf(str, pred))
        {}
        return str.begin() == str.end();
    }

    template <typename Decoder1, typename Decoder2, typename BinaryPred>
    bool advanceWhileEqual(Decoder1& str, Decoder2& cmp, BinaryPred compare)
    {
        while (advanceIfEqual(str, cmp, compare))
        {}
        return cmp.begin() == cmp.end();
    }

    template <typename Decoder1, typename Decoder2>
    bool advanceWhileEqual(Decoder1& str, Decoder2& cmp)
    {
        return advanceWhileEqual(str, cmp,
                                 [](char32_t a, char32_t b){return a == b;});
    }

    template <typename Decoder1, typename Decoder2, typename BinaryPred>
    Decoder1 search(Decoder1& str, Decoder2& cmp, BinaryPred compare)
    {
        while (true)
        {
            auto copyOfStr = str;
            auto copyOfCmp = cmp;
            if (advanceWhileEqual(copyOfStr, copyOfCmp, compare))
            {
                str.setLogicalEnd(copyOfStr.getLogicalBegin());
                std::swap(str, copyOfStr);
                return copyOfStr;
            }
            if (!str.skip())
                break;
        }
        return str;
    }

    template <typename Decoder1, typename Decoder2>
    Decoder1 search(Decoder1& str, Decoder2& cmp)
    {
        return Ystring::EncodedString::search(str, cmp, [](char32_t a, char32_t b){return a == b;});
    }
}}
<|endoftext|>


<commit_before>// @(#)root/eve:$Id$
// Author: Matevz Tadel 2007

/*************************************************************************
 * Copyright (C) 1995-2007, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include "TEveArrowGL.h"
#include "TEveArrow.h"

#include "TGLRnrCtx.h"
#include "TGLIncludes.h"
#include "TGLUtil.h"
#include "TGLQuadric.h"

// #include "TAttLine.h"

//______________________________________________________________________________
// OpenGL renderer class for TEveArrow.
//

ClassImp(TEveArrowGL);

//______________________________________________________________________________
TEveArrowGL::TEveArrowGL() :
   TGLObject(), fM(0)
{
   // Constructor.
}

/******************************************************************************/

//______________________________________________________________________________
Bool_t TEveArrowGL::SetModel(TObject* obj, const Option_t* /*opt*/)
{
   // Set model object.

   if (SetModelCheckClass(obj, TEveArrow::Class())) {
      fM = dynamic_cast<TEveArrow*>(obj);
      return kTRUE;
   }
   return kFALSE;
}

//______________________________________________________________________________
void TEveArrowGL::SetBBox()
{
   // Set bounding box.

   // !! This ok if master sub-classed from TAttBBox
   SetAxisAlignedBBox(((TEveArrow*)fExternalObj)->AssertBBox());
}

/******************************************************************************/

//______________________________________________________________________________
void TEveArrowGL::DirectDraw(TGLRnrCtx & rnrCtx) const
{
   // Render with OpenGL.

   // printf("TEveArrowGL::DirectDraw LOD \n");

   static TGLQuadric quad;
   UInt_t drawQuality = 10;
   // Draw 3D line (tube) with optional head shape

   // glPushAttrib(GL_ENABLE_BIT | GL_POLYGON_BIT);
   glDisable(GL_CULL_FACE);

   glPushMatrix();

   TGLVertex3 uo(fM->fOrigin.fX, fM->fOrigin.fY, fM->fOrigin.fZ);
   TGLVector3 uv(fM->fVector.fX, fM->fVector.fY, fM->fVector.fZ);
   TGLMatrix local(uo, uv);
   glMultMatrixd(local.CArr());
   Float_t size = fM->fVector.Mag();

   // Line (tube) component
   Float_t tr = size*fM->fTubeR;
   Float_t hh = size*fM->fConeL;
   gluCylinder(quad.Get(), tr, tr, size - hh, drawQuality, 1);

   // disks
   gluQuadricOrientation(quad.Get(), (GLenum)GLU_INSIDE);
   gluDisk(quad.Get(), 0.0, tr, drawQuality, 1);
   glTranslated(0.0, 0.0, size -hh );
   gluDisk(quad.Get(), 0.0, tr, drawQuality, 1);

   // Arrow cone
   gluQuadricOrientation(quad.Get(), (GLenum)GLU_OUTSIDE);
   gluCylinder(quad.Get(), size*fM->fConeR, 0., hh , drawQuality, 1);
   gluDisk(quad.Get(), 0.0, size*fM->fConeR, drawQuality, 1);

   glPopMatrix();
   // glPopAttrib();
}

<commit_msg>From Alja. Fix compilation warnings.<commit_after>// @(#)root/eve:$Id$
// Author: Matevz Tadel 2007

/*************************************************************************
 * Copyright (C) 1995-2007, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include "TEveArrowGL.h"
#include "TEveArrow.h"

#include "TGLRnrCtx.h"
#include "TGLIncludes.h"
#include "TGLUtil.h"
#include "TGLQuadric.h"

//______________________________________________________________________________
// OpenGL renderer class for TEveArrow.
//

ClassImp(TEveArrowGL);

//______________________________________________________________________________
TEveArrowGL::TEveArrowGL() :
   TGLObject(), fM(0)
{
   // Constructor.
}

/******************************************************************************/

//______________________________________________________________________________
Bool_t TEveArrowGL::SetModel(TObject* obj, const Option_t* /*opt*/)
{
   // Set model object.

   if (SetModelCheckClass(obj, TEveArrow::Class())) {
      fM = dynamic_cast<TEveArrow*>(obj);
      return kTRUE;
   }
   return kFALSE;
}

//______________________________________________________________________________
void TEveArrowGL::SetBBox()
{
   // Set bounding box.

   // !! This ok if master sub-classed from TAttBBox
   SetAxisAlignedBBox(((TEveArrow*)fExternalObj)->AssertBBox());
}

/******************************************************************************/

//______________________________________________________________________________
void TEveArrowGL::DirectDraw(TGLRnrCtx& /*rnrCtx*/) const
{
   // Render with OpenGL.

   // printf("TEveArrowGL::DirectDraw LOD \n");

   static TGLQuadric quad;
   UInt_t drawQuality = 10;
   // Draw 3D line (tube) with optional head shape

   glPushMatrix();

   TGLVertex3 uo(fM->fOrigin.fX, fM->fOrigin.fY, fM->fOrigin.fZ);
   TGLVector3 uv(fM->fVector.fX, fM->fVector.fY, fM->fVector.fZ);
   TGLMatrix local(uo, uv);
   glMultMatrixd(local.CArr());
   Float_t size = fM->fVector.Mag();

   // Line (tube) component
   Float_t tr = size*fM->fTubeR;
   Float_t hh = size*fM->fConeL;
   gluCylinder(quad.Get(), tr, tr, size - hh, drawQuality, 1);

   // disks
   gluQuadricOrientation(quad.Get(), (GLenum)GLU_INSIDE);
   gluDisk(quad.Get(), 0.0, tr, drawQuality, 1);
   glTranslated(0.0, 0.0, size -hh );
   gluDisk(quad.Get(), 0.0, tr, drawQuality, 1);

   // Arrow cone
   gluQuadricOrientation(quad.Get(), (GLenum)GLU_OUTSIDE);
   gluCylinder(quad.Get(), size*fM->fConeR, 0., hh , drawQuality, 1);
   gluDisk(quad.Get(), 0.0, size*fM->fConeR, drawQuality, 1);

   glPopMatrix();
}
<|endoftext|>


<commit_before>#include "input.h"
#include "engine.h"

P<WindowManager> InputHandler::windowManager;
bool InputHandler::touch_screen = false;
sf::Transform InputHandler::mouse_transform;
PVector<InputEventHandler> InputHandler::input_event_handlers;
PVector<JoystickEventHandler> InputHandler::joystick_event_handlers;

bool InputHandler::keyboard_button_down[sf::Keyboard::KeyCount];
bool InputHandler::keyboard_button_pressed[sf::Keyboard::KeyCount];
bool InputHandler::keyboard_button_released[sf::Keyboard::KeyCount];
sf::Event::KeyEvent InputHandler::last_key_press;

sf::Vector2f InputHandler::mouse_position;
float InputHandler::mouse_wheel_delta;
bool InputHandler::mouse_button_down[sf::Mouse::ButtonCount];
bool InputHandler::mouse_button_pressed[sf::Mouse::ButtonCount];
bool InputHandler::mouse_button_released[sf::Mouse::ButtonCount];

float InputHandler::joystick_axis_pos[sf::Joystick::Count][sf::Joystick::AxisCount];
float InputHandler::joystick_axis_changed[sf::Joystick::Count][sf::Joystick::AxisCount];
bool InputHandler::joystick_button_down[sf::Joystick::Count][sf::Joystick::ButtonCount];
bool InputHandler::joystick_button_changed[sf::Joystick::Count][sf::Joystick::ButtonCount];

InputEventHandler::InputEventHandler()
{
    InputHandler::input_event_handlers.push_back(this);
}

InputEventHandler::~InputEventHandler()
{
}

JoystickEventHandler::JoystickEventHandler()
{
    InputHandler::joystick_event_handlers.push_back(this);
}

JoystickEventHandler::~JoystickEventHandler()
{
}

void InputHandler::initialize()
{
    memset(mouse_button_down, 0, sizeof(mouse_button_down));
    memset(keyboard_button_down, 0, sizeof(keyboard_button_down));
    memset(joystick_axis_pos, 0, sizeof(joystick_axis_pos));
#ifdef __ANDROID__
    touch_screen = true;
#endif
    last_key_press.code = sf::Keyboard::Unknown;
}

void InputHandler::preEventsUpdate()
{
    if (!windowManager)
        windowManager = engine->getObject("windowManager");

    for(unsigned int n=0; n<sf::Keyboard::KeyCount; n++)
    {
        if (keyboard_button_pressed[n])
            keyboard_button_pressed[n] = false;
        else
            keyboard_button_released[n] = false;
    }
    for(unsigned int n=0; n<sf::Mouse::ButtonCount; n++)
    {
        if (mouse_button_pressed[n])
            mouse_button_pressed[n] = false;
        else
            mouse_button_released[n] = false;
    }
    for(unsigned int i=0; i<sf::Joystick::Count; i++)
    {
        for(unsigned int n=0; n<sf::Joystick::AxisCount; n++)
        {
            joystick_axis_changed[i][n] = false;
        }
        for(unsigned int n=0; n<sf::Joystick::ButtonCount; n++)
        {
            joystick_button_changed[i][n] = false;
        }
    }
    mouse_wheel_delta = 0;
}

void InputHandler::handleEvent(sf::Event& event)
{
    if (event.type == sf::Event::KeyPressed)
    {
        if (event.key.code > sf::Keyboard::Unknown && event.key.code < sf::Keyboard::KeyCount)
        {
            keyboard_button_down[event.key.code] = true;
            keyboard_button_pressed[event.key.code] = true;
        }
        last_key_press = event.key;
    }
	else if (event.type == sf::Event::KeyReleased)
	{
        if (event.key.code > sf::Keyboard::Unknown && event.key.code < sf::Keyboard::KeyCount)
        {
            keyboard_button_down[event.key.code] = false;
            keyboard_button_released[event.key.code] = true;
        }
	}
    else if (event.type == sf::Event::TextEntered && event.text.unicode > 31 && event.text.unicode < 128)
    {
        if (last_key_press.code != sf::Keyboard::Unknown)
        {
            fireKeyEvent(last_key_press, event.text.unicode);
            last_key_press.code = sf::Keyboard::Unknown;
        }
    }
    else if (event.type == sf::Event::MouseWheelMoved)
        mouse_wheel_delta += event.mouseWheel.delta;
    if (event.type == sf::Event::MouseButtonPressed)
    {
        mouse_button_down[event.mouseButton.button] = true;
        mouse_button_pressed[event.mouseButton.button] = true;
    }
    else if (event.type == sf::Event::MouseButtonReleased)
    {
        mouse_button_down[event.mouseButton.button] = false;
        mouse_button_released[event.mouseButton.button] = true;
    }
    else if (event.type == sf::Event::JoystickMoved)
    {
        float axis_pos;
        if (event.joystickMove.position > joystick_axis_snap_to_0_range) {
            axis_pos = (event.joystickMove.position - joystick_axis_snap_to_0_range) * ((joystick_axis_snap_to_0_range / 100) + 1);
        } else if (event.joystickMove.position < -joystick_axis_snap_to_0_range) {
            axis_pos = (event.joystickMove.position + joystick_axis_snap_to_0_range) * ((joystick_axis_snap_to_0_range / 100) + 1);
        } else {
            axis_pos = 0.0;
        }
        if (joystick_axis_pos[event.joystickMove.joystickId][event.joystickMove.axis] != axis_pos){
            joystick_axis_changed[event.joystickMove.joystickId][event.joystickMove.axis] = true;
        }
        joystick_axis_pos[event.joystickMove.joystickId][event.joystickMove.axis] = axis_pos;
    }
    else if (event.type == sf::Event::JoystickButtonPressed)
    {
        joystick_button_down[event.joystickMove.joystickId][event.joystickButton.button] = true;
        joystick_button_changed[event.joystickMove.joystickId][event.joystickButton.button] = true;
    }
    else if (event.type == sf::Event::JoystickButtonReleased)
    {
        joystick_button_down[event.joystickMove.joystickId][event.joystickButton.button] = false;
        joystick_button_changed[event.joystickMove.joystickId][event.joystickButton.button] = true;
    }
}

void InputHandler::postEventsUpdate()
{
    if (last_key_press.code != sf::Keyboard::Unknown)
    {
        InputHandler::fireKeyEvent(last_key_press, -1);
        last_key_press.code = sf::Keyboard::Unknown;
    }

#ifdef __ANDROID__
    if (sf::Touch::isDown(0))
    {
        mouse_position = realWindowPosToVirtual(sf::Touch::getPosition(0));
        if (!mouse_button_down[sf::Mouse::Left])
            mouse_button_pressed[sf::Mouse::Left] = true;
        mouse_button_down[sf::Mouse::Left] = true;
    }else{
        if (mouse_button_down[sf::Mouse::Left])
            mouse_button_released[sf::Mouse::Left] = true;
        mouse_button_down[sf::Mouse::Left] = false;
    }
#else
    mouse_position = realWindowPosToVirtual(sf::Mouse::getPosition(windowManager->window));
#endif
    mouse_position = mouse_transform.transformPoint(mouse_position);

    if (touch_screen)
    {
        bool any_button_down = false;
        for(unsigned int n=0; n<sf::Mouse::ButtonCount; n++)
            if (mouse_button_down[n] || mouse_button_released[n])
                any_button_down = true;
        if (!any_button_down)
        {
            mouse_position = sf::Vector2f(-1, -1);
        }
    }
    for(unsigned int i=0; i<sf::Joystick::Count; i++)
    {
        for(unsigned int n=0; n<sf::Joystick::AxisCount; n++)
        {
            if(joystick_axis_changed[i][n])
            {
                foreach(JoystickEventHandler, e, joystick_event_handlers)
                {
                    e->handleJoystickAxis(i, (sf::Joystick::Axis) n, joystick_axis_pos[i][n]);
                }
            }
        }
        for(unsigned int n=0; n<sf::Joystick::ButtonCount; n++)
        {
            if(joystick_button_changed[i][n])
            {
                foreach(JoystickEventHandler, e, joystick_event_handlers)
                {
                    e->handleJoystickButton(i, n, joystick_button_down[n]);
                }
            }
        }
    }
}

void InputHandler::setMousePos(sf::Vector2f position)
{
    if (!windowManager)
        windowManager = engine->getObject("windowManager");

    sf::Mouse::setPosition(virtualWindowPosToReal(position), windowManager->window);
    mouse_position = realWindowPosToVirtual(sf::Mouse::getPosition(windowManager->window));
}

void InputHandler::fireKeyEvent(sf::Event::KeyEvent key, int unicode)
{
    foreach(InputEventHandler, e, input_event_handlers)
    {
        e->handleKeyPress(key, unicode);
    }
}

sf::Vector2f InputHandler::realWindowPosToVirtual(sf::Vector2i position)
{
    sf::FloatRect viewport = windowManager->window.getView().getViewport();
    sf::Vector2f pos = sf::Vector2f(position);

    pos.x -= viewport.left * float(windowManager->window.getSize().x);
    pos.y -= viewport.top * float(windowManager->window.getSize().y);
    pos.x *= float(windowManager->virtualSize.x) / float(windowManager->window.getSize().x) / viewport.width;
    pos.y *= float(windowManager->virtualSize.y) / float(windowManager->window.getSize().y) / viewport.height;
    return pos;
}

sf::Vector2i InputHandler::virtualWindowPosToReal(sf::Vector2f position)
{
    sf::FloatRect viewport = windowManager->window.getView().getViewport();

    position.x /= float(windowManager->virtualSize.x) / float(windowManager->window.getSize().x) / viewport.width;
    position.y /= float(windowManager->virtualSize.y) / float(windowManager->window.getSize().y) / viewport.height;

    position.x += viewport.left * float(windowManager->window.getSize().x);
    position.y += viewport.top * float(windowManager->window.getSize().y);
    return sf::Vector2i(position);
}
<commit_msg>fix joystick button event bug - send correct state<commit_after>#include "input.h"
#include "engine.h"

P<WindowManager> InputHandler::windowManager;
bool InputHandler::touch_screen = false;
sf::Transform InputHandler::mouse_transform;
PVector<InputEventHandler> InputHandler::input_event_handlers;
PVector<JoystickEventHandler> InputHandler::joystick_event_handlers;

bool InputHandler::keyboard_button_down[sf::Keyboard::KeyCount];
bool InputHandler::keyboard_button_pressed[sf::Keyboard::KeyCount];
bool InputHandler::keyboard_button_released[sf::Keyboard::KeyCount];
sf::Event::KeyEvent InputHandler::last_key_press;

sf::Vector2f InputHandler::mouse_position;
float InputHandler::mouse_wheel_delta;
bool InputHandler::mouse_button_down[sf::Mouse::ButtonCount];
bool InputHandler::mouse_button_pressed[sf::Mouse::ButtonCount];
bool InputHandler::mouse_button_released[sf::Mouse::ButtonCount];

float InputHandler::joystick_axis_pos[sf::Joystick::Count][sf::Joystick::AxisCount];
float InputHandler::joystick_axis_changed[sf::Joystick::Count][sf::Joystick::AxisCount];
bool InputHandler::joystick_button_down[sf::Joystick::Count][sf::Joystick::ButtonCount];
bool InputHandler::joystick_button_changed[sf::Joystick::Count][sf::Joystick::ButtonCount];

InputEventHandler::InputEventHandler()
{
    InputHandler::input_event_handlers.push_back(this);
}

InputEventHandler::~InputEventHandler()
{
}

JoystickEventHandler::JoystickEventHandler()
{
    InputHandler::joystick_event_handlers.push_back(this);
}

JoystickEventHandler::~JoystickEventHandler()
{
}

void InputHandler::initialize()
{
    memset(mouse_button_down, 0, sizeof(mouse_button_down));
    memset(keyboard_button_down, 0, sizeof(keyboard_button_down));
    memset(joystick_axis_pos, 0, sizeof(joystick_axis_pos));
#ifdef __ANDROID__
    touch_screen = true;
#endif
    last_key_press.code = sf::Keyboard::Unknown;
}

void InputHandler::preEventsUpdate()
{
    if (!windowManager)
        windowManager = engine->getObject("windowManager");

    for(unsigned int n=0; n<sf::Keyboard::KeyCount; n++)
    {
        if (keyboard_button_pressed[n])
            keyboard_button_pressed[n] = false;
        else
            keyboard_button_released[n] = false;
    }
    for(unsigned int n=0; n<sf::Mouse::ButtonCount; n++)
    {
        if (mouse_button_pressed[n])
            mouse_button_pressed[n] = false;
        else
            mouse_button_released[n] = false;
    }
    for(unsigned int i=0; i<sf::Joystick::Count; i++)
    {
        for(unsigned int n=0; n<sf::Joystick::AxisCount; n++)
        {
            joystick_axis_changed[i][n] = false;
        }
        for(unsigned int n=0; n<sf::Joystick::ButtonCount; n++)
        {
            joystick_button_changed[i][n] = false;
        }
    }
    mouse_wheel_delta = 0;
}

void InputHandler::handleEvent(sf::Event& event)
{
    if (event.type == sf::Event::KeyPressed)
    {
        if (event.key.code > sf::Keyboard::Unknown && event.key.code < sf::Keyboard::KeyCount)
        {
            keyboard_button_down[event.key.code] = true;
            keyboard_button_pressed[event.key.code] = true;
        }
        last_key_press = event.key;
    }
	else if (event.type == sf::Event::KeyReleased)
	{
        if (event.key.code > sf::Keyboard::Unknown && event.key.code < sf::Keyboard::KeyCount)
        {
            keyboard_button_down[event.key.code] = false;
            keyboard_button_released[event.key.code] = true;
        }
	}
    else if (event.type == sf::Event::TextEntered && event.text.unicode > 31 && event.text.unicode < 128)
    {
        if (last_key_press.code != sf::Keyboard::Unknown)
        {
            fireKeyEvent(last_key_press, event.text.unicode);
            last_key_press.code = sf::Keyboard::Unknown;
        }
    }
    else if (event.type == sf::Event::MouseWheelMoved)
        mouse_wheel_delta += event.mouseWheel.delta;
    if (event.type == sf::Event::MouseButtonPressed)
    {
        mouse_button_down[event.mouseButton.button] = true;
        mouse_button_pressed[event.mouseButton.button] = true;
    }
    else if (event.type == sf::Event::MouseButtonReleased)
    {
        mouse_button_down[event.mouseButton.button] = false;
        mouse_button_released[event.mouseButton.button] = true;
    }
    else if (event.type == sf::Event::JoystickMoved)
    {
        float axis_pos;
        if (event.joystickMove.position > joystick_axis_snap_to_0_range) {
            axis_pos = (event.joystickMove.position - joystick_axis_snap_to_0_range) * ((joystick_axis_snap_to_0_range / 100) + 1);
        } else if (event.joystickMove.position < -joystick_axis_snap_to_0_range) {
            axis_pos = (event.joystickMove.position + joystick_axis_snap_to_0_range) * ((joystick_axis_snap_to_0_range / 100) + 1);
        } else {
            axis_pos = 0.0;
        }
        if (joystick_axis_pos[event.joystickMove.joystickId][event.joystickMove.axis] != axis_pos){
            joystick_axis_changed[event.joystickMove.joystickId][event.joystickMove.axis] = true;
        }
        joystick_axis_pos[event.joystickMove.joystickId][event.joystickMove.axis] = axis_pos;
    }
    else if (event.type == sf::Event::JoystickButtonPressed)
    {
        joystick_button_down[event.joystickMove.joystickId][event.joystickButton.button] = true;
        joystick_button_changed[event.joystickMove.joystickId][event.joystickButton.button] = true;
    }
    else if (event.type == sf::Event::JoystickButtonReleased)
    {
        joystick_button_down[event.joystickMove.joystickId][event.joystickButton.button] = false;
        joystick_button_changed[event.joystickMove.joystickId][event.joystickButton.button] = true;
    }
}

void InputHandler::postEventsUpdate()
{
    if (last_key_press.code != sf::Keyboard::Unknown)
    {
        InputHandler::fireKeyEvent(last_key_press, -1);
        last_key_press.code = sf::Keyboard::Unknown;
    }

#ifdef __ANDROID__
    if (sf::Touch::isDown(0))
    {
        mouse_position = realWindowPosToVirtual(sf::Touch::getPosition(0));
        if (!mouse_button_down[sf::Mouse::Left])
            mouse_button_pressed[sf::Mouse::Left] = true;
        mouse_button_down[sf::Mouse::Left] = true;
    }else{
        if (mouse_button_down[sf::Mouse::Left])
            mouse_button_released[sf::Mouse::Left] = true;
        mouse_button_down[sf::Mouse::Left] = false;
    }
#else
    mouse_position = realWindowPosToVirtual(sf::Mouse::getPosition(windowManager->window));
#endif
    mouse_position = mouse_transform.transformPoint(mouse_position);

    if (touch_screen)
    {
        bool any_button_down = false;
        for(unsigned int n=0; n<sf::Mouse::ButtonCount; n++)
            if (mouse_button_down[n] || mouse_button_released[n])
                any_button_down = true;
        if (!any_button_down)
        {
            mouse_position = sf::Vector2f(-1, -1);
        }
    }
    for(unsigned int i=0; i<sf::Joystick::Count; i++)
    {
        for(unsigned int n=0; n<sf::Joystick::AxisCount; n++)
        {
            if(joystick_axis_changed[i][n])
            {
                foreach(JoystickEventHandler, e, joystick_event_handlers)
                {
                    e->handleJoystickAxis(i, (sf::Joystick::Axis) n, joystick_axis_pos[i][n]);
                }
            }
        }
        for(unsigned int n=0; n<sf::Joystick::ButtonCount; n++)
        {
            if(joystick_button_changed[i][n])
            {
                foreach(JoystickEventHandler, e, joystick_event_handlers)
                {
                    e->handleJoystickButton(i, n, joystick_button_down[i][n]);
                }
            }
        }
    }
}

void InputHandler::setMousePos(sf::Vector2f position)
{
    if (!windowManager)
        windowManager = engine->getObject("windowManager");

    sf::Mouse::setPosition(virtualWindowPosToReal(position), windowManager->window);
    mouse_position = realWindowPosToVirtual(sf::Mouse::getPosition(windowManager->window));
}

void InputHandler::fireKeyEvent(sf::Event::KeyEvent key, int unicode)
{
    foreach(InputEventHandler, e, input_event_handlers)
    {
        e->handleKeyPress(key, unicode);
    }
}

sf::Vector2f InputHandler::realWindowPosToVirtual(sf::Vector2i position)
{
    sf::FloatRect viewport = windowManager->window.getView().getViewport();
    sf::Vector2f pos = sf::Vector2f(position);

    pos.x -= viewport.left * float(windowManager->window.getSize().x);
    pos.y -= viewport.top * float(windowManager->window.getSize().y);
    pos.x *= float(windowManager->virtualSize.x) / float(windowManager->window.getSize().x) / viewport.width;
    pos.y *= float(windowManager->virtualSize.y) / float(windowManager->window.getSize().y) / viewport.height;
    return pos;
}

sf::Vector2i InputHandler::virtualWindowPosToReal(sf::Vector2f position)
{
    sf::FloatRect viewport = windowManager->window.getView().getViewport();

    position.x /= float(windowManager->virtualSize.x) / float(windowManager->window.getSize().x) / viewport.width;
    position.y /= float(windowManager->virtualSize.y) / float(windowManager->window.getSize().y) / viewport.height;

    position.x += viewport.left * float(windowManager->window.getSize().x);
    position.y += viewport.top * float(windowManager->window.getSize().y);
    return sf::Vector2i(position);
}
<|endoftext|>


<commit_before>#include <cstdio>
#include <vector>
#include <stack>
#include <algorithm>

using namespace std;

enum class Frog  { None, Brown, Green };
enum class Step  { None, JumpLeft, LeapLeft, JumpRight, LeapRight };

struct FrogsState
{
    size_t Count;
    vector<Frog> Lilies;
    int BlankPos;
    Step Movement;

    FrogsState(): Count(0), BlankPos(-1), Movement(Step::None) {}
    FrogsState(size_t count): Count(count), Lilies(2 * Count + 1), BlankPos(Count), Movement(Step::None)
    {
        for (auto i = 0; i < Count; i++)
        {
            Lilies[i] = Frog::Brown;
            Lilies[2 * Count - i] = Frog::Green;
        }

        Lilies[BlankPos] = Frog::None;
    }

    bool operator==(const FrogsState& other) const
    {
        return Count == other.Count && Lilies == other.Lilies && BlankPos == other.BlankPos;
    }

    bool IsStuckJumpLeft()  const  { return BlankPos >= Lilies.size() - 1 || Lilies[BlankPos + 1] != Frog::Green; }
    bool IsStuckLeapLeft()  const  { return BlankPos >= Lilies.size() - 2 || Lilies[BlankPos + 2] != Frog::Green; }
    bool IsStuckJumpRight() const  { return BlankPos < 1                  || Lilies[BlankPos - 1] != Frog::Brown; }
    bool IsStuckLeapRight() const  { return BlankPos < 2                  || Lilies[BlankPos - 2] != Frog::Brown; }

    bool WasTargetReached() const
    {
        for (auto i = 0; i < Count; i++)
            if (Lilies[i] != Frog::Green || Lilies[2 * Count - i] != Frog::Brown)
                return false;

        return Lilies[Count] == Frog::None;
    };

    void Print() const
    {
        for (auto frog: Lilies)
            switch (frog)
            {
                case Frog::Brown:
                    printf(">");
                    break;

                case Frog::Green:
                    printf("<");
                    break;

                case Frog::None:
                    printf(" ");
                    break;
            }

        printf("\n");
    }

    pair<bool, FrogsState> Move(Step movement) const
    {
        auto canMove = false;
        auto moved = *this;
        moved.Movement = movement;

        switch (movement)
        {
            case Step::JumpLeft:
                if (!IsStuckJumpLeft())
                {
                    moved.Lilies[moved.BlankPos] = Frog::Green;
                    moved.BlankPos++;
                    canMove = true;
                }
                break;

            case Step::LeapLeft:
                if (!IsStuckLeapLeft())
                {
                    moved.Lilies[moved.BlankPos] = Frog::Green;
                    moved.BlankPos += 2;
                    canMove = true;
                }
                break;

            case Step::JumpRight:
                if (!IsStuckJumpRight())
                {
                    moved.Lilies[moved.BlankPos] = Frog::Brown;
                    moved.BlankPos--;
                    canMove = true;
                }
                break;

            case Step::LeapRight:
                if (!IsStuckLeapRight())
                {
                    moved.Lilies[moved.BlankPos] = Frog::Brown;
                    moved.BlankPos -= 2;
                    canMove = true;
                }
                break;

            default:
                break;
        }

        if (canMove)
            moved.Lilies[moved.BlankPos] = Frog::None;
        return make_pair(canMove, moved);
    }

    bool UndoStep(Step prevMovement)
    {
        auto canUndoStep = false;

        switch (Movement)
        {
            case Step::JumpLeft:
                Lilies[BlankPos] = Frog::Green;
                BlankPos--;
                canUndoStep = true;
                break;

            case Step::LeapLeft:
                Lilies[BlankPos] = Frog::Green;
                BlankPos -= 2;
                canUndoStep = true;
                break;

            case Step::JumpRight:
                Lilies[BlankPos] = Frog::Brown;
                BlankPos++;
                canUndoStep = true;
                break;

            case Step::LeapRight:
                Lilies[BlankPos] = Frog::Brown;
                BlankPos += 2;
                canUndoStep = true;
                break;

            default:
                break;
        }

        if (canUndoStep)
        {
            Lilies[BlankPos] = Frog::None;
            Movement = prevMovement;
        }
        return canUndoStep;
    };
};

int main()
{
    unsigned int count;
    scanf_s("%u", &count);

    vector<FrogsState> visited;
    stack<FrogsState> trace;
    stack<Step> movements;
    trace.push(FrogsState(count));

    while (!trace.empty() && !trace.top().WasTargetReached())
    {
        auto state = trace.top();
        trace.pop();

        auto move = [&](Step movement)
        {
            auto newStateOptional = state.Move(movement);
            if (newStateOptional.first)
                trace.push(newStateOptional.second);
        };

        while (!movements.empty() && state.IsStuckJumpLeft() && state.IsStuckLeapLeft() && state.IsStuckJumpRight() && state.IsStuckLeapRight())
        {
            state.UndoStep(movements.top());
            movements.pop();
        }

        if (visited.crend() == find(visited.crbegin(), visited.crend(), state))
        {
            visited.push_back(state);
            movements.push(state.Movement);
            move(Step::JumpLeft);
            move(Step::LeapLeft);
            move(Step::JumpRight);
            move(Step::LeapRight);

            state.Print();
        }
    }

    if (!trace.empty())
        trace.top().Print();

    return 0;
}
<commit_msg>fix: forgot the Movement member in the equality operator for FrogsState<commit_after>#include <cstdio>
#include <vector>
#include <stack>
#include <algorithm>

using namespace std;

enum class Frog  { None, Brown, Green };
enum class Step  { None, JumpLeft, LeapLeft, JumpRight, LeapRight };

struct FrogsState
{
    size_t Count;
    vector<Frog> Lilies;
    int BlankPos;
    Step Movement;

    FrogsState(): Count(0), BlankPos(-1), Movement(Step::None) {}
    FrogsState(size_t count): Count(count), Lilies(2 * Count + 1), BlankPos(Count), Movement(Step::None)
    {
        for (auto i = 0; i < Count; i++)
        {
            Lilies[i] = Frog::Brown;
            Lilies[2 * Count - i] = Frog::Green;
        }

        Lilies[BlankPos] = Frog::None;
    }

    bool operator==(const FrogsState& other) const
    {
        return Count == other.Count && Lilies == other.Lilies && BlankPos == other.BlankPos && Movement == other.Movement;
    }

    bool IsStuckJumpLeft()  const  { return BlankPos >= Lilies.size() - 1 || Lilies[BlankPos + 1] != Frog::Green; }
    bool IsStuckLeapLeft()  const  { return BlankPos >= Lilies.size() - 2 || Lilies[BlankPos + 2] != Frog::Green; }
    bool IsStuckJumpRight() const  { return BlankPos < 1                  || Lilies[BlankPos - 1] != Frog::Brown; }
    bool IsStuckLeapRight() const  { return BlankPos < 2                  || Lilies[BlankPos - 2] != Frog::Brown; }

    bool WasTargetReached() const
    {
        for (auto i = 0; i < Count; i++)
            if (Lilies[i] != Frog::Green || Lilies[2 * Count - i] != Frog::Brown)
                return false;

        return Lilies[Count] == Frog::None;
    };

    void Print() const
    {
        for (auto frog: Lilies)
            switch (frog)
            {
                case Frog::Brown:
                    printf(">");
                    break;

                case Frog::Green:
                    printf("<");
                    break;

                case Frog::None:
                    printf(" ");
                    break;
            }

        printf("\n");
    }

    pair<bool, FrogsState> Move(Step movement) const
    {
        auto canMove = false;
        auto moved = *this;
        moved.Movement = movement;

        switch (movement)
        {
            case Step::JumpLeft:
                if (!IsStuckJumpLeft())
                {
                    moved.Lilies[moved.BlankPos] = Frog::Green;
                    moved.BlankPos++;
                    canMove = true;
                }
                break;

            case Step::LeapLeft:
                if (!IsStuckLeapLeft())
                {
                    moved.Lilies[moved.BlankPos] = Frog::Green;
                    moved.BlankPos += 2;
                    canMove = true;
                }
                break;

            case Step::JumpRight:
                if (!IsStuckJumpRight())
                {
                    moved.Lilies[moved.BlankPos] = Frog::Brown;
                    moved.BlankPos--;
                    canMove = true;
                }
                break;

            case Step::LeapRight:
                if (!IsStuckLeapRight())
                {
                    moved.Lilies[moved.BlankPos] = Frog::Brown;
                    moved.BlankPos -= 2;
                    canMove = true;
                }
                break;

            default:
                break;
        }

        if (canMove)
            moved.Lilies[moved.BlankPos] = Frog::None;
        return make_pair(canMove, moved);
    }

    bool UndoStep(Step prevMovement)
    {
        auto canUndoStep = false;

        switch (Movement)
        {
            case Step::JumpLeft:
                Lilies[BlankPos] = Frog::Green;
                BlankPos--;
                canUndoStep = true;
                break;

            case Step::LeapLeft:
                Lilies[BlankPos] = Frog::Green;
                BlankPos -= 2;
                canUndoStep = true;
                break;

            case Step::JumpRight:
                Lilies[BlankPos] = Frog::Brown;
                BlankPos++;
                canUndoStep = true;
                break;

            case Step::LeapRight:
                Lilies[BlankPos] = Frog::Brown;
                BlankPos += 2;
                canUndoStep = true;
                break;

            default:
                break;
        }

        if (canUndoStep)
        {
            Lilies[BlankPos] = Frog::None;
            Movement = prevMovement;
        }
        return canUndoStep;
    };
};

int main()
{
    unsigned int count;
    scanf_s("%u", &count);

    vector<FrogsState> visited;
    stack<FrogsState> trace;
    stack<Step> movements;
    trace.push(FrogsState(count));

    while (!trace.empty() && !trace.top().WasTargetReached())
    {
        auto state = trace.top();
        trace.pop();

        auto move = [&](Step movement)
        {
            auto newStateOptional = state.Move(movement);
            if (newStateOptional.first)
                trace.push(newStateOptional.second);
        };

        while (!movements.empty() && state.IsStuckJumpLeft() && state.IsStuckLeapLeft() && state.IsStuckJumpRight() && state.IsStuckLeapRight())
        {
            state.UndoStep(movements.top());
            movements.pop();
        }

        if (visited.crend() == find(visited.crbegin(), visited.crend(), state))
        {
            visited.push_back(state);
            movements.push(state.Movement);
            move(Step::JumpLeft);
            move(Step::LeapLeft);
            move(Step::JumpRight);
            move(Step::LeapRight);

            state.Print();
        }
    }

    if (!trace.empty())
        trace.top().Print();

    return 0;
}
<|endoftext|>


<commit_before>/*
 * PluginFramework.cpp
 *
 *  Created on: 21.06.2017
 *      Author: alwi0251
 */

#include "pluginFramework/impl/PluginFrameworkImpl.hpp"

#ifdef NDEBUG
  #define DEBUG_MESSAGE(a) /**/
#else
  #define DEBUG_MESSAGE(a) a
#endif

#define MAX_CHAR 260
typedef std::shared_ptr<MDE4CPPPlugin> (__stdcall *StartFunction)();

#include <iostream>
#include <dirent.h>

#ifdef __linux__

#elif defined(_WIN32)
	#include <windows.h>
#endif

#include "pluginFramework/MDE4CPPPlugin.hpp"

PluginFrameworkImpl::PluginFrameworkImpl()
{
	initialize();
}

PluginFrameworkImpl::~PluginFrameworkImpl()
{
	m_mapPluginName.clear();
	m_mapPluginUri.clear();
}

PluginFramework* PluginFrameworkImpl::create()
{
	return new PluginFrameworkImpl();
}

std::vector<std::string> PluginFrameworkImpl::findAllAvailableLibraries()
{
	char folderBuffer[MAX_CHAR];
	char nameBuffer[MAX_CHAR];

	m_debugMode = false;
#ifdef __linux__
	m_endingDebug = "d.so";
	m_endingRelease = ".so";
	m_endingString = "d";
	std::cerr << "PluginFrameworkImpl::findAllAvailableLibraries is not implemented for Linux systems!"
	return libraries;
#elif defined(_WIN32)
	GetCurrentDirectory(MAX_CHAR, folderBuffer);
	GetModuleFileName(NULL, nameBuffer, MAX_CHAR);
	m_endingDebug = "d.dll";
	m_endingRelease = ".dll";
	m_endingString = "d.exe";
#else
	std::cerr << "PluginFrameworkImpl::findAllAvailableLibraries is not implemented for this system!"
	return libraries;
#endif

	std::string fileName(nameBuffer);
	std::string folderName(folderBuffer);

	std::vector<std::string> libraries;
	if (fileName.length() >= m_endingString.length())
	{
		m_debugMode =  (0 == fileName.compare(fileName.length() - m_endingString.length(), m_endingString.length(), m_endingString));
	}

	DIR *dir;
	struct dirent *file;

#ifdef __linux__
	std::cerr << "PluginFrameworkImpl::findAllAvailableLibraries is not implemented for Linux systems!"
#elif defined(_WIN32)
	if((dir = opendir(folderBuffer)) != NULL)
	{
		while((file = readdir(dir)) != NULL)
		{
			std::string libName = checkLibrary(file, folderName);
			if (!libName.empty())
			{
				libraries.push_back(libName);
			}
		}
		closedir (dir);
	}
	else
	{
		std::cerr << "Could not open directory " << folderName << " failed" << std::endl;
	}
#else
	std::cerr << "PluginFrameworkImpl::findAllAvailableLibraries is not implemented for this system!"
#endif

	return libraries;
}

std::string PluginFrameworkImpl::checkLibrary(struct dirent* file, std::string folderName)
{
	std::string name(file->d_name);
	if(m_debugMode)
	{
		if(name.length() >= m_endingDebug.length())
		{
			if((0 == name.compare(name.length() - m_endingDebug.length(), m_endingDebug.length(), m_endingDebug)))
			{
				return folderName + "\\" + name;
			}
		}
	}
	else
	{
		if(name.length() >= m_endingRelease.length())
		{
			if((0 == name.compare(name.length() - m_endingRelease.length(), m_endingRelease.length(), m_endingRelease)))
			{
				if(name.length() >= m_endingDebug.length())
				{
					if((0 != name.compare(name.length() - m_endingDebug.length(), m_endingDebug.length(), m_endingDebug)))
					{
						return folderName + "\\" + name;
					}
				}
			}
		}
	}
	return "";
}

void PluginFrameworkImpl::initialize()
{
	std::vector<std::string> libraries = findAllAvailableLibraries();

	for (std::string libraryPath : libraries)
	{
		loadLibrary(libraryPath);
	}
}

void PluginFrameworkImpl::loadLibrary(std::string libraryPath)
{
	HINSTANCE hGetProcIDDLL = LoadLibrary(libraryPath.c_str());
	if(!hGetProcIDDLL)
	{
		std::cerr << "could not load the dynamic library, ErrorCode: " << GetLastError() << std::endl;
		return;
	}

	StartFunction startFunction = (StartFunction) GetProcAddress(hGetProcIDDLL, "_Z5startv");
	if(!startFunction)
	{
		DEBUG_MESSAGE(std::cout << "Could not locate the start function 'std::shared_ptr<MDE4CPPPlugin> start()' in library " << libraryPath << std::endl;)
	}
	else
	{
		std::shared_ptr<MDE4CPPPlugin> plugin = startFunction();
		m_mapPluginName.insert(std::pair<std::string, std::shared_ptr<MDE4CPPPlugin>>(plugin->eNAME(), plugin));
		m_mapPluginUri.insert(std::pair<std::string, std::shared_ptr<MDE4CPPPlugin>>(plugin->eNS_URI(), plugin));
		std::string eclipseURI = plugin->eclipseURI();
		if (!eclipseURI.empty())
		{
			m_mapPluginUri.insert(std::pair<std::string, std::shared_ptr<MDE4CPPPlugin>>(eclipseURI, plugin));
		}

		DEBUG_MESSAGE(std::cout << "library " << plugin << " started" << std::endl;)
	}
}

void PluginFrameworkImpl::clear()
{
	m_mapPluginName.clear();
	m_mapPluginUri.clear();
}

std::shared_ptr<MDE4CPPPlugin> PluginFrameworkImpl::findPluginByName(const std::string name) const
{
	std::map<std::string, std::shared_ptr<MDE4CPPPlugin>>::const_iterator iter = m_mapPluginName.find(name);

	std::shared_ptr<MDE4CPPPlugin> pluginObject;
	if(iter != m_mapPluginName.end())
	{
		return iter->second;
	}

	return nullptr;
}

std::shared_ptr<MDE4CPPPlugin> PluginFrameworkImpl::findPluginByUri(const std::string uri) const
{
	std::map<std::string, std::shared_ptr<MDE4CPPPlugin>>::const_iterator iter = m_mapPluginUri.find(uri);

	std::shared_ptr<MDE4CPPPlugin> pluginObject;
	if(iter != m_mapPluginUri.end())
	{
		return iter->second;
	}

	return nullptr;
}

<commit_msg>[PluginFramework] add missing ";", define variable libraries on top of function findAllAvailableLibraries<commit_after>/*
 * PluginFramework.cpp
 *
 *  Created on: 21.06.2017
 *      Author: alwi0251
 */

#include "pluginFramework/impl/PluginFrameworkImpl.hpp"

#ifdef NDEBUG
  #define DEBUG_MESSAGE(a) /**/
#else
  #define DEBUG_MESSAGE(a) a
#endif

#define MAX_CHAR 260
typedef std::shared_ptr<MDE4CPPPlugin> (__stdcall *StartFunction)();

#include <iostream>
#include <dirent.h>

#ifdef __linux__

#elif defined(_WIN32)
	#include <windows.h>
#endif

#include "pluginFramework/MDE4CPPPlugin.hpp"

PluginFrameworkImpl::PluginFrameworkImpl()
{
	initialize();
}

PluginFrameworkImpl::~PluginFrameworkImpl()
{
	m_mapPluginName.clear();
	m_mapPluginUri.clear();
}

PluginFramework* PluginFrameworkImpl::create()
{
	return new PluginFrameworkImpl();
}

std::vector<std::string> PluginFrameworkImpl::findAllAvailableLibraries()
{
	char folderBuffer[MAX_CHAR];
	char nameBuffer[MAX_CHAR];
	std::vector<std::string> libraries;

	m_debugMode = false;
#ifdef __linux__
	m_endingDebug = "d.so";
	m_endingRelease = ".so";
	m_endingString = "d";
	std::cerr << "PluginFrameworkImpl::findAllAvailableLibraries is not implemented for Linux systems!";
	return libraries;
#elif defined(_WIN32)
	GetCurrentDirectory(MAX_CHAR, folderBuffer);
	GetModuleFileName(NULL, nameBuffer, MAX_CHAR);
	m_endingDebug = "d.dll";
	m_endingRelease = ".dll";
	m_endingString = "d.exe";
#else
	std::cerr << "PluginFrameworkImpl::findAllAvailableLibraries is not implemented for this system!";
	return libraries;
#endif

	std::string fileName(nameBuffer);
	std::string folderName(folderBuffer);

	if (fileName.length() >= m_endingString.length())
	{
		m_debugMode =  (0 == fileName.compare(fileName.length() - m_endingString.length(), m_endingString.length(), m_endingString));
	}

	DIR *dir;
	struct dirent *file;

#ifdef __linux__
	std::cerr << "PluginFrameworkImpl::findAllAvailableLibraries is not implemented for Linux systems!";
#elif defined(_WIN32)
	if((dir = opendir(folderBuffer)) != NULL)
	{
		while((file = readdir(dir)) != NULL)
		{
			std::string libName = checkLibrary(file, folderName);
			if (!libName.empty())
			{
				libraries.push_back(libName);
			}
		}
		closedir (dir);
	}
	else
	{
		std::cerr << "Could not open directory " << folderName << " failed" << std::endl;
	}
#else
	std::cerr << "PluginFrameworkImpl::findAllAvailableLibraries is not implemented for this system!";
#endif

	return libraries;
}

std::string PluginFrameworkImpl::checkLibrary(struct dirent* file, std::string folderName)
{
	std::string name(file->d_name);
	if(m_debugMode)
	{
		if(name.length() >= m_endingDebug.length())
		{
			if((0 == name.compare(name.length() - m_endingDebug.length(), m_endingDebug.length(), m_endingDebug)))
			{
				return folderName + "\\" + name;
			}
		}
	}
	else
	{
		if(name.length() >= m_endingRelease.length())
		{
			if((0 == name.compare(name.length() - m_endingRelease.length(), m_endingRelease.length(), m_endingRelease)))
			{
				if(name.length() >= m_endingDebug.length())
				{
					if((0 != name.compare(name.length() - m_endingDebug.length(), m_endingDebug.length(), m_endingDebug)))
					{
						return folderName + "\\" + name;
					}
				}
			}
		}
	}
	return "";
}

void PluginFrameworkImpl::initialize()
{
	std::vector<std::string> libraries = findAllAvailableLibraries();

	for (std::string libraryPath : libraries)
	{
		loadLibrary(libraryPath);
	}
}

void PluginFrameworkImpl::loadLibrary(std::string libraryPath)
{
	HINSTANCE hGetProcIDDLL = LoadLibrary(libraryPath.c_str());
	if(!hGetProcIDDLL)
	{
		std::cerr << "could not load the dynamic library, ErrorCode: " << GetLastError() << std::endl;
		return;
	}

	StartFunction startFunction = (StartFunction) GetProcAddress(hGetProcIDDLL, "_Z5startv");
	if(!startFunction)
	{
		DEBUG_MESSAGE(std::cout << "Could not locate the start function 'std::shared_ptr<MDE4CPPPlugin> start()' in library " << libraryPath << std::endl;)
	}
	else
	{
		std::shared_ptr<MDE4CPPPlugin> plugin = startFunction();
		m_mapPluginName.insert(std::pair<std::string, std::shared_ptr<MDE4CPPPlugin>>(plugin->eNAME(), plugin));
		m_mapPluginUri.insert(std::pair<std::string, std::shared_ptr<MDE4CPPPlugin>>(plugin->eNS_URI(), plugin));
		std::string eclipseURI = plugin->eclipseURI();
		if (!eclipseURI.empty())
		{
			m_mapPluginUri.insert(std::pair<std::string, std::shared_ptr<MDE4CPPPlugin>>(eclipseURI, plugin));
		}

		DEBUG_MESSAGE(std::cout << "library " << plugin << " started" << std::endl;)
	}
}

void PluginFrameworkImpl::clear()
{
	m_mapPluginName.clear();
	m_mapPluginUri.clear();
}

std::shared_ptr<MDE4CPPPlugin> PluginFrameworkImpl::findPluginByName(const std::string name) const
{
	std::map<std::string, std::shared_ptr<MDE4CPPPlugin>>::const_iterator iter = m_mapPluginName.find(name);

	std::shared_ptr<MDE4CPPPlugin> pluginObject;
	if(iter != m_mapPluginName.end())
	{
		return iter->second;
	}

	return nullptr;
}

std::shared_ptr<MDE4CPPPlugin> PluginFrameworkImpl::findPluginByUri(const std::string uri) const
{
	std::map<std::string, std::shared_ptr<MDE4CPPPlugin>>::const_iterator iter = m_mapPluginUri.find(uri);

	std::shared_ptr<MDE4CPPPlugin> pluginObject;
	if(iter != m_mapPluginUri.end())
	{
		return iter->second;
	}

	return nullptr;
}

<|endoftext|>


<commit_before>/* Copyright 2007-2015 QReal Research Group
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. */

#include "kitBase/devicesConfigurationWidget.h"

#include <QtWidgets/QBoxLayout>
#include <QtWidgets/QComboBox>
#include <QtWidgets/QLabel>

#include "kitBase/robotModel/robotModelInterface.h"

using namespace kitBase;
using namespace robotModel;

DevicesConfigurationWidget::DevicesConfigurationWidget(QWidget *parent, bool autosaveMode, bool compactMode)
	: QScrollArea(parent)
	, mAutosaveMode(autosaveMode)
	, mCompactMode(compactMode)
	, mSaving(false)
	, mRefreshing(false)
{
	setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
	setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
	setMinimumHeight(125);
	setFrameShape(QFrame::NoFrame);

	setWidgetResizable(true);
	QPalette palette = this->palette();
	palette.setColor(QPalette::Background, Qt::transparent);
	setPalette(palette);
}

void DevicesConfigurationWidget::loadRobotModels(QList<RobotModelInterface *> const &models)
{
	for (RobotModelInterface * const model : models) {
		const QString name = model->name();
		mRobotModels[name] = model;
		QWidget * const configurer = configurerForRobotModel(*model);
		mRobotModelConfigurers[name] = configurer;
	}
}

void DevicesConfigurationWidget::selectRobotModel(RobotModelInterface &robotModel)
{
	mCurrentModelType = robotModel.name();
	mCurrentModelId = robotModel.robotId();
	takeWidget();
	if (mRobotModels.contains(mCurrentModelType)) {
		setWidget(mRobotModelConfigurers[mCurrentModelType]);
		refresh();
	}
}

void DevicesConfigurationWidget::prependCustomWidget(RobotModelInterface &robotModel, QWidget * const widget)
{
	if (!widget) {
		return;
	}

	Q_ASSERT(mRobotModelConfigurers.contains(robotModel.name()));
	QVBoxLayout *layout = dynamic_cast<QVBoxLayout *>(mRobotModelConfigurers[robotModel.name()]->layout());
	Q_ASSERT(layout);
	layout->insertWidget(0, widget);
}

QWidget *DevicesConfigurationWidget::configurerForRobotModel(RobotModelInterface &robotModel)
{
	/// @todo: What if robot model has no configurable sensors?
	QWidget *result = new QWidget;
	QPalette palette = result->palette();
	palette.setColor(QPalette::Background, Qt::transparent);
	result->setPalette(palette);
	QVBoxLayout * const layout = new QVBoxLayout(result);
	layout->setContentsMargins(0, 0, 0, 0);
	QList<PortInfo> const configurablePorts = robotModel.configurablePorts();
	for (const PortInfo &port : configurablePorts) {
		layout->addLayout(initPort(robotModel.name(), port, robotModel.allowedDevices(port)));
	}

	return result;
}

QLayout *DevicesConfigurationWidget::initPort(const QString &robotModel
		, const PortInfo &port, QList<DeviceInfo> const &sensors)
{
	const QString labelText = mCompactMode ? tr("%1:") : tr("Port %1:");
	QLabel * const portLabel = new QLabel(labelText.arg(port.userFriendlyName()), this);
	QComboBox * const comboBox = new QComboBox(this);
	comboBox->setSizeAdjustPolicy(QComboBox::AdjustToMinimumContentsLengthWithIcon);
	comboBox->setProperty("robotModel", robotModel);
	comboBox->setProperty("port", QVariant::fromValue(port));
	mConfigurers << comboBox;
	comboBox->addItem(tr("Unused"), QVariant::fromValue(DeviceInfo()));
	for (const DeviceInfo &sensor : sensors) {
		comboBox->addItem(sensor.friendlyName(), QVariant::fromValue(sensor));
	}

	if (mAutosaveMode) {
		connect(comboBox, &QComboBox::currentTextChanged, this, &DevicesConfigurationWidget::save);
	}

	QHBoxLayout * const layout = new QHBoxLayout;
	layout->addWidget(portLabel);
	layout->addWidget(comboBox);
	layout->setStretch(0, 0);
	layout->setStretch(1, 1);

	return layout;
}

void DevicesConfigurationWidget::onDeviceConfigurationChanged(const QString &robotModel
		, const PortInfo &port, const DeviceInfo &sensor, Reason reason)
{
	Q_UNUSED(port)
	Q_UNUSED(sensor)
	Q_UNUSED(reason)

	// This method can be called when we did not accomplish processing all combo boxes during saving.
	// So ignoring such case.
	if (!mSaving && robotModel == mCurrentModelId) {
		refresh();
	}
}

void DevicesConfigurationWidget::refresh()
{
	mRefreshing = true;
	for (QComboBox * const box : mConfigurers) {
		const PortInfo port = box->property("port").value<PortInfo>();
		const DeviceInfo device = currentConfiguration(mCurrentModelId, port);
		if (device.isNull()) {
			box->setCurrentIndex(0);
		} else {
			for (int index = 0; index < box->count(); ++index) {
				if (box->itemData(index).value<DeviceInfo>().isA(device)) {
					box->setCurrentIndex(index);
					break;
				}
			}
		}
	}

	mRefreshing = false;
}

void DevicesConfigurationWidget::save()
{
	// Refreshing may affect combobox current index. No saving is needed then.
	if (mRefreshing) {
		return;
	}

	mSaving = true;
	for (QComboBox * const box : mConfigurers) {
		if (!box->isVisible()) {
			continue;
		}

		const QString robotModel = box->property("robotModel").toString();
		const PortInfo port = box->property("port").value<PortInfo>();
		const DeviceInfo device = box->itemData(box->currentIndex()).value<DeviceInfo>();
		if (robotModel == mCurrentModelType && currentConfiguration(mCurrentModelId, port) != device) {
			propagateChanges(port, device);
		}
	}

	mSaving = false;
}

void DevicesConfigurationWidget::propagateChanges(const PortInfo &port, const DeviceInfo &sensor)
{
	for (const QString &robotModelType : mRobotModels.keys()) {
		const RobotModelInterface *robotModel = mRobotModels[robotModelType];
		for (const PortInfo &otherPort : robotModel->configurablePorts()) {
			if (areConvertible(port, otherPort)) {
				if (sensor.isNull()) {
					deviceConfigurationChanged(robotModel->robotId(), otherPort, DeviceInfo(), Reason::userAction);
				} else {
					const DeviceInfo otherDevice = convertibleDevice(robotModel, otherPort, sensor);
					if (!otherDevice.isNull()) {
						deviceConfigurationChanged(robotModel->robotId(), otherPort, otherDevice, Reason::userAction);
					}
				}
			}
		}
	}
}

bool DevicesConfigurationWidget::areConvertible(const PortInfo &port1, const PortInfo &port2) const
{
	return (port1.name() == port2.name()
			|| port1.nameAliases().contains(port2.name())
			|| port2.nameAliases().contains(port1.name()))
			&& port1.direction() == port2.direction();
}

DeviceInfo DevicesConfigurationWidget::convertibleDevice(const RobotModelInterface *robotModel
		, const PortInfo &port, const DeviceInfo &device) const
{
	QList<DeviceInfo> const convertibleBases = robotModel->convertibleBases();
	for (const DeviceInfo &allowedDevice : robotModel->allowedDevices(port)) {
		for (const DeviceInfo &convertibleBase : convertibleBases) {
			if (device.isA(convertibleBase) && allowedDevice.isA(convertibleBase)) {
				return allowedDevice;
			}
		}
	}

	return DeviceInfo();
}
<commit_msg>Fixed sensors configurers background in 2D model<commit_after>/* Copyright 2007-2015 QReal Research Group
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. */

#include "kitBase/devicesConfigurationWidget.h"

#include <QtWidgets/QBoxLayout>
#include <QtWidgets/QComboBox>
#include <QtWidgets/QLabel>

#include "kitBase/robotModel/robotModelInterface.h"

using namespace kitBase;
using namespace robotModel;

DevicesConfigurationWidget::DevicesConfigurationWidget(QWidget *parent, bool autosaveMode, bool compactMode)
	: QScrollArea(parent)
	, mAutosaveMode(autosaveMode)
	, mCompactMode(compactMode)
	, mSaving(false)
	, mRefreshing(false)
{
	setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
	setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
	setMinimumHeight(125);
	setFrameShape(QFrame::NoFrame);

	setWidgetResizable(true);
	QPalette palette = this->palette();
	palette.setColor(QPalette::Background, Qt::transparent);
	setPalette(palette);
}

void DevicesConfigurationWidget::loadRobotModels(QList<RobotModelInterface *> const &models)
{
	for (RobotModelInterface * const model : models) {
		const QString name = model->name();
		mRobotModels[name] = model;
		QWidget * const configurer = configurerForRobotModel(*model);
		mRobotModelConfigurers[name] = configurer;
	}
}

void DevicesConfigurationWidget::selectRobotModel(RobotModelInterface &robotModel)
{
	mCurrentModelType = robotModel.name();
	mCurrentModelId = robotModel.robotId();
	takeWidget();
	if (mRobotModels.contains(mCurrentModelType)) {
		setWidget(mRobotModelConfigurers[mCurrentModelType]);
		refresh();
	}
}

void DevicesConfigurationWidget::prependCustomWidget(RobotModelInterface &robotModel, QWidget * const widget)
{
	if (!widget) {
		return;
	}

	Q_ASSERT(mRobotModelConfigurers.contains(robotModel.name()));
	QVBoxLayout *layout = dynamic_cast<QVBoxLayout *>(mRobotModelConfigurers[robotModel.name()]->layout());
	Q_ASSERT(layout);
	layout->insertWidget(0, widget);
}

QWidget *DevicesConfigurationWidget::configurerForRobotModel(RobotModelInterface &robotModel)
{
	/// @todo: What if robot model has no configurable sensors?
	QWidget *result = new QWidget;
	QPalette palette = result->palette();
	palette.setColor(QPalette::Background, Qt::transparent);
	result->setPalette(palette);
	QVBoxLayout * const layout = new QVBoxLayout(result);
	layout->setContentsMargins(0, 0, 0, 0);
	QList<PortInfo> const configurablePorts = robotModel.configurablePorts();
	for (const PortInfo &port : configurablePorts) {
		layout->addLayout(initPort(robotModel.name(), port, robotModel.allowedDevices(port)));
	}

	return result;
}

QLayout *DevicesConfigurationWidget::initPort(const QString &robotModel
		, const PortInfo &port, QList<DeviceInfo> const &sensors)
{
	const QString labelText = mCompactMode ? tr("%1:") : tr("Port %1:");
	QLabel * const portLabel = new QLabel(labelText.arg(port.userFriendlyName()), this);
	QComboBox * const comboBox = new QComboBox(this);
	QPalette palette = comboBox->palette();
	palette.setColor(QPalette::Base, Qt::white);
	comboBox->setPalette(Qt::white);
	comboBox->setSizeAdjustPolicy(QComboBox::AdjustToMinimumContentsLengthWithIcon);
	comboBox->setProperty("robotModel", robotModel);
	comboBox->setProperty("port", QVariant::fromValue(port));
	mConfigurers << comboBox;
	comboBox->addItem(tr("Unused"), QVariant::fromValue(DeviceInfo()));
	for (const DeviceInfo &sensor : sensors) {
		comboBox->addItem(sensor.friendlyName(), QVariant::fromValue(sensor));
	}

	if (mAutosaveMode) {
		connect(comboBox, &QComboBox::currentTextChanged, this, &DevicesConfigurationWidget::save);
	}

	QHBoxLayout * const layout = new QHBoxLayout;
	layout->addWidget(portLabel);
	layout->addWidget(comboBox);
	layout->setStretch(0, 0);
	layout->setStretch(1, 1);

	return layout;
}

void DevicesConfigurationWidget::onDeviceConfigurationChanged(const QString &robotModel
		, const PortInfo &port, const DeviceInfo &sensor, Reason reason)
{
	Q_UNUSED(port)
	Q_UNUSED(sensor)
	Q_UNUSED(reason)

	// This method can be called when we did not accomplish processing all combo boxes during saving.
	// So ignoring such case.
	if (!mSaving && robotModel == mCurrentModelId) {
		refresh();
	}
}

void DevicesConfigurationWidget::refresh()
{
	mRefreshing = true;
	for (QComboBox * const box : mConfigurers) {
		const PortInfo port = box->property("port").value<PortInfo>();
		const DeviceInfo device = currentConfiguration(mCurrentModelId, port);
		if (device.isNull()) {
			box->setCurrentIndex(0);
		} else {
			for (int index = 0; index < box->count(); ++index) {
				if (box->itemData(index).value<DeviceInfo>().isA(device)) {
					box->setCurrentIndex(index);
					break;
				}
			}
		}
	}

	mRefreshing = false;
}

void DevicesConfigurationWidget::save()
{
	// Refreshing may affect combobox current index. No saving is needed then.
	if (mRefreshing) {
		return;
	}

	mSaving = true;
	for (QComboBox * const box : mConfigurers) {
		if (!box->isVisible()) {
			continue;
		}

		const QString robotModel = box->property("robotModel").toString();
		const PortInfo port = box->property("port").value<PortInfo>();
		const DeviceInfo device = box->itemData(box->currentIndex()).value<DeviceInfo>();
		if (robotModel == mCurrentModelType && currentConfiguration(mCurrentModelId, port) != device) {
			propagateChanges(port, device);
		}
	}

	mSaving = false;
}

void DevicesConfigurationWidget::propagateChanges(const PortInfo &port, const DeviceInfo &sensor)
{
	for (const QString &robotModelType : mRobotModels.keys()) {
		const RobotModelInterface *robotModel = mRobotModels[robotModelType];
		for (const PortInfo &otherPort : robotModel->configurablePorts()) {
			if (areConvertible(port, otherPort)) {
				if (sensor.isNull()) {
					deviceConfigurationChanged(robotModel->robotId(), otherPort, DeviceInfo(), Reason::userAction);
				} else {
					const DeviceInfo otherDevice = convertibleDevice(robotModel, otherPort, sensor);
					if (!otherDevice.isNull()) {
						deviceConfigurationChanged(robotModel->robotId(), otherPort, otherDevice, Reason::userAction);
					}
				}
			}
		}
	}
}

bool DevicesConfigurationWidget::areConvertible(const PortInfo &port1, const PortInfo &port2) const
{
	return (port1.name() == port2.name()
			|| port1.nameAliases().contains(port2.name())
			|| port2.nameAliases().contains(port1.name()))
			&& port1.direction() == port2.direction();
}

DeviceInfo DevicesConfigurationWidget::convertibleDevice(const RobotModelInterface *robotModel
		, const PortInfo &port, const DeviceInfo &device) const
{
	QList<DeviceInfo> const convertibleBases = robotModel->convertibleBases();
	for (const DeviceInfo &allowedDevice : robotModel->allowedDevices(port)) {
		for (const DeviceInfo &convertibleBase : convertibleBases) {
			if (device.isA(convertibleBase) && allowedDevice.isA(convertibleBase)) {
				return allowedDevice;
			}
		}
	}

	return DeviceInfo();
}
<|endoftext|>


<commit_before>// @(#)root/qtgsi:$Id$
// Author: Denis Bertini, M. Al-Turany  01/11/2000

/*************************************************************************
 * Copyright (C) 1995-2006, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include "Riostream.h"
#include "qevent.h"
#include "qdialog.h"
#include "qpushbutton.h"
#include "qlabel.h"
#include "qpainter.h"
#if  (QT_VERSION > 0x039999) // Added by cholm@nbi.dk - for Qt 4
# include "qmenu.h"
# include "q3popupmenu.h"
typedef Q3PopupMenu QPopupMenu;
#else
# include "qpopupmenu.h"
#endif

#include "TQCanvasMenu.h"
#include "TClass.h"
#include "TROOT.h"
#include "TMethod.h"
#include "TMethodCall.h"
#include "TMethodArg.h"
#include "TCanvas.h"
#include "TDataType.h"
#include "TQRootDialog.h"

ClassImp(TQCanvasMenu)

//______________________________________________________________________________
TQCanvasMenu::TQCanvasMenu(QWidget* parent, TCanvas *canvas)
{
   // ctor, create the popup menu

   fc       = canvas;
   fPopup   = new QPopupMenu;
   fCurrObj = 0;
   fParent  = parent;
   fTabWin  = 0;
   fDialog  = 0;
   fMousePosX = fMousePosY = 0;
}

//______________________________________________________________________________
TQCanvasMenu::TQCanvasMenu(QWidget* parent, QWidget *tabWin, TCanvas *canvas)
{
   // ctor, create the popup menu

   fc       = canvas;
   fPopup   = new QPopupMenu;
   fParent  = parent;
   fTabWin  = tabWin;
   fCurrObj = 0;
   fDialog  = 0;
   fMousePosX = fMousePosY = 0;
}

//______________________________________________________________________________
TQCanvasMenu::~TQCanvasMenu()
{
   // dtor

   if (fPopup) delete fPopup;
}

//______________________________________________________________________________
char *TQCanvasMenu::CreateDialogTitle( TObject *object, TMethod *method )
{
   // Create title for dialog box retrieving argument values.

   static char methodTitle[128];

   if (object && method)
      snprintf(methodTitle, 127, "%s::%s", object->ClassName(), method->GetName());
   else
      *methodTitle = 0;
   return methodTitle;

}

//______________________________________________________________________________
char *TQCanvasMenu::CreateArgumentTitle(TMethodArg *argument)
{
   // Create string describing argument (for use in dialog box).

   static Char_t argTitle[128];
   if (argument) {
      snprintf(argTitle, 127, "(%s)  %s", argument->GetTitle(), argument->GetName());
      const char *arg_def = argument->GetDefault();
      if (arg_def && *arg_def) {
         strncat(argTitle, "  [default: ", 127 - strlen(argTitle));
         strncat(argTitle, arg_def, 127 - strlen(argTitle));
         strncat(argTitle, "]", 127 - strlen(argTitle));
      }
   }
   else
      *argTitle = 0;

   return argTitle;
}

//______________________________________________________________________________
void TQCanvasMenu::Popup(TObject *obj, double x, double y, QMouseEvent *e)
{
   // Perform the corresponding selected TObject  popup
   // in the position defined
   // by x, y coordinates (in user coordinate system).
   // @param obj (TObject*)
   // @param p (QPoint&)

   TClass *klass=obj->IsA();
   Int_t curId=-1;

   fCurrObj=obj;
   fPopup->clear();
   fMethods.Clear();

   QString buffer=klass->GetName();
   buffer+="::";
   buffer+=obj->GetName();
   fPopup->insertItem(buffer, this, SLOT( Execute(int) ), 0,curId); curId++;
   klass->GetMenuItems(&fMethods);
   fPopup->insertSeparator();
   TIter iter(&fMethods);
   TMethod *method=0;
   while ( (method = dynamic_cast<TMethod*>(iter())) != 0) {
      buffer=method->GetName();
      fPopup->insertItem(buffer, this, SLOT( Execute(int) ), 0,curId);
      curId++;
   }
   // hold the position where the mouse was clicked
   fMousePosX= x;
   fMousePosY= y;

   // let Qt decide how to draw the popup Menu otherwise we have a problem that
   // the visible rectangle can get outside the screen (M.T. 03.06.02)
   fPopup->popup(e->globalPos(), 0);

}

//______________________________________________________________________________
void TQCanvasMenu::Execute(int id)
{
   // Slot defined to execute a method from a selected TObject
   // using TObject::Execute() function.

   QString text="";

   TVirtualPad  *psave = gROOT->GetSelectedPad();
   TMethod *method=(TMethod *)fMethods.At(id);
   fc->HandleInput(kButton3Up,gPad->XtoAbsPixel(fMousePosX), gPad->YtoAbsPixel(fMousePosY) );
   if (  method->GetListOfMethodArgs()->First() ) {
      Dialog(fCurrObj,method);
   }
   else {
      gROOT->SetFromPopUp(kTRUE);
      fCurrObj->Execute((char *) method->GetName(), "");
   }
   fc->GetPadSave()->Update();
   fc->GetPadSave()->Modified();
   gROOT->SetSelectedPad(psave);
   gROOT->GetSelectedPad()->Update();
   gROOT->GetSelectedPad()->Modified();
   fc->Modified();
   fc->ForceUpdate();
   gROOT->SetFromPopUp( kFALSE );
}

//______________________________________________________________________________
void TQCanvasMenu::Dialog(TObject* object, TMethod* method)
{
   // Create dialog object with OK and Cancel buttons. This dialog
   // prompts for the arguments of "method".

   if (!(object && method)) return;
   fDialog = new TQRootDialog(fParent,CreateDialogTitle(object, method),0,object ,method);
   fDialog->SetTCanvas(fc);
   // iterate through all arguments and create apropriate input-data objects:
   // inputlines, option menus...
   TMethodArg *argument = 0;
   TIter next(method->GetListOfMethodArgs());
   while ((argument = (TMethodArg *) next())) {
      char       *argname    = CreateArgumentTitle(argument);
      const char *type       = argument->GetTypeName();
      TDataType    *datatype   = gROOT->GetType(type);
      const char *charstar   = "char*";
      char        basictype [32];

      if (datatype) {
         strlcpy(basictype, datatype->GetTypeName(),32);
      }
      else {
         if (strncmp(type, "enum", 4) != 0)
         cout << "*** Warning in Dialog(): data type is not basic type, assuming (int)\n";
         strcpy(basictype, "int");
      }

      if (strchr(argname, '*')) {
         strcat(basictype, "*");
         type = charstar;
      }

      TDataMember *m = argument->GetDataMember();
      if (m && m->GetterMethod()) {
         char gettername[256] = "";
         strlcpy(gettername, m->GetterMethod()->GetMethodName(),256);
         m->GetterMethod()->Init(object->IsA(), gettername, "");
         // Get the current value and form it as a text:
         char val[256];
         if (!strncmp(basictype, "char*", 5)) {
            char *tdefval;
            m->GetterMethod()->Execute(object, "", &tdefval);
            strlcpy(val, tdefval, 256);
         }
         else if (!strncmp(basictype, "float", 5) ||
            !strncmp(basictype, "double", 6)) {
            Double_t ddefval;
            m->GetterMethod()->Execute(object, "", ddefval);
            snprintf(val, 255, "%g", ddefval);
         }
         else if (!strncmp(basictype, "char", 4) ||
             !strncmp(basictype, "int", 3)  ||
             !strncmp(basictype, "long", 4) ||
             !strncmp(basictype, "short", 5)) {
            Long_t ldefval;
            m->GetterMethod()->Execute(object, "", ldefval);
            snprintf(val, 255, "%li", ldefval);
         }
         // Find out whether we have options ...
         TList *opt;
         if ((opt = m->GetOptions())) {
            cout << "*** Warning in Dialog(): option menu not yet implemented " << opt << endl;
            // should stop dialog
            return;
         }
         else {
            // we haven't got options - textfield ...
            fDialog->Add(argname, val, type);
         }
      }
      else {    // if m not found ...
         char val[256] = "";
         const char *tval = argument->GetDefault();
         if (tval) strlcpy(val, tval, 256);
         fDialog->Add(argname, val, type);
      }
   } //end while

   fDialog->Popup();
}
<commit_msg>Fix coverity reports #32499 & #32500 (uninitialized scalar variables)<commit_after>// @(#)root/qtgsi:$Id$
// Author: Denis Bertini, M. Al-Turany  01/11/2000

/*************************************************************************
 * Copyright (C) 1995-2006, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include "Riostream.h"
#include "qevent.h"
#include "qdialog.h"
#include "qpushbutton.h"
#include "qlabel.h"
#include "qpainter.h"
#if  (QT_VERSION > 0x039999) // Added by cholm@nbi.dk - for Qt 4
# include "qmenu.h"
# include "q3popupmenu.h"
typedef Q3PopupMenu QPopupMenu;
#else
# include "qpopupmenu.h"
#endif

#include "TQCanvasMenu.h"
#include "TClass.h"
#include "TROOT.h"
#include "TMethod.h"
#include "TMethodCall.h"
#include "TMethodArg.h"
#include "TCanvas.h"
#include "TDataType.h"
#include "TQRootDialog.h"

ClassImp(TQCanvasMenu)

//______________________________________________________________________________
TQCanvasMenu::TQCanvasMenu(QWidget* parent, TCanvas *canvas)
{
   // ctor, create the popup menu

   fc       = canvas;
   fPopup   = new QPopupMenu;
   fCurrObj = 0;
   fParent  = parent;
   fTabWin  = 0;
   fDialog  = 0;
   fMousePosX = fMousePosY = 0;
}

//______________________________________________________________________________
TQCanvasMenu::TQCanvasMenu(QWidget* parent, QWidget *tabWin, TCanvas *canvas)
{
   // ctor, create the popup menu

   fc       = canvas;
   fPopup   = new QPopupMenu;
   fParent  = parent;
   fTabWin  = tabWin;
   fCurrObj = 0;
   fDialog  = 0;
   fMousePosX = fMousePosY = 0;
}

//______________________________________________________________________________
TQCanvasMenu::~TQCanvasMenu()
{
   // dtor

   if (fPopup) delete fPopup;
}

//______________________________________________________________________________
char *TQCanvasMenu::CreateDialogTitle( TObject *object, TMethod *method )
{
   // Create title for dialog box retrieving argument values.

   static char methodTitle[128];

   if (object && method)
      snprintf(methodTitle, 127, "%s::%s", object->ClassName(), method->GetName());
   else
      *methodTitle = 0;
   return methodTitle;

}

//______________________________________________________________________________
char *TQCanvasMenu::CreateArgumentTitle(TMethodArg *argument)
{
   // Create string describing argument (for use in dialog box).

   static Char_t argTitle[128];
   if (argument) {
      snprintf(argTitle, 127, "(%s)  %s", argument->GetTitle(), argument->GetName());
      const char *arg_def = argument->GetDefault();
      if (arg_def && *arg_def) {
         strncat(argTitle, "  [default: ", 127 - strlen(argTitle));
         strncat(argTitle, arg_def, 127 - strlen(argTitle));
         strncat(argTitle, "]", 127 - strlen(argTitle));
      }
   }
   else
      *argTitle = 0;

   return argTitle;
}

//______________________________________________________________________________
void TQCanvasMenu::Popup(TObject *obj, double x, double y, QMouseEvent *e)
{
   // Perform the corresponding selected TObject  popup
   // in the position defined
   // by x, y coordinates (in user coordinate system).
   // @param obj (TObject*)
   // @param p (QPoint&)

   TClass *klass=obj->IsA();
   Int_t curId=-1;

   fCurrObj=obj;
   fPopup->clear();
   fMethods.Clear();

   QString buffer=klass->GetName();
   buffer+="::";
   buffer+=obj->GetName();
   fPopup->insertItem(buffer, this, SLOT( Execute(int) ), 0,curId); curId++;
   klass->GetMenuItems(&fMethods);
   fPopup->insertSeparator();
   TIter iter(&fMethods);
   TMethod *method=0;
   while ( (method = dynamic_cast<TMethod*>(iter())) != 0) {
      buffer=method->GetName();
      fPopup->insertItem(buffer, this, SLOT( Execute(int) ), 0,curId);
      curId++;
   }
   // hold the position where the mouse was clicked
   fMousePosX= x;
   fMousePosY= y;

   // let Qt decide how to draw the popup Menu otherwise we have a problem that
   // the visible rectangle can get outside the screen (M.T. 03.06.02)
   fPopup->popup(e->globalPos(), 0);

}

//______________________________________________________________________________
void TQCanvasMenu::Execute(int id)
{
   // Slot defined to execute a method from a selected TObject
   // using TObject::Execute() function.

   QString text="";

   TVirtualPad  *psave = gROOT->GetSelectedPad();
   TMethod *method=(TMethod *)fMethods.At(id);
   fc->HandleInput(kButton3Up,gPad->XtoAbsPixel(fMousePosX), gPad->YtoAbsPixel(fMousePosY) );
   if (  method->GetListOfMethodArgs()->First() ) {
      Dialog(fCurrObj,method);
   }
   else {
      gROOT->SetFromPopUp(kTRUE);
      fCurrObj->Execute((char *) method->GetName(), "");
   }
   fc->GetPadSave()->Update();
   fc->GetPadSave()->Modified();
   gROOT->SetSelectedPad(psave);
   gROOT->GetSelectedPad()->Update();
   gROOT->GetSelectedPad()->Modified();
   fc->Modified();
   fc->ForceUpdate();
   gROOT->SetFromPopUp( kFALSE );
}

//______________________________________________________________________________
void TQCanvasMenu::Dialog(TObject* object, TMethod* method)
{
   // Create dialog object with OK and Cancel buttons. This dialog
   // prompts for the arguments of "method".

   if (!(object && method)) return;
   fDialog = new TQRootDialog(fParent,CreateDialogTitle(object, method),0,object ,method);
   fDialog->SetTCanvas(fc);
   // iterate through all arguments and create apropriate input-data objects:
   // inputlines, option menus...
   TMethodArg *argument = 0;
   TIter next(method->GetListOfMethodArgs());
   while ((argument = (TMethodArg *) next())) {
      char       *argname    = CreateArgumentTitle(argument);
      const char *type       = argument->GetTypeName();
      TDataType    *datatype   = gROOT->GetType(type);
      const char *charstar   = "char*";
      char        basictype [32];

      if (datatype) {
         strlcpy(basictype, datatype->GetTypeName(),32);
      }
      else {
         if (strncmp(type, "enum", 4) != 0)
         cout << "*** Warning in Dialog(): data type is not basic type, assuming (int)\n";
         strcpy(basictype, "int");
      }

      if (strchr(argname, '*')) {
         strcat(basictype, "*");
         type = charstar;
      }

      TDataMember *m = argument->GetDataMember();
      if (m && m->GetterMethod()) {
         char gettername[256] = "";
         strlcpy(gettername, m->GetterMethod()->GetMethodName(),256);
         m->GetterMethod()->Init(object->IsA(), gettername, "");
         // Get the current value and form it as a text:
         char val[256];
         if (!strncmp(basictype, "char*", 5)) {
            char *tdefval;
            m->GetterMethod()->Execute(object, "", &tdefval);
            strlcpy(val, tdefval, 256);
         }
         else if (!strncmp(basictype, "float", 5) ||
            !strncmp(basictype, "double", 6)) {
            Double_t ddefval = 0.0;
            m->GetterMethod()->Execute(object, "", ddefval);
            snprintf(val, 255, "%g", ddefval);
         }
         else if (!strncmp(basictype, "char", 4) ||
             !strncmp(basictype, "int", 3)  ||
             !strncmp(basictype, "long", 4) ||
             !strncmp(basictype, "short", 5)) {
            Long_t ldefval = 0L;
            m->GetterMethod()->Execute(object, "", ldefval);
            snprintf(val, 255, "%li", ldefval);
         }
         // Find out whether we have options ...
         TList *opt;
         if ((opt = m->GetOptions())) {
            cout << "*** Warning in Dialog(): option menu not yet implemented " << opt << endl;
            // should stop dialog
            return;
         }
         else {
            // we haven't got options - textfield ...
            fDialog->Add(argname, val, type);
         }
      }
      else {    // if m not found ...
         char val[256] = "";
         const char *tval = argument->GetDefault();
         if (tval) strlcpy(val, tval, 256);
         fDialog->Add(argname, val, type);
      }
   } //end while

   fDialog->Popup();
}
<|endoftext|>