<commit_before>/*      _______   __   __   __   ______   __   __   _______   __   __
 *     / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___  /\ /  |\/ /\
 *    / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / /
 *   / / /__   / / // / // / // / /    / ___  / // ___  / // /| ' / /
 *  / /_// /\ / /_// / // / // /_/_   / / // / // /\_/ / // / |  / /
 * /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ /
 * \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/
 *
 * Copyright (c) 2004, 2005, 2006, 2007 Olof Naessn and Per Larsson
 *
 *                                                         Js_./
 * Per Larsson a.k.a finalman                          _RqZ{a<^_aa
 * Olof Naessn a.k.a jansem/yakslem                _asww7!uY`>  )\a//
 *                                                 _Qhm`] _f "'c  1!5m
 * Visit: http://guichan.darkbits.org             )Qk<P ` _: :+' .'  "{[
 *                                               .)j(] .d_/ '-(  P .   S
 * License: (BSD)                                <Td/Z <fP"5(\"??"\a.  .L
 * Redistribution and use in source and          _dV>ws?a-?'      ._/L  #'
 * binary forms, with or without                 )4d[#7r, .   '     )d`)[
 * modification, are permitted provided         _Q-5'5W..j/?'   -?!\)cam'
 * that the following conditions are met:       j<<WP+k/);.        _W=j f
 * 1. Redistributions of source code must       .$%w\/]Q  . ."'  .  mj$
 *    retain the above copyright notice,        ]E.pYY(Q]>.   a     J@\
 *    this list of conditions and the           j(]1u<sE"L,. .   ./^ ]{a
 *    following disclaimer.                     4'_uomm\.  )L);-4     (3=
 * 2. Redistributions in binary form must        )_]X{Z('a_"a7'<a"a,  ]"[
 *    reproduce the above copyright notice,       #}<]m7`Za??4,P-"'7. ).m
 *    this list of conditions and the            ]d2e)Q(<Q(  ?94   b-  LQ/
 *    following disclaimer in the                <B!</]C)d_, '(<' .f. =C+m
 *    documentation and/or other materials      .Z!=J ]e []('-4f _ ) -.)m]'
 *    provided with the distribution.          .w[5]' _[ /.)_-"+?   _/ <W"
 * 3. Neither the name of Guichan nor the      :$we` _! + _/ .        j?
 *    names of its contributors may be used     =3)= _f  (_yQmWW$#(    "
 *    to endorse or promote products derived     -   W,  sQQQQmZQ#Wwa]..
 *    from this software without specific        (js, \[QQW$QWW#?!V"".
 *    prior written permission.                    ]y:.<\..          .
 *                                                 -]n w/ '         [.
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT       )/ )/           !
 * HOLDERS AND CONTRIBUTORS "AS IS" AND ANY         <  (; sac    ,    '
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING,               ]^ .-  %
 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF            c <   r
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR            aga<  <La
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE          5%  )P'-3L
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR        _bQf` y`..)a
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,          ,J?4P'.P"_(\?d'.,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES               _Pa,)!f/<[]/  ?"
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT      _2-..:. .r+_,.. .
 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,     ?a.<%"'  " -'.a_ _,
 * 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.
 */

/*
 * For comments regarding functions please see the header file.
 */

#include "guichan/focushandler.hpp"

#include "guichan/exception.hpp"
#include "guichan/widget.hpp"

namespace gcn
{
    FocusHandler::FocusHandler()
    {
        mFocusedWidget = NULL;
        mToBeFocused = NULL;
        mModalFocusedWidget = NULL;
        mModalMouseInputFocusedWidget = NULL;
    }

    void FocusHandler::requestFocus(Widget* widget)
    {
        mToBeFocused = widget;
    }

    void FocusHandler::requestModalFocus(Widget* widget)
    {
        if (mModalFocusedWidget != NULL && mModalFocusedWidget != widget)
        {
            throw GCN_EXCEPTION("Another widget allready has modal focus.");
        }

        mModalFocusedWidget = widget;

        if (mFocusedWidget != NULL && !mFocusedWidget->hasModalFocus())
        {
            focusNone();
        }
    }

    void FocusHandler::requestModalMouseInputFocus(Widget* widget)
    {
        if (mModalMouseInputFocusedWidget != NULL
            && mModalMouseInputFocusedWidget != widget)
        {
            throw GCN_EXCEPTION("Another widget allready has modal input focus.");
        }

        mModalMouseInputFocusedWidget = widget;
    }

    void FocusHandler::releaseModalFocus(Widget* widget)
    {
        if (mModalFocusedWidget == widget)
        {
            mModalFocusedWidget = NULL;
        }
    }

    void FocusHandler::releaseModalMouseInputFocus(Widget* widget)
    {
        if (mModalMouseInputFocusedWidget == widget)
        {
            mModalMouseInputFocusedWidget = NULL;
        }
    }

    Widget* FocusHandler::getFocused() const
    {
        return mFocusedWidget;
    }

    Widget* FocusHandler::getModalFocused() const
    {
        return mModalFocusedWidget;
    }

    Widget* FocusHandler::getModalMouseInputFocused() const
    {
        return mModalMouseInputFocusedWidget;
    }

    void FocusHandler::focusNext()
    {
        int i;
        int focusedWidget = -1;
        for (i = 0; i < (int)mWidgets.size(); ++i)
        {
            if (mWidgets[i] == mFocusedWidget)
            {
                focusedWidget = i;
            }
        }
        int focused = focusedWidget;

        // i is a counter that ensures that the following loop
        // won't get stuck in an infinite loop
        i = (int)mWidgets.size();
        do
        {
            ++focusedWidget;

            if (i==0)
            {
                focusedWidget = -1;
                break;
            }

            --i;

            if (focusedWidget >= (int)mWidgets.size())
            {
                focusedWidget = 0;
            }

            if (focusedWidget == focused)
            {
                return;
            }
        }
        while (!mWidgets.at(focusedWidget)->isFocusable());

        if (focusedWidget >= 0)
        {
            mFocusedWidget = mWidgets.at(focusedWidget);
            mWidgets.at(focusedWidget)->focusGained();
        }

        if (focused >= 0)
        {
            mWidgets.at(focused)->focusLost();
        }
    }

    void FocusHandler::focusPrevious()
    {
        if (mWidgets.size() == 0)
        {
            mFocusedWidget = NULL;
            return;
        }

        int i;
        int focusedWidget = -1;
        for (i = 0; i < (int)mWidgets.size(); ++i)
        {
            if (mWidgets[i] == mFocusedWidget)
            {
                focusedWidget = i;
            }
        }
        int focused = focusedWidget;

        // i is a counter that ensures that the following loop
        // won't get stuck in an infinite loop
        i = (int)mWidgets.size();
        do
        {
            --focusedWidget;

            if (i==0)
            {
                focusedWidget = -1;
                break;
            }

            --i;

            if (focusedWidget <= 0)
            {
                focusedWidget = mWidgets.size() - 1;
            }

            if (focusedWidget == focused)
            {
                return;
            }
        }
        while (!mWidgets.at(focusedWidget)->isFocusable());

        if (focusedWidget >= 0)
        {
            mFocusedWidget = mWidgets.at(focusedWidget);
            mWidgets.at(focusedWidget)->focusGained();
        }

        if (focused >= 0)
        {
            mWidgets.at(focused)->focusLost();
        }
    }

    bool FocusHandler::isFocused(const Widget* widget) const
    {
        return mFocusedWidget == widget;
    }

    void FocusHandler::add(Widget* widget)
    {
        mWidgets.push_back(widget);
    }

    void FocusHandler::remove(Widget* widget)
    {
        if (widget == mToBeFocused)
        {
            mToBeFocused = NULL;
        }

        if (isFocused(widget))
        {
            mFocusedWidget = NULL;
            mToBeFocused = NULL;
        }

        WidgetIterator iter;

        for (iter = mWidgets.begin(); iter != mWidgets.end(); ++iter)
        {
            if ((*iter) == widget)
            {
                mWidgets.erase(iter);
                return;
            }
        }
    }

    void FocusHandler::focusNone()
    {

        if (mFocusedWidget != NULL)
        {
            Widget* focused = mFocusedWidget;
            mFocusedWidget = NULL;
            focused->focusLost();
        }

        mToBeFocused = NULL;
    }

    void FocusHandler::tabNext()
    {
        if (mFocusedWidget != NULL)
        {
            if (!mFocusedWidget->isTabOutEnabled())
            {
                return;
            }
        }

        if (mWidgets.size() == 0)
        {
            mFocusedWidget = NULL;
            return;
        }

        int i;
        int focusedWidget = -1;
        for (i = 0; i < (int)mWidgets.size(); ++i)
        {
            if (mWidgets[i] == mFocusedWidget)
            {
                focusedWidget = i;
            }
        }
        int focused = focusedWidget;
        bool done = false;

        // i is a counter that ensures that the following loop
        // won't get stuck in an infinite loop
        i = (int)mWidgets.size();
        do
        {
            ++focusedWidget;

            if (i==0)
            {
                focusedWidget = -1;
                break;
            }

            --i;

            if (focusedWidget >= (int)mWidgets.size())
            {
                focusedWidget = 0;
            }

            if (focusedWidget == focused)
            {
                return;
            }

            if (mWidgets.at(focusedWidget)->isFocusable() &&
                mWidgets.at(focusedWidget)->isTabInEnabled() &&
                (mModalFocusedWidget == NULL ||
                 mWidgets.at(focusedWidget)->hasModalFocus()))
            {
                done = true;
            }
        }
        while (!done);

        if (focusedWidget >= 0)
        {
            mFocusedWidget = mWidgets.at(focusedWidget);
            mWidgets.at(focusedWidget)->focusGained();
        }

        if (focused >= 0)
        {
            mWidgets.at(focused)->focusLost();
        }
    }

    void FocusHandler::tabPrevious()
    {
        if (mFocusedWidget != NULL)
        {
            if (!mFocusedWidget->isTabOutEnabled())
            {
                return;
            }
        }

        if (mWidgets.size() == 0)
        {
            mFocusedWidget = NULL;
            return;
        }

        int i;
        int focusedWidget = -1;
        for (i = 0; i < (int)mWidgets.size(); ++i)
        {
            if (mWidgets[i] == mFocusedWidget)
            {
                focusedWidget = i;
            }
        }
        int focused = focusedWidget;
        bool done = false;

        // i is a counter that ensures that the following loop
        // won't get stuck in an infinite loop
        i = (int)mWidgets.size();
        do
        {
            --focusedWidget;

            if (i==0)
            {
                focusedWidget = -1;
                break;
            }

            --i;

            if (focusedWidget <= 0)
            {
                focusedWidget = mWidgets.size() - 1;
            }

            if (focusedWidget == focused)
            {
                return;
            }

            if (mWidgets.at(focusedWidget)->isFocusable() &&
                mWidgets.at(focusedWidget)->isTabInEnabled() &&
                (mModalFocusedWidget == NULL ||
                 mWidgets.at(focusedWidget)->hasModalFocus()))
            {
                done = true;
            }
        }
        while (!done);

        if (focusedWidget >= 0)
        {
            mFocusedWidget = mWidgets.at(focusedWidget);
            mWidgets.at(focusedWidget)->focusGained();
        }

        if (focused >= 0)
        {
            mWidgets.at(focused)->focusLost();
        }
    }

