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

#include "CEGUI/CEGUI.h"

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

using namespace CEGUI;

struct GamePlate
{
    GamePlate(HUDDemo* hudDemo);
    ~GamePlate();

    void update(float timeSinceLastUpdate);
    int getPoints();

    CEGUI::Window* d_window;
    bool d_isComingFromRight;
    bool d_isDestroyed;
};

GamePlate::GamePlate(HUDDemo* hudDemo)
    : d_isDestroyed(false)
{
    d_window = hudDemo->spawnPlate();

    int randumNumber = rand() % 2;
    d_isComingFromRight = (randumNumber == 0 ? false : true);

    if(d_isComingFromRight)
    {
        d_window->setHorizontalAlignment(HA_RIGHT);
        d_window->setPosition(d_window->getPosition() + CEGUI::UVector2(cegui_reldim(0.2f), cegui_absdim(0.0f)));
    }
    else
        d_window->setPosition(d_window->getPosition() + CEGUI::UVector2(cegui_reldim(-0.2f), cegui_absdim(0.0f)));
}

GamePlate::~GamePlate()
{
    CEGUI::WindowManager& winMgr = CEGUI::WindowManager::getSingleton();
    winMgr.destroyWindow(d_window);
}

void GamePlate::update(float timeSinceLastUpdate)
{
    CEGUI::UVector2 positionOffset;

    if(d_isComingFromRight)
        positionOffset = CEGUI::UVector2(cegui_reldim(timeSinceLastUpdate * -0.24f), cegui_absdim(0.f));
    else
        positionOffset = CEGUI::UVector2(cegui_reldim(timeSinceLastUpdate * 0.24f), cegui_absdim(0.f));

    d_window->setPosition(d_window->getPosition() + positionOffset);

    const CEGUI::UVector2& position = d_window->getPosition();

    if(d_isComingFromRight)
    {
        if(position.d_x.d_scale < -1.2f)
            d_isDestroyed = true;
    }
    else
    {
        if(position.d_x.d_scale > 1.2f)
            d_isDestroyed = true;
    }
}

int GamePlate::getPoints()
{
    CEGUI::Window* window = d_window->getChild("ImageWindowObject");

    CEGUI::String objectImage = window->getProperty("Image");

    if(objectImage.compare(HUDDemo::s_imageNameBread) == 0)
        return 2;
    else if(objectImage.compare(HUDDemo::s_imageNamePoo) == 0)
        return -6;
    else if(objectImage.compare(HUDDemo::s_imageNameSteak) == 0)
        return -13;
    else if(objectImage.compare(HUDDemo::s_imageNamePrizza) == 0)
        return 3;
    else if(objectImage.compare(HUDDemo::s_imageNameVegPeople) == 0)
        return 1;
    else if(objectImage.compare(HUDDemo::s_imageNameVegFruits) == 0)
        return 88;

    return 0;
}

const CEGUI::String HUDDemo::s_imageNamePlate = "HUDDemo/Plate";
const CEGUI::String HUDDemo::s_imageNameBread = "HUDDemo/Bread";
const CEGUI::String HUDDemo::s_imageNamePoo = "HUDDemo/Poo";
const CEGUI::String HUDDemo::s_imageNamePrizza = "HUDDemo/Prizza";
const CEGUI::String HUDDemo::s_imageNameSteak = "HUDDemo/Steak";
const CEGUI::String HUDDemo::s_imageNameVegPeople = "HUDDemo/VegetablePeople";
const CEGUI::String HUDDemo::s_imageNameVegFruits = "HUDDemo/VegetablesAndFruits";

bool HUDDemo::initialise(CEGUI::GUIContext* guiContext)
{
    using namespace CEGUI;

    d_usedFiles = CEGUI::String(__FILE__);
    d_guiContext = guiContext;

    SchemeManager::getSingleton().createFromFile("HUDDemo.scheme");
    SchemeManager::getSingleton().createFromFile("Generic.scheme");

    FontManager::getSingleton().createFromFile("DejaVuSans-14.font");

    CEGUI::WindowManager& winMgr = CEGUI::WindowManager::getSingleton();
    // Load the HUDDemo Layout
    d_rootIngame = winMgr.loadLayoutFromFile("HUDDemoIngame.layout");
    d_rootGameOver = winMgr.loadLayoutFromFile("HUDDemoGameOver.layout");
    d_root = winMgr.createWindow("DefaultWindow", "HUDDemoRoot");
    d_root->addChild(d_rootIngame);
    d_guiContext->setRootWindow(d_root);

    if(!ImageManager::getSingleton().isDefined("HUDDemoGameOver"))
        ImageManager::getSingleton().addFromImageFile("HUDDemoGameOver", "HUDDemoGameOver.png");
    d_rootGameOver->getChild("GameOverImage")->setProperty("Image", "HUDDemoGameOver");

    setupMouseCursor();

    srand(static_cast<unsigned int >(time(0)));

    d_lifeBar = static_cast<CEGUI::ProgressBar*>(d_rootIngame->getChild("TopBar/LifeBar"));

    initGame();

    d_rootIngame->getChild("BotBar/WeaponBGImage/LeftArrowArea")->subscribeEvent(CEGUI::Window::EventPointerActivate, Event::Subscriber(&HUDDemo::handleWeaponLeftArrowClicked, this));
    d_rootIngame->getChild("BotBar/WeaponBGImage/RightArrowArea")->subscribeEvent(CEGUI::Window::EventPointerActivate, Event::Subscriber(&HUDDemo::handleWeaponRightArrowClicked, this));

    d_rootGameOver->getChild("ButtonRestart")->subscribeEvent(CEGUI::PushButton::EventClicked, Event::Subscriber(&HUDDemo::handleRestartButtonClicked, this));

    return true;
}

/*************************************************************************
Cleans up resources allocated in the initialiseSample call.
*************************************************************************/
void HUDDemo::deinitialise()
{
    while(!d_gamePlates.empty())
    {
        GamePlate* curPlate = d_gamePlates.back();
        delete curPlate;

        d_gamePlates.pop_back();
    }
}

void HUDDemo::onEnteringSample()
{
    initGame();
}

void HUDDemo::update(float timeSinceLastUpdate)
{
    static float timeSinceLastSpawn(0.0f);

    timeSinceLastSpawn += timeSinceLastUpdate;

    updateMouseCursor();

    if(timeSinceLastSpawn> 1.2f)
    {
        d_gamePlates.push_back(new GamePlate(this));
        timeSinceLastSpawn -= 1.2f;
    }

    updatePlates(timeSinceLastUpdate);

    delayDestroyWindows();

    d_guiContext->markAsDirty();
}

void HUDDemo::setupMouseCursor()
{
    CEGUI::WindowManager& winMgr = CEGUI::WindowManager::getSingleton();

    d_mouseCursorWnd = winMgr.createWindow("Generic/Image");
    d_mouseCursorWnd->setProperty("Image", "HUDDemo/Spoon");
    d_mouseCursorWnd->setAspectMode(CEGUI::AM_EXPAND);
    d_mouseCursorWnd->setAspectRatio(1.f);
    d_mouseCursorWnd->setSize(CEGUI::USize(cegui_absdim(0.0f), cegui_reldim(0.1f)));
    d_mouseCursorWnd->setAlwaysOnTop(true);
    d_mouseCursorWnd->setPointerPassThroughEnabled(true);
    d_rootIngame->addChild(d_mouseCursorWnd);
}

void HUDDemo::updateMouseCursor()
{
    CEGUI::Vector2f position = d_guiContext->getPointerIndicator().getPosition();

    // We want to position the image-window right top of the actual
    // cursor point so we add its height
    float absHeight = d_mouseCursorWnd->getPixelSize().d_height;
    position.d_y -= absHeight;

    d_mouseCursorWnd->setPosition(
        CEGUI::UVector2(
        cegui_absdim(position.d_x - 5.0f), cegui_absdim(position.d_y + 5.0f))
        );
}

CEGUI::Window* HUDDemo::spawnPlate()
{
    CEGUI::WindowManager& winMgr = CEGUI::WindowManager::getSingleton();

    CEGUI::Window* plateRoot = winMgr.createWindow("DefaultWindow");
    plateRoot->setSize(CEGUI::USize(cegui_absdim(0.0f), cegui_reldim(0.16f)));
    plateRoot->setAspectMode(CEGUI::AM_EXPAND);
    plateRoot->setAspectRatio(1.0f);
    plateRoot->setRiseOnClickEnabled(false);
    plateRoot->setPixelAligned(false);
    plateRoot->subscribeEvent(CEGUI::Window::EventPointerPressHold, Event::Subscriber(&HUDDemo::handlePlateWindowClicked, this));
    d_rootIngame->addChild(plateRoot);

    CEGUI::Window* plateImgWnd = winMgr.createWindow("Generic/Image", "ImageWindowPlate");
    plateImgWnd->setProperty("Image", s_imageNamePlate);
    plateImgWnd->setSize(CEGUI::USize(cegui_reldim(1.0f), cegui_absdim(0.0f)));
    plateImgWnd->setAspectRatio(3.308f);
    plateImgWnd->setAspectMode(CEGUI::AM_EXPAND);
    plateImgWnd->setVerticalAlignment(CEGUI::VA_BOTTOM);
    plateImgWnd->setPointerPassThroughEnabled(true);
    plateImgWnd->setPixelAligned(false);
    plateRoot->addChild(plateImgWnd);

    CEGUI::String image = getRandomGameImage();

    CEGUI::Window* plateTopping = winMgr.createWindow("Generic/Image", "ImageWindowObject");
    plateTopping->setProperty("Image", image);
    plateTopping->setSize(CEGUI::USize(cegui_reldim(0.88f), cegui_absdim(0.0f)));
    plateTopping->setAspectRatio(1.0f);
    plateTopping->setAspectMode(CEGUI::AM_EXPAND);
    plateTopping->setHorizontalAlignment(CEGUI::HA_CENTRE);
    plateTopping->setPointerPassThroughEnabled(true);
    plateTopping->setPixelAligned(false);
    plateRoot->addChild(plateTopping);

    int randumNumber = rand() % 10000;
    float posY = randumNumber / 10000.0f;

    plateRoot->setPosition(CEGUI::UVector2(cegui_absdim(0.0f), cegui_reldim(0.1f + 0.6f * posY)));

    return plateRoot;
}