    void FocusHandler::applyChanges()
    {
        if (mToBeFocused == mFocusedWidget)
        {
            return;
        }

        if (mToBeFocused != NULL)
        {
            unsigned int i = 0;
            int toBeFocusedIndex = -1;
            for (i = 0; i < mWidgets.size(); ++i)
            {
                if (mWidgets[i] == mToBeFocused)
                {
                    toBeFocusedIndex = i;
                    break;
                }
            }

            if (toBeFocusedIndex < 0)
            {
                throw GCN_EXCEPTION("Trying to focus a none existing widget.");
            }

            Widget *oldFocused = mFocusedWidget;

            if (oldFocused != mToBeFocused)
            {
                mFocusedWidget = mWidgets.at(toBeFocusedIndex);

                if (oldFocused != NULL)
                {
                    oldFocused->focusLost();
                }

                mWidgets.at(toBeFocusedIndex)->focusGained();
            }

            mToBeFocused = NULL;
        }
    }
}
<commit_msg>distributeFocusGainedEvent and distributeFocusLostEvent have been added. Focus lost events and focus gained events are now distributed to the source widget's focus listeners.<commit_after>/*      _______   __   __   __   ______   __   __   _______   __   __
 *     / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___  /\ /  |\/ /\
 *    / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / /
 *   / / /__   / / // / // / // / /    / ___  / // ___  / // /| ' / /
 *  / /_// /\ / /_// / // / // /_/_   / / // / // /\_/ / // / |  / /
 * /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ /
 * \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/
 *
 * Copyright (c) 2004, 2005, 2006, 2007 Olof Naessn and Per Larsson
 *
 *                                                         Js_./
 * Per Larsson a.k.a finalman                          _RqZ{a<^_aa
 * Olof Naessn a.k.a jansem/yakslem                _asww7!uY`>  )\a//
 *                                                 _Qhm`] _f "'c  1!5m
 * Visit: http://guichan.darkbits.org             )Qk<P ` _: :+' .'  "{[
 *                                               .)j(] .d_/ '-(  P .   S
 * License: (BSD)                                <Td/Z <fP"5(\"??"\a.  .L
 * Redistribution and use in source and          _dV>ws?a-?'      ._/L  #'
 * binary forms, with or without                 )4d[#7r, .   '     )d`)[
 * modification, are permitted provided         _Q-5'5W..j/?'   -?!\)cam'
 * that the following conditions are met:       j<<WP+k/);.        _W=j f
 * 1. Redistributions of source code must       .$%w\/]Q  . ."'  .  mj$
 *    retain the above copyright notice,        ]E.pYY(Q]>.   a     J@\
 *    this list of conditions and the           j(]1u<sE"L,. .   ./^ ]{a
 *    following disclaimer.                     4'_uomm\.  )L);-4     (3=
 * 2. Redistributions in binary form must        )_]X{Z('a_"a7'<a"a,  ]"[
 *    reproduce the above copyright notice,       #}<]m7`Za??4,P-"'7. ).m
 *    this list of conditions and the            ]d2e)Q(<Q(  ?94   b-  LQ/
 *    following disclaimer in the                <B!</]C)d_, '(<' .f. =C+m
 *    documentation and/or other materials      .Z!=J ]e []('-4f _ ) -.)m]'
 *    provided with the distribution.          .w[5]' _[ /.)_-"+?   _/ <W"
 * 3. Neither the name of Guichan nor the      :$we` _! + _/ .        j?
 *    names of its contributors may be used     =3)= _f  (_yQmWW$#(    "
 *    to endorse or promote products derived     -   W,  sQQQQmZQ#Wwa]..
 *    from this software without specific        (js, \[QQW$QWW#?!V"".
 *    prior written permission.                    ]y:.<\..          .
 *                                                 -]n w/ '         [.
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT       )/ )/           !
 * HOLDERS AND CONTRIBUTORS "AS IS" AND ANY         <  (; sac    ,    '
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING,               ]^ .-  %
 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF            c <   r
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR            aga<  <La
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE          5%  )P'-3L
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR        _bQf` y`..)a
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,          ,J?4P'.P"_(\?d'.,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES               _Pa,)!f/<[]/  ?"
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT      _2-..:. .r+_,.. .
 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,     ?a.<%"'  " -'.a_ _,
 * 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.
 */

/*
 * For comments regarding functions please see the header file.
 */

#include "guichan/focushandler.hpp"

#include "guichan/focuslistener.hpp"
#include "guichan/exception.hpp"
#include "guichan/widget.hpp"

namespace gcn
{
    FocusHandler::FocusHandler()
    {
        mFocusedWidget = NULL;
        mToBeFocused = NULL;
        mModalFocusedWidget = NULL;
        mModalMouseInputFocusedWidget = NULL;
    }

    void FocusHandler::requestFocus(Widget* widget)
    {
        mToBeFocused = widget;
    }

    void FocusHandler::requestModalFocus(Widget* widget)
    {
        if (mModalFocusedWidget != NULL && mModalFocusedWidget != widget)
        {
            throw GCN_EXCEPTION("Another widget allready has modal focus.");
        }

        mModalFocusedWidget = widget;

        if (mFocusedWidget != NULL && !mFocusedWidget->hasModalFocus())
        {
            focusNone();
        }
    }

    void FocusHandler::requestModalMouseInputFocus(Widget* widget)
    {
        if (mModalMouseInputFocusedWidget != NULL
            && mModalMouseInputFocusedWidget != widget)
        {
            throw GCN_EXCEPTION("Another widget allready has modal input focus.");
        }

        mModalMouseInputFocusedWidget = widget;
    }

    void FocusHandler::releaseModalFocus(Widget* widget)
    {
        if (mModalFocusedWidget == widget)
        {
            mModalFocusedWidget = NULL;
        }
    }

    void FocusHandler::releaseModalMouseInputFocus(Widget* widget)
    {
        if (mModalMouseInputFocusedWidget == widget)
        {
            mModalMouseInputFocusedWidget = NULL;
        }
    }

    Widget* FocusHandler::getFocused() const
    {
        return mFocusedWidget;
    }

    Widget* FocusHandler::getModalFocused() const
    {
        return mModalFocusedWidget;
    }

    Widget* FocusHandler::getModalMouseInputFocused() const
    {
        return mModalMouseInputFocusedWidget;
    }

    void FocusHandler::focusNext()
    {
        int i;
        int focusedWidget = -1;
        for (i = 0; i < (int)mWidgets.size(); ++i)
        {
            if (mWidgets[i] == mFocusedWidget)
            {
                focusedWidget = i;
            }
        }
        int focused = focusedWidget;

        // i is a counter that ensures that the following loop
        // won't get stuck in an infinite loop
        i = (int)mWidgets.size();
        do
        {
            ++focusedWidget;

            if (i==0)
            {
                focusedWidget = -1;
                break;
            }

            --i;

            if (focusedWidget >= (int)mWidgets.size())
            {
                focusedWidget = 0;
            }

            if (focusedWidget == focused)
            {
                return;
            }
        }
        while (!mWidgets.at(focusedWidget)->isFocusable());

        if (focusedWidget >= 0)
        {
            mFocusedWidget = mWidgets.at(focusedWidget);

            Event focusEvent(mFocusedWidget);
            distributeFocusGainedEvent(focusEvent);
            //mWidgets.at(focusedWidget)->focusGained();
        }

        if (focused >= 0)
        {
            Event focusEvent(mWidgets.at(focused));
            distributeFocusLostEvent(focusEvent);
           // mWidgets.at(focused)->focusLost();
        }
    }

    void FocusHandler::focusPrevious()
    {
        if (mWidgets.size() == 0)
        {
            mFocusedWidget = NULL;
            return;
        }

        int i;
        int focusedWidget = -1;
        for (i = 0; i < (int)mWidgets.size(); ++i)
        {
            if (mWidgets[i] == mFocusedWidget)
            {
                focusedWidget = i;
            }
        }
        int focused = focusedWidget;

        // i is a counter that ensures that the following loop
        // won't get stuck in an infinite loop
        i = (int)mWidgets.size();
        do
        {
            --focusedWidget;

            if (i==0)
            {
                focusedWidget = -1;
                break;
            }

            --i;

            if (focusedWidget <= 0)
            {
                focusedWidget = mWidgets.size() - 1;
            }

            if (focusedWidget == focused)
            {
                return;
            }
        }
        while (!mWidgets.at(focusedWidget)->isFocusable());

        if (focusedWidget >= 0)
        {
            mFocusedWidget = mWidgets.at(focusedWidget);
            Event focusEvent(mFocusedWidget);
            distributeFocusGainedEvent(focusEvent);
            //mWidgets.at(focusedWidget)->focusGained();
        }

        if (focused >= 0)
        {
            Event focusEvent(mWidgets.at(focused));
            distributeFocusLostEvent(focusEvent);
            //mWidgets.at(focused)->focusLost();
        }
    }

    bool FocusHandler::isFocused(const Widget* widget) const
    {
        return mFocusedWidget == widget;
    }

    void FocusHandler::add(Widget* widget)
    {
        mWidgets.push_back(widget);
    }

    void FocusHandler::remove(Widget* widget)
    {
        if (widget == mToBeFocused)
        {
            mToBeFocused = NULL;
        }

        if (isFocused(widget))
        {
            mFocusedWidget = NULL;
            mToBeFocused = NULL;
        }

        WidgetIterator iter;

        for (iter = mWidgets.begin(); iter != mWidgets.end(); ++iter)
        {
            if ((*iter) == widget)
            {
                mWidgets.erase(iter);
                return;
            }
        }
    }

    void FocusHandler::focusNone()
    {

        if (mFocusedWidget != NULL)
        {
            Widget* focused = mFocusedWidget;
            mFocusedWidget = NULL;

            Event focusEvent(focused);
            distributeFocusLostEvent(focusEvent);
            //focused->focusLost();
        }

        mToBeFocused = NULL;
    }

    void FocusHandler::tabNext()
    {
        if (mFocusedWidget != NULL)
        {
            if (!mFocusedWidget->isTabOutEnabled())
            {
                return;
            }
        }

        if (mWidgets.size() == 0)
        {
            mFocusedWidget = NULL;
            return;
        }

        int i;
        int focusedWidget = -1;
        for (i = 0; i < (int)mWidgets.size(); ++i)
        {
            if (mWidgets[i] == mFocusedWidget)
            {
                focusedWidget = i;
            }
        }
        int focused = focusedWidget;
        bool done = false;

        // i is a counter that ensures that the following loop
        // won't get stuck in an infinite loop
        i = (int)mWidgets.size();
        do
        {
            ++focusedWidget;

            if (i==0)
            {
                focusedWidget = -1;
                break;
            }

            --i;

            if (focusedWidget >= (int)mWidgets.size())
            {
                focusedWidget = 0;
            }

            if (focusedWidget == focused)
            {
                return;
            }

            if (mWidgets.at(focusedWidget)->isFocusable() &&
                mWidgets.at(focusedWidget)->isTabInEnabled() &&
                (mModalFocusedWidget == NULL ||
                 mWidgets.at(focusedWidget)->hasModalFocus()))
            {
                done = true;
            }
        }
        while (!done);

        if (focusedWidget >= 0)
        {
            mFocusedWidget = mWidgets.at(focusedWidget);
            Event focusEvent(mFocusedWidget);
            distributeFocusGainedEvent(focusEvent);
            //mWidgets.at(focusedWidget)->focusGained();
        }

        if (focused >= 0)
        {
            Event focusEvent(mWidgets.at(focused));
            distributeFocusLostEvent(focusEvent);
            //mWidgets.at(focused)->focusLost();
        }
    }

    void FocusHandler::tabPrevious()
    {
        if (mFocusedWidget != NULL)
        {
            if (!mFocusedWidget->isTabOutEnabled())
            {
                return;
            }
        }

        if (mWidgets.size() == 0)
        {
            mFocusedWidget = NULL;
            return;
        }

        int i;
        int focusedWidget = -1;
        for (i = 0; i < (int)mWidgets.size(); ++i)
        {
            if (mWidgets[i] == mFocusedWidget)
            {
                focusedWidget = i;
            }
        }
        int focused = focusedWidget;
        bool done = false;

        // i is a counter that ensures that the following loop
        // won't get stuck in an infinite loop
        i = (int)mWidgets.size();
        do
        {
            --focusedWidget;

            if (i==0)
            {
                focusedWidget = -1;
                break;
            }

            --i;

            if (focusedWidget <= 0)
            {
                focusedWidget = mWidgets.size() - 1;
            }

            if (focusedWidget == focused)
            {
                return;
            }

            if (mWidgets.at(focusedWidget)->isFocusable() &&
                mWidgets.at(focusedWidget)->isTabInEnabled() &&
                (mModalFocusedWidget == NULL ||
                 mWidgets.at(focusedWidget)->hasModalFocus()))
            {
                done = true;
            }
        }
        while (!done);

        if (focusedWidget >= 0)
        {
            mFocusedWidget = mWidgets.at(focusedWidget);
            Event focusEvent(mFocusedWidget);
            distributeFocusGainedEvent(focusEvent);
            //mWidgets.at(focusedWidget)->focusGained();
        }

        if (focused >= 0)
        {
            Event focusEvent(mWidgets.at(focused));
            distributeFocusLostEvent(focusEvent);
            //mWidgets.at(focused)->focusLost();
        }
    }

    void FocusHandler::applyChanges()
    {
        if (mToBeFocused == mFocusedWidget)
        {
            return;
        }

        if (mToBeFocused != NULL)
        {
            unsigned int i = 0;
            int toBeFocusedIndex = -1;
            for (i = 0; i < mWidgets.size(); ++i)
            {
                if (mWidgets[i] == mToBeFocused)
                {
                    toBeFocusedIndex = i;
                    break;
                }
            }

            if (toBeFocusedIndex < 0)
            {
                throw GCN_EXCEPTION("Trying to focus a none existing widget.");
            }

            Widget *oldFocused = mFocusedWidget;

            if (oldFocused != mToBeFocused)
            {
                mFocusedWidget = mWidgets.at(toBeFocusedIndex);

                if (oldFocused != NULL)
                {
                    Event focusEvent(oldFocused);
                    distributeFocusLostEvent(focusEvent);
                    //oldFocused->focusLost();
                }

                Event focusEvent(mWidgets.at(toBeFocusedIndex));
                distributeFocusGainedEvent(focusEvent);
                //mWidgets.at(toBeFocusedIndex)->focusGained();
            }

            mToBeFocused = NULL;
        }
    }

    void FocusHandler::distributeFocusLostEvent(const Event& focusEvent)
    {
        Widget* sourceWidget = focusEvent.getSource();

        std::list<FocusListener*> focusListeners = sourceWidget->_getFocusListeners();

        // Send the event to all focus listeners of the widget.
        for (std::list<FocusListener*>::iterator it = focusListeners.begin();
             it != focusListeners.end();
             ++it)
        {
            (*it)->focusLost(focusEvent);
        }
    }

    void FocusHandler::distributeFocusGainedEvent(const Event& focusEvent)
    {
        Widget* sourceWidget = focusEvent.getSource();

        std::list<FocusListener*> focusListeners = sourceWidget->_getFocusListeners();

        // Send the event to all focus listeners of the widget.
        for (std::list<FocusListener*>::iterator it = focusListeners.begin();
             it != focusListeners.end();
             ++it)
        {
            (*it)->focusGained(focusEvent);
        }
    }
}
<|endoftext|>


<commit_before>#include "nan.h"
#include "nanodbc.h"
#include "picojson.h"

using std::string;

static v8::Persistent<v8::FunctionTemplate> nodbc_constructor;

class NodbcConnection : node::ObjectWrap {
public:
    static void Init();
    static NAN_METHOD(New);
    static NAN_METHOD(IsConnected);
    static NAN_METHOD(Open);
    static NAN_METHOD(Close);
    static NAN_METHOD(Execute);
private:
    nanodbc::connection connection;
};

NAN_METHOD(NodbcConnection::New) {
    NanScope();

    NodbcConnection *obj = new NodbcConnection();
    obj->Wrap(args.Holder());

    NanReturnValue(args.Holder());
}

NAN_METHOD(NodbcConnection::IsConnected) {
    NanScope();

    NodbcConnection *self = ObjectWrap::Unwrap<NodbcConnection>(args.Holder());

    NanReturnValue(NanNew(self->connection.connected()));
}

class OpenWorker : public NanAsyncWorker {
public:
    OpenWorker(NanCallback *callback, nanodbc::connection *connection, string connectionString)
        : NanAsyncWorker(callback), connection(connection), connectionString(connectionString) {}

    void Execute() {
        try {
            connection->connect(connectionString);
        }
        catch (const nanodbc::database_error &err) {
            SetErrorMessage(err.what());
        }
    }

private:
    nanodbc::connection *connection;
    string connectionString;
};

NAN_METHOD(NodbcConnection::Open) {
    NanScope();

    NodbcConnection *self = ObjectWrap::Unwrap<NodbcConnection>(args.Holder());
    string connectionString(*NanAsciiString(args[0].As<v8::String>()));
    NanCallback *callback = new NanCallback(args[1].As<v8::Function>());

    OpenWorker *worker = new OpenWorker(callback, &self->connection, connectionString);
    worker->SaveToPersistent("database", args.Holder());
    NanAsyncQueueWorker(worker);

    NanReturnUndefined();
}

class CloseWorker : public NanAsyncWorker {
public:
    CloseWorker(NanCallback *callback, nanodbc::connection *connection)
        : NanAsyncWorker(callback), connection(connection) {}

    void Execute() {
        connection->disconnect();
    }

private:
    nanodbc::connection *connection;
};

NAN_METHOD(NodbcConnection::Close) {
    NanScope();

    NodbcConnection *self = ObjectWrap::Unwrap<NodbcConnection>(args.Holder());
    NanCallback *callback = new NanCallback(args[0].As<v8::Function>());

    CloseWorker *worker = new CloseWorker(callback, &self->connection);
    worker->SaveToPersistent("database", args.Holder());
    NanAsyncQueueWorker(worker);

    NanReturnUndefined();
}

class ExecuteWorker : public NanAsyncWorker {
public:
    ExecuteWorker(NanCallback *callback, nanodbc::connection *connection, string query)
        : NanAsyncWorker(callback), connection(connection), query(query) {}

    void Execute() {
        try {
            nanodbc::result result = nanodbc::execute(*connection, query);

            picojson::array rows;
            const short columns = result.columns();

            while (result.next()) {
                picojson::object row;
                for (short col = 0; col < columns; col++) {
                    row[result.column_name(col)] = picojson::value(result.get<string>(col));
                }
                rows.push_back(picojson::value(row));
            }

            json = picojson::value(rows).serialize();
        }
        catch (const nanodbc::database_error &err) {
            SetErrorMessage(err.what());
        }
    }

    void HandleOKCallback() {
        NanScope();

        v8::Local<v8::Value> argv[] = {
            NanNull(),
            NanNew(json.c_str())
        };

        callback->Call(2, argv);
    };

private:
    nanodbc::connection *connection;
    string query;
    string json;
};

NAN_METHOD(NodbcConnection::Execute) {
    NanScope();

    NodbcConnection *self = ObjectWrap::Unwrap<NodbcConnection>(args.Holder());
    string query(*NanAsciiString(args[0].As<v8::String>()));
    NanCallback *callback = new NanCallback(args[1].As<v8::Function>());

    ExecuteWorker *worker = new ExecuteWorker(callback, &self->connection, query);
    worker->SaveToPersistent("database", args.Holder());
    NanAsyncQueueWorker(worker);

    NanReturnUndefined();
}

void NodbcConnection::Init() {
    v8::Local<v8::FunctionTemplate> tpl = NanNew<v8::FunctionTemplate>(NodbcConnection::New);
    NanAssignPersistent(nodbc_constructor, tpl);
    tpl->SetClassName(NanNew("NodbcConnection"));
    tpl->InstanceTemplate()->SetInternalFieldCount(1);
    NODE_SET_PROTOTYPE_METHOD(tpl, "isConnected", NodbcConnection::IsConnected);
    NODE_SET_PROTOTYPE_METHOD(tpl, "open", NodbcConnection::Open);
    NODE_SET_PROTOTYPE_METHOD(tpl, "close", NodbcConnection::Close);
    NODE_SET_PROTOTYPE_METHOD(tpl, "execute", NodbcConnection::Execute);
}

void Init(v8::Handle<v8::Object> target) {
    NodbcConnection::Init();
    target->Set(NanNew("NodbcConnection"),
        NanNew<v8::FunctionTemplate>(nodbc_constructor)->GetFunction());
}

NODE_MODULE(nodbc, Init)
<commit_msg>Add type conversions to query return values.<commit_after>#ifdef _WIN32
    #define WIN32_LEAN_AND_MEAN
    #include <windows.h>
#endif

#include <sql.h>
#include <sqlext.h>

#include "nan.h"
#include "nanodbc.h"
#include "picojson.h"

using std::string;

static v8::Persistent<v8::FunctionTemplate> nodbc_constructor;

class NodbcConnection : node::ObjectWrap {
public:
    static void Init();
    static NAN_METHOD(New);
    static NAN_METHOD(IsConnected);
    static NAN_METHOD(Open);
    static NAN_METHOD(Close);
    static NAN_METHOD(Execute);
private:
    nanodbc::connection connection;
};

NAN_METHOD(NodbcConnection::New) {
    NanScope();

    NodbcConnection *obj = new NodbcConnection();
    obj->Wrap(args.Holder());

    NanReturnValue(args.Holder());
}

NAN_METHOD(NodbcConnection::IsConnected) {
    NanScope();

    NodbcConnection *self = ObjectWrap::Unwrap<NodbcConnection>(args.Holder());

    NanReturnValue(NanNew(self->connection.connected()));
}

class OpenWorker : public NanAsyncWorker {
public:
    OpenWorker(NanCallback *callback, nanodbc::connection *connection, string connectionString)
        : NanAsyncWorker(callback), connection(connection), connectionString(connectionString) {}

    void Execute() {
        try {
            connection->connect(connectionString);
        }
        catch (const nanodbc::database_error &err) {
            SetErrorMessage(err.what());
        }
    }

private:
    nanodbc::connection *connection;
    string connectionString;
};

NAN_METHOD(NodbcConnection::Open) {
    NanScope();

    NodbcConnection *self = ObjectWrap::Unwrap<NodbcConnection>(args.Holder());
    string connectionString(*NanAsciiString(args[0].As<v8::String>()));
    NanCallback *callback = new NanCallback(args[1].As<v8::Function>());

    OpenWorker *worker = new OpenWorker(callback, &self->connection, connectionString);
    worker->SaveToPersistent("database", args.Holder());
    NanAsyncQueueWorker(worker);

    NanReturnUndefined();
}

class CloseWorker : public NanAsyncWorker {
public:
    CloseWorker(NanCallback *callback, nanodbc::connection *connection)
        : NanAsyncWorker(callback), connection(connection) {}

    void Execute() {
        connection->disconnect();
    }

private:
    nanodbc::connection *connection;
};

NAN_METHOD(NodbcConnection::Close) {
    NanScope();

    NodbcConnection *self = ObjectWrap::Unwrap<NodbcConnection>(args.Holder());
    NanCallback *callback = new NanCallback(args[0].As<v8::Function>());

    CloseWorker *worker = new CloseWorker(callback, &self->connection);
    worker->SaveToPersistent("database", args.Holder());
    NanAsyncQueueWorker(worker);

    NanReturnUndefined();
}

class ExecuteWorker : public NanAsyncWorker {
public:
    ExecuteWorker(NanCallback *callback, nanodbc::connection *connection, string query)
        : NanAsyncWorker(callback), connection(connection), query(query) {}

    void Execute() {
        try {
            nanodbc::result result = nanodbc::execute(*connection, query);

            picojson::array rows;
            const short columns = result.columns();

            while (result.next()) {
                picojson::object row;
                for (short col = 0; col < columns; col++) {
                    row[result.column_name(col)] = GetJsonValue(&result, col);
                }
                rows.push_back(picojson::value(row));
            }

            json = picojson::value(rows).serialize();
        }
        catch (const nanodbc::database_error &err) {
            SetErrorMessage(err.what());
        }
    }

    void HandleOKCallback() {
        NanScope();

        v8::Local<v8::Value> argv[] = {
            NanNull(),
            NanNew(json.c_str())
        };

        callback->Call(2, argv);
    };

private:
    picojson::value GetJsonValue(nanodbc::result *result, short col) {
        if (result->is_null(col)) {
            return picojson::value();
        }

        switch (result->column_datatype(col)) {
        case SQL_NUMERIC:
        case SQL_DECIMAL:
        case SQL_INTEGER:
        case SQL_SMALLINT:
        case SQL_TINYINT:
        case SQL_BIGINT:
        case SQL_FLOAT:
        case SQL_REAL:
        case SQL_DOUBLE:
            return picojson::value(result->get<double>(col));
        default:
            return picojson::value(result->get<string>(col));
        }
    }

    nanodbc::connection *connection;
    string query;
    string json;
};

NAN_METHOD(NodbcConnection::Execute) {
    NanScope();

    NodbcConnection *self = ObjectWrap::Unwrap<NodbcConnection>(args.Holder());
    string query(*NanAsciiString(args[0].As<v8::String>()));
    NanCallback *callback = new NanCallback(args[1].As<v8::Function>());

    ExecuteWorker *worker = new ExecuteWorker(callback, &self->connection, query);
    worker->SaveToPersistent("database", args.Holder());
    NanAsyncQueueWorker(worker);

    NanReturnUndefined();
}

void NodbcConnection::Init() {
    v8::Local<v8::FunctionTemplate> tpl = NanNew<v8::FunctionTemplate>(NodbcConnection::New);
    NanAssignPersistent(nodbc_constructor, tpl);
    tpl->SetClassName(NanNew("NodbcConnection"));
    tpl->InstanceTemplate()->SetInternalFieldCount(1);
    NODE_SET_PROTOTYPE_METHOD(tpl, "isConnected", NodbcConnection::IsConnected);
    NODE_SET_PROTOTYPE_METHOD(tpl, "open", NodbcConnection::Open);
    NODE_SET_PROTOTYPE_METHOD(tpl, "close", NodbcConnection::Close);
    NODE_SET_PROTOTYPE_METHOD(tpl, "execute", NodbcConnection::Execute);
}

void Init(v8::Handle<v8::Object> target) {
    NodbcConnection::Init();
    target->Set(NanNew("NodbcConnection"),
        NanNew<v8::FunctionTemplate>(nodbc_constructor)->GetFunction());
}

NODE_MODULE(nodbc, Init)
<|endoftext|>


<commit_before>#define THEWIZARDPLUSPLUS_WIZARD_PARSER_PARSER_MACROSES

#include "vendor/better-enums/enum_strict.hpp"
#include "vendor/range/v3/view/drop.hpp"
#include "vendor/range/v3/view/transform.hpp"
#include "vendor/fmt/format.hpp"
#include "vendor/range/v3/view/chunk.hpp"
#include "vendor/range/v3/to_container.hpp"
#include "vendor/range/v3/numeric/accumulate.hpp"
#include "vendor/docopt/docopt.hpp"
#include "vendor/range/v3/algorithm/find_if.hpp"
#include <thewizardplusplus/wizard_parser/exceptions/unexpected_entity_exception.hpp>
#include <thewizardplusplus/wizard_parser/lexer/lexeme.hpp>
#include <thewizardplusplus/wizard_parser/lexer/tokenize.hpp>
#include <thewizardplusplus/wizard_parser/parser/rule_parser.hpp>
#include <thewizardplusplus/wizard_parser/parser/dummy_parser.hpp>
#include <thewizardplusplus/wizard_parser/parser/typing_parser.hpp>
#include <thewizardplusplus/wizard_parser/parser/match_parser.hpp>
#include <thewizardplusplus/wizard_parser/parser/concatenation_parser.hpp>
#include <thewizardplusplus/wizard_parser/parser/lookahead_parser.hpp>
#include <thewizardplusplus/wizard_parser/parser/repetition_parser.hpp>
#include <thewizardplusplus/wizard_parser/parser/list_parser.hpp>
#include <thewizardplusplus/wizard_parser/parser/alternation_parser.hpp>
#include <thewizardplusplus/wizard_parser/parser/ast_node.hpp>
#include <thewizardplusplus/wizard_parser/exceptions/positional_exception.hpp>
#include <thewizardplusplus/wizard_parser/parser/parse.hpp>
#include <thewizardplusplus/wizard_parser/utilities/utilities.hpp>
#include <cstddef>
#include <functional>
#include <vector>
#include <cstdint>
#include <regex>
#include <unordered_map>
#include <string>
#include <cstdlib>
#include <iostream>
#include <stdexcept>
#include <string_view>
#include <iterator>
#include <sstream>
#include <limits>
#include <iomanip>
#include <exception>

using namespace thewizardplusplus::wizard_parser;
using namespace thewizardplusplus::wizard_parser::parser::operators;
using namespace std::literals::string_literals;

struct function final {
	const std::size_t arity;
	const std::function<double(const std::vector<double>&)> handler;
};

BETTER_ENUM(entity_type, std::uint8_t,
	node = exceptions::entity_type::_size(),
	constant,
	function
)

template<entity_type::_integral type>
using unexpected_entity_exception =
	exceptions::base_unexpected_entity_exception<entity_type, type>;

const auto usage =
R"(Usage:
  ./example [options] [--] [<expression>]

Options:
  -h, --help                           - show this message;
  -t TARGET, --target TARGET           - preliminary target of processing
                                       (allowed: tokens, cst);
  -p PRECISION, --precision PRECISION  - precision of a result;
  -s, --stdin                          - read an expression from stdin;
  -V, --verbose                        - mark an error.)";
const auto lexemes = lexer::lexeme_group{
	{std::regex{R"(\+)"}, "plus"},
	{std::regex{R"(-)"}, "minus"},
	{std::regex{R"(\*)"}, "star"},
	{std::regex{R"(/)"}, "slash"},
	{std::regex{R"(%)"}, "percent"},
	{std::regex{R"(\()"}, "opening_parenthesis"},
	{std::regex{R"(\))"}, "closing_parenthesis"},
	{std::regex{R"(,)"}, "comma"},
	{std::regex{R"(\d+(\.\d+)?(e-?\d+)?)"}, "number"},
	{std::regex{R"([A-Za-z_]\w*)"}, "identifier"},
	{std::regex{R"(\s+)"}, "whitespace"}
};
const auto lexemes_exceptions = lexer::type_group{"whitespace"};
// precision is taken from Boost 1.70.0, Math Toolkit 2.9.0
const auto constants = std::unordered_map<std::string, double>{
	{"pi", 3.141592653589793238462643383279502884},
	{"e", 2.718281828459045235360287471352662497}
};
const auto functions = std::unordered_map<std::string, function>{
	{"+", {2, [] (const auto& args) { return args[0] + args[1]; }}},
	{"-", {2, [] (const auto& args) { return args[0] - args[1]; }}},
	{"*", {2, [] (const auto& args) { return args[0] * args[1]; }}},
	{"/", {2, [] (const auto& args) { return args[0] / args[1]; }}},
	{"%", {2, [] (const auto& args) { return std::fmod(args[0], args[1]); }}},
	{"floor", {1, [] (const auto& args) { return std::floor(args[0]); }}},
	{"ceil", {1, [] (const auto& args) { return std::ceil(args[0]); }}},
	{"trunc", {1, [] (const auto& args) { return std::trunc(args[0]); }}},
	{"round", {1, [] (const auto& args) { return std::round(args[0]); }}},
	{"sin", {1, [] (const auto& args) { return std::sin(args[0]); }}},
	{"cos", {1, [] (const auto& args) { return std::cos(args[0]); }}},
	{"tn", {1, [] (const auto& args) { return std::tan(args[0]); }}},
	{"arcsin", {1, [] (const auto& args) { return std::asin(args[0]); }}},
	{"arccos", {1, [] (const auto& args) { return std::acos(args[0]); }}},
	{"arctn", {1, [] (const auto& args) { return std::atan(args[0]); }}},
	{"angle", {2, [] (const auto& args) { return std::atan2(args[1], args[0]); }}},
	{"pow", {2, [] (const auto& args) { return std::pow(args[0], args[1]); }}},
	{"sqrt", {1, [] (const auto& args) { return std::sqrt(args[0]); }}},
	{"exp", {1, [] (const auto& args) { return std::exp(args[0]); }}},
	{"ln", {1, [] (const auto& args) { return std::log(args[0]); }}},
	{"lg", {1, [] (const auto& args) { return std::log10(args[0]); }}},
	{"abs", {1, [] (const auto& args) { return std::abs(args[0]); }}},
};

template<typename streamable>
void exit(const int& code, const streamable& message) {
	(code == EXIT_SUCCESS ? std::cout : std::cerr) << message << '\n';
	std::exit(code);
}

parser::rule_parser::pointer make_parser() {
	const auto expression_dummy = parser::dummy();
	RULE(function_call) = "identifier"_t >> &"("_v >>
		-(expression_dummy % &","_v)
	>> &")"_v;
	RULE(atom) = "number"_t
		| function_call
		| "identifier"_t
		| (&"("_v >> expression_dummy >> &")"_v);
	RULE(unary) = *("-"_v) >> atom;
	RULE(product) = unary % ("*"_v | "/"_v | "%"_v);
	RULE(sum) = product % ("+"_v | "-"_v);
	expression_dummy->set_parser(sum);

	return sum;
}

double evaluate_ast_node(
	const parser::ast_node& ast,
	const std::unordered_map<std::string, double>& constants,
	const std::unordered_map<std::string, function>& functions
) {
	const auto inspect_sequence = [] (const auto& ast) -> const auto& {
		return ast.children[0].children;
	};
	const auto evaluate_with_context = [&] (const auto& ast) {
		return evaluate_ast_node(ast, constants, functions);
	};

	if (ast.type == "number") {
		return std::stod(ast.value, nullptr);
	} else if (ast.type == "identifier") {
		try {
			return constants.at(ast.value);
		} catch (const std::out_of_range& exception) {
			const auto offset = parser::get_offset(ast);
			throw unexpected_entity_exception<entity_type::constant>{offset};
		}
	} else if (ast.type == "atom") {
		const auto type = (+parser::ast_node_type::sequence)._to_string();
		const auto first_child = ast.children[0].type == type
			? inspect_sequence(ast)[0]
			: ast.children[0];
		return evaluate_with_context(first_child);
	} else if (ast.type == "unary") {
		const auto result = evaluate_with_context(inspect_sequence(ast).back());
		const auto sign = (inspect_sequence(ast).size() - 1) % 2 ? -1 : 1;
		return sign * result;
	} else if (ast.type == "function_call") {
		try {
			const auto name = inspect_sequence(ast)[0].value;
			const auto arguments = inspect_sequence(ast)
				| ranges::view::drop(1)
				| ranges::view::transform([&] (const auto& ast) {
					return evaluate_with_context(ast);
				});
			const auto function = functions.at(name);
			if (arguments.size() != function.arity) {
				const auto unit = function.arity == 1 ? "argument" : "arguments";
				const auto description =
					fmt::format("function requires {:d} {:s}", function.arity, unit);
				const auto offset = parser::get_offset(ast);
				throw exceptions::positional_exception{description, offset};
			}

			return function.handler(arguments);
		} catch (const std::out_of_range& exception) {
			const auto offset = parser::get_offset(ast);
			throw unexpected_entity_exception<entity_type::function>{offset};
		}
	} else if (ast.type == "product" || ast.type == "sum") {
		const auto first_operand = evaluate_with_context(inspect_sequence(ast)[0]);
		const auto children_chunks = inspect_sequence(ast)
			| ranges::view::drop(1)
			| ranges::view::chunk(2)
			| ranges::view::transform([] (const auto& chunk) {
				return chunk | ranges::to_<parser::ast_node_group>();
			});
		return ranges::accumulate(
			children_chunks,
			first_operand,
			[&] (const auto& result, const auto& chunk) {
				const auto name = chunk[0].value;
				const auto second_operand = evaluate_with_context(chunk[1]);
				return functions.at(name).handler({result, second_operand});
			}
		);
	} else {
		const auto offset = parser::get_offset(ast);
		throw unexpected_entity_exception<entity_type::node>{offset};
	}
}

std::runtime_error enrich_exception(
	const exceptions::positional_exception& exception,
	const std::string_view& code,
	const std::size_t& mark_length
) {
	const auto mark_offset = std::string(exception.offset, ' ');
	const auto mark = std::string(mark_length, '^');
	return std::runtime_error{fmt::format(
		"{:s}\n| \"{:s}\"\n|  {:s}{:s}",
		exception.what(),
		code,
		mark_offset,
		mark
	)};
}

int main(int argc, char* argv[]) try {
	const auto options = docopt::docopt(usage, {argv+1, argv+argc}, true);
	const auto expression = options.at("<expression>")
		? options.at("<expression>").asString()
		: "";
	const auto code = options.at("--stdin").asBool()
		? std::string{std::istreambuf_iterator<char>{std::cin}, {}}
		: expression;
	const auto enrich = options.at("--verbose").asBool()
		? std::function{enrich_exception}
		: [] (
			const exceptions::positional_exception& exception,
			const std::string_view& code,
			const std::size_t& mark_length
		) { return exception; };
	try {
		auto tokens = lexer::tokenize_all(lexemes, lexemes_exceptions, code);
		if (options.at("--target") == "tokens"s) {
			exit(EXIT_SUCCESS, tokens);
		}

		const auto eoi = exceptions::entity_type::eoi;
		try {
			const auto ast = parser::parse_all(make_parser(), tokens);
			if (options.at("--target") == "cst"s) {
				exit(EXIT_SUCCESS, ast);
			}

			auto buffer = std::ostringstream{};
			const auto precision = options.at("--precision")
				? options.at("--precision").asLong()
				: std::numeric_limits<double>::max_digits10;
			const auto result = evaluate_ast_node(ast, constants, functions);
			buffer << std::setprecision(precision) << result;

			exit(EXIT_SUCCESS, buffer.str());
		} catch (const exceptions::unexpected_entity_exception<eoi>& exception) {
			const auto offset = exception.offset == utilities::integral_infinity
				? code.size()
				: exception.offset;
			throw exceptions::unexpected_entity_exception<eoi>{offset};
		} catch (const exceptions::positional_exception& exception) {
			const auto token = ranges::find_if(tokens, [&] (const auto& token) {
				return token.offset == exception.offset;
			});
			throw enrich(exception, code, token->value.size());
		}
	} catch (const exceptions::positional_exception& exception) {
		throw enrich(exception, code, 1);
	}
} catch (const std::exception& exception) {
	exit(EXIT_FAILURE, fmt::format("error: {:s}", exception.what()));
}
<commit_msg>Unifying header for all parsers: use it in the example<commit_after>#define THEWIZARDPLUSPLUS_WIZARD_PARSER_PARSER_MACROSES

#include "vendor/better-enums/enum_strict.hpp"
#include "vendor/range/v3/view/drop.hpp"
#include "vendor/range/v3/view/transform.hpp"
#include "vendor/fmt/format.hpp"
#include "vendor/range/v3/view/chunk.hpp"
#include "vendor/range/v3/to_container.hpp"
#include "vendor/range/v3/numeric/accumulate.hpp"
#include "vendor/docopt/docopt.hpp"
#include "vendor/range/v3/algorithm/find_if.hpp"
#include <thewizardplusplus/wizard_parser/exceptions/unexpected_entity_exception.hpp>
#include <thewizardplusplus/wizard_parser/lexer/lexeme.hpp>
#include <thewizardplusplus/wizard_parser/lexer/tokenize.hpp>
#include <thewizardplusplus/wizard_parser/parser/rule_parser.hpp>
#include <thewizardplusplus/wizard_parser/parser/parsers.hpp>
#include <thewizardplusplus/wizard_parser/parser/ast_node.hpp>
#include <thewizardplusplus/wizard_parser/exceptions/positional_exception.hpp>
#include <thewizardplusplus/wizard_parser/parser/parse.hpp>
#include <thewizardplusplus/wizard_parser/utilities/utilities.hpp>
#include <cstddef>
#include <functional>
#include <vector>
#include <cstdint>
#include <regex>
#include <unordered_map>
#include <string>
#include <cstdlib>
#include <iostream>
#include <stdexcept>
#include <string_view>
#include <iterator>
#include <sstream>
#include <limits>
#include <iomanip>
#include <exception>

using namespace thewizardplusplus::wizard_parser;
using namespace thewizardplusplus::wizard_parser::parser::operators;
using namespace std::literals::string_literals;

struct function final {
	const std::size_t arity;
	const std::function<double(const std::vector<double>&)> handler;
};

BETTER_ENUM(entity_type, std::uint8_t,
	node = exceptions::entity_type::_size(),
	constant,
	function
)

template<entity_type::_integral type>
using unexpected_entity_exception =
	exceptions::base_unexpected_entity_exception<entity_type, type>;

const auto usage =
R"(Usage:
  ./example [options] [--] [<expression>]

Options:
  -h, --help                           - show this message;
  -t TARGET, --target TARGET           - preliminary target of processing
                                       (allowed: tokens, cst);
  -p PRECISION, --precision PRECISION  - precision of a result;
  -s, --stdin                          - read an expression from stdin;
  -V, --verbose                        - mark an error.)";
const auto lexemes = lexer::lexeme_group{
	{std::regex{R"(\+)"}, "plus"},
	{std::regex{R"(-)"}, "minus"},
	{std::regex{R"(\*)"}, "star"},
	{std::regex{R"(/)"}, "slash"},
	{std::regex{R"(%)"}, "percent"},
	{std::regex{R"(\()"}, "opening_parenthesis"},
	{std::regex{R"(\))"}, "closing_parenthesis"},
	{std::regex{R"(,)"}, "comma"},
	{std::regex{R"(\d+(\.\d+)?(e-?\d+)?)"}, "number"},
	{std::regex{R"([A-Za-z_]\w*)"}, "identifier"},
	{std::regex{R"(\s+)"}, "whitespace"}
};
const auto lexemes_exceptions = lexer::type_group{"whitespace"};
// precision is taken from Boost 1.70.0, Math Toolkit 2.9.0
const auto constants = std::unordered_map<std::string, double>{
	{"pi", 3.141592653589793238462643383279502884},
	{"e", 2.718281828459045235360287471352662497}
};
const auto functions = std::unordered_map<std::string, function>{
	{"+", {2, [] (const auto& args) { return args[0] + args[1]; }}},
	{"-", {2, [] (const auto& args) { return args[0] - args[1]; }}},
	{"*", {2, [] (const auto& args) { return args[0] * args[1]; }}},
	{"/", {2, [] (const auto& args) { return args[0] / args[1]; }}},
	{"%", {2, [] (const auto& args) { return std::fmod(args[0], args[1]); }}},
	{"floor", {1, [] (const auto& args) { return std::floor(args[0]); }}},
	{"ceil", {1, [] (const auto& args) { return std::ceil(args[0]); }}},
	{"trunc", {1, [] (const auto& args) { return std::trunc(args[0]); }}},
	{"round", {1, [] (const auto& args) { return std::round(args[0]); }}},
	{"sin", {1, [] (const auto& args) { return std::sin(args[0]); }}},
	{"cos", {1, [] (const auto& args) { return std::cos(args[0]); }}},
	{"tn", {1, [] (const auto& args) { return std::tan(args[0]); }}},
	{"arcsin", {1, [] (const auto& args) { return std::asin(args[0]); }}},
	{"arccos", {1, [] (const auto& args) { return std::acos(args[0]); }}},
	{"arctn", {1, [] (const auto& args) { return std::atan(args[0]); }}},
	{"angle", {2, [] (const auto& args) { return std::atan2(args[1], args[0]); }}},
	{"pow", {2, [] (const auto& args) { return std::pow(args[0], args[1]); }}},
	{"sqrt", {1, [] (const auto& args) { return std::sqrt(args[0]); }}},
	{"exp", {1, [] (const auto& args) { return std::exp(args[0]); }}},
	{"ln", {1, [] (const auto& args) { return std::log(args[0]); }}},
	{"lg", {1, [] (const auto& args) { return std::log10(args[0]); }}},
	{"abs", {1, [] (const auto& args) { return std::abs(args[0]); }}},
};

template<typename streamable>
void exit(const int& code, const streamable& message) {
	(code == EXIT_SUCCESS ? std::cout : std::cerr) << message << '\n';
	std::exit(code);
}

parser::rule_parser::pointer make_parser() {
	const auto expression_dummy = parser::dummy();
	RULE(function_call) = "identifier"_t >> &"("_v >>
		-(expression_dummy % &","_v)
	>> &")"_v;
	RULE(atom) = "number"_t
		| function_call
		| "identifier"_t
		| (&"("_v >> expression_dummy >> &")"_v);
	RULE(unary) = *("-"_v) >> atom;
	RULE(product) = unary % ("*"_v | "/"_v | "%"_v);
	RULE(sum) = product % ("+"_v | "-"_v);
	expression_dummy->set_parser(sum);

	return sum;
}

double evaluate_ast_node(
	const parser::ast_node& ast,
	const std::unordered_map<std::string, double>& constants,
	const std::unordered_map<std::string, function>& functions
) {
	const auto inspect_sequence = [] (const auto& ast) -> const auto& {
		return ast.children[0].children;
	};
	const auto evaluate_with_context = [&] (const auto& ast) {
		return evaluate_ast_node(ast, constants, functions);
	};

	if (ast.type == "number") {
		return std::stod(ast.value, nullptr);
	} else if (ast.type == "identifier") {
		try {
			return constants.at(ast.value);
		} catch (const std::out_of_range& exception) {
			const auto offset = parser::get_offset(ast);
			throw unexpected_entity_exception<entity_type::constant>{offset};
		}
	} else if (ast.type == "atom") {
		const auto type = (+parser::ast_node_type::sequence)._to_string();
		const auto first_child = ast.children[0].type == type
			? inspect_sequence(ast)[0]
			: ast.children[0];
		return evaluate_with_context(first_child);
	} else if (ast.type == "unary") {
		const auto result = evaluate_with_context(inspect_sequence(ast).back());
		const auto sign = (inspect_sequence(ast).size() - 1) % 2 ? -1 : 1;
		return sign * result;
	} else if (ast.type == "function_call") {
		try {
			const auto name = inspect_sequence(ast)[0].value;
			const auto arguments = inspect_sequence(ast)
				| ranges::view::drop(1)
				| ranges::view::transform([&] (const auto& ast) {
					return evaluate_with_context(ast);
				});
			const auto function = functions.at(name);
			if (arguments.size() != function.arity) {
				const auto unit = function.arity == 1 ? "argument" : "arguments";
				const auto description =
					fmt::format("function requires {:d} {:s}", function.arity, unit);
				const auto offset = parser::get_offset(ast);
				throw exceptions::positional_exception{description, offset};
			}

			return function.handler(arguments);
		} catch (const std::out_of_range& exception) {
			const auto offset = parser::get_offset(ast);
			throw unexpected_entity_exception<entity_type::function>{offset};
		}
	} else if (ast.type == "product" || ast.type == "sum") {
		const auto first_operand = evaluate_with_context(inspect_sequence(ast)[0]);
		const auto children_chunks = inspect_sequence(ast)
			| ranges::view::drop(1)
			| ranges::view::chunk(2)
			| ranges::view::transform([] (const auto& chunk) {
				return chunk | ranges::to_<parser::ast_node_group>();
			});
		return ranges::accumulate(
			children_chunks,
			first_operand,
			[&] (const auto& result, const auto& chunk) {
				const auto name = chunk[0].value;
				const auto second_operand = evaluate_with_context(chunk[1]);
				return functions.at(name).handler({result, second_operand});
			}
		);
	} else {
		const auto offset = parser::get_offset(ast);
		throw unexpected_entity_exception<entity_type::node>{offset};
	}
}

std::runtime_error enrich_exception(
	const exceptions::positional_exception& exception,
	const std::string_view& code,
	const std::size_t& mark_length
) {
	const auto mark_offset = std::string(exception.offset, ' ');
	const auto mark = std::string(mark_length, '^');
	return std::runtime_error{fmt::format(
		"{:s}\n| \"{:s}\"\n|  {:s}{:s}",
		exception.what(),
		code,
		mark_offset,
		mark
	)};
}

int main(int argc, char* argv[]) try {
	const auto options = docopt::docopt(usage, {argv+1, argv+argc}, true);
	const auto expression = options.at("<expression>")
		? options.at("<expression>").asString()
		: "";
	const auto code = options.at("--stdin").asBool()
		? std::string{std::istreambuf_iterator<char>{std::cin}, {}}
		: expression;
	const auto enrich = options.at("--verbose").asBool()
		? std::function{enrich_exception}
		: [] (
			const exceptions::positional_exception& exception,
			const std::string_view& code,
			const std::size_t& mark_length
		) { return exception; };
	try {
		auto tokens = lexer::tokenize_all(lexemes, lexemes_exceptions, code);
		if (options.at("--target") == "tokens"s) {
			exit(EXIT_SUCCESS, tokens);
		}

		const auto eoi = exceptions::entity_type::eoi;
		try {
			const auto ast = parser::parse_all(make_parser(), tokens);
			if (options.at("--target") == "cst"s) {
				exit(EXIT_SUCCESS, ast);
			}

			auto buffer = std::ostringstream{};
			const auto precision = options.at("--precision")
				? options.at("--precision").asLong()
				: std::numeric_limits<double>::max_digits10;
			const auto result = evaluate_ast_node(ast, constants, functions);
			buffer << std::setprecision(precision) << result;

			exit(EXIT_SUCCESS, buffer.str());
		} catch (const exceptions::unexpected_entity_exception<eoi>& exception) {
			const auto offset = exception.offset == utilities::integral_infinity
				? code.size()
				: exception.offset;
			throw exceptions::unexpected_entity_exception<eoi>{offset};
		} catch (const exceptions::positional_exception& exception) {
			const auto token = ranges::find_if(tokens, [&] (const auto& token) {
				return token.offset == exception.offset;
			});
			throw enrich(exception, code, token->value.size());
		}
	} catch (const exceptions::positional_exception& exception) {
		throw enrich(exception, code, 1);
	}
} catch (const std::exception& exception) {
	exit(EXIT_FAILURE, fmt::format("error: {:s}", exception.what()));
}
<|endoftext|>


<commit_before>/**
 ** \file rewrite/rescoper.cc
 ** \brief Implementation of rewrite::Rescoper.
 */

#include <ast/flavor.hh>
#include <ast/parametric-ast.hh>
#include <parser/ast-factory.hh>
#include <rewrite/rescoper.hh>

namespace rewrite
{

  /*----------.
  | Helpers.  |
  `----------*/

  namespace
  {
    static
    ast::rExp
    make_declaration(const ast::loc& l, libport::Symbol s)
    {
      static ast::ParametricAst a("nil");
      return new ast::Declaration(l, s, exp(a));
    }

    static
    ast::rExp
    make_assignment(const ast::loc& l, libport::Symbol s, ast::rExp value)
    {
      return parser::ast_closure(new ast::Assignment(l, s, value, 0));
    }
  }

  Rescoper::Rescoper()
  {}

  Rescoper::~Rescoper()
  {}

  void Rescoper::visit(ast::rConstAnd a)
  {
    ast::rAnd res = new ast::And(a->location_get(), ast::exps_type());
    foreach (ast::rExp child, a->children_get())
      // Wrap every children in a closure
      res->children_get().push_back(recurse(parser::ast_closure(child)));
    result_ = res;
  }

  void
  Rescoper::visit(ast::rConstNary nary)
  {
    ast::rNary res = new ast::Nary(nary->location_get());
    foreach (ast::rExp child, (nary->children_get()))
    {
      ast::rStmt stm = child.unsafe_cast<ast::Stmt>();
      if (stm && stm->flavor_get() == ast::flavor_comma)
      {
        if (ast::rDeclaration dec =
            stm->expression_get().unsafe_cast<ast::Declaration>())
        {
          const ast::loc l = dec->location_get();
          const libport::Symbol s = dec->what_get();
          res->push_back(recurse(make_declaration(l, s)),
                         ast::flavor_semicolon);
          res->push_back(recurse(make_assignment(l, s, dec->value_get())),
                         ast::flavor_comma);
        }
        else
          res->push_back(recurse(parser::ast_closure(child)),
                         ast::flavor_comma);
      }
      else
        res->push_back(recurse(child));
    }
    result_ = res;
  }

}
<commit_msg>Unscope variables declared as '&' operands.<commit_after>/**
 ** \file rewrite/rescoper.cc
 ** \brief Implementation of rewrite::Rescoper.
 */