const CEGUI::String& HUDDemo::getRandomGameImage()
{
    int randumNumber = rand() % 100;

    if(randumNumber > 88)
        return s_imageNamePoo;
    else if(randumNumber > 72)
        return s_imageNamePrizza;
    else if(randumNumber > 55)
        return s_imageNameSteak;
    else if(randumNumber > 52)
        return s_imageNameVegFruits;
    else if(randumNumber > 25)
        return s_imageNameVegPeople;
    else if(randumNumber > 0)
        return s_imageNameBread;

    return s_imageNameBread;
}

void HUDDemo::updatePlates(float timeSinceLastUpdate)
{
    unsigned int vectorSize = d_gamePlates.size();

    for(unsigned int i = 0; i < vectorSize;)
    {
        GamePlate* currentPlate = d_gamePlates[i];

        currentPlate->update(timeSinceLastUpdate);
        if(currentPlate->d_isDestroyed)
        {
            delete currentPlate;
            d_gamePlates[i] = d_gamePlates.back();
            d_gamePlates.pop_back();
            vectorSize = d_gamePlates.size();
        }
        else
            ++i;
    }
}

void HUDDemo::updateScoreWindow()
{
    CEGUI::Window* scoreWnd = d_rootIngame->getChild("TopBar/ScoreBGImage/Score");
    scoreWnd->setText(CEGUI::PropertyHelper<int>::toString(d_score));
}

bool HUDDemo::handlePlateWindowClicked(const CEGUI::EventArgs& args)
{
    const CEGUI::MouseEventArgs& mouseArgs = static_cast<const CEGUI::MouseEventArgs&>(args);

    for(unsigned int i = 0; i < d_gamePlates.size(); ++i)
    {
        GamePlate* gamePlate = d_gamePlates[i];

        if(gamePlate->d_window == mouseArgs.window)
        {
            int points = gamePlate->getPoints();
            d_score += points;
            updateScoreWindow();

            if(points < 0)
            {
                float newProgress = d_lifeBar->getProgress() - 0.35f;

                if(newProgress < 0.0f)
                {
                    d_lives--;
                    handleLivesChanged();
                    newProgress = 1.0f;
                }

                d_lifeBar->setProgress(newProgress);
            }

            gamePlate->d_isDestroyed = true;
            createScorePopup(mouseArgs.position, points);
        }
    }

    return false;
}

void HUDDemo::createScorePopup(const CEGUI::Vector2<float>& mousePos, int points)
{
    CEGUI::WindowManager& winMgr = CEGUI::WindowManager::getSingleton();

    CEGUI::Window* popupWindow = winMgr.createWindow("HUDDemo/PopupLabel");
    d_rootIngame->addChild(popupWindow);
    popupWindow->setPosition(CEGUI::UVector2(cegui_absdim(mousePos.d_x), cegui_absdim(mousePos.d_y)));
    popupWindow->setText(CEGUI::PropertyHelper<int>::toString(points));
    popupWindow->setRiseOnClickEnabled(false);
    popupWindow->subscribeEvent(AnimationInstance::EventAnimationEnded, Event::Subscriber(&HUDDemo::handleScorePopupAnimationEnded, this));
    popupWindow->setPixelAligned(false);
    popupWindow->setFont("DejaVuSans-14");

    popupWindow->setPosition(popupWindow->getPosition() + CEGUI::UVector2(cegui_reldim(0.03f), cegui_reldim(-0.02f)));

    if(points < 0)
        popupWindow->setProperty("NormalTextColour", "FF880000");
    else
    {
        popupWindow->setText( "+" + popupWindow->getText());
        popupWindow->setProperty("NormalTextColour", "FF006600");
    }

    CEGUI::EventArgs args;
    popupWindow->fireEvent("StartAnimation", args);
}

bool HUDDemo::handleScorePopupAnimationEnded(const CEGUI::EventArgs& args)
{
    const CEGUI::AnimationEventArgs& animArgs = static_cast<const CEGUI::AnimationEventArgs&>(args);

    CEGUI::Window* window = static_cast<CEGUI::Window*>( animArgs.instance->getTarget());
    d_delayDestroyWindows.push_back(window);

    return false;
}

void HUDDemo::delayDestroyWindows()
{
    CEGUI::WindowManager& winMgr = CEGUI::WindowManager::getSingleton();

    while(!d_delayDestroyWindows.empty())
    {
        CEGUI::Window* curWindow = d_delayDestroyWindows.back();
        winMgr.destroyWindow(curWindow);

        d_delayDestroyWindows.pop_back();
    }
}

void HUDDemo::handleLivesChanged()
{
    bool life1Visible = (d_lives >= 1);
    bool life2Visible = (d_lives >= 2);
    bool life3Visible = (d_lives >= 3);

    d_rootIngame->getChild("TopBar/Life1")->setAlpha( life1Visible ? 1.0f : 0.5f );
    d_rootIngame->getChild("TopBar/Life2")->setAlpha( life2Visible ? 1.0f : 0.5f );
    d_rootIngame->getChild("TopBar/Life3")->setAlpha( life3Visible ? 1.0f : 0.5f );

    if(d_lives <= 0)
    {
        d_root->addChild(d_rootGameOver);
        d_rootGameOver->addChild(d_mouseCursorWnd);
    }
}

void HUDDemo::initGame()
{
    d_lives = 3;
    handleLivesChanged();

    selectedWeapon(SW_Spoon);

    d_score = 0;
    updateScoreWindow();

    d_lifeBar->setProgress(1.0f);
}

void HUDDemo::selectedWeapon(SelectedWeapon weapon)
{
    d_selectedWeapon = weapon;

    switch(d_selectedWeapon)
    {
    case SW_Spoon:
        d_rootIngame->getChild("BotBar/WeaponSpoon")->setAlpha(1.0f);
        d_rootIngame->getChild("BotBar/WeaponKnife")->setAlpha(0.5f);
        d_rootIngame->getChild("BotBar/WeaponFork")->setAlpha(0.5f);
        d_rootIngame->getChild("BotBar/WeaponBGImage/WeaponLabel")->setText("Le Spoon");

        break;
    case SW_Fork:
        d_rootIngame->getChild("BotBar/WeaponSpoon")->setAlpha(0.5f);
        d_rootIngame->getChild("BotBar/WeaponKnife")->setAlpha(0.5f);
        d_rootIngame->getChild("BotBar/WeaponFork")->setAlpha(1.0f);
        d_rootIngame->getChild("BotBar/WeaponBGImage/WeaponLabel")->setText("Le Fork");
        break;
    case SW_Knife:
        d_rootIngame->getChild("BotBar/WeaponSpoon")->setAlpha(0.5f);
        d_rootIngame->getChild("BotBar/WeaponKnife")->setAlpha(1.0f);
        d_rootIngame->getChild("BotBar/WeaponFork")->setAlpha(0.5f);
        d_rootIngame->getChild("BotBar/WeaponBGImage/WeaponLabel")->setText("Le Knife");
        break;
    default:
        break;
    }
}

bool HUDDemo::handleWeaponRightArrowClicked(const CEGUI::EventArgs& args)
{
    int weaponIndex = static_cast<int>(d_selectedWeapon);
    weaponIndex = (weaponIndex - 1) % 3;
    if(weaponIndex < 0)
        weaponIndex += 3;
    selectedWeapon( static_cast<SelectedWeapon>(weaponIndex) );

    return false;
}

bool HUDDemo::handleRestartButtonClicked(const CEGUI::EventArgs& args)
{
    d_root->removeChild(d_rootGameOver);
    d_rootIngame->addChild(d_mouseCursorWnd);

    initGame();

    return false;
}

bool HUDDemo::handleWeaponLeftArrowClicked(const CEGUI::EventArgs& args)
{
    int weaponIndex = static_cast<int>(d_selectedWeapon);
    selectedWeapon( static_cast<SelectedWeapon>(++weaponIndex % 3) );

    return false;
}

/*************************************************************************
Define the module function that returns an instance of the sample
*************************************************************************/
extern "C" SAMPLE_EXPORT Sample& getSampleInstance()
{
    static HUDDemo sample;
    return sample;
}<commit_msg>Remove a file left undeleted from a merge<commit_after><|endoftext|>


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

#include "RequestManagerDelete.h"

using namespace std;

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

Request::ErrorCode RequestManagerDelete::delete_authorization(
        PoolSQL*                pool,
        int                     oid,
        AuthRequest::Operation  auth_op,
        RequestAttributes&      att)
{
    PoolObjectSQL * object;
    PoolObjectAuth  perms;

    if ( att.uid == 0 )
    {
        return SUCCESS;
    }

    object = pool->get(oid, true);

    if ( object == 0 )
    {
        att.resp_id = oid;
        return NO_EXISTS;
    }

    object->get_permissions(perms);

    object->unlock();

    AuthRequest ar(att.uid, att.group_ids);

    ar.add_auth(auth_op, perms);    // <MANAGE|ADMIN> OBJECT

    if (UserPool::authorize(ar) == -1)
    {
        att.resp_msg = ar.message;
        return AUTHORIZATION;
    }

    return SUCCESS;
}

/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */

void RequestManagerDelete::request_execute(xmlrpc_c::paramList const& paramList,
                                           RequestAttributes& att)
{
    int             oid = xmlrpc_c::value_int(paramList.getInt(1));
    PoolObjectSQL * object;
    string          error_msg;
    ErrorCode       ec;

    ec = delete_authorization(pool, oid, auth_op, att);

    if ( ec != SUCCESS )
    {
        failure_response(ec, att);
        return;
    }

    object = pool->get(oid,true);

    if ( object == 0 )
    {
        att.resp_id = oid;
        failure_response(NO_EXISTS, att);
        return;
    }

    int rc = drop(oid, object, error_msg);

    if ( rc != 0 )
    {
        att.resp_msg = "Cannot delete " + object_name(auth_object) + ". " +  error_msg;
        failure_response(ACTION, att);
        return;
    }

    aclm->del_resource_rules(oid, auth_object);

    success_response(oid, att);

    return;
}

/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */

int RequestManagerDelete::drop(
        int             oid,
        PoolObjectSQL * object,
        string&         error_msg)
{
    int cluster_id = get_cluster_id(object);

    int rc = pool->drop(object, error_msg);

    object->unlock();

    if ( cluster_id != ClusterPool::NONE_CLUSTER_ID && rc == 0 )
    {
        Cluster * cluster = clpool->get(cluster_id, true);

        if( cluster != 0 )
        {
            rc = del_from_cluster(cluster, oid, error_msg);

            if ( rc < 0 )
            {
                cluster->unlock();
                return rc;
            }

            clpool->update(cluster);

            cluster->unlock();
        }
    }

    return rc;
}

/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */

void TemplateDelete::request_execute(
        xmlrpc_c::paramList const& paramList, RequestAttributes& att)
{
    int             oid = xmlrpc_c::value_int(paramList.getInt(1));
    bool            recursive = false;
    VMTemplate *    object;
    string          error_msg;
    vector<int>     img_ids;
    ErrorCode       ec;

    if (paramList.size() > 2)
    {
        recursive = xmlrpc_c::value_boolean(paramList.getBoolean(2));
    }

    ec = delete_authorization(pool, oid, auth_op, att);

    if ( ec != SUCCESS )
    {
        failure_response(ec, att);
        return;
    }

    object = static_cast<VMTemplatePool*>(pool)->get(oid, true);

    if ( object == 0 )
    {
        att.resp_id = oid;
        failure_response(NO_EXISTS, att);
        return;
    }

    int rc = pool->drop(object, error_msg);

    if (recursive)
    {
        img_ids = object->get_img_ids();
    }

    object->unlock();

    if ( rc != 0 )
    {
        att.resp_msg = "Cannot delete " + object_name(auth_object) + ". " +  error_msg;
        failure_response(ACTION, att);
        return;
    }

    aclm->del_resource_rules(oid, auth_object);

    if (recursive)
    {
        ErrorCode ec;

        for (vector<int>::iterator it = img_ids.begin(); it != img_ids.end(); it++)
        {
            ec = ImageDelete::delete_img(*it, att);

            if (ec != SUCCESS)
            {
                NebulaLog::log("ReM", Log::ERROR, failure_message(ec, att));
            }

            // TODO rollback?
        }
    }

    success_response(oid, att);

    return;
}

/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */

int HostDelete::drop(int oid, PoolObjectSQL * object, string& error_msg)
{
    Nebula& nd              = Nebula::instance();
    InformationManager * im = nd.get_im();

    HostPool * hpool = nd.get_hpool();

    Host* host = static_cast<Host *>(object);

    //Do not trigger delete event on IM if there are VMs running on the host
    if ( host->get_share_running_vms() > 0 )
    {
        error_msg = "Can not remove a host with running VMs";

        host->unlock();

        return -1;
    }

    host->disable();

    hpool->update(host);

    host->unlock();

    im->trigger(InformationManager::STOPMONITOR, oid);

    return 0;
}

/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */

void ImageDelete::request_execute(
        xmlrpc_c::paramList const& paramList, RequestAttributes& att)
{
    int oid = xmlrpc_c::value_int(paramList.getInt(1));

    ErrorCode ec = delete_img(oid, att);

    if ( ec == SUCCESS )
    {
        success_response(oid, att);
    }
    else
    {
        failure_response(ec, att);
    }
}

/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */

Request::ErrorCode ImageDelete::delete_img(int oid, RequestAttributes& att)
{
    Image *         object;
    string          error_msg;
    ErrorCode       ec;

    Nebula&        nd     = Nebula::instance();
    ImageManager * imagem = nd.get_imagem();
    AclManager *   aclm   = nd.get_aclm();
    ImagePool *    pool   = nd.get_ipool();

    PoolObjectSQL::ObjectType auth_object = PoolObjectSQL::IMAGE;

    ec = delete_authorization(pool, oid, AuthRequest::MANAGE, att);

    if ( ec != SUCCESS )
    {
        att.resp_obj = auth_object;
        return ec;
    }

    object = pool->get(oid, false);

    if ( object == 0 )
    {
        att.resp_id = oid;
        return NO_EXISTS;
    }

    int rc = imagem->delete_image(oid, error_msg);

    if ( rc != 0 )
    {
        att.resp_msg = "Cannot delete " + object_name(auth_object) + ". " +  error_msg;
        return ACTION;
    }

    aclm->del_resource_rules(oid, auth_object);

    return SUCCESS;
}

/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */

int GroupDelete::drop(int oid, PoolObjectSQL * object, string& error_msg)
{
    int rc = RequestManagerDelete::drop(oid, object, error_msg);

    if ( rc == 0 )
    {
        aclm->del_gid_rules(oid);
    }

    return rc;
}

/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */

int ClusterDelete::drop(int oid, PoolObjectSQL * object, string& error_msg)
{
    int rc = RequestManagerDelete::drop(oid, object, error_msg);

    if ( rc == 0 )
    {
        aclm->del_cid_rules(oid);
    }

    return rc;
}

/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */

int UserDelete::drop(int oid, PoolObjectSQL * object, string& error_msg)
{
    set<int>            group_set;
    set<int>::iterator  it;

    User * user = static_cast<User *>(object);
    group_set   = user->get_groups();

    if (oid == 0)
    {
        error_msg = "oneadmin cannot be deleted.";

        object->unlock();
        return -1;
    }

    int rc = pool->drop(object, error_msg);

    object->unlock();

    if ( rc == 0 )
    {
        Group * group;

        for ( it = group_set.begin(); it != group_set.end(); it++ )
        {
            group = gpool->get(*it, true);

            if( group == 0 )
            {
                continue;
            }

            group->del_user(oid);
            gpool->update(group);

            group->unlock();
        }

        aclm->del_uid_rules(oid);
    }

    return rc;
}

/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */

int ZoneDelete::drop(int oid, PoolObjectSQL * object, string& error_msg)
{
    int rc = RequestManagerDelete::drop(oid, object, error_msg);

    if ( rc == 0 )
    {
        aclm->del_zid_rules(oid);
    }

    return rc;
}

/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */

int VirtualNetworkDelete::drop(int oid, PoolObjectSQL * object, string& error_msg)
{
    VirtualNetwork * vnet = static_cast<VirtualNetwork *>(object);

    if ( vnet->get_used() > 0 )
    {
        error_msg = "Can not remove a virtual network with leases in use";

        vnet->unlock();

        return -1;
    }

    int pvid = vnet->get_parent();
    int uid  = vnet->get_uid();
    int gid  = vnet->get_gid();

    int rc  = RequestManagerDelete::drop(oid, object, error_msg);

    if (pvid != -1)
    {
        vnet = (static_cast<VirtualNetworkPool *>(pool))->get(pvid, true);

        if (vnet == 0)
        {
            return rc;
        }

        int freed = vnet->free_addr_by_owner(PoolObjectSQL::NET, oid);

        pool->update(vnet);

        vnet->unlock();

        if (freed > 0)
        {
            ostringstream oss;
            Template      tmpl;

            for (int i= 0 ; i < freed ; i++)
            {
                oss << " NIC = [ NETWORK_ID = " << pvid << " ]" << endl;
            }

            tmpl.parse_str_or_xml(oss.str(), error_msg);

            Quotas::quota_del(Quotas::NETWORK, uid, gid, &tmpl);
        }
    }

    return rc;
}

/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */

int SecurityGroupDelete::drop(int oid, PoolObjectSQL * object, string& error_msg)
{
    if (object->get_oid() == 0)
    {
        error_msg = "The default security group (ID 0) cannot be deleted.";

        object->unlock();

        return -1;
    }

    SecurityGroup * sgroup = static_cast<SecurityGroup *>(object);

    if ( sgroup->get_vms() > 0 )
    {
        error_msg = "The security group has VMs using it";

        sgroup->unlock();

        return -1;
    }

    return RequestManagerDelete::drop(oid, object, error_msg);
}

/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */

int MarketPlaceAppDelete::drop(int oid, PoolObjectSQL * object, string& emsg)
{
    Nebula& nd = Nebula::instance();

    MarketPlaceManager * marketm = nd.get_marketm();
    MarketPlacePool * marketpool = nd.get_marketpool();

    MarketPlaceApp * app = static_cast<MarketPlaceApp *>(object);

    int mp_id = app->get_market_id();

    app->unlock();

    MarketPlace * mp = marketpool->get(mp_id, true);

    if ( mp == 0 )
    {
        emsg = "Cannot find associated MARKETPLACE";
        return -1;
    }

    std::string mp_name = mp->get_name();
    std::string mp_data;

    if ( !mp->is_action_supported(MarketPlaceApp::DELETE) )
    {
        emsg = "Delete disabled for market: " + mp_name;
        mp->unlock();

        return -1;
    }

    mp->to_xml(mp_data);

    mp->unlock();

    return marketm->delete_app(oid, mp_data, emsg);
}

/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */

int MarketPlaceDelete::drop(int oid, PoolObjectSQL * object, string& emsg)
{
    MarketPlace * mp = static_cast<MarketPlace *>(object);
    set<int> apps    = mp->get_marketapp_ids();

    int rc = pool->drop(object, emsg);

    object->unlock();

    if ( rc != 0 || apps.empty() )
    {
        return rc;
    }

    Nebula& nd = Nebula::instance();

    MarketPlaceApp *     app;
    MarketPlaceAppPool * apppool = nd.get_apppool();

    string app_error;

    for ( set<int>::iterator i = apps.begin(); i != apps.end(); ++i )
    {
        app = apppool->get(*i, true);

        if ( app == 0 )
        {
            continue;
        }

       if ( apppool->drop(app, app_error) != 0 )
       {
           ostringstream oss;

           oss << "Cannot remove " << object_name(PoolObjectSQL::MARKETPLACEAPP)
               << " " << *i << ": " << app_error << ". ";

           emsg = emsg + oss.str();

           rc = -1;
       }

       app->unlock();
    }

    return rc;
}

/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */

<commit_msg>feature #4317: Return error when a template image cannot be deleted (recursive mode)<commit_after>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2015, OpenNebula Project, OpenNebula Systems                */
/*                                                                            */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may    */
/* not use this file except in compliance with the License. You may obtain    */
/* a copy of the License at                                                   */
/*                                                                            */
/* http://www.apache.org/licenses/LICENSE-2.0                                 */
/*                                                                            */
/* Unless required by applicable law or agreed to in writing, software        */
/* distributed under the License is distributed on an "AS IS" BASIS,          */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   */
/* See the License for the specific language governing permissions and        */
/* limitations under the License.                                             */
/* -------------------------------------------------------------------------- */