#include <ast/flavor.hh>
#include <ast/parametric-ast.hh>
#include <parser/ast-factory.hh>
#include <rewrite/rescoper.hh>

namespace rewrite
{

  /*----------.
  | Helpers.  |
  `----------*/

  namespace
  {
    static
    ast::rExp
    make_declaration(const ast::loc& l, libport::Symbol s)
    {
      static ast::ParametricAst a("nil");
      return new ast::Declaration(l, s, exp(a));
    }

    static
    ast::rExp
    make_assignment(const ast::loc& l, libport::Symbol s, ast::rExp value)
    {
      return new ast::Assignment(l, s, value, 0);
    }
  }

  Rescoper::Rescoper()
  {}

  Rescoper::~Rescoper()
  {}

  void Rescoper::visit(ast::rConstAnd a)
  {
    ast::loc l = a->location_get();
    ast::rAnd res = new ast::And(l, ast::exps_type());
    ast::rNary nary = new ast::Nary(l);
    foreach (ast::rExp child, a->children_get())
    {
      if (ast::rConstDeclaration dec =
          child.unsafe_cast<const ast::Declaration>())
      {
        const libport::Symbol name = dec->what_get();
        nary->push_back(make_declaration(l, name), ast::flavor_pipe);
        child = make_assignment(l, name, dec->value_get());
      }
      // Wrap every child in a closure
      res->children_get().push_back(recurse(parser::ast_closure(child)));
    }

    nary->push_back(res);
    result_ = nary;
  }