#include "RequestManagerDelete.h"
#include "NebulaUtil.h"

using namespace std;

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

Request::ErrorCode RequestManagerDelete::delete_authorization(
        PoolSQL*                pool,
        int                     oid,
        AuthRequest::Operation  auth_op,
        RequestAttributes&      att)
{
    PoolObjectSQL * object;
    PoolObjectAuth  perms;

    if ( att.uid == 0 )
    {
        return SUCCESS;
    }

    object = pool->get(oid, true);

    if ( object == 0 )
    {
        att.resp_id = oid;
        return NO_EXISTS;
    }

    object->get_permissions(perms);

    object->unlock();

    AuthRequest ar(att.uid, att.group_ids);

    ar.add_auth(auth_op, perms);    // <MANAGE|ADMIN> OBJECT

    if (UserPool::authorize(ar) == -1)
    {
        att.resp_msg = ar.message;
        return AUTHORIZATION;
    }

    return SUCCESS;
}

/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */

void RequestManagerDelete::request_execute(xmlrpc_c::paramList const& paramList,
                                           RequestAttributes& att)
{
    int             oid = xmlrpc_c::value_int(paramList.getInt(1));
    PoolObjectSQL * object;
    string          error_msg;
    ErrorCode       ec;

    ec = delete_authorization(pool, oid, auth_op, att);

    if ( ec != SUCCESS )
    {
        failure_response(ec, att);
        return;
    }

    object = pool->get(oid,true);

    if ( object == 0 )
    {
        att.resp_id = oid;
        failure_response(NO_EXISTS, att);
        return;
    }

    int rc = drop(oid, object, error_msg);

    if ( rc != 0 )
    {
        att.resp_msg = "Cannot delete " + object_name(auth_object) + ". " +  error_msg;
        failure_response(ACTION, att);
        return;
    }

    aclm->del_resource_rules(oid, auth_object);

    success_response(oid, att);

    return;
}

/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */

int RequestManagerDelete::drop(
        int             oid,
        PoolObjectSQL * object,
        string&         error_msg)
{
    int cluster_id = get_cluster_id(object);

    int rc = pool->drop(object, error_msg);

    object->unlock();

    if ( cluster_id != ClusterPool::NONE_CLUSTER_ID && rc == 0 )
    {
        Cluster * cluster = clpool->get(cluster_id, true);

        if( cluster != 0 )
        {
            rc = del_from_cluster(cluster, oid, error_msg);

            if ( rc < 0 )
            {
                cluster->unlock();
                return rc;
            }

            clpool->update(cluster);

            cluster->unlock();
        }
    }

    return rc;
}

/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */

void TemplateDelete::request_execute(
        xmlrpc_c::paramList const& paramList, RequestAttributes& att)
{
    int             oid = xmlrpc_c::value_int(paramList.getInt(1));
    bool            recursive = false;
    VMTemplate *    object;
    string          error_msg;
    vector<int>     img_ids;
    set<int>        error_ids;
    ErrorCode       ec;

    if (paramList.size() > 2)
    {
        recursive = xmlrpc_c::value_boolean(paramList.getBoolean(2));
    }

    ec = delete_authorization(pool, oid, auth_op, att);

    if ( ec != SUCCESS )
    {
        failure_response(ec, att);
        return;
    }

    object = static_cast<VMTemplatePool*>(pool)->get(oid, true);

    if ( object == 0 )
    {
        att.resp_id = oid;
        failure_response(NO_EXISTS, att);
        return;
    }

    int rc = pool->drop(object, error_msg);

    if (recursive)
    {
        img_ids = object->get_img_ids();
    }

    object->unlock();

    if ( rc != 0 )
    {
        att.resp_msg = "Cannot delete " + object_name(auth_object) + ". " +  error_msg;
        failure_response(ACTION, att);
        return;
    }

    aclm->del_resource_rules(oid, auth_object);

    if (recursive)
    {
        ErrorCode ec;

        for (vector<int>::iterator it = img_ids.begin(); it != img_ids.end(); it++)
        {
            ec = ImageDelete::delete_img(*it, att);

            if (ec != SUCCESS)
            {
                NebulaLog::log("ReM", Log::ERROR, failure_message(ec, att));

                error_ids.insert(*it);
                rc = -1;
            }
        }
    }

    if ( rc != 0 )
    {
        att.resp_msg = "Cannot delete " + object_name(PoolObjectSQL::IMAGE) +
            ": " + one_util::join<set<int>::iterator>(error_ids.begin(),
            error_ids.end(), ',');

        failure_response(ACTION, att);
        return;
    }

    success_response(oid, att);

    return;
}

/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */

int HostDelete::drop(int oid, PoolObjectSQL * object, string& error_msg)
{
    Nebula& nd              = Nebula::instance();
    InformationManager * im = nd.get_im();

    HostPool * hpool = nd.get_hpool();

    Host* host = static_cast<Host *>(object);

    //Do not trigger delete event on IM if there are VMs running on the host
    if ( host->get_share_running_vms() > 0 )
    {
        error_msg = "Can not remove a host with running VMs";

        host->unlock();

        return -1;
    }

    host->disable();

    hpool->update(host);

    host->unlock();

    im->trigger(InformationManager::STOPMONITOR, oid);

    return 0;
}

/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */

void ImageDelete::request_execute(
        xmlrpc_c::paramList const& paramList, RequestAttributes& att)
{
    int oid = xmlrpc_c::value_int(paramList.getInt(1));

    ErrorCode ec = delete_img(oid, att);

    if ( ec == SUCCESS )
    {
        success_response(oid, att);
    }
    else
    {
        failure_response(ec, att);
    }
}

/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */

Request::ErrorCode ImageDelete::delete_img(int oid, RequestAttributes& att)
{
    Image *         object;
    string          error_msg;
    ErrorCode       ec;

    Nebula&        nd     = Nebula::instance();
    ImageManager * imagem = nd.get_imagem();
    AclManager *   aclm   = nd.get_aclm();
    ImagePool *    pool   = nd.get_ipool();

    PoolObjectSQL::ObjectType auth_object = PoolObjectSQL::IMAGE;

    ec = delete_authorization(pool, oid, AuthRequest::MANAGE, att);

    if ( ec != SUCCESS )
    {
        att.resp_obj = auth_object;
        return ec;
    }

    object = pool->get(oid, false);

    if ( object == 0 )
    {
        att.resp_id = oid;
        return NO_EXISTS;
    }

    int rc = imagem->delete_image(oid, error_msg);

    if ( rc != 0 )
    {
        att.resp_msg = "Cannot delete " + object_name(auth_object) + ". " +  error_msg;
        return ACTION;
    }

    aclm->del_resource_rules(oid, auth_object);

    return SUCCESS;
}

/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */

int GroupDelete::drop(int oid, PoolObjectSQL * object, string& error_msg)
{
    int rc = RequestManagerDelete::drop(oid, object, error_msg);

    if ( rc == 0 )
    {
        aclm->del_gid_rules(oid);
    }

    return rc;
}

/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */

int ClusterDelete::drop(int oid, PoolObjectSQL * object, string& error_msg)
{
    int rc = RequestManagerDelete::drop(oid, object, error_msg);

    if ( rc == 0 )
    {
        aclm->del_cid_rules(oid);
    }

    return rc;
}

/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */

int UserDelete::drop(int oid, PoolObjectSQL * object, string& error_msg)
{
    set<int>            group_set;
    set<int>::iterator  it;

    User * user = static_cast<User *>(object);
    group_set   = user->get_groups();

    if (oid == 0)
    {
        error_msg = "oneadmin cannot be deleted.";

        object->unlock();
        return -1;
    }

    int rc = pool->drop(object, error_msg);

    object->unlock();

    if ( rc == 0 )
    {
        Group * group;

        for ( it = group_set.begin(); it != group_set.end(); it++ )
        {
            group = gpool->get(*it, true);

            if( group == 0 )
            {
                continue;
            }

            group->del_user(oid);
            gpool->update(group);

            group->unlock();
        }

        aclm->del_uid_rules(oid);
    }

    return rc;
}

/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */

int ZoneDelete::drop(int oid, PoolObjectSQL * object, string& error_msg)
{
    int rc = RequestManagerDelete::drop(oid, object, error_msg);

    if ( rc == 0 )
    {
        aclm->del_zid_rules(oid);
    }

    return rc;
}

/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */

int VirtualNetworkDelete::drop(int oid, PoolObjectSQL * object, string& error_msg)
{
    VirtualNetwork * vnet = static_cast<VirtualNetwork *>(object);

    if ( vnet->get_used() > 0 )
    {
        error_msg = "Can not remove a virtual network with leases in use";

        vnet->unlock();

        return -1;
    }

    int pvid = vnet->get_parent();
    int uid  = vnet->get_uid();
    int gid  = vnet->get_gid();

    int rc  = RequestManagerDelete::drop(oid, object, error_msg);

    if (pvid != -1)
    {
        vnet = (static_cast<VirtualNetworkPool *>(pool))->get(pvid, true);

        if (vnet == 0)
        {
            return rc;
        }

        int freed = vnet->free_addr_by_owner(PoolObjectSQL::NET, oid);

        pool->update(vnet);

        vnet->unlock();

        if (freed > 0)
        {
            ostringstream oss;
            Template      tmpl;

            for (int i= 0 ; i < freed ; i++)
            {
                oss << " NIC = [ NETWORK_ID = " << pvid << " ]" << endl;
            }

            tmpl.parse_str_or_xml(oss.str(), error_msg);

            Quotas::quota_del(Quotas::NETWORK, uid, gid, &tmpl);
        }
    }

    return rc;
}

/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */

int SecurityGroupDelete::drop(int oid, PoolObjectSQL * object, string& error_msg)
{
    if (object->get_oid() == 0)
    {
        error_msg = "The default security group (ID 0) cannot be deleted.";

        object->unlock();

        return -1;
    }

    SecurityGroup * sgroup = static_cast<SecurityGroup *>(object);

    if ( sgroup->get_vms() > 0 )
    {
        error_msg = "The security group has VMs using it";

        sgroup->unlock();

        return -1;
    }

    return RequestManagerDelete::drop(oid, object, error_msg);
}

/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */

int MarketPlaceAppDelete::drop(int oid, PoolObjectSQL * object, string& emsg)
{
    Nebula& nd = Nebula::instance();

    MarketPlaceManager * marketm = nd.get_marketm();
    MarketPlacePool * marketpool = nd.get_marketpool();

    MarketPlaceApp * app = static_cast<MarketPlaceApp *>(object);

    int mp_id = app->get_market_id();

    app->unlock();

    MarketPlace * mp = marketpool->get(mp_id, true);

    if ( mp == 0 )
    {
        emsg = "Cannot find associated MARKETPLACE";
        return -1;
    }

    std::string mp_name = mp->get_name();
    std::string mp_data;

    if ( !mp->is_action_supported(MarketPlaceApp::DELETE) )
    {
        emsg = "Delete disabled for market: " + mp_name;
        mp->unlock();

        return -1;
    }

    mp->to_xml(mp_data);

    mp->unlock();

    return marketm->delete_app(oid, mp_data, emsg);
}

/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */

int MarketPlaceDelete::drop(int oid, PoolObjectSQL * object, string& emsg)
{
    MarketPlace * mp = static_cast<MarketPlace *>(object);
    set<int> apps    = mp->get_marketapp_ids();

    int rc = pool->drop(object, emsg);

    object->unlock();

    if ( rc != 0 || apps.empty() )
    {
        return rc;
    }

    Nebula& nd = Nebula::instance();

    MarketPlaceApp *     app;
    MarketPlaceAppPool * apppool = nd.get_apppool();

    string app_error;

    for ( set<int>::iterator i = apps.begin(); i != apps.end(); ++i )
    {
        app = apppool->get(*i, true);

        if ( app == 0 )
        {
            continue;
        }

       if ( apppool->drop(app, app_error) != 0 )
       {
           ostringstream oss;

           oss << "Cannot remove " << object_name(PoolObjectSQL::MARKETPLACEAPP)
               << " " << *i << ": " << app_error << ". ";

           emsg = emsg + oss.str();

           rc = -1;
       }

       app->unlock();
    }

    return rc;
}

/* ------------------------------------------------------------------------- */
/* ------------------------------------------------------------------------- */

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: invmerge.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 23:00:14 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifdef PCH
#include "ui_pch.hxx"
#endif

#pragma hdrstop

#include <vcl/window.hxx>
#include <tools/debug.hxx>

#include "invmerge.hxx"

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

ScInvertMerger::ScInvertMerger( Window* pWindow ) :
    pWin( pWindow )
{
    //  both rectangles empty
}

ScInvertMerger::~ScInvertMerger()
{
    Flush();
}

void ScInvertMerger::Flush()
{
    FlushLine();
    FlushTotal();

    DBG_ASSERT( aLineRect.IsEmpty() && aTotalRect.IsEmpty(), "Flush: not empty" );
}

void ScInvertMerger::FlushTotal()
{
    if( aTotalRect.IsEmpty() )
        return;                         // nothing to do

    pWin->Invert( aTotalRect, INVERT_HIGHLIGHT );
    aTotalRect.SetEmpty();
}

void ScInvertMerger::FlushLine()
{
    if( aLineRect.IsEmpty() )
        return;                         // nothing to do

    if ( aTotalRect.IsEmpty() )
    {
        aTotalRect = aLineRect;         // start new total rect
    }
    else
    {
        if ( aLineRect.Left()  == aTotalRect.Left()  &&
             aLineRect.Right() == aTotalRect.Right() &&
             aLineRect.Top()   == aTotalRect.Bottom() + 1 )
        {
            // extend total rect
            aTotalRect.Bottom() = aLineRect.Bottom();
        }
        else
        {
            FlushTotal();                   // draw old total rect
            aTotalRect = aLineRect;         // and start new one
        }
    }

    aLineRect.SetEmpty();
}

void ScInvertMerger::AddRect( const Rectangle& rRect )
{
    if ( aLineRect.IsEmpty() )
    {
        aLineRect = rRect;          // start new line rect
    }
    else
    {
        Rectangle aJustified = rRect;
        if ( rRect.Left() > rRect.Right() )     // switch for RTL layout
        {
            aJustified.Left() = rRect.Right();
            aJustified.Right() = rRect.Left();
        }

        BOOL bDone = FALSE;
        if ( aJustified.Top()    == aLineRect.Top()    &&
             aJustified.Bottom() == aLineRect.Bottom() )
        {
            // try to extend line rect
            if ( aJustified.Left() == aLineRect.Right() + 1 )
            {
                aLineRect.Right() = aJustified.Right();
                bDone = TRUE;
            }
            else if ( aJustified.Right() + 1 == aLineRect.Left() )  // for RTL layout
            {
                aLineRect.Left() = aJustified.Left();
                bDone = TRUE;
            }
        }
        if (!bDone)
        {
            FlushLine();                // use old line rect for total rect
            aLineRect = aJustified;     // and start new one
        }
    }
}

<commit_msg>INTEGRATION: CWS pchfix01 (1.3.214); FILE MERGED 2006/07/12 10:03:05 kaib 1.3.214.1: #i67080# Converted cxx files in sc, added initial project level pch and stripped old PCH definitions.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: invmerge.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: kz $ $Date: 2006-07-21 15:02:25 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"

#include <vcl/window.hxx>
#include <tools/debug.hxx>

#include "invmerge.hxx"

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

ScInvertMerger::ScInvertMerger( Window* pWindow ) :
    pWin( pWindow )
{
    //  both rectangles empty
}

ScInvertMerger::~ScInvertMerger()
{
    Flush();
}

void ScInvertMerger::Flush()
{
    FlushLine();
    FlushTotal();

    DBG_ASSERT( aLineRect.IsEmpty() && aTotalRect.IsEmpty(), "Flush: not empty" );
}

void ScInvertMerger::FlushTotal()
{
    if( aTotalRect.IsEmpty() )
        return;                         // nothing to do

    pWin->Invert( aTotalRect, INVERT_HIGHLIGHT );
    aTotalRect.SetEmpty();
}

void ScInvertMerger::FlushLine()
{
    if( aLineRect.IsEmpty() )
        return;                         // nothing to do

    if ( aTotalRect.IsEmpty() )
    {
        aTotalRect = aLineRect;         // start new total rect
    }
    else
    {
        if ( aLineRect.Left()  == aTotalRect.Left()  &&
             aLineRect.Right() == aTotalRect.Right() &&
             aLineRect.Top()   == aTotalRect.Bottom() + 1 )
        {
            // extend total rect
            aTotalRect.Bottom() = aLineRect.Bottom();
        }
        else
        {
            FlushTotal();                   // draw old total rect
            aTotalRect = aLineRect;         // and start new one
        }
    }

    aLineRect.SetEmpty();
}

void ScInvertMerger::AddRect( const Rectangle& rRect )
{
    if ( aLineRect.IsEmpty() )
    {
        aLineRect = rRect;          // start new line rect
    }
    else
    {
        Rectangle aJustified = rRect;
        if ( rRect.Left() > rRect.Right() )     // switch for RTL layout
        {
            aJustified.Left() = rRect.Right();
            aJustified.Right() = rRect.Left();
        }

        BOOL bDone = FALSE;
        if ( aJustified.Top()    == aLineRect.Top()    &&
             aJustified.Bottom() == aLineRect.Bottom() )
        {
            // try to extend line rect
            if ( aJustified.Left() == aLineRect.Right() + 1 )
            {
                aLineRect.Right() = aJustified.Right();
                bDone = TRUE;
            }
            else if ( aJustified.Right() + 1 == aLineRect.Left() )  // for RTL layout
            {
                aLineRect.Left() = aJustified.Left();
                bDone = TRUE;
            }
        }
        if (!bDone)
        {
            FlushLine();                // use old line rect for total rect
            aLineRect = aJustified;     // and start new one
        }
    }
}

<|endoftext|>


<commit_before><commit_msg>Removed unnecessary std::move<commit_after><|endoftext|>


<commit_before>//
//  GridZone.cpp
//  Created by Matt Kaufmann on 01/07/14.
//

#include "ExampleGame/Components/ComponentTypes/ComponentTypeIds.h"
#include "ExampleGame/Components/Grid/GridCell.h"
#include "ExampleGame/Components/Grid/GridManager.h"
#include "ExampleGame/Components/Grid/GridZone.h"
#include "ExampleGame/GameSingletons/GameSingletons.h"
#include "ExampleGame/Messages/Declarations.h"
#include "Vajra/Engine/Components/DerivedComponents/Transform/Transform.h"

unsigned int GridZone::componentTypeId = COMPONENT_TYPE_ID_GRID_ZONE;

GridZone::GridZone() : Component() {
	this->init();
}

GridZone::GridZone(Object* object_) : Component(object_) {
	this->init();
}

GridZone::~GridZone() {
	this->destroy();
}

void GridZone::GetZoneBounds(int& west, int& east, int& south, int& north) {
	Transform* trans = this->GetObject()->GetComponent<Transform>();

	int centerX, centerZ;
	SINGLETONS->GetGridManager()->GetGrid()->GetCoordinates(centerX, centerZ, trans->GetPositionWorld());

	glm::vec3 forward = trans->GetForward();

	// Determine the rough orientation of the object.
	if (abs(forward.z) >= abs(forward.x)) {
		if (forward.z >= 0.0f) {
			west  = centerX + this->westBound;
			east  = centerX + this->eastBound;
			south = centerZ + this->southBound;
			north = centerZ + this->northBound;
		}
		else {
			west  = centerX - this->eastBound;
			east  = centerX - this->westBound;
			south = centerZ - this->northBound;
			north = centerZ - this->southBound;
		}
	}
	else {
		if (forward.x >= 0.0f) {
			west  = centerX - this->northBound;
			east  = centerX - this->southBound;
			south = centerZ + this->westBound;
			north = centerZ + this->eastBound;
		}
		else {
			west  = centerX + this->southBound;
			east  = centerX + this->northBound;
			south = centerZ - this->eastBound;
			north = centerZ - this->westBound;
		}
	}
}