  void
  Rescoper::visit(ast::rConstNary nary)
  {
    ast::rNary res = new ast::Nary(nary->location_get());
    foreach (ast::rExp child, (nary->children_get()))
    {
      ast::rStmt stm = child.unsafe_cast<ast::Stmt>();
      if (stm && stm->flavor_get() == ast::flavor_comma)
      {
        if (ast::rDeclaration dec =
            stm->expression_get().unsafe_cast<ast::Declaration>())
        {
          const ast::loc l = dec->location_get();
          const libport::Symbol s = dec->what_get();
          res->push_back(recurse(make_declaration(l, s)),
                         ast::flavor_semicolon);
          res->push_back(
            recurse(
              parser::ast_closure(make_assignment(l, s, dec->value_get()))),
            ast::flavor_comma);
        }
        else
          res->push_back(recurse(parser::ast_closure(child)),
                         ast::flavor_comma);
      }
      else
        res->push_back(recurse(child));
    }
    result_ = res;
  }

}
<|endoftext|>


<commit_before>/* bzflag
 * Copyright (c) 1993 - 2005 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named LICENSE that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

/* interface header */
#include "LagInfo.h"

float LagInfo::threshold = 0.0;
float LagInfo::max       = 0.0;

LagInfo::LagInfo(PlayerInfo *_info)
  : info(_info), lagavg(0), jitteravg(0), lostavg(0), lagalpha(1),
    jitteralpha(1), lostalpha(1), lagcount(0), laglastwarn(0), lagwarncount(0),
    pingpending(false), pingseqno(0), pingssent(0), lasttimestamp(0.0f) {
}