void GridZone::SetZoneBounds(int xMin, int zMin, int xMax, int zMax) {
	if (xMin <= xMax) {
		this->westBound = xMin;
		this->eastBound = xMax;
	}
	else {
		this->westBound = xMax;
		this->eastBound = xMin;
	}
	if (zMin <= zMax) {
		this->southBound = zMin;
		this->northBound = zMax;
	}
	else {
		this->southBound = zMax;
		this->northBound = zMin;
	}
}

bool GridZone::IsCellWithinZone(GridCell* cell) {
	if (cell != nullptr) {
		int west, east, south, north;

		this->GetZoneBounds(west, east, south, north);

		return ((cell->x >= west) && (cell->x <= east) && (cell->z >= south) && (cell->z <= north));
	}

	return false;
}

void GridZone::init() {
	this->zoneType = GRID_ZONE_TYPE_UNKNOWN;
	this->westBound = -1;
	this->eastBound = -1;
	this->southBound = -1;
	this->northBound = -1;

	SINGLETONS->GetGridManager()->GetGrid()->AddGridZone(this->GetObject()->GetId());
}

void GridZone::destroy() {
	this->removeSubscriptionToAllMessageTypes(this->GetTypeId());
}
<commit_msg>GridZone coordinates are now calculated correctly based on the object's world orientation<commit_after>//
//  GridZone.cpp
//  Created by Matt Kaufmann on 01/07/14.
//

#include "ExampleGame/Components/ComponentTypes/ComponentTypeIds.h"
#include "ExampleGame/Components/Grid/GridCell.h"
#include "ExampleGame/Components/Grid/GridManager.h"
#include "ExampleGame/Components/Grid/GridZone.h"
#include "ExampleGame/GameSingletons/GameSingletons.h"
#include "ExampleGame/Messages/Declarations.h"
#include "Vajra/Engine/Components/DerivedComponents/Transform/Transform.h"

unsigned int GridZone::componentTypeId = COMPONENT_TYPE_ID_GRID_ZONE;

GridZone::GridZone() : Component() {
	this->init();
}

GridZone::GridZone(Object* object_) : Component(object_) {
	this->init();
}

GridZone::~GridZone() {
	this->destroy();
}

void GridZone::GetZoneBounds(int& west, int& east, int& south, int& north) {
	Transform* trans = this->GetObject()->GetComponent<Transform>();

	int centerX, centerZ;
	SINGLETONS->GetGridManager()->GetGrid()->GetCoordinates(centerX, centerZ, trans->GetPositionWorld());

	glm::vec3 forward = QuaternionForwardVector(trans->GetOrientationWorld());

	// Determine the rough orientation of the object.
	if (abs(forward.z) >= abs(forward.x)) {
		if (forward.z >= 0.0f) {
			west  = centerX + this->westBound;
			east  = centerX + this->eastBound;
			south = centerZ + this->southBound;
			north = centerZ + this->northBound;
		}
		else {
			west  = centerX - this->eastBound;
			east  = centerX - this->westBound;
			south = centerZ - this->northBound;
			north = centerZ - this->southBound;
		}
	}
	else {
		if (forward.x >= 0.0f) {
			west  = centerX - this->northBound;
			east  = centerX - this->southBound;
			south = centerZ + this->westBound;
			north = centerZ + this->eastBound;
		}
		else {
			west  = centerX + this->southBound;
			east  = centerX + this->northBound;
			south = centerZ - this->eastBound;
			north = centerZ - this->westBound;
		}
	}
}

void GridZone::SetZoneBounds(int xMin, int zMin, int xMax, int zMax) {
	if (xMin <= xMax) {
		this->westBound = xMin;
		this->eastBound = xMax;
	}
	else {
		this->westBound = xMax;
		this->eastBound = xMin;
	}
	if (zMin <= zMax) {
		this->southBound = zMin;
		this->northBound = zMax;
	}
	else {
		this->southBound = zMax;
		this->northBound = zMin;
	}
}

bool GridZone::IsCellWithinZone(GridCell* cell) {
	if (cell != nullptr) {
		int west, east, south, north;

		this->GetZoneBounds(west, east, south, north);

		return ((cell->x >= west) && (cell->x <= east) && (cell->z >= south) && (cell->z <= north));
	}

	return false;
}

void GridZone::init() {
	this->zoneType = GRID_ZONE_TYPE_UNKNOWN;
	this->westBound = -1;
	this->eastBound = -1;
	this->southBound = -1;
	this->northBound = -1;

	SINGLETONS->GetGridManager()->GetGrid()->AddGridZone(this->GetObject()->GetId());
}

void GridZone::destroy() {
	this->removeSubscriptionToAllMessageTypes(this->GetTypeId());
}
<|endoftext|>


<commit_before>#include <cstdlib>
#include <iostream>

#include <SFML/Graphics.hpp>

#include "context.hpp"
#include "../debug.hpp"

static sf::Font font;
static sf::Text debugText;

static sf::RenderWindow window;
static sf::Texture displayTexture;
static sf::Sprite displaySprite; // SFML needs a sprite to render a texture
static uint8_t* displayBuffer = nullptr;

static float speedInput = 1.0f;

// Placeholder
uint8_t  pixels[160 * 144 * 4];
uint8_t* joypad = nullptr;

// Placeholder
bool prevShouldHalt = false;
bool prevShouldStep = false;

bool Context::SetupContext (const int scale = 1) {
	font.loadFromFile("../resources/fonts/OpenSans-Bold.ttf");
	debugText.setFont(font);
	debugText.setColor(sf::Color::Magenta);
	debugText.setCharacterSize(15);
	debugText.setString("Debug :D");

	window.create(sf::VideoMode(160 * scale, 144 * scale), "Hi, I'm a secret message :D");

	displayTexture.create(160, 144);
	displayTexture.setSmooth(false);
	displaySprite.setTexture(displayTexture);

	sf::Vector2u textureSize = displayTexture.getSize();
	sf::Vector2u windowSize = window.getSize();

	float scaleX = (float) windowSize.x / textureSize.x;
	float scaleY = (float) windowSize.y / textureSize.y;

	displaySprite.setScale(scaleX, scaleY);

	return true;
}

void Context::DestroyContext () {
	if (window.isOpen())
		window.close();
}

void Context::HandleEvents () {
	sf::Event event;
	while (window.pollEvent(event)) {
		if (event.type == sf::Event::Closed)
			window.close();
		else if (event.type == sf::Event::KeyPressed) {
			if (event.key.code == sf::Keyboard::Escape) {
				window.close();
			}
			else if (event.key.code == sf::Keyboard::Num0) {
				speedInput = 1.0f;
			}
			else if (event.key.code == sf::Keyboard::Num9) {
				speedInput = 0.5f;
			}
			else if (event.key.code == sf::Keyboard::Num8) {
				speedInput = 0.25f;
			}
			else if (event.key.code == sf::Keyboard::Num7) {
				speedInput = 0.1f;
			}
			else if (event.key.code == sf::Keyboard::Num6) {
				speedInput = 0.05f;
			}
			else if (event.key.code == sf::Keyboard::Num5) {
				speedInput = 0.01f;
			}
		}
	}

	joypad[0] = sf::Keyboard::isKeyPressed(sf::Keyboard::D);
	joypad[1] = sf::Keyboard::isKeyPressed(sf::Keyboard::A);
	joypad[2] = sf::Keyboard::isKeyPressed(sf::Keyboard::W);
	joypad[3] = sf::Keyboard::isKeyPressed(sf::Keyboard::S);
	joypad[4] = sf::Keyboard::isKeyPressed(sf::Keyboard::H);
	joypad[5] = sf::Keyboard::isKeyPressed(sf::Keyboard::G);
	joypad[6] = sf::Keyboard::isKeyPressed(sf::Keyboard::B);
	joypad[7] = sf::Keyboard::isKeyPressed(sf::Keyboard::N);
}

void Context::RenderDebugText () {
	debugText.setPosition(0, 0);
	window.draw(debugText);

	std::string inputDebugString =
		"Right: "  + std::string(joypad[0] ? "1" : "0") + "\n" +
		"Left: "   + std::string(joypad[1] ? "1" : "0") + "\n" +
		"Up: "     + std::string(joypad[2] ? "1" : "0") + "\n" +
		"Down: "   + std::string(joypad[3] ? "1" : "0") + "\n" +
		"A: "      + std::string(joypad[4] ? "1" : "0") + "\n" +
		"B: "      + std::string(joypad[5] ? "1" : "0") + "\n" +
		"Select: " + std::string(joypad[6] ? "1" : "0") + "\n" +
		"Start: "  + std::string(joypad[7] ? "1" : "0");

	debugText.setString(inputDebugString);
	debugText.setPosition(100, 0);
	window.draw(debugText);
}

void Context::RenderDisplay () {
	window.clear();

	CopyDisplayBuffer(displayBuffer);
	displayTexture.update(pixels);
	window.draw(displaySprite);
	RenderDebugText();

	window.display();
}

void Context::SetJoypadBuffer (uint8_t* const buffer) {
	assert(buffer != nullptr);
	joypad = buffer;
}

// TODO: Use opengl texture binding and GL_R8UI color format to use the VRAM di-
//rectly as a pixel buffer.
// http://fr.sfml-dev.org/forums/index.php?topic=17847.0
// http://www.sfml-dev.org/documentation/2.4.1/classsf_1_1Texture.php
void Context::SetDisplayBuffer (uint8_t* const buffer) {
	assert(buffer != nullptr);
	displayBuffer = buffer;
}

// HACK: Temporary solution
// Currently, Instead of accessing the VRAM memory directly, we convert it's contents to a
//color format that SFML can understand.
void Context::CopyDisplayBuffer (uint8_t* const buffer) {
	for (size_t i = 0; i < 160 * 144 * 4; i += 4) {
		int luminosity = 255 - ((buffer[i / 4] + 1) * 64 - 1);
		pixels[i] = luminosity;
		pixels[i + 1] = luminosity;
		pixels[i + 2] = luminosity;
		pixels[i + 3] = 255;
	}
}

void Context::SetTitle (std::string title) {
	window.setTitle(title);
}

bool Context::IsOpen () {
	return window.isOpen();
}