void LagInfo::reset()
{
  nextping       = info->now;
  nextping      += 10.0;
  lastupdate     = info->now;
}

int LagInfo::getLag() const
{
  return int(lagavg * 1000);
}

void LagInfo::getLagStats(char* msg) const
{
  msg[0] = 0;
  if (!info->isPlaying() || !info->isHuman())
    return;

  // don't wait for ping to come back
  int lag = int(lagavg * 1000);
  if (pingpending) {
    float timepassed = info->now - lastping;
    int lastLag = int((lagavg * (1 - lagalpha) + lagalpha * timepassed) * 1000);
    if (lastLag > lag)
      lag = lastLag;
  }
  sprintf(msg,"%s\t: %3d +- %2dms", info->getCallSign(),
	  lag, int(jitteravg * 1000));
  if (lostavg >= 0.01f)
    sprintf(msg + strlen(msg), " %d%% lost/ooo", int(lostavg * 100));
}

// update absolute latency based on LagPing messages
int LagInfo::updatePingLag(void *buf, bool &warn, bool &kick) {
  uint16_t _pingseqno;
  int lag = 0;
  nboUnpackUShort(buf, _pingseqno);
  if (pingseqno == _pingseqno) {
    float timepassed = info->now - lastping;
    // time is smoothed exponentially using a dynamic smoothing factor
    lagavg   = lagavg * (1 - lagalpha) + lagalpha * timepassed;
    lagalpha = lagalpha / (0.9f + lagalpha);
    lag      = int(lagavg * 1000);
    lagcount++;

    // if lag has been good for some time, forget old warnings
    if (lagavg < threshold && lagcount - laglastwarn >= 20)
      lagwarncount = 0;

    // warn players from time to time whose lag is > threshold (-lagwarn)
    if (!info->isObserver() && (threshold > 0) && lagavg > threshold
	&& lagcount - laglastwarn > 2 * lagwarncount) {
      laglastwarn = lagcount;
      warn = true;
      kick = (lagwarncount++ > max);
    } else {
      warn = false;
      kick = false;
    }
    lostavg     = lostavg * (1 - lostalpha);
    lostalpha   = lostalpha / (0.99f + lostalpha);
    pingpending = false;
  } else {
    warn = false;
    kick = false;
  }
  return lag;
}