bool Context::ShouldHalt () {
	bool curr = sf::Keyboard::isKeyPressed(sf::Keyboard::P);
	bool prev = prevShouldHalt;
	prevShouldHalt = curr;
	return curr ^ prev && curr;
}

bool Context::ShouldStep () {
	bool curr = sf::Keyboard::isKeyPressed(sf::Keyboard::O);
	bool prev = prevShouldStep;
	prevShouldStep = curr;
	return curr ^ prev && curr;
}

void Context::SetDebugText (std::string text) {
	debugText.setString(text);
}

float Context::GetSpeedInput () {
	return speedInput;
}
<commit_msg>Changed boring greyscale color palette to cool retro green gameboy palette<commit_after>#include <cstdlib>
#include <iostream>

#include <SFML/Graphics.hpp>
// #include <SFML/Vector3.hpp>
// #include <Vector3.hpp>
#include "context.hpp"
#include "../debug.hpp"

static sf::Font font;
static sf::Text debugText;

static sf::RenderWindow window;
static sf::Texture displayTexture;
static sf::Sprite displaySprite; // SFML needs a sprite to render a texture
static uint8_t* displayBuffer = nullptr;

static float speedInput = 1.0f;

// Placeholder
uint8_t  pixels[160 * 144 * 4];
uint8_t* joypad = nullptr;

// Placeholder
bool prevShouldHalt = false;
bool prevShouldStep = false;

bool Context::SetupContext (const int scale = 1) {
	font.loadFromFile("../resources/fonts/OpenSans-Bold.ttf");
	debugText.setFont(font);
	debugText.setColor(sf::Color::Magenta);
	debugText.setCharacterSize(15);
	debugText.setString("Debug :D");

	window.create(sf::VideoMode(160 * scale, 144 * scale), "Hi, I'm a secret message :D");

	displayTexture.create(160, 144);
	displayTexture.setSmooth(false);
	displaySprite.setTexture(displayTexture);

	sf::Vector2u textureSize = displayTexture.getSize();
	sf::Vector2u windowSize = window.getSize();

	float scaleX = (float) windowSize.x / textureSize.x;
	float scaleY = (float) windowSize.y / textureSize.y;

	displaySprite.setScale(scaleX, scaleY);

	return true;
}

void Context::DestroyContext () {
	if (window.isOpen())
		window.close();
}

void Context::HandleEvents () {
	sf::Event event;
	while (window.pollEvent(event)) {
		if (event.type == sf::Event::Closed)
			window.close();
		else if (event.type == sf::Event::KeyPressed) {
			if (event.key.code == sf::Keyboard::Escape) {
				window.close();
			}
			else if (event.key.code == sf::Keyboard::Num0) {
				speedInput = 1.0f;
			}
			else if (event.key.code == sf::Keyboard::Num9) {
				speedInput = 0.5f;
			}
			else if (event.key.code == sf::Keyboard::Num8) {
				speedInput = 0.25f;
			}
			else if (event.key.code == sf::Keyboard::Num7) {
				speedInput = 0.1f;
			}
			else if (event.key.code == sf::Keyboard::Num6) {
				speedInput = 0.05f;
			}
			else if (event.key.code == sf::Keyboard::Num5) {
				speedInput = 0.01f;
			}
		}
	}

	joypad[0] = sf::Keyboard::isKeyPressed(sf::Keyboard::D);
	joypad[1] = sf::Keyboard::isKeyPressed(sf::Keyboard::A);
	joypad[2] = sf::Keyboard::isKeyPressed(sf::Keyboard::W);
	joypad[3] = sf::Keyboard::isKeyPressed(sf::Keyboard::S);
	joypad[4] = sf::Keyboard::isKeyPressed(sf::Keyboard::H);
	joypad[5] = sf::Keyboard::isKeyPressed(sf::Keyboard::G);
	joypad[6] = sf::Keyboard::isKeyPressed(sf::Keyboard::B);
	joypad[7] = sf::Keyboard::isKeyPressed(sf::Keyboard::N);
}

void Context::RenderDebugText () {
	debugText.setPosition(0, 0);
	window.draw(debugText);

	std::string inputDebugString =
		"Right: "  + std::string(joypad[0] ? "1" : "0") + "\n" +
		"Left: "   + std::string(joypad[1] ? "1" : "0") + "\n" +
		"Up: "     + std::string(joypad[2] ? "1" : "0") + "\n" +
		"Down: "   + std::string(joypad[3] ? "1" : "0") + "\n" +
		"A: "      + std::string(joypad[4] ? "1" : "0") + "\n" +
		"B: "      + std::string(joypad[5] ? "1" : "0") + "\n" +
		"Select: " + std::string(joypad[6] ? "1" : "0") + "\n" +
		"Start: "  + std::string(joypad[7] ? "1" : "0");

	debugText.setString(inputDebugString);
	debugText.setPosition(100, 0);
	window.draw(debugText);
}

void Context::RenderDisplay () {
	window.clear();

	CopyDisplayBuffer(displayBuffer);
	displayTexture.update(pixels);
	window.draw(displaySprite);
	RenderDebugText();

	window.display();
}

void Context::SetJoypadBuffer (uint8_t* const buffer) {
	assert(buffer != nullptr);
	joypad = buffer;
}

// TODO: Use opengl texture binding and GL_R8UI color format to use the VRAM di-
//rectly as a pixel buffer.
// http://fr.sfml-dev.org/forums/index.php?topic=17847.0
// http://www.sfml-dev.org/documentation/2.4.1/classsf_1_1Texture.php
void Context::SetDisplayBuffer (uint8_t* const buffer) {
	assert(buffer != nullptr);
	displayBuffer = buffer;
}

// HACK: Temporary solution
// Currently, Instead of accessing the VRAM memory directly, we convert it's contents to a
//color format that SFML can understand.
void Context::CopyDisplayBuffer (uint8_t* const buffer) {
	for (size_t i = 0; i < 160 * 144 * 4; i += 4) {
		sf::Vector3<uint8_t> shades[] = {
			sf::Vector3<uint8_t>(155, 188, 15),
			sf::Vector3<uint8_t>(139, 172, 15),
			sf::Vector3<uint8_t>( 48,  98, 48),
			sf::Vector3<uint8_t>( 15,  56, 15),
		};
		pixels[i]     = shades[buffer[i / 4]].x;
		pixels[i + 1] = shades[buffer[i / 4]].y;
		pixels[i + 2] = shades[buffer[i / 4]].z;
		pixels[i + 3] = 255;
	}
}

void Context::SetTitle (std::string title) {
	window.setTitle(title);
}

bool Context::IsOpen () {
	return window.isOpen();
}

bool Context::ShouldHalt () {
	bool curr = sf::Keyboard::isKeyPressed(sf::Keyboard::P);
	bool prev = prevShouldHalt;
	prevShouldHalt = curr;
	return curr ^ prev && curr;
}

bool Context::ShouldStep () {
	bool curr = sf::Keyboard::isKeyPressed(sf::Keyboard::O);
	bool prev = prevShouldStep;
	prevShouldStep = curr;
	return curr ^ prev && curr;
}

void Context::SetDebugText (std::string text) {
	debugText.setString(text);
}