void LagInfo::updateLag(float timestamp, bool ooo) {
  if (!info->isPlaying())
    return;
  if (ooo) {
    lostavg   = lostavg * (1 - lostalpha) + lostalpha;
    lostalpha = lostalpha / (0.99f + lostalpha);
  }
  // don't calc jitter if more than 2 seconds between packets
  if (lasttimestamp > 0.0f && timestamp - lasttimestamp < 2.0f) {
    const float jitter = fabs(info->now - lastupdate
			      - (timestamp - lasttimestamp));
    // time is smoothed exponentially using a dynamic smoothing factor
    jitteravg   = jitteravg * (1 - jitteralpha) + jitteralpha * fabs(jitter);
    jitteralpha = jitteralpha / (0.99f + jitteralpha);
    lostavg     = lostavg * (1 - lostalpha);
    lostalpha   = lostalpha / (0.99f + lostalpha);
  }
  lasttimestamp = timestamp;
  lastupdate    = info->now;
}

int LagInfo::getNextPingSeqno(bool &warn, bool &kick) {

  warn = false;
  kick = false;

  if (!info->isPlaying() || !info->isHuman())
    return -1;

  if (info->now <= nextping)
    // no time for pinging
    return -1;

  pingseqno = (pingseqno + 1) % 10000;
  if (pingpending) {
    // ping lost
    lostavg   = lostavg * (1 - lostalpha) + lostalpha;
    lostalpha = lostalpha / (0.99f + lostalpha);
    if (!info->isObserver() && (threshold > 0)
	&& lagcount - laglastwarn > 2 * lagwarncount) {
      laglastwarn = lagcount;
      warn = true;
      kick = (lagwarncount++ > max);
    }
  }

  pingpending = true;
  lastping    = info->now;
  nextping    = info->now;
  nextping   += 10.0f;
  pingssent++;
  return pingseqno;
}