float Context::GetSpeedInput () {
	return speedInput;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: recursionhelper.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 17:51:05 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef INCLUDED_RECURSIONHELPER_HXX
#define INCLUDED_RECURSIONHELPER_HXX

#include <list>
#include <stack>
#include <tools/solar.h>

class ScFormulaCell;

struct ScFormulaRecursionEntry
{
    ScFormulaCell*  pCell;
    BOOL            bOldRunning;
    double          fPreviousResult;
    ScFormulaRecursionEntry( ScFormulaCell* p, BOOL b, double f ) : pCell(p),
                                                                    bOldRunning(b),
                                                                    fPreviousResult(f)
    {}
};

typedef ::std::list< ScFormulaRecursionEntry > ScFormulaRecursionList;

class ScRecursionHelper
{
    typedef ::std::stack< ScFormulaCell* >  ScRecursionInIterationStack;
    ScFormulaRecursionList              aRecursionFormulas;
    ScFormulaRecursionList::iterator    aInsertPos;
    ScFormulaRecursionList::iterator    aLastIterationStart;
    ScRecursionInIterationStack         aRecursionInIterationStack;
    USHORT                              nRecursionCount;
    USHORT                              nIteration;
    bool                                bInRecursionReturn;
    bool                                bDoingRecursion;
    bool                                bInIterationReturn;
    bool                                bConverging;

    void    Init()
    {
        nRecursionCount    = 0;
        bInRecursionReturn = bDoingRecursion = bInIterationReturn = false;
        aInsertPos = GetEnd();
        ResetIteration();
    }
    void    ResetIteration()
    {
        aLastIterationStart = GetEnd();
        nIteration = 0;
        bConverging = false;
    }

    public:

    ScRecursionHelper() { Init(); }
    USHORT  GetRecursionCount() const       { return nRecursionCount; }
    void    IncRecursionCount()             { ++nRecursionCount; }
    void    DecRecursionCount()             { --nRecursionCount; }
    /// A pure recursion return, no iteration.
    bool    IsInRecursionReturn() const     { return bInRecursionReturn &&
        !bInIterationReturn; }
    void    SetInRecursionReturn( bool b )
    {
        // Do not use IsInRecursionReturn() here, it decouples iteration.
        if (b && !bInRecursionReturn)
            aInsertPos = aRecursionFormulas.begin();
        bInRecursionReturn = b;
    }
    bool    IsDoingRecursion() const        { return bDoingRecursion; }
    void    SetDoingRecursion( bool b )     { bDoingRecursion = b; }
    void    Insert( ScFormulaCell* p, BOOL bOldRunning, double fResult )
    {
        aRecursionFormulas.insert( aInsertPos, ScFormulaRecursionEntry( p,
                    bOldRunning, fResult));
    }
    ScFormulaRecursionList::iterator    GetStart()
    {
        return aRecursionFormulas.begin();
    }
    ScFormulaRecursionList::iterator    GetEnd()
    {
        return aRecursionFormulas.end();
    }
    bool    IsInIterationReturn() const     { return bInIterationReturn; }
    void    SetInIterationReturn( bool b )
    {
        // An iteration return is always coupled to a recursion return.
        SetInRecursionReturn( b);
        bInIterationReturn = b;
    }
    bool    IsDoingIteration() const        { return nIteration > 0; }
    USHORT  GetIteration() const            { return nIteration; }
    bool &  GetConvergingReference()        { return bConverging; }
    void    StartIteration()
    {
        SetInIterationReturn( false);
        nIteration = 1;
        bConverging = false;
        aLastIterationStart = GetIterationStart();
    }
    void    ResumeIteration()
    {
        SetInIterationReturn( false);
        aLastIterationStart = GetIterationStart();
    }
    void    IncIteration()                  { ++nIteration; }
    void    EndIteration()
    {
        aRecursionFormulas.erase( GetIterationStart(), GetIterationEnd());
        ResetIteration();
    }
    ScFormulaRecursionList::iterator GetLastIterationStart() { return aLastIterationStart; }
    ScFormulaRecursionList::iterator GetIterationStart() { return GetStart(); }
    ScFormulaRecursionList::iterator GetIterationEnd() { return GetEnd(); }
    /** Any return, recursion or iteration, iteration is always coupled with
        recursion. */
    bool    IsInReturn() const              { return bInRecursionReturn; }
    const ScFormulaRecursionList&   GetList() const { return aRecursionFormulas; }
    ScFormulaRecursionList&         GetList()       { return aRecursionFormulas; }
    ScRecursionInIterationStack&    GetRecursionInIterationStack()  { return aRecursionInIterationStack; }
    void    Clear()
    {
        aRecursionFormulas.clear();
        while (!aRecursionInIterationStack.empty())
            aRecursionInIterationStack.pop();
        Init();
    }
};

#endif // INCLUDED_RECURSIONHELPER_HXX
<commit_msg>INTEGRATION: CWS dr41 (1.2.118); FILE MERGED 2005/10/04 21:05:54 dr 1.2.118.2: RESYNC: (1.2-1.3); FILE MERGED 2005/09/07 11:11:50 er 1.2.118.1: #i54276# include string results in iteration convergence tests<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: recursionhelper.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-10-21 11:52:08 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef INCLUDED_RECURSIONHELPER_HXX
#define INCLUDED_RECURSIONHELPER_HXX

#include <list>
#include <stack>
#include <tools/solar.h>

class ScFormulaCell;

struct ScFormulaRecursionEntry
{
    ScFormulaCell*  pCell;
    BOOL            bOldRunning;
    BOOL            bPreviousNumeric;
    double          fPreviousResult;
    String          aPreviousString;
    ScFormulaRecursionEntry( ScFormulaCell* p, BOOL bR, BOOL bN, double f,
            const String& rS ) : pCell(p), bOldRunning(bR),
                                 bPreviousNumeric(bN), fPreviousResult(f)
    {
        if (!bPreviousNumeric)
            aPreviousString = rS;
    }
};

typedef ::std::list< ScFormulaRecursionEntry > ScFormulaRecursionList;

class ScRecursionHelper
{
    typedef ::std::stack< ScFormulaCell* >  ScRecursionInIterationStack;
    ScFormulaRecursionList              aRecursionFormulas;
    ScFormulaRecursionList::iterator    aInsertPos;
    ScFormulaRecursionList::iterator    aLastIterationStart;
    ScRecursionInIterationStack         aRecursionInIterationStack;
    USHORT                              nRecursionCount;
    USHORT                              nIteration;
    bool                                bInRecursionReturn;
    bool                                bDoingRecursion;
    bool                                bInIterationReturn;
    bool                                bConverging;

    void    Init()
    {
        nRecursionCount    = 0;
        bInRecursionReturn = bDoingRecursion = bInIterationReturn = false;
        aInsertPos = GetEnd();
        ResetIteration();
    }
    void    ResetIteration()
    {
        aLastIterationStart = GetEnd();
        nIteration = 0;
        bConverging = false;
    }

    public:

    ScRecursionHelper() { Init(); }
    USHORT  GetRecursionCount() const       { return nRecursionCount; }
    void    IncRecursionCount()             { ++nRecursionCount; }
    void    DecRecursionCount()             { --nRecursionCount; }
    /// A pure recursion return, no iteration.
    bool    IsInRecursionReturn() const     { return bInRecursionReturn &&
        !bInIterationReturn; }
    void    SetInRecursionReturn( bool b )
    {
        // Do not use IsInRecursionReturn() here, it decouples iteration.
        if (b && !bInRecursionReturn)
            aInsertPos = aRecursionFormulas.begin();
        bInRecursionReturn = b;
    }
    bool    IsDoingRecursion() const        { return bDoingRecursion; }
    void    SetDoingRecursion( bool b )     { bDoingRecursion = b; }
    void    Insert( ScFormulaCell* p, BOOL bOldRunning, BOOL bNumeric,
                    double fResult, const String& rStrResult )
    {
        aRecursionFormulas.insert( aInsertPos, ScFormulaRecursionEntry( p,
                    bOldRunning, bNumeric, fResult, rStrResult));
    }
    ScFormulaRecursionList::iterator    GetStart()
    {
        return aRecursionFormulas.begin();
    }
    ScFormulaRecursionList::iterator    GetEnd()
    {
        return aRecursionFormulas.end();
    }
    bool    IsInIterationReturn() const     { return bInIterationReturn; }
    void    SetInIterationReturn( bool b )
    {
        // An iteration return is always coupled to a recursion return.
        SetInRecursionReturn( b);
        bInIterationReturn = b;
    }
    bool    IsDoingIteration() const        { return nIteration > 0; }
    USHORT  GetIteration() const            { return nIteration; }
    bool &  GetConvergingReference()        { return bConverging; }
    void    StartIteration()
    {
        SetInIterationReturn( false);
        nIteration = 1;
        bConverging = false;
        aLastIterationStart = GetIterationStart();
    }
    void    ResumeIteration()
    {
        SetInIterationReturn( false);
        aLastIterationStart = GetIterationStart();
    }
    void    IncIteration()                  { ++nIteration; }
    void    EndIteration()
    {
        aRecursionFormulas.erase( GetIterationStart(), GetIterationEnd());
        ResetIteration();
    }
    ScFormulaRecursionList::iterator GetLastIterationStart() { return aLastIterationStart; }
    ScFormulaRecursionList::iterator GetIterationStart() { return GetStart(); }
    ScFormulaRecursionList::iterator GetIterationEnd() { return GetEnd(); }
    /** Any return, recursion or iteration, iteration is always coupled with
        recursion. */
    bool    IsInReturn() const              { return bInRecursionReturn; }
    const ScFormulaRecursionList&   GetList() const { return aRecursionFormulas; }
    ScFormulaRecursionList&         GetList()       { return aRecursionFormulas; }
    ScRecursionInIterationStack&    GetRecursionInIterationStack()  { return aRecursionInIterationStack; }
    void    Clear()
    {
        aRecursionFormulas.clear();
        while (!aRecursionInIterationStack.empty())
            aRecursionInIterationStack.pop();
        Init();
    }
};

#endif // INCLUDED_RECURSIONHELPER_HXX
<|endoftext|>


<commit_before><commit_msg>Actually add new topic to list of topics in producer<commit_after><|endoftext|>


<commit_before>/**
 *  @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved.
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may find a copy of the License in the LICENCE file.
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *  @file HitFinderTools.h
 */

#include "HitFinderTools.h"

using namespace std;

vector<JPetHit> HitFinderTools::createHits(const SignalsContainer& allSignalsInTimeWindow, const double timeDifferenceWindow){

    // This method takes signal from side A on a scintilator and compares it with signals on side B - if they are within time window then it creates hit

    vector<JPetHit> hits;

    for (auto scintillator : allSignalsInTimeWindow) {

        auto sideA = scintillator.second.first;
        auto sideB = scintillator.second.second;

        if(sideA.size() > 0 and sideB.size() > 0){

            for(auto signalA : sideA){
                for(auto signalB : sideB){

                    if(abs(signalA.getTime() - signalB.getTime()) < timeDifferenceWindow /*ps*/){

                        JPetHit hit;
                        hit.setSignalA(signalA);
                        hit.setSignalB(signalB);
                        hit.setTime( (signalA.getTime() + signalB.getTime())/2.0 );
                        hit.setScintillator(signalA.getRecoSignal().getRawSignal().getPM().getScin());
                        hit.setBarrelSlot(signalA.getRecoSignal().getRawSignal().getPM().getScin().getBarrelSlot());

                        hits.push_back(hit);
                    }
                }
            }

        }
    }
    return hits;
}
<commit_msg>Sort signals<commit_after>/**
 *  @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved.
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may find a copy of the License in the LICENCE file.
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *  @file HitFinderTools.h
 */

#include "HitFinderTools.h"

using namespace std;

vector<JPetHit> HitFinderTools::createHits(const SignalsContainer& allSignalsInTimeWindow, const double timeDifferenceWindow){

    // This method takes signal from side A on a scintilator and compares it with signals on side B - if they are within time window then it creates hit

    vector<JPetHit> hits;

    for (auto scintillator : allSignalsInTimeWindow) {

        auto sideA = scintillator.second.first;
        auto sideB = scintillator.second.second;

        if(sideA.size() > 0 and sideB.size() > 0){

        std::sort(sideA.begin(), sideA.end(), [] (const JPetPhysSignal & h1, const JPetPhysSignal & h2) {return h1.getTime() < h2.getTime();});
        std::sort(sideB.begin(), sideB.end(), [] (const JPetPhysSignal & h1, const JPetPhysSignal & h2) {return h1.getTime() < h2.getTime();});
            for(auto signalA : sideA){
                for(auto signalB : sideB){

                    if(abs(signalA.getTime() - signalB.getTime()) < timeDifferenceWindow  && (signalA.getTime() - signalB.getTime()) < timeDifferenceWindow/*ps*/){

                        JPetHit hit;
                        hit.setSignalA(signalA);
                        hit.setSignalB(signalB);
                        hit.setTime( (signalA.getTime() + signalB.getTime())/2.0 );
                        hit.setScintillator(signalA.getRecoSignal().getRawSignal().getPM().getScin());
                        hit.setBarrelSlot(signalA.getRecoSignal().getRawSignal().getPM().getScin().getBarrelSlot());

                        hits.push_back(hit);
                    }
                }
            }

        }
    }
    return hits;
}
<|endoftext|>