// update absolute latency based on LagPing messages
void LagInfo::updateLatency(float &waitTime) {
  if (!info->isPlaying() || !info->isHuman())
    return;
  float delta = nextping - info->now;
  if (delta < waitTime)
    waitTime  = delta;
}

void LagInfo::setThreshold(float _threshold, float _max) {
  threshold = _threshold;
  max       = _max;
}

// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>Don't take into account ping loss for now<commit_after>/* bzflag
 * Copyright (c) 1993 - 2005 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named LICENSE that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

/* interface header */
#include "LagInfo.h"

float LagInfo::threshold = 0.0;
float LagInfo::max       = 0.0;

LagInfo::LagInfo(PlayerInfo *_info)
  : info(_info), lagavg(0), jitteravg(0), lostavg(0), lagalpha(1),
    jitteralpha(1), lostalpha(1), lagcount(0), laglastwarn(0), lagwarncount(0),
    pingpending(false), pingseqno(0), pingssent(0), lasttimestamp(0.0f) {
}

void LagInfo::reset()
{
  nextping       = info->now;
  nextping      += 10.0;
  lastupdate     = info->now;
}

int LagInfo::getLag() const
{
  return int(lagavg * 1000);
}

void LagInfo::getLagStats(char* msg) const
{
  msg[0] = 0;
  if (!info->isPlaying() || !info->isHuman())
    return;

  // don't wait for ping to come back
  int lag = int(lagavg * 1000);
  if (pingpending) {
    float timepassed = info->now - lastping;
    int lastLag = int((lagavg * (1 - lagalpha) + lagalpha * timepassed) * 1000);
    if (lastLag > lag)
      lag = lastLag;
  }
  sprintf(msg,"%s\t: %3d +- %2dms", info->getCallSign(),
	  lag, int(jitteravg * 1000));
  if (lostavg >= 0.01f)
    sprintf(msg + strlen(msg), " %d%% lost/ooo", int(lostavg * 100));
}

// update absolute latency based on LagPing messages
int LagInfo::updatePingLag(void *buf, bool &warn, bool &kick) {
  uint16_t _pingseqno;
  int lag = 0;
  nboUnpackUShort(buf, _pingseqno);
  if (pingseqno == _pingseqno) {
    float timepassed = info->now - lastping;
    // time is smoothed exponentially using a dynamic smoothing factor
    lagavg   = lagavg * (1 - lagalpha) + lagalpha * timepassed;
    lagalpha = lagalpha / (0.9f + lagalpha);
    lag      = int(lagavg * 1000);
    lagcount++;

    // if lag has been good for some time, forget old warnings
    if (lagavg < threshold && lagcount - laglastwarn >= 20)
      lagwarncount = 0;

    // warn players from time to time whose lag is > threshold (-lagwarn)
    if (!info->isObserver() && (threshold > 0) && lagavg > threshold
	&& lagcount - laglastwarn > 2 * lagwarncount) {
      laglastwarn = lagcount;
      warn = true;
      kick = (lagwarncount++ > max);
    } else {
      warn = false;
      kick = false;
    }
    lostavg     = lostavg * (1 - lostalpha);
    lostalpha   = lostalpha / (0.99f + lostalpha);
    pingpending = false;
  } else {
    warn = false;
    kick = false;
  }
  return lag;
}

void LagInfo::updateLag(float timestamp, bool ooo) {
  if (!info->isPlaying())
    return;
  if (ooo) {
    lostavg   = lostavg * (1 - lostalpha) + lostalpha;
    lostalpha = lostalpha / (0.99f + lostalpha);
  }
  // don't calc jitter if more than 2 seconds between packets
  if (lasttimestamp > 0.0f && timestamp - lasttimestamp < 2.0f) {
    const float jitter = fabs(info->now - lastupdate
			      - (timestamp - lasttimestamp));
    // time is smoothed exponentially using a dynamic smoothing factor
    jitteravg   = jitteravg * (1 - jitteralpha) + jitteralpha * fabs(jitter);
    jitteralpha = jitteralpha / (0.99f + jitteralpha);
    lostavg     = lostavg * (1 - lostalpha);
    lostalpha   = lostalpha / (0.99f + lostalpha);
  }
  lasttimestamp = timestamp;
  lastupdate    = info->now;
}

int LagInfo::getNextPingSeqno(bool &warn, bool &kick) {

  warn = false;
  kick = false;

  if (!info->isPlaying() || !info->isHuman())
    return -1;

  if (info->now <= nextping)
    // no time for pinging
    return -1;

  pingseqno = (pingseqno + 1) % 10000;
  if (pingpending) {
    // ping lost
    lostavg   = lostavg * (1 - lostalpha) + lostalpha;
    lostalpha = lostalpha / (0.99f + lostalpha);
  }

  pingpending = true;
  lastping    = info->now;
  nextping    = info->now;
  nextping   += 10.0f;
  pingssent++;
  return pingseqno;
}

// update absolute latency based on LagPing messages
void LagInfo::updateLatency(float &waitTime) {
  if (!info->isPlaying() || !info->isHuman())
    return;
  float delta = nextping - info->now;
  if (delta < waitTime)
    waitTime  = delta;
}

void LagInfo::setThreshold(float _threshold, float _max) {
  threshold = _threshold;
  max       = _max;
}

// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>
#include <vector>
#include <string>

using namespace std;

int main()
{
	vector<string> directories;
	directories.push_back(string("10.1"));
	directories.push_back(string("10.2"));
	directories.push_back(string("10.3"));
	directories.push_back(string("10.4"));
	directories.push_back(string("10.5"));
	directories.push_back(string("10.6"));

	fstream fout1("logw.txt", ios::out);
	fstream fout2("scalars.txt", ios::out);

	int k = 0;
	for(size_t i=0; i<directories.size(); i++)
	{
		string filename1 = directories[i] + string("/logw.txt");
		fstream fin1(filename1.c_str(), ios::in);

		string filename2 = directories[i] + string("/scalars.txt");
		fstream fin2(filename2.c_str(), ios::in);

		double temp1, temp2, temp3;
		while(fin1>>temp1 && fin2>>temp2 && fin2>>temp3)
		{
			fout1<<temp1<<endl;
			fout2<<temp2<<' '<<temp3<<endl;
			k++;
		}

		fin1.close();
		fin2.close();

		cout<<"# Processed "<<k<<" points."<<endl;
	}

	fout1.close();
	fout2.close();

	return 0;
}

<commit_msg>Two more directories<commit_after>#include <iostream>
#include <fstream>
#include <vector>
#include <string>

using namespace std;

int main()
{
	vector<string> directories;
	directories.push_back(string("10.1"));
	directories.push_back(string("10.2"));
	directories.push_back(string("10.3"));
	directories.push_back(string("10.4"));
	directories.push_back(string("10.5"));
	directories.push_back(string("10.6"));
	directories.push_back(string("10.7"));
	directories.push_back(string("10.8"));

	fstream fout1("logw.txt", ios::out);
	fstream fout2("scalars.txt", ios::out);

	int k = 0;
	for(size_t i=0; i<directories.size(); i++)
	{
		string filename1 = directories[i] + string("/logw.txt");
		fstream fin1(filename1.c_str(), ios::in);

		string filename2 = directories[i] + string("/scalars.txt");
		fstream fin2(filename2.c_str(), ios::in);

		double temp1, temp2, temp3;
		while(fin1>>temp1 && fin2>>temp2 && fin2>>temp3)
		{
			fout1<<temp1<<endl;
			fout2<<temp2<<' '<<temp3<<endl;
			k++;
		}

		fin1.close();
		fin2.close();

		cout<<"# Processed "<<k<<" points."<<endl;
	}

	fout1.close();
	fout2.close();

	return 0;
}

<|endoftext|>


<commit_before>/*
# Copyright (c) 2011, Georgia Tech Research Corporation
# 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 Georgia Tech Research Corporation 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 GEORGIA TECH RESEARCH CORPORATION ''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 GEORGIA TECH 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.
#

## author Advait Jain (Healthcare Robotics Lab, Georgia Tech.)
## author Chih-Hung Aaron King (Healthcare Robotics Lab, Georgia Tech.)
*/

//== This application listens for a rigid body named 'Tracker' on a remote machine
//== and publishes & tf it's position and orientation through ROS.

#include <ros/ros.h>
#include <tf/transform_broadcaster.h>
#include <geometry_msgs/TransformStamped.h>
#include <stdio.h>
#include <math.h>

#include <vrpn_Connection.h>
#include <vrpn_Tracker.h>

#include <LinearMath/btQuaternion.h>

void VRPN_CALLBACK track_target (void *, const vrpn_TRACKERCB t);

class TargetState{
    public:
        geometry_msgs::TransformStamped target;
};

TargetState *target_state;
std::string frame_id;
std::string corrdinate_system_string;

enum CoordinateSystem {
  vicon,
  optitrack
} corrdinate_system;

// set to true in the VRPN callback function.
bool fresh_data = false;
vrpn_TRACKERCB prev_vrpn_data;

class Rigid_Body {
    private:
        ros::Publisher target_pub;
        tf::TransformBroadcaster br;
        vrpn_Connection *connection;
        vrpn_Tracker_Remote *tracker;

    public:
        Rigid_Body(ros::NodeHandle& nh, std::string server_ip,
                   int port)
        {
            target_pub = nh.advertise<geometry_msgs::TransformStamped>("pose", 100);
            std::string connec_nm = server_ip + ":" + boost::lexical_cast<std::string>(port);
            connection = vrpn_get_connection_by_name(connec_nm.c_str());
            std::string target_name = nh.getNamespace().substr(1);
            tracker = new vrpn_Tracker_Remote(target_name.c_str(), connection);
            this->tracker->register_change_handler(NULL, track_target);
        }

        void publish_target_state(TargetState *target_state)
        {
            br.sendTransform(target_state->target);
            target_pub.publish(target_state->target);
        }

        void step_vrpn()
        {
            this->tracker->mainloop();
            this->connection->mainloop();
        }
};

//== Tracker Position/Orientation Callback ==--
void VRPN_CALLBACK track_target (void *, const vrpn_TRACKERCB t)
{
    btQuaternion q_orig(t.quat[0], t.quat[1], t.quat[2], t.quat[3]);
    btQuaternion q_fix(0.70710678, 0., 0., 0.70710678);

    btQuaternion q_rot;
    btVector3 pos;
    switch(corrdinate_system) {
      case optitrack: {
        // optitrak <-- funky <-- object
        // the q_fix.inverse() esures that when optitrak_funky says 0 0 0
        // for roll pitch yaw, there is still a rotation that aligns the
        // object frame with the /optitrak frame (and not /optitrak_funky)
        q_rot = q_fix * q_orig * q_fix.inverse();
        pos = btVector3(t.pos[0], -t.pos[2], t.pos[1]);
        break;
      }
      case vicon: {
        q_rot = q_orig;  //TODO(gohlp) verify this
        pos = btVector3(t.pos[0], t.pos[1], t.pos[2]);
        break;
      }
      default: {
        ROS_FATAL("Coordinate system not defined!");
        break;
      }
    }

    // verifying that each callback indeed gives fresh data.
    if ( prev_vrpn_data.quat[0] == t.quat[0] and \
         prev_vrpn_data.quat[1] == t.quat[1] and \
         prev_vrpn_data.quat[2] == t.quat[2] and \
         prev_vrpn_data.quat[3] == t.quat[3] and \
         prev_vrpn_data.pos[0] == t.pos[0] and \
         prev_vrpn_data.pos[1] == t.pos[1] and \
         prev_vrpn_data.pos[2] == t.pos[2] )
        ROS_WARN("Repeated Values");

    prev_vrpn_data = t;

    target_state->target.transform.translation.x = pos.x();
    target_state->target.transform.translation.y = pos.y();
    target_state->target.transform.translation.z = pos.z();

    target_state->target.transform.rotation.x = q_rot.x();
    target_state->target.transform.rotation.y = q_rot.y();
    target_state->target.transform.rotation.z = q_rot.z();
    target_state->target.transform.rotation.w = q_rot.w();

    target_state->target.header.frame_id = corrdinate_system_string;
    target_state->target.child_frame_id = frame_id;
    target_state->target.header.stamp = ros::Time::now();

    fresh_data = true;
}

int main(int argc, char* argv[])
{
    ros::init(argc, argv, "vrpn_tracked_object_1");
    ros::NodeHandle nh("~");

    target_state = new TargetState;
    //frame_id = nh.getNamespace().substr(1);
    frame_id = nh.getNamespace();

    std::string vrpn_server_ip;
    int vrpn_port;
    std::string tracked_object_name;

    nh.param<std::string>("vrpn_server_ip", vrpn_server_ip, std::string());
    nh.param<int>("vrpn_port", vrpn_port, 3883);
    nh.param<std::string>("vrpn_coordinate_system", corrdinate_system_string, "vicon");

    std::cout<<"vrpn_server_ip:"<<vrpn_server_ip<<std::endl;
    std::cout<<"vrpn_port:"<<vrpn_port<<std::endl;
    std::cout << "vrpn_coordinate_system:" << corrdinate_system_string << std::endl;

    if(corrdinate_system_string == std::string("vicon")) {

    } else if(corrdinate_system_string == std::string("optitrack")) {

    } else {
      ROS_FATAL("ROS param vrpn_coordinate_system should be either 'vicon' or 'optitrack'!");
    }

    Rigid_Body tool(nh, vrpn_server_ip, vrpn_port);

    ros::Rate loop_rate(1000); //TODO(gohlp): fix this

    while(ros::ok())
    {
        tool.step_vrpn();
        //vrpn_SleepMsecs(10);
        if (fresh_data == true)
        { // only publish when receive data over VRPN.
            tool.publish_target_state(target_state);
            fresh_data = false;
        }
        //ros::spinOnce();
        loop_rate.sleep();
    }
	return 0;
}

<commit_msg>clean up<commit_after>/*
# Copyright (c) 2011, Georgia Tech Research Corporation
# 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 Georgia Tech Research Corporation 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 GEORGIA TECH RESEARCH CORPORATION ''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 GEORGIA TECH 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.
#

## author Advait Jain (Healthcare Robotics Lab, Georgia Tech.)
## author Chih-Hung Aaron King (Healthcare Robotics Lab, Georgia Tech.)
*/

//== This application listens for a rigid body named 'Tracker' on a remote machine
//== and publishes & tf it's position and orientation through ROS.

#include <ros/ros.h>
#include <tf/transform_broadcaster.h>
#include <geometry_msgs/TransformStamped.h>
#include <stdio.h>
#include <math.h>

#include <vrpn_Connection.h>
#include <vrpn_Tracker.h>

#include <LinearMath/btQuaternion.h>

void VRPN_CALLBACK track_target (void *, const vrpn_TRACKERCB t);

class TargetState{
    public:
        geometry_msgs::TransformStamped target;
};

TargetState *target_state;
std::string frame_id;
std::string corrdinate_system_string;

enum CoordinateSystem {
  vicon,
  optitrack
} corrdinate_system;

// set to true in the VRPN callback function.
bool fresh_data = false;
vrpn_TRACKERCB prev_vrpn_data;

class Rigid_Body {
    private:
        ros::Publisher target_pub;
        tf::TransformBroadcaster br;
        vrpn_Connection *connection;
        vrpn_Tracker_Remote *tracker;

    public:
        Rigid_Body(ros::NodeHandle& nh, std::string server_ip,
                   int port)
        {
            target_pub = nh.advertise<geometry_msgs::TransformStamped>("pose", 100);
            std::string connec_nm = server_ip + ":" + boost::lexical_cast<std::string>(port);
            connection = vrpn_get_connection_by_name(connec_nm.c_str());
            std::string target_name = nh.getNamespace().substr(1);
            tracker = new vrpn_Tracker_Remote(target_name.c_str(), connection);
            this->tracker->register_change_handler(NULL, track_target);
        }

        void publish_target_state(TargetState *target_state)
        {
            br.sendTransform(target_state->target);
            target_pub.publish(target_state->target);
        }

        void step_vrpn()
        {
            this->tracker->mainloop();
            this->connection->mainloop();
        }
};

//== Tracker Position/Orientation Callback ==--
void VRPN_CALLBACK track_target (void *, const vrpn_TRACKERCB t)
{
    btQuaternion q_orig(t.quat[0], t.quat[1], t.quat[2], t.quat[3]);
    btQuaternion q_fix(0.70710678, 0., 0., 0.70710678);

    btQuaternion q_rot;
    btVector3 pos;
    switch(corrdinate_system) {
      case optitrack: {
        // optitrak <-- funky <-- object
        // the q_fix.inverse() esures that when optitrak_funky says 0 0 0
        // for roll pitch yaw, there is still a rotation that aligns the
        // object frame with the /optitrak frame (and not /optitrak_funky)
        q_rot = q_fix * q_orig * q_fix.inverse();
        pos = btVector3(t.pos[0], -t.pos[2], t.pos[1]);
        break;
      }
      case vicon: {
        q_rot = q_orig;
        pos = btVector3(t.pos[0], t.pos[1], t.pos[2]);
        break;
      }
      default: {
        ROS_FATAL("Coordinate system not defined!");
        break;
      }
    }

    // verifying that each callback indeed gives fresh data.
    if ( prev_vrpn_data.quat[0] == t.quat[0] and \
         prev_vrpn_data.quat[1] == t.quat[1] and \
         prev_vrpn_data.quat[2] == t.quat[2] and \
         prev_vrpn_data.quat[3] == t.quat[3] and \
         prev_vrpn_data.pos[0] == t.pos[0] and \
         prev_vrpn_data.pos[1] == t.pos[1] and \
         prev_vrpn_data.pos[2] == t.pos[2] )
        ROS_WARN("Repeated Values");

    prev_vrpn_data = t;

    target_state->target.transform.translation.x = pos.x();
    target_state->target.transform.translation.y = pos.y();
    target_state->target.transform.translation.z = pos.z();

    target_state->target.transform.rotation.x = q_rot.x();
    target_state->target.transform.rotation.y = q_rot.y();
    target_state->target.transform.rotation.z = q_rot.z();
    target_state->target.transform.rotation.w = q_rot.w();

    target_state->target.header.frame_id = corrdinate_system_string;
    target_state->target.child_frame_id = frame_id;
    target_state->target.header.stamp = ros::Time::now();

    fresh_data = true;
}

int main(int argc, char* argv[])
{
    ros::init(argc, argv, "vrpn_tracked_object_1");
    ros::NodeHandle nh("~");

    target_state = new TargetState;
    //frame_id = nh.getNamespace().substr(1);
    frame_id = nh.getNamespace();

    std::string vrpn_server_ip;
    int vrpn_port;
    std::string tracked_object_name;

    nh.param<std::string>("vrpn_server_ip", vrpn_server_ip, std::string());
    nh.param<int>("vrpn_port", vrpn_port, 3883);
    nh.param<std::string>("vrpn_coordinate_system", corrdinate_system_string, "vicon");

    std::cout<<"vrpn_server_ip:"<<vrpn_server_ip<<std::endl;
    std::cout<<"vrpn_port:"<<vrpn_port<<std::endl;
    std::cout << "vrpn_coordinate_system:" << corrdinate_system_string << std::endl;

    if(corrdinate_system_string == std::string("vicon")) {

    } else if(corrdinate_system_string == std::string("optitrack")) {

    } else {
      ROS_FATAL("ROS param vrpn_coordinate_system should be either 'vicon' or 'optitrack'!");
    }

    Rigid_Body tool(nh, vrpn_server_ip, vrpn_port);

    ros::Rate loop_rate(1000); //TODO(gohlp): fix this

    while(ros::ok())
    {
        tool.step_vrpn();
        //vrpn_SleepMsecs(10);
        if (fresh_data == true)
        { // only publish when receive data over VRPN.
            tool.publish_target_state(target_state);
            fresh_data = false;
        }
        //ros::spinOnce();
        loop_rate.sleep();
    }
	return 0;
}

<|endoftext|>