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

#include "CEGUIIrrlichtGeometryBuffer.h"
#include "CEGUIRenderEffect.h"
#include "CEGUIIrrlichtTexture.h"
#include "CEGUIVertex.h"

// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
IrrlichtGeometryBuffer::IrrlichtGeometryBuffer(irr::video::IVideoDriver& driver):
    d_driver(driver),
    d_activeTexture(0),
    d_clipRect(0, 0, 0, 0),
    d_translation(0, 0, 0),
    d_rotation(0, 0, 0),
    d_pivot(0, 0, 0),
    d_effect(0),
    d_matrixValid(false),
    d_xViewDir(driver.getDriverType() != irr::video::EDT_OPENGL ? 1.0f : -1.0f),
    d_texelOffset(driver.getDriverType() != irr::video::EDT_OPENGL ? -0.5f : 0.0f)
{
    d_material.BackfaceCulling = false;
    d_material.Lighting = false;
    d_material.ZBuffer = 0;
    d_material.ZWriteEnable = false;
    #if CEGUI_IRR_SDK_VERSION >= 16
        d_material.MaterialType = irr::video::EMT_ONETEXTURE_BLEND;
        d_material.MaterialTypeParam = irr::video::pack_texureBlendFunc(
                irr::video::EBF_SRC_ALPHA,
                irr::video::EBF_ONE_MINUS_SRC_ALPHA,
                irr::video::EMFN_MODULATE_1X,
                irr::video::EAS_NONE);
    #else
        d_material.MaterialType = irr::video::EMT_TRANSPARENT_ALPHA_CHANNEL;
        d_material.MaterialTypeParam = 0;
    #endif
}

//----------------------------------------------------------------------------//
void IrrlichtGeometryBuffer::draw() const
{
    // Set up clipping for this buffer
    //
    // NB: This is done via viewport & projection manipulation because Irrlicht
    // does not expose scissoring facilities of underlying APIs.  This has the
    // unfortunate side effect of being much more expensive to set up.
    const irr::core::rect<irr::s32> target_vp(d_driver.getViewPort());
    const irr::core::matrix4 proj
        (d_driver.getTransform(irr::video::ETS_PROJECTION));

    const Size csz(d_clipRect.getSize());
    const Size tsz(static_cast<float>(target_vp.getWidth()),
                   static_cast<float>(target_vp.getHeight()));

    // set modified projection 'scissor' matix that negates scale and
    // translation that would be done by setting the viewport to the clip area.
    irr::core::matrix4 scsr(irr::core::matrix4::EM4CONST_IDENTITY);
    scsr(0, 0) = tsz.d_width / csz.d_width;
    scsr(1, 1) = tsz.d_height / csz.d_height;
    scsr(3, 0) = d_xViewDir * (tsz.d_width + 2.0f *
                   (target_vp.UpperLeftCorner.X -
                     (d_clipRect.d_left + csz.d_width * 0.5f))) / csz.d_width;
    scsr(3, 1) = -(tsz.d_height + 2.0f *
                   (target_vp.UpperLeftCorner.Y -
                     (d_clipRect.d_top + csz.d_height * 0.5f))) / csz.d_height;
    scsr *= proj;
    d_driver.setTransform(irr::video::ETS_PROJECTION, scsr);

    // set new viewport for the clipping area
    const irr::core::rect<irr::s32> vp(
            static_cast<irr::s32>(d_clipRect.d_left),
            static_cast<irr::s32>(d_clipRect.d_top),
            static_cast<irr::s32>(d_clipRect.d_right),
            static_cast<irr::s32>(d_clipRect.d_bottom));
    d_driver.setViewPort(vp);

    if (!d_matrixValid)
        updateMatrix();

    d_driver.setTransform(irr::video::ETS_WORLD, d_matrix);

    const int pass_count = d_effect ? d_effect->getPassCount() : 1;
    for (int pass = 0; pass < pass_count; ++pass)
    {
        // set up RenderEffect
        if (d_effect)
            d_effect->performPreRenderFunctions(pass);

        // draw the batches
        size_t pos = 0;
        BatchList::const_iterator i = d_batches.begin();
        for ( ; i != d_batches.end(); ++i)
        {
            d_material.setTexture(0, (*i).first);
            d_driver.setMaterial(d_material);
            d_driver.drawIndexedTriangleList(&d_vertices[pos], (*i).second,
                                            &d_indices[pos], (*i).second / 3);
            pos += (*i).second;
        }
    }

    // clean up RenderEffect
    if (d_effect)
        d_effect->performPostRenderFunctions();

    // restore original projection matrix and viewport.
    d_driver.setTransform(irr::video::ETS_PROJECTION, proj);
    d_driver.setViewPort(target_vp);
}

//----------------------------------------------------------------------------//
void IrrlichtGeometryBuffer::setTranslation(const Vector3& v)
{
    d_translation.X = v.d_x;
    d_translation.Y = v.d_y;
    d_translation.Z = v.d_z;
    d_matrixValid = false;
}

//----------------------------------------------------------------------------//
void IrrlichtGeometryBuffer::setRotation(const Vector3& r)
{
    d_rotation.X = r.d_x;
    d_rotation.Y = r.d_y;
    d_rotation.Z = r.d_z;
    d_matrixValid = false;
}

//----------------------------------------------------------------------------//
void IrrlichtGeometryBuffer::setPivot(const Vector3& p)
{
    d_pivot.X = p.d_x;
    d_pivot.Y = p.d_y;
    d_pivot.Z = p.d_z;
    d_matrixValid = false;
}

//----------------------------------------------------------------------------//
void IrrlichtGeometryBuffer::setClippingRegion(const Rect& region)
{
    d_clipRect.d_top    = ceguimax(0.0f, PixelAligned(region.d_top));
    d_clipRect.d_bottom = ceguimax(0.0f, PixelAligned(region.d_bottom));
    d_clipRect.d_left   = ceguimax(0.0f, PixelAligned(region.d_left));
    d_clipRect.d_right  = ceguimax(0.0f, PixelAligned(region.d_right));
}

//----------------------------------------------------------------------------//
void IrrlichtGeometryBuffer::appendVertex(const Vertex& vertex)
{
    appendGeometry(&vertex, 1);
}

//----------------------------------------------------------------------------//
void IrrlichtGeometryBuffer::appendGeometry(const Vertex* const vbuff,
                                            uint vertex_count)
{
    // see if we should start a new batch
    irr::video::ITexture* t =
        d_activeTexture ? d_activeTexture->getIrrlichtTexture() : 0;

    if (d_batches.empty() || d_batches.back().first != t)
        d_batches.push_back(BatchInfo(t, 0));

    // buffer these vertices
    const irr::u16 idx_start = d_batches.back().second;
    irr::video::S3DVertex v;
    for (uint i = 0; i < vertex_count; ++i)
    {
        const Vertex& vs = vbuff[i];
        v.Pos.X     = vs.position.d_x + d_texelOffset;
        v.Pos.Y     = vs.position.d_y + d_texelOffset;
        v.Pos.Z     = vs.position.d_z;
        v.TCoords.X = vs.tex_coords.d_x;
        v.TCoords.Y = vs.tex_coords.d_y;
        v.Color.set(vs.colour_val.getARGB());
        d_vertices.push_back(v);
        d_indices.push_back(idx_start + i);
    }

    // update size of current batch
    d_batches.back().second += vertex_count;
}

//----------------------------------------------------------------------------//
void IrrlichtGeometryBuffer::setActiveTexture(Texture* texture)
{
    d_activeTexture = static_cast<IrrlichtTexture*>(texture);
}

//----------------------------------------------------------------------------//
void IrrlichtGeometryBuffer::reset()
{
    d_vertices.clear();
    d_indices.clear();
    d_batches.clear();
    d_activeTexture = 0;
}

//----------------------------------------------------------------------------//
Texture* IrrlichtGeometryBuffer::getActiveTexture() const
{
    return d_activeTexture;
}

//----------------------------------------------------------------------------//
uint IrrlichtGeometryBuffer::getVertexCount() const
{
    return d_vertices.size();
}

//----------------------------------------------------------------------------//
uint IrrlichtGeometryBuffer::getBatchCount() const
{
    return d_batches.size();
}

//----------------------------------------------------------------------------//
void IrrlichtGeometryBuffer::setRenderEffect(RenderEffect* effect)
{
    d_effect = effect;
}

//----------------------------------------------------------------------------//
RenderEffect* IrrlichtGeometryBuffer::getRenderEffect()
{
    return d_effect;
}

//----------------------------------------------------------------------------//
const irr::core::matrix4& IrrlichtGeometryBuffer::getMatrix() const
{
    return d_matrix;
}

//----------------------------------------------------------------------------//
void IrrlichtGeometryBuffer::updateMatrix() const
{
    d_matrix.makeIdentity();
    d_matrix.setTranslation(d_translation + d_pivot);

    irr::core::matrix4 rot;
    rot.setRotationDegrees(d_rotation);
    irr::core::matrix4 ptrans;
    ptrans.setTranslation(-d_pivot);

    d_matrix *= rot;
    d_matrix *= ptrans;

    d_matrixValid = true;
}

//----------------------------------------------------------------------------//
irr::video::SMaterial& IrrlichtGeometryBuffer::getMaterial()
{
    return const_cast<irr::video::SMaterial&>(
        static_cast<const IrrlichtGeometryBuffer*>(this)->getMaterial());
}

//----------------------------------------------------------------------------//
const irr::video::SMaterial& IrrlichtGeometryBuffer::getMaterial() const
{
    return d_material;
}

} // End of  CEGUI namespace section
<commit_msg>Deal with the Irrlicht texure vs texture situation<commit_after>/***********************************************************************
    filename:   CEGUIIrrlichtGeometryBuffer.cpp
    created:    Tue Mar 3 2009
    author:     Paul D Turner (parts based on original code by Thomas Suter)
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team
 *
 *   Permission is hereby granted, free of charge, to any person obtaining
 *   a copy of this software and associated documentation files (the
 *   "Software"), to deal in the Software without restriction, including
 *   without limitation the rights to use, copy, modify, merge, publish,
 *   distribute, sublicense, and/or sell copies of the Software, and to
 *   permit persons to whom the Software is furnished to do so, subject to
 *   the following conditions:
 *
 *   The above copyright notice and this permission notice shall be
 *   included in all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *   OTHER DEALINGS IN THE SOFTWARE.
 ***************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include "CEGUIIrrlichtGeometryBuffer.h"
#include "CEGUIRenderEffect.h"
#include "CEGUIIrrlichtTexture.h"
#include "CEGUIVertex.h"

// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
IrrlichtGeometryBuffer::IrrlichtGeometryBuffer(irr::video::IVideoDriver& driver):
    d_driver(driver),
    d_activeTexture(0),
    d_clipRect(0, 0, 0, 0),
    d_translation(0, 0, 0),
    d_rotation(0, 0, 0),
    d_pivot(0, 0, 0),
    d_effect(0),
    d_matrixValid(false),
    d_xViewDir(driver.getDriverType() != irr::video::EDT_OPENGL ? 1.0f : -1.0f),
    d_texelOffset(driver.getDriverType() != irr::video::EDT_OPENGL ? -0.5f : 0.0f)
{
    d_material.BackfaceCulling = false;
    d_material.Lighting = false;
    d_material.ZBuffer = 0;
    d_material.ZWriteEnable = false;
    #if CEGUI_IRR_SDK_VERSION >= 16
        d_material.MaterialType = irr::video::EMT_ONETEXTURE_BLEND;
        d_material.MaterialTypeParam =
#if IRRLICHT_VERSION_MAJOR > 1 || (IRRLICHT_VERSION_MAJOR == 1 && IRRLICHT_VERSION_MINOR >= 8)
            irr::video::pack_textureBlendFunc(
#else
            irr::video::pack_texureBlendFunc(
#endif
                irr::video::EBF_SRC_ALPHA,
                irr::video::EBF_ONE_MINUS_SRC_ALPHA,
                irr::video::EMFN_MODULATE_1X,
                irr::video::EAS_NONE);
    #else
        d_material.MaterialType = irr::video::EMT_TRANSPARENT_ALPHA_CHANNEL;
        d_material.MaterialTypeParam = 0;
    #endif
}

//----------------------------------------------------------------------------//
void IrrlichtGeometryBuffer::draw() const
{
    // Set up clipping for this buffer
    //
    // NB: This is done via viewport & projection manipulation because Irrlicht
    // does not expose scissoring facilities of underlying APIs.  This has the
    // unfortunate side effect of being much more expensive to set up.
    const irr::core::rect<irr::s32> target_vp(d_driver.getViewPort());
    const irr::core::matrix4 proj
        (d_driver.getTransform(irr::video::ETS_PROJECTION));

    const Size csz(d_clipRect.getSize());
    const Size tsz(static_cast<float>(target_vp.getWidth()),
                   static_cast<float>(target_vp.getHeight()));

    // set modified projection 'scissor' matix that negates scale and
    // translation that would be done by setting the viewport to the clip area.
    irr::core::matrix4 scsr(irr::core::matrix4::EM4CONST_IDENTITY);
    scsr(0, 0) = tsz.d_width / csz.d_width;
    scsr(1, 1) = tsz.d_height / csz.d_height;
    scsr(3, 0) = d_xViewDir * (tsz.d_width + 2.0f *
                   (target_vp.UpperLeftCorner.X -
                     (d_clipRect.d_left + csz.d_width * 0.5f))) / csz.d_width;
    scsr(3, 1) = -(tsz.d_height + 2.0f *
                   (target_vp.UpperLeftCorner.Y -
                     (d_clipRect.d_top + csz.d_height * 0.5f))) / csz.d_height;
    scsr *= proj;
    d_driver.setTransform(irr::video::ETS_PROJECTION, scsr);

    // set new viewport for the clipping area
    const irr::core::rect<irr::s32> vp(
            static_cast<irr::s32>(d_clipRect.d_left),
            static_cast<irr::s32>(d_clipRect.d_top),
            static_cast<irr::s32>(d_clipRect.d_right),
            static_cast<irr::s32>(d_clipRect.d_bottom));
    d_driver.setViewPort(vp);

    if (!d_matrixValid)
        updateMatrix();

    d_driver.setTransform(irr::video::ETS_WORLD, d_matrix);

    const int pass_count = d_effect ? d_effect->getPassCount() : 1;
    for (int pass = 0; pass < pass_count; ++pass)
    {
        // set up RenderEffect
        if (d_effect)
            d_effect->performPreRenderFunctions(pass);

        // draw the batches
        size_t pos = 0;
        BatchList::const_iterator i = d_batches.begin();
        for ( ; i != d_batches.end(); ++i)
        {
            d_material.setTexture(0, (*i).first);
            d_driver.setMaterial(d_material);
            d_driver.drawIndexedTriangleList(&d_vertices[pos], (*i).second,
                                            &d_indices[pos], (*i).second / 3);
            pos += (*i).second;
        }
    }

    // clean up RenderEffect
    if (d_effect)
        d_effect->performPostRenderFunctions();

    // restore original projection matrix and viewport.
    d_driver.setTransform(irr::video::ETS_PROJECTION, proj);
    d_driver.setViewPort(target_vp);
}

//----------------------------------------------------------------------------//
void IrrlichtGeometryBuffer::setTranslation(const Vector3& v)
{
    d_translation.X = v.d_x;
    d_translation.Y = v.d_y;
    d_translation.Z = v.d_z;
    d_matrixValid = false;
}

//----------------------------------------------------------------------------//
void IrrlichtGeometryBuffer::setRotation(const Vector3& r)
{
    d_rotation.X = r.d_x;
    d_rotation.Y = r.d_y;
    d_rotation.Z = r.d_z;
    d_matrixValid = false;
}

//----------------------------------------------------------------------------//
void IrrlichtGeometryBuffer::setPivot(const Vector3& p)
{
    d_pivot.X = p.d_x;
    d_pivot.Y = p.d_y;
    d_pivot.Z = p.d_z;
    d_matrixValid = false;
}

//----------------------------------------------------------------------------//
void IrrlichtGeometryBuffer::setClippingRegion(const Rect& region)
{
    d_clipRect.d_top    = ceguimax(0.0f, PixelAligned(region.d_top));
    d_clipRect.d_bottom = ceguimax(0.0f, PixelAligned(region.d_bottom));
    d_clipRect.d_left   = ceguimax(0.0f, PixelAligned(region.d_left));
    d_clipRect.d_right  = ceguimax(0.0f, PixelAligned(region.d_right));
}

//----------------------------------------------------------------------------//
void IrrlichtGeometryBuffer::appendVertex(const Vertex& vertex)
{
    appendGeometry(&vertex, 1);
}

//----------------------------------------------------------------------------//
void IrrlichtGeometryBuffer::appendGeometry(const Vertex* const vbuff,
                                            uint vertex_count)
{
    // see if we should start a new batch
    irr::video::ITexture* t =
        d_activeTexture ? d_activeTexture->getIrrlichtTexture() : 0;

    if (d_batches.empty() || d_batches.back().first != t)
        d_batches.push_back(BatchInfo(t, 0));

    // buffer these vertices
    const irr::u16 idx_start = d_batches.back().second;
    irr::video::S3DVertex v;
    for (uint i = 0; i < vertex_count; ++i)
    {
        const Vertex& vs = vbuff[i];
        v.Pos.X     = vs.position.d_x + d_texelOffset;
        v.Pos.Y     = vs.position.d_y + d_texelOffset;
        v.Pos.Z     = vs.position.d_z;
        v.TCoords.X = vs.tex_coords.d_x;
        v.TCoords.Y = vs.tex_coords.d_y;
        v.Color.set(vs.colour_val.getARGB());
        d_vertices.push_back(v);
        d_indices.push_back(idx_start + i);
    }

    // update size of current batch
    d_batches.back().second += vertex_count;
}

//----------------------------------------------------------------------------//
void IrrlichtGeometryBuffer::setActiveTexture(Texture* texture)
{
    d_activeTexture = static_cast<IrrlichtTexture*>(texture);
}

//----------------------------------------------------------------------------//
void IrrlichtGeometryBuffer::reset()
{
    d_vertices.clear();
    d_indices.clear();
    d_batches.clear();
    d_activeTexture = 0;
}

//----------------------------------------------------------------------------//
Texture* IrrlichtGeometryBuffer::getActiveTexture() const
{
    return d_activeTexture;
}

//----------------------------------------------------------------------------//
uint IrrlichtGeometryBuffer::getVertexCount() const
{
    return d_vertices.size();
}

//----------------------------------------------------------------------------//
uint IrrlichtGeometryBuffer::getBatchCount() const
{
    return d_batches.size();
}

//----------------------------------------------------------------------------//
void IrrlichtGeometryBuffer::setRenderEffect(RenderEffect* effect)
{
    d_effect = effect;
}

//----------------------------------------------------------------------------//
RenderEffect* IrrlichtGeometryBuffer::getRenderEffect()
{
    return d_effect;
}

//----------------------------------------------------------------------------//
const irr::core::matrix4& IrrlichtGeometryBuffer::getMatrix() const
{
    return d_matrix;
}

//----------------------------------------------------------------------------//
void IrrlichtGeometryBuffer::updateMatrix() const
{
    d_matrix.makeIdentity();
    d_matrix.setTranslation(d_translation + d_pivot);

    irr::core::matrix4 rot;
    rot.setRotationDegrees(d_rotation);
    irr::core::matrix4 ptrans;
    ptrans.setTranslation(-d_pivot);

    d_matrix *= rot;
    d_matrix *= ptrans;

    d_matrixValid = true;
}

//----------------------------------------------------------------------------//
irr::video::SMaterial& IrrlichtGeometryBuffer::getMaterial()
{
    return const_cast<irr::video::SMaterial&>(
        static_cast<const IrrlichtGeometryBuffer*>(this)->getMaterial());
}

//----------------------------------------------------------------------------//
const irr::video::SMaterial& IrrlichtGeometryBuffer::getMaterial() const
{
    return d_material;
}

} // End of  CEGUI namespace section
<|endoftext|>


<commit_before>#include <stdio.h>

#include <iostream>
#include <fstream>
#include <opencv2/opencv.hpp>
#include <time.h>
#include <unistd.h>
#include <memory>

#include "objectTracking/ColorTracker.h"
#include "objectTracking/Flooder.h"
#include "CoordinateConverter.h"
#include "Pool.h"

enum PROGRAM_STATE
{
    WAIT_FOR_SELECT,
    SELECT_PARAMETERS,
    PLAY
};
PROGRAM_STATE state;

enum SELECT_STATE
{
    WHITE_BALL,
    TARGET,
    HOLE
};
SELECT_STATE selState;

cv::VideoCapture camera(1);

Vec3 targetColor(29, 227, 218);
Vec3 minColor;
Vec3 maxColor;
Vec3 redColor(1, 227, 218);
Vec3 minRed;
Vec3 maxRed;

Vec3 threshold(30, 80, 80);

std::deque< Flooder::Blob > blobs;

bool running = true;

//Used as a safe way of shutting down the program since ctrl+c doesn't stop
//using the webcam
void onMouse(int event, int x, int y, int, void*);
void selectColor(int event, int x, int y, int , void*);
void setMinMaxColor(Vec3 target, Vec3& minColor, Vec3& maxColor, Vec3 threshold);
void captureNewImage();
void runSelect(float x, float y);

void mainLoop();

std::unique_ptr<CoordinateConverter> coordinateConverter;

cv::Mat currentImage;
ColorTracker ct;

Pool pool;

int main()
{
    //Reading bounds of the table
    std::ifstream boundFile;
    boundFile.open("bounds");

    std::vector<Vec2> boundCoords;
    for(int i = 0; i < 3; ++i)
    {
        float x, y;

        boundFile >> x >> y;

        boundCoords.push_back(Vec2(x, y));
    }
    coordinateConverter.reset(new CoordinateConverter(boundCoords));

    if(camera.isOpened() == false)
    {
        std::cout << "Failed to open camera" << std::endl;
    }

    //capture 1 image for use as reference
    cv::Mat ref;
    camera >> ref;

    ColorTracker ct;
    ct.setImage(ref);

    //targetColor = ct.getObjectColor();
    minColor = targetColor - threshold;
    maxColor = targetColor + threshold;
    minRed = redColor - threshold;
    maxRed = redColor + threshold;

    cv::namedWindow("GUI");
    cv::setMouseCallback("GUI", onMouse);
    cv::moveWindow("GUI", 0, 500);

    cv::namedWindow("Display Image");
    cv::setMouseCallback("Display Image", selectColor);

    cv::namedWindow("Threshold img");
    cv::moveWindow("Threshold img", 0, 0);

    while(running == true)
    {
        mainLoop();
    }

    return 0;
}

void mainLoop()
{
    if(state == WAIT_FOR_SELECT)
    {
        captureNewImage();

        //Colortracking
        ct.setImage(currentImage);
        ct.generateBinary(minColor, maxColor, true);

        //Getting the blob data from the trackers
        ct.generateBlobs();
        blobs = ct.getBlobs(60);

        int maxBlobSize = 0;
        auto maxBlob= blobs.begin();
        for(auto it = blobs.begin(); it != blobs.end(); ++it)
        {
            if(it->pixelAmount > maxBlobSize)
            {
                maxBlobSize = it->pixelAmount;
                maxBlob= it;
            }
        }
        blobs.erase(maxBlob);
    }
    else if(state == SELECT_PARAMETERS)
    {
    }
    else if(state == PLAY)
    {
        state = WAIT_FOR_SELECT;
    }

    for(unsigned int i = 0; i < blobs.size(); i++)
    {
        ct.drawCircle(blobs.at(i).center, 5, cv::Scalar(255, 0, 0));
    }

    cv::imshow("Threshold img", ct.getBinary());
    cv::imshow("Display Image", currentImage);

    cv::waitKey(1);
}

void onMouse(int event, int x, int y, int, void*)
{
    if(event != 1)
    {
        return;
    }

    //Exiting the program
    running = false;
}

void selectColor(int event, int x, int y, int, void*)
{
    if(event == CV_EVENT_RBUTTONDOWN) //If this isn't a left click
    {

        //Create a color tracker to get the color
        ColorTracker ct;
        ct.setImage(currentImage);

        redColor = ct.getColorInPixel(Vec2(x, y));

        //Recalculating the threshold
        setMinMaxColor(redColor, minColor, maxColor, threshold);
    }
    else if(event == CV_EVENT_LBUTTONDOWN)
    {
        //std::cout << coordinateConverter->convertTo(Vec2(x,y)).getString() << std::endl;
        switch(state)
        {
            case WAIT_FOR_SELECT:
            {
                state = SELECT_PARAMETERS;
                break;
            }
            case SELECT_PARAMETERS:
            {
                runSelect(x, y);
                break;
            }
        }
    }
}

void setMinMaxColor(Vec3 target, Vec3& minColor, Vec3& maxColor, Vec3 threshold)
{
    minColor = target - threshold;
    maxColor = target + threshold;
}

void captureNewImage()
{
    cv::Mat img;
    camera >> img;

    //Fix fisheye problems
    cv::Mat tmpImg;

    //Read fisheye correction stuff from a file. Generate using the "cpp/calibration" sample
    cv::Mat camera_matrix, distortion;
    cv::FileStorage fs("fisheye0.txt", cv::FileStorage::READ);
    cv::FileNode fn = fs["IntParam"];
    fn["camera_matrix"] >> camera_matrix;
    fn["distortion"] >> distortion;

    cv::undistort(img, tmpImg, camera_matrix, distortion);

    img = tmpImg;
    currentImage = tmpImg;
}

void runSelect(float x, float y)
{
    //Finding the closest ball
    float minBlobDistance = 0;
    auto closestBlob = blobs.begin();
    for(auto it = blobs.begin(); it != blobs.end(); ++it)
    {
        Vec2 diff = closestBlob->center - Vec2(x, y);

        if(diff.getLength() < minBlobDistance)
        {
            closestBlob = it;
        }
    }

    switch(selState)
    {
        case WHITE_BALL:
        {
            pool.setWhiteBall(closestBlob->center);
            selState = TARGET;
            break;
        }
        case TARGET:
        {
            pool.setTargetBall(closestBlob->center);

            selState = HOLE;
            break;
        }
        case HOLE:
        {
            float holeX = round(x * 2) / 2.0;
            float holeY = round(y * 2) / 2.0;

            if(holeX < 0)
                holeX = 0;
            if(holeX > 1)
                holeX = 1;
            if(holeY < 0)
                holeY = 0;
            if(holeY > 0.5)
                holeX = 0.5;

            pool.setHole(Vec2(holeX, holeY));
            selState = WHITE_BALL;
            state = PLAY;
            break;
        }
    }
}
<commit_msg>fix broken code from last commit<commit_after>#include <stdio.h>

#include <iostream>
#include <fstream>
#include <opencv2/opencv.hpp>
#include <time.h>
#include <unistd.h>
#include <memory>

#include "objectTracking/ColorTracker.h"
#include "objectTracking/Flooder.h"
#include "CoordinateConverter.h"
#include "Pool.h"

enum PROGRAM_STATE
{
    WAIT_FOR_SELECT,
    SELECT_PARAMETERS,
    PLAY
};
PROGRAM_STATE state;

enum SELECT_STATE
{
    WHITE_BALL,
    TARGET,
    HOLE
};
SELECT_STATE selState;

cv::VideoCapture camera(1);

Vec3 targetColor(29, 227, 218);
Vec3 minColor;
Vec3 maxColor;
Vec3 redColor(1, 227, 218);
Vec3 minRed;
Vec3 maxRed;

Vec3 threshold(30, 80, 80);

std::deque< Flooder::Blob > blobs;

bool running = true;

//Used as a safe way of shutting down the program since ctrl+c doesn't stop
//using the webcam
void onMouse(int event, int x, int y, int, void*);
void selectColor(int event, int x, int y, int , void*);
void setMinMaxColor(Vec3 target, Vec3& minColor, Vec3& maxColor, Vec3 threshold);
void captureNewImage();
void runSelect(float x, float y);

void mainLoop();

std::unique_ptr<CoordinateConverter> coordinateConverter;

cv::Mat currentImage;
ColorTracker ct;

Pool pool;

int main()
{
    //Reading bounds of the table
    std::ifstream boundFile;
    boundFile.open("bounds");

    std::vector<Vec2> boundCoords;
    for(int i = 0; i < 3; ++i)
    {
        float x, y;

        boundFile >> x >> y;

        boundCoords.push_back(Vec2(x, y));
    }
    coordinateConverter.reset(new CoordinateConverter(boundCoords));

    if(camera.isOpened() == false)
    {
        std::cout << "Failed to open camera" << std::endl;
    }

    //capture 1 image for use as reference
    cv::Mat ref;
    camera >> ref;

    ColorTracker ct;
    ct.setImage(ref);

    //targetColor = ct.getObjectColor();
    minColor = targetColor - threshold;
    maxColor = targetColor + threshold;
    minRed = redColor - threshold;
    maxRed = redColor + threshold;

    cv::namedWindow("GUI");
    cv::setMouseCallback("GUI", onMouse);
    cv::moveWindow("GUI", 0, 500);

    cv::namedWindow("Display Image");
    cv::setMouseCallback("Display Image", selectColor);

    cv::namedWindow("Threshold img");
    cv::moveWindow("Threshold img", 0, 0);

    while(running == true)
    {
        mainLoop();
    }

    return 0;
}

void mainLoop()
{
    if(state == WAIT_FOR_SELECT)
    {
        captureNewImage();

        //Colortracking
        ct.setImage(currentImage);
        ct.generateBinary(minColor, maxColor, true);

        //Getting the blob data from the trackers
        ct.generateBlobs();
        blobs = ct.getBlobs(60);

        int maxBlobSize = 0;
        auto maxBlob= blobs.begin();
        for(auto it = blobs.begin(); it != blobs.end(); ++it)
        {
            if(it->pixelAmount > maxBlobSize)
            {
                maxBlobSize = it->pixelAmount;
                maxBlob= it;
            }
        }
        blobs.erase(maxBlob);
    }
    else if(state == SELECT_PARAMETERS)
    {
    }
    else if(state == PLAY)
    {
        state = WAIT_FOR_SELECT;
    }

    for(unsigned int i = 0; i < blobs.size(); i++)
    {
        ct.drawCircle(blobs.at(i).center, 5, cv::Scalar(255, 0, 0));
    }

    cv::imshow("Threshold img", ct.getBinary());
    cv::imshow("Display Image", currentImage);

    cv::waitKey(1);
}

void onMouse(int event, int x, int y, int, void*)
{
    if(event != 1)
    {
        return;
    }

    //Exiting the program
    running = false;
}

void selectColor(int event, int x, int y, int, void*)
{
    if(event == CV_EVENT_RBUTTONDOWN) //If this isn't a left click
    {

        //Create a color tracker to get the color
        ColorTracker ct;
        ct.setImage(currentImage);

        redColor = ct.getColorInPixel(Vec2(x, y));

        //Recalculating the threshold
        setMinMaxColor(redColor, minColor, maxColor, threshold);
    }
    else if(event == CV_EVENT_LBUTTONDOWN)
    {
        //std::cout << coordinateConverter->convertTo(Vec2(x,y)).getString() << std::endl;
        switch(state)
        {
            case WAIT_FOR_SELECT:
            {
                state = SELECT_PARAMETERS;
                break;
            }
            case SELECT_PARAMETERS:
            {
                runSelect(x, y);
                break;
            }
        }
    }
}

void setMinMaxColor(Vec3 target, Vec3& minColor, Vec3& maxColor, Vec3 threshold)
{
    minColor = target - threshold;
    maxColor = target + threshold;
}

void captureNewImage()
{
    cv::Mat img;
    camera >> img;

    //Fix fisheye problems
    cv::Mat tmpImg;

    //Read fisheye correction stuff from a file. Generate using the "cpp/calibration" sample
    cv::Mat camera_matrix, distortion;
    cv::FileStorage fs("fisheye0.txt", cv::FileStorage::READ);
    cv::FileNode fn = fs["IntParam"];
    fn["camera_matrix"] >> camera_matrix;
    fn["distortion"] >> distortion;

    cv::undistort(img, tmpImg, camera_matrix, distortion);

    img = tmpImg;
    currentImage = tmpImg;
}

void runSelect(float x, float y)
{
    //Finding the closest ball
    float minBlobDistance = 0;
    auto closestBlob = blobs.begin();
    for(auto it = blobs.begin(); it != blobs.end(); ++it)
    {
        Vec2 diff = closestBlob->center - Vec2(x, y);

        if(diff.getLength() < minBlobDistance)
        {
            closestBlob = it;
        }
    }

    switch(selState)
    {
        case WHITE_BALL:
        {
            pool.setWhiteBall(closestBlob->center);
            selState = TARGET;
            break;
        }
        case TARGET:
        {
            pool.setTargetBall(closestBlob->center);

            selState = HOLE;
            break;
        }
        case HOLE:
        {
            float holeX = round(x * 2) / 2.0;
            float holeY = round(y * 2) / 2.0;

            if(holeX < 0)
                holeX = 0;
            if(holeX > 1)
                holeX = 1;
            if(holeY < 0)
                holeY = 0;
            if(holeY > 0.5)
                holeX = 0.5;

            pool.setPocket(Vec2(holeX, holeY));
            selState = WHITE_BALL;
            state = PLAY;
            break;
        }
    }
}
<|endoftext|>


<commit_before>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/cdm/renderer/widevine_key_systems.h"

#include <string>
#include <vector>

#include "base/logging.h"
#include "components/cdm/common/cdm_messages_android.h"
#include "content/public/renderer/key_system_info.h"
#include "content/public/renderer/render_thread.h"

#include "widevine_cdm_version.h" // In SHARED_INTERMEDIATE_DIR.

#if defined(WIDEVINE_CDM_AVAILABLE)

using content::KeySystemInfo;
using content::SupportedCodecs;

namespace cdm {

// Return |name|'s parent key system.
static std::string GetDirectParentName(std::string name) {
  int last_period = name.find_last_of('.');
  DCHECK_GT(last_period, 0);
  return name.substr(0, last_period);
}

void AddWidevineWithCodecs(WidevineCdmType widevine_cdm_type,
                           SupportedCodecs supported_codecs,
                           std::vector<KeySystemInfo>* concrete_key_systems) {
  KeySystemInfo info(kWidevineKeySystem);

  switch (widevine_cdm_type) {
    case WIDEVINE:
      // For standard Widevine, add parent name.
      info.parent_key_system = GetDirectParentName(kWidevineKeySystem);
      break;
#if defined(OS_ANDROID)
    case WIDEVINE_HR_NON_COMPOSITING:
      info.key_system.append(".hrnoncompositing");
      break;
#endif  // defined(OS_ANDROID)
    default:
      NOTREACHED();
  }

  // TODO(xhwang): A container or an initDataType may be supported even though
  // there are no codecs supported in that container. Fix this when we support
  // initDataType.
  info.supported_codecs = supported_codecs;

#if defined(ENABLE_PEPPER_CDMS)
  info.pepper_type = kWidevineCdmPluginMimeType;
#endif  // defined(ENABLE_PEPPER_CDMS)

  concrete_key_systems->push_back(info);
}

#if defined(OS_ANDROID)
void AddAndroidWidevine(std::vector<KeySystemInfo>* concrete_key_systems) {
  SupportedKeySystemRequest request;
  SupportedKeySystemResponse response;

  request.key_system = kWidevineKeySystem;
  request.codecs = content::EME_CODEC_WEBM_ALL | content::EME_CODEC_MP4_ALL;
  content::RenderThread::Get()->Send(
      new ChromeViewHostMsg_GetSupportedKeySystems(request, &response));
  DCHECK(response.compositing_codecs & content::EME_CODEC_ALL)
      << "unrecognized codec";
  DCHECK(response.non_compositing_codecs & content::EME_CODEC_ALL)
      << "unrecognized codec";
  if (response.compositing_codecs != content::EME_CODEC_NONE) {
    AddWidevineWithCodecs(
        WIDEVINE,
        static_cast<SupportedCodecs>(response.compositing_codecs),
        concrete_key_systems);
  }

  if (response.non_compositing_codecs != content::EME_CODEC_NONE) {
    AddWidevineWithCodecs(
        WIDEVINE_HR_NON_COMPOSITING,
        static_cast<SupportedCodecs>(response.non_compositing_codecs),
        concrete_key_systems);
  }
}
#endif  // OS_ANDROID

}  // namespace cdm

#endif  // defined(WIDEVINE_CDM_AVAILABLE)
<commit_msg>Fix the compile error for win64: widevine_key_systems.cc.<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/cdm/renderer/widevine_key_systems.h"

#include <string>
#include <vector>

#include "base/logging.h"
#include "components/cdm/common/cdm_messages_android.h"
#include "content/public/renderer/key_system_info.h"
#include "content/public/renderer/render_thread.h"

#include "widevine_cdm_version.h" // In SHARED_INTERMEDIATE_DIR.

#if defined(WIDEVINE_CDM_AVAILABLE)

using content::KeySystemInfo;
using content::SupportedCodecs;

namespace cdm {

// Return |name|'s parent key system.
static std::string GetDirectParentName(std::string name) {
  size_t last_period = name.find_last_of('.');
  DCHECK_GT(last_period, 0u);
  return name.substr(0u, last_period);
}

void AddWidevineWithCodecs(WidevineCdmType widevine_cdm_type,
                           SupportedCodecs supported_codecs,
                           std::vector<KeySystemInfo>* concrete_key_systems) {
  KeySystemInfo info(kWidevineKeySystem);

  switch (widevine_cdm_type) {
    case WIDEVINE:
      // For standard Widevine, add parent name.
      info.parent_key_system = GetDirectParentName(kWidevineKeySystem);
      break;
#if defined(OS_ANDROID)
    case WIDEVINE_HR_NON_COMPOSITING:
      info.key_system.append(".hrnoncompositing");
      break;
#endif  // defined(OS_ANDROID)
    default:
      NOTREACHED();
  }

  // TODO(xhwang): A container or an initDataType may be supported even though
  // there are no codecs supported in that container. Fix this when we support
  // initDataType.
  info.supported_codecs = supported_codecs;

#if defined(ENABLE_PEPPER_CDMS)
  info.pepper_type = kWidevineCdmPluginMimeType;
#endif  // defined(ENABLE_PEPPER_CDMS)

  concrete_key_systems->push_back(info);
}

#if defined(OS_ANDROID)
void AddAndroidWidevine(std::vector<KeySystemInfo>* concrete_key_systems) {
  SupportedKeySystemRequest request;
  SupportedKeySystemResponse response;

  request.key_system = kWidevineKeySystem;
  request.codecs = content::EME_CODEC_WEBM_ALL | content::EME_CODEC_MP4_ALL;
  content::RenderThread::Get()->Send(
      new ChromeViewHostMsg_GetSupportedKeySystems(request, &response));
  DCHECK(response.compositing_codecs & content::EME_CODEC_ALL)
      << "unrecognized codec";
  DCHECK(response.non_compositing_codecs & content::EME_CODEC_ALL)
      << "unrecognized codec";
  if (response.compositing_codecs != content::EME_CODEC_NONE) {
    AddWidevineWithCodecs(
        WIDEVINE,
        static_cast<SupportedCodecs>(response.compositing_codecs),
        concrete_key_systems);
  }

  if (response.non_compositing_codecs != content::EME_CODEC_NONE) {
    AddWidevineWithCodecs(
        WIDEVINE_HR_NON_COMPOSITING,
        static_cast<SupportedCodecs>(response.non_compositing_codecs),
        concrete_key_systems);
  }
}
#endif  // OS_ANDROID

}  // namespace cdm

#endif  // defined(WIDEVINE_CDM_AVAILABLE)
<|endoftext|>


<commit_before>#include <bits/stdc++.h>
#include <zmqpp/zmqpp.hpp>
#include "lib/json.hpp"
#include "lib/base64.hpp"

#define NAME_REQ 0
#define LS_REQ 1
#define GET_REQ 2
#define SEND_REQ 3
#define RM_REQ 4

using namespace std;
using namespace zmqpp;
using json = nlohmann::json;

void Pause() {
  cout << "Press any key to continue...";
  cin.ignore().get();
}

string GetName(socket& s) {
  regex r("[a-zA-Z]\\w*");
  string name;

  bool ok;
  do {
    system("clear");
    cout << "Username: ";
    getline(cin, name);
    json req;
    req["type"] = NAME_REQ;
    req["user"] = name;

    message m;
    m << req.dump();
    s.send(m);

    cout << "Waiting response" << endl;
    message ans;
    s.receive(ans);
    string _res;
    ans >> _res;
    json res = json::parse(_res);

    ok = res["res"] == "OK";
    if (!ok) {
      cout << "Invalid name" << endl;
      Pause();
    }
  } while(!ok);

  return name;
}

int GetOption(string& opt) {
  stringstream ss(opt);
  int o;
  ss >> o;

  if (!ss)
    return -1;
  return o;
}

void ListFiles(string &user, socket& s) {
  json req;
  req["type"] = LS_REQ;
  req["user"] = user;

  message m;
  m << req.dump();
  s.send(m);

  message ans;
  s.receive(ans);
  string _res;
  ans >> _res;
  json res = json::parse(_res);

  if (res["res"] == "OK") {
    cout << "Your files are:" << endl;
    for (auto &f : res["data"]) {
      cout << f << endl;
    }
  } else {
    cout << res["res"] << endl;
  }

  Pause();
}

void GetFile(string &user, socket& s) {
  // TODO: Get files from server
}

void SendFile(string &user, socket& s) {
  string filename;
  cin >> filename;

  json req;
  req["type"] = SEND_REQ;
  req["user"] = user;

  message m;
  m << req.dump();
  s.send(m);

  message ans;
  s.receive(ans);
  string _res;
  ans >> _res;
  json res = json::parse(_res);

  if (res["res"] == "OK") {
  } else {
    cout << res["res"] << endl;
  }

  Pause();
}

bool ExecuteOpt(int opt, string &user, socket& s) {
  switch (opt) {
    case LS_REQ:
      ListFiles(user, s);
      break;
    case GET_REQ:
      break;
    case SEND_REQ:
      SendFile(user, s);
      break;
    case RM_REQ:
     break;
    case 0:
      return false;
      break;
    default:
      cout << "Invalid option" << endl;
      Pause();
      break;
  }

  return true;
}

bool PrintMenu(string &user, socket& s) {
  system("clear");

  cout << "Welcome " << user << " to SuperFancy FileSystem (SFFS)" << endl;
  cout << "Please enter your choice :)" << endl;
  cout << "1. List your files" << endl;
  cout << "2. Get a file" << endl;
  cout << "3. Upload a file" << endl;
  cout << "4. Delete a file" << endl;
  cout << "0. Exit" << endl;
  cout << "> ";

  string _opt;
  cin >> _opt;
  int opt = GetOption(_opt);
  return ExecuteOpt(opt, user, s);
}

int main(int argc, const char *argv[]) {
  string ip = "localhost", port = "5555";
  context ctx;
  socket s(ctx, socket_type::req);
  s.connect("tcp://" + ip + ":" + port);

  string user = GetName(s);

  bool cont;
  do {
    cont = PrintMenu(user, s);
  } while(cont);

  // context ctx;
  // socket s(ctx, socket_type::req);
  // s.connect("tcp://localhost:5555");
  //
  // json load;
  // load["user"] = "leiver";
  // load["name"] = "copy.mp3";
  //
  // ifstream fin("fs/Super Mario World Music - Title Theme.mp3", ios::binary);
  // if (!fin) {
  //   cout << "Mucha loca" << endl;
  //   return 0;
  // }
  // stringstream oss;
  // oss << fin.rdbuf();
  // fin.close();
  //
  // Base64 b64;
  // string in = oss.str(), out;
  // b64.Encode(in, &out);
  // load["file"] = out;
  //
  // message m;
  // m << load.dump();
  // s.send(m);

  return 0;
}
<commit_msg>Added ReadFileBase64 to client<commit_after>#include <bits/stdc++.h>
#include <zmqpp/zmqpp.hpp>
#include "lib/json.hpp"
#include "lib/base64.hpp"

#define NAME_REQ 0
#define LS_REQ 1
#define GET_REQ 2
#define SEND_REQ 3
#define RM_REQ 4

using namespace std;
using namespace zmqpp;
using json = nlohmann::json;

void Pause() {
  cout << "Press any key to continue...";
  cin.ignore().get();
}

string GetName(socket& s) {
  regex r("[a-zA-Z]\\w*");
  string name;

  bool ok;
  do {
    system("clear");
    cout << "Username: ";
    getline(cin, name);
    json req;
    req["type"] = NAME_REQ;
    req["user"] = name;

    message m;
    m << req.dump();
    s.send(m);

    cout << "Waiting response" << endl;
    message ans;
    s.receive(ans);
    string _res;
    ans >> _res;
    json res = json::parse(_res);

    ok = res["res"] == "OK";
    if (!ok) {
      cout << "Invalid name" << endl;
      // Pause();
    }
  } while(!ok);

  return name;
}

int GetOption(string& opt) {
  stringstream ss(opt);
  int o;
  ss >> o;

  if (!ss)
    return -1;
  return o;
}

void ListFiles(string &user, socket& s) {
  json req;
  req["type"] = LS_REQ;
  req["user"] = user;

  message m;
  m << req.dump();
  s.send(m);

  message ans;
  s.receive(ans);
  string _res;
  ans >> _res;
  json res = json::parse(_res);

  if (res["res"] == "OK") {
    cout << "Your files are:" << endl;
    for (auto &f : res["data"]) {
      cout << f << endl;
    }
  } else {
    cout << res["res"] << endl;
  }

  // Pause();
}

void GetFile(string &user, socket& s) {
  // TODO: Get files from server
}

string ReadFileBase64(string& filename) {
  ifstream fin(filename, ios::binary);
  if (!fin) {
    return "";
  }

  stringstream oss;
  oss << fin.rdbuf();
  fin.close();

  Base64 b64;
  string in = oss.str(), out;
  b64.Encode(in, &out);

  return out;
}

void SendFile(string &user, socket& s) {
  string filename;
  cin >> filename;

  json req;
  req["type"] = SEND_REQ;
  req["user"] = user;

  string file = ReadFileBase64(filename);

  message m;
  m << req.dump();
  s.send(m);

  message ans;
  s.receive(ans);
  string _res;
  ans >> _res;
  json res = json::parse(_res);

  if (res["res"] == "OK") {
  } else {
    cout << res["res"] << endl;
  }

  // Pause();
}

bool ExecuteOpt(int opt, string &user, socket& s) {
  switch (opt) {
    case LS_REQ:
      ListFiles(user, s);
      break;
    case GET_REQ:
      break;
    case SEND_REQ:
      SendFile(user, s);
      break;
    case RM_REQ:
     break;
    case 0:
      return false;
      break;
    default:
      cout << "Invalid option" << endl;
      // Pause();
      break;
  }

  return true;
}

bool PrintMenu(string &user, socket& s) {
  // system("clear");

  cout << "Welcome " << user << " to SuperFancy FileSystem (SFFS)" << endl;
  cout << "Please enter your choice :)" << endl;
  cout << "1. List your files" << endl;
  cout << "2. Get a file" << endl;
  cout << "3. Upload a file" << endl;
  cout << "4. Delete a file" << endl;
  cout << "0. Exit" << endl;
  cout << "> ";

  string _opt;
  cin >> _opt;
  int opt = GetOption(_opt);
  return ExecuteOpt(opt, user, s);
}

int main(int argc, const char *argv[]) {
  string ip = "localhost", port = "5555";
  context ctx;
  socket s(ctx, socket_type::req);
  s.connect("tcp://" + ip + ":" + port);

  string user = GetName(s);

  bool cont;
  do {
    cont = PrintMenu(user, s);
  } while(cont);

  // context ctx;
  // socket s(ctx, socket_type::req);
  // s.connect("tcp://localhost:5555");
  //
  // json load;
  // load["user"] = "leiver";
  // load["name"] = "copy.mp3";
  //
  // ifstream fin("fs/Super Mario World Music - Title Theme.mp3", ios::binary);
  // if (!fin) {
  //   cout << "Mucha loca" << endl;
  //   return 0;
  // }
  // stringstream oss;
  // oss << fin.rdbuf();
  // fin.close();
  //
  // Base64 b64;
  // string in = oss.str(), out;
  // b64.Encode(in, &out);
  // load["file"] = out;
  //
  // message m;
  // m << load.dump();
  // s.send(m);

  return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: layerupdatehandler.cxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 03:31:49 $
 *
 *  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
 *
 ************************************************************************/

#include "layerupdatehandler.hxx"

#ifndef CONFIGMGR_BACKEND_LAYERUPDATEMERGER_HXX
#include "layerupdatemerger.hxx"
#endif

#ifndef CONFIGMGR_API_FACTORY_HXX_
#include "confapifactory.hxx"
#endif

#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XLAYERHANDLER_HPP_
#include <com/sun/star/configuration/backend/XLayerHandler.hpp>
#endif
#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XLAYER_HPP_
#include <com/sun/star/configuration/backend/XLayer.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYEXISTEXCEPTION_HPP_
#include <com/sun/star/beans/PropertyExistException.hpp>
#endif

// -----------------------------------------------------------------------------
#define OUSTR( str ) OUString( RTL_CONSTASCII_USTRINGPARAM( str ) )
// -----------------------------------------------------------------------------
namespace configmgr
{
// -----------------------------------------------------------------------------
    namespace backend
    {
// -----------------------------------------------------------------------------
        namespace uno       = ::com::sun::star::uno;
        namespace lang      = ::com::sun::star::lang;
        namespace backenduno = ::com::sun::star::configuration::backend;
// -----------------------------------------------------------------------------

uno::Reference< uno::XInterface > SAL_CALL instantiateUpdateMerger
( CreationContext const& xContext )
{
    return * new LayerUpdateHandler( xContext );
}

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

LayerUpdateHandler::LayerUpdateHandler(CreationArg _xContext)
: UpdateService(_xContext)
, m_aBuilder()
{
}
// -----------------------------------------------------------------------------

LayerUpdateHandler::~LayerUpdateHandler()
{
}
// -----------------------------------------------------------------------------
inline
void LayerUpdateHandler::checkBuilder(bool _bForProperty)
{
    if ( m_aBuilder.isEmpty() )
        raiseMalformedDataException("LayerUpdateHandler: Illegal operation - no update is in progress");

    if ( !m_aBuilder.isActive() )
        raiseMalformedDataException("LayerUpdateHandler: Illegal operation - no context for update available");

    if ( m_aBuilder.isPropertyActive() != _bForProperty )
        raiseMalformedDataException("LayerUpdateHandler: Illegal operation - a property is in progress");
}
// -----------------------------------------------------------------------------

void LayerUpdateHandler::raiseMalformedDataException(sal_Char const * pMsg)
{
    OUString sMsg = OUString::createFromAscii(pMsg);
    throw backenduno::MalformedDataException(sMsg,*this,uno::Any());
}
// -----------------------------------------------------------------------------

void LayerUpdateHandler::raiseNodeChangedBeforeException(sal_Char const * pMsg)
{
    OUString sMsg = OUString::createFromAscii(pMsg);
    throw backenduno::MalformedDataException(sMsg,*this,uno::Any());
}
// -----------------------------------------------------------------------------

void LayerUpdateHandler::raisePropChangedBeforeException(sal_Char const * pMsg)
{
    OUString sMsg = OUString::createFromAscii(pMsg);
    throw backenduno::MalformedDataException(sMsg,*this,uno::Any());
}
// -----------------------------------------------------------------------------

void LayerUpdateHandler::raisePropExistsException(sal_Char const * pMsg)
{
    OUString sMsg = OUString::createFromAscii(pMsg);
    com::sun::star::beans::PropertyExistException e(sMsg,*this);

    throw backenduno::MalformedDataException(sMsg,*this, uno::makeAny(e));
}
// -----------------------------------------------------------------------------

// XUpdateHandler
void SAL_CALL
    LayerUpdateHandler::startUpdate(  )
        throw ( MalformedDataException, lang::IllegalAccessException,
                lang::WrappedTargetException, uno::RuntimeException)
{
    this->checkSourceLayer();
    if (!m_aBuilder.init())
        raiseMalformedDataException("LayerUpdateHandler: Cannot start update - update is already in progress");
}
// -----------------------------------------------------------------------------

void SAL_CALL
    LayerUpdateHandler::endUpdate(  )
        throw ( MalformedDataException, lang::IllegalAccessException,
                lang::WrappedTargetException, uno::RuntimeException)
{
    checkBuilder();

    if (!m_aBuilder.finish())
        raiseMalformedDataException("LayerUpdateHandler: Cannot finish update - a node is still open.");

    uno::Reference< backenduno::XLayer > xMergedLayer( LayerUpdateMerger::getMergedLayer(this->getSourceLayer(), m_aBuilder.result()) );

    m_aBuilder.clear();

    this->writeUpdatedLayer(xMergedLayer);
}
// -----------------------------------------------------------------------------

void SAL_CALL
    LayerUpdateHandler::modifyNode( const OUString& aName, sal_Int16 aAttributes, sal_Int16 aAttributeMask, sal_Bool bReset )
        throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)
{
    checkBuilder();

    if (!m_aBuilder.modifyNode(aName,aAttributes,aAttributeMask,bReset))
        raiseNodeChangedBeforeException("LayerUpdateHandler: Cannot start node modification - node has already been changed.");
}
// -----------------------------------------------------------------------------

void SAL_CALL
    LayerUpdateHandler::addOrReplaceNode( const OUString& aName, sal_Int16 aAttributes )
        throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)
{
    checkBuilder();

    if (!m_aBuilder.replaceNode(aName,aAttributes,NULL))
        raiseNodeChangedBeforeException("LayerUpdateHandler: Cannot start added/replaced node - node has already been changed.");
}
// -----------------------------------------------------------------------------

void SAL_CALL
    LayerUpdateHandler::addOrReplaceNodeFromTemplate( const OUString& aName, sal_Int16 aAttributes, const TemplateIdentifier& aTemplate )
        throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)
{
    checkBuilder();

    if (!m_aBuilder.replaceNode(aName,aAttributes,&aTemplate))
        raiseNodeChangedBeforeException("LayerUpdateHandler: Cannot start added/replaced node - node has already been changed.");
}
// -----------------------------------------------------------------------------

void SAL_CALL
    LayerUpdateHandler::endNode(  )
        throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)
{
    checkBuilder();

    if (!m_aBuilder.finishNode())
    {
        OSL_ENSURE(m_aBuilder.isPropertyActive() || !m_aBuilder.isActive(), "LayerUpdateHandler: Unexpected failure mode for finishNode");
        if (m_aBuilder.isPropertyActive())
            raiseMalformedDataException("LayerUpdateHandler: Cannot finish node update - open property has not been ended.");
        else
            raiseMalformedDataException("LayerUpdateHandler: Cannot finish node update - no node has been started.");
    }
}
// -----------------------------------------------------------------------------

void SAL_CALL
    LayerUpdateHandler::removeNode( const OUString& aName )
        throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)
{
    checkBuilder();

    if (!m_aBuilder.removeNode(aName))
        raiseNodeChangedBeforeException("LayerUpdateHandler: Cannot remove node - node has already been changed.");
}
// -----------------------------------------------------------------------------

void SAL_CALL
    LayerUpdateHandler:: modifyProperty( const OUString& aName, sal_Int16 aAttributes, sal_Int16 aAttributeMask, const uno::Type & aType )
        throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)
{
    checkBuilder(false);

    if (!m_aBuilder.modifyProperty(aName,aAttributes,aAttributeMask, aType))
        raisePropChangedBeforeException("LayerUpdateHandler: Cannot start property modification - property has already been changed.");
}
// -----------------------------------------------------------------------------

void SAL_CALL
    LayerUpdateHandler:: setPropertyValue( const uno::Any& aValue )
        throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)
{
    checkBuilder(true); // already checks for open property

    OSL_VERIFY( m_aBuilder.setPropertyValue(aValue) );
}
// -----------------------------------------------------------------------------

void SAL_CALL
    LayerUpdateHandler:: setPropertyValueForLocale( const uno::Any& aValue, const OUString& aLocale )
        throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)
{
    checkBuilder(true); // already checks for open property

    OSL_VERIFY( m_aBuilder.setPropertyValueForLocale(aValue,aLocale) );
}
// -----------------------------------------------------------------------------

void SAL_CALL
    LayerUpdateHandler::resetPropertyValue( )
        throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)
{
    checkBuilder(true); // already checks for open property

    OSL_VERIFY( m_aBuilder.resetPropertyValue() );
}
// -----------------------------------------------------------------------------

void SAL_CALL
    LayerUpdateHandler::resetPropertyValueForLocale( const OUString& aLocale )
        throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)
{
    checkBuilder(true); // already checks for open property

    OSL_VERIFY( m_aBuilder.resetPropertyValueForLocale(aLocale) );
}
// -----------------------------------------------------------------------------

void SAL_CALL
    LayerUpdateHandler::endProperty(  )
        throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)
{
    checkBuilder(true); // already checks for open property

    OSL_VERIFY ( m_aBuilder.finishProperty() );
}
// -----------------------------------------------------------------------------

void SAL_CALL
    LayerUpdateHandler::resetProperty( const OUString& aName )
        throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)
{
    if (!m_aBuilder.resetProperty(aName))
        raisePropChangedBeforeException("LayerUpdateHandler: Cannot reset property - property has already been changed.");
}
// -----------------------------------------------------------------------------

void SAL_CALL
    LayerUpdateHandler::addOrReplaceProperty( const OUString& aName, sal_Int16 aAttributes, const uno::Type& aType )
        throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)
{
    if (!m_aBuilder.addNullProperty(aName,aAttributes,aType))
        raisePropExistsException("LayerUpdateHandler: Cannot add property - property exists (and has already been changed).");
}
// -----------------------------------------------------------------------------

void SAL_CALL
    LayerUpdateHandler::addOrReplacePropertyWithValue( const OUString& aName, sal_Int16 aAttributes, const uno::Any& aValue )
        throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)
{
    if (!m_aBuilder.addProperty(aName,aAttributes,aValue))
        raisePropExistsException("LayerUpdateHandler: Cannot add property - property exists (and has already been changed).");
}
// -----------------------------------------------------------------------------

void SAL_CALL
    LayerUpdateHandler::removeProperty( const OUString& aName )
        throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)
{
    // treat 'remove' as 'reset'. (Note: does not verify that this actually amounts to dropping the property)
    if (!m_aBuilder.resetProperty(aName))
        raisePropChangedBeforeException("LayerUpdateHandler: Cannot remove property - property has already been changed.");
}
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
    } // namespace

// -----------------------------------------------------------------------------
} // namespace

<commit_msg>INTEGRATION: CWS pchfix02 (1.10.60); FILE MERGED 2006/09/01 17:20:30 kaib 1.10.60.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: layerupdatehandler.cxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-16 15:05:45 $
 *
 *  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_configmgr.hxx"

#include "layerupdatehandler.hxx"

#ifndef CONFIGMGR_BACKEND_LAYERUPDATEMERGER_HXX
#include "layerupdatemerger.hxx"
#endif

#ifndef CONFIGMGR_API_FACTORY_HXX_
#include "confapifactory.hxx"
#endif

#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XLAYERHANDLER_HPP_
#include <com/sun/star/configuration/backend/XLayerHandler.hpp>
#endif
#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XLAYER_HPP_
#include <com/sun/star/configuration/backend/XLayer.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYEXISTEXCEPTION_HPP_
#include <com/sun/star/beans/PropertyExistException.hpp>
#endif

// -----------------------------------------------------------------------------
#define OUSTR( str ) OUString( RTL_CONSTASCII_USTRINGPARAM( str ) )
// -----------------------------------------------------------------------------
namespace configmgr
{
// -----------------------------------------------------------------------------
    namespace backend
    {
// -----------------------------------------------------------------------------
        namespace uno       = ::com::sun::star::uno;
        namespace lang      = ::com::sun::star::lang;
        namespace backenduno = ::com::sun::star::configuration::backend;
// -----------------------------------------------------------------------------

uno::Reference< uno::XInterface > SAL_CALL instantiateUpdateMerger
( CreationContext const& xContext )
{
    return * new LayerUpdateHandler( xContext );
}

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

LayerUpdateHandler::LayerUpdateHandler(CreationArg _xContext)
: UpdateService(_xContext)
, m_aBuilder()
{
}
// -----------------------------------------------------------------------------

LayerUpdateHandler::~LayerUpdateHandler()
{
}
// -----------------------------------------------------------------------------
inline
void LayerUpdateHandler::checkBuilder(bool _bForProperty)
{
    if ( m_aBuilder.isEmpty() )
        raiseMalformedDataException("LayerUpdateHandler: Illegal operation - no update is in progress");

    if ( !m_aBuilder.isActive() )
        raiseMalformedDataException("LayerUpdateHandler: Illegal operation - no context for update available");

    if ( m_aBuilder.isPropertyActive() != _bForProperty )
        raiseMalformedDataException("LayerUpdateHandler: Illegal operation - a property is in progress");
}
// -----------------------------------------------------------------------------

void LayerUpdateHandler::raiseMalformedDataException(sal_Char const * pMsg)
{
    OUString sMsg = OUString::createFromAscii(pMsg);
    throw backenduno::MalformedDataException(sMsg,*this,uno::Any());
}
// -----------------------------------------------------------------------------

void LayerUpdateHandler::raiseNodeChangedBeforeException(sal_Char const * pMsg)
{
    OUString sMsg = OUString::createFromAscii(pMsg);
    throw backenduno::MalformedDataException(sMsg,*this,uno::Any());
}
// -----------------------------------------------------------------------------

void LayerUpdateHandler::raisePropChangedBeforeException(sal_Char const * pMsg)
{
    OUString sMsg = OUString::createFromAscii(pMsg);
    throw backenduno::MalformedDataException(sMsg,*this,uno::Any());
}
// -----------------------------------------------------------------------------

void LayerUpdateHandler::raisePropExistsException(sal_Char const * pMsg)
{
    OUString sMsg = OUString::createFromAscii(pMsg);
    com::sun::star::beans::PropertyExistException e(sMsg,*this);

    throw backenduno::MalformedDataException(sMsg,*this, uno::makeAny(e));
}
// -----------------------------------------------------------------------------

// XUpdateHandler
void SAL_CALL
    LayerUpdateHandler::startUpdate(  )
        throw ( MalformedDataException, lang::IllegalAccessException,
                lang::WrappedTargetException, uno::RuntimeException)
{
    this->checkSourceLayer();
    if (!m_aBuilder.init())
        raiseMalformedDataException("LayerUpdateHandler: Cannot start update - update is already in progress");
}
// -----------------------------------------------------------------------------

void SAL_CALL
    LayerUpdateHandler::endUpdate(  )
        throw ( MalformedDataException, lang::IllegalAccessException,
                lang::WrappedTargetException, uno::RuntimeException)
{
    checkBuilder();

    if (!m_aBuilder.finish())
        raiseMalformedDataException("LayerUpdateHandler: Cannot finish update - a node is still open.");

    uno::Reference< backenduno::XLayer > xMergedLayer( LayerUpdateMerger::getMergedLayer(this->getSourceLayer(), m_aBuilder.result()) );

    m_aBuilder.clear();

    this->writeUpdatedLayer(xMergedLayer);
}
// -----------------------------------------------------------------------------

void SAL_CALL
    LayerUpdateHandler::modifyNode( const OUString& aName, sal_Int16 aAttributes, sal_Int16 aAttributeMask, sal_Bool bReset )
        throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)
{
    checkBuilder();

    if (!m_aBuilder.modifyNode(aName,aAttributes,aAttributeMask,bReset))
        raiseNodeChangedBeforeException("LayerUpdateHandler: Cannot start node modification - node has already been changed.");
}
// -----------------------------------------------------------------------------

void SAL_CALL
    LayerUpdateHandler::addOrReplaceNode( const OUString& aName, sal_Int16 aAttributes )
        throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)
{
    checkBuilder();

    if (!m_aBuilder.replaceNode(aName,aAttributes,NULL))
        raiseNodeChangedBeforeException("LayerUpdateHandler: Cannot start added/replaced node - node has already been changed.");
}
// -----------------------------------------------------------------------------

void SAL_CALL
    LayerUpdateHandler::addOrReplaceNodeFromTemplate( const OUString& aName, sal_Int16 aAttributes, const TemplateIdentifier& aTemplate )
        throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)
{
    checkBuilder();

    if (!m_aBuilder.replaceNode(aName,aAttributes,&aTemplate))
        raiseNodeChangedBeforeException("LayerUpdateHandler: Cannot start added/replaced node - node has already been changed.");
}
// -----------------------------------------------------------------------------

void SAL_CALL
    LayerUpdateHandler::endNode(  )
        throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)
{
    checkBuilder();

    if (!m_aBuilder.finishNode())
    {
        OSL_ENSURE(m_aBuilder.isPropertyActive() || !m_aBuilder.isActive(), "LayerUpdateHandler: Unexpected failure mode for finishNode");
        if (m_aBuilder.isPropertyActive())
            raiseMalformedDataException("LayerUpdateHandler: Cannot finish node update - open property has not been ended.");
        else
            raiseMalformedDataException("LayerUpdateHandler: Cannot finish node update - no node has been started.");
    }
}
// -----------------------------------------------------------------------------

void SAL_CALL
    LayerUpdateHandler::removeNode( const OUString& aName )
        throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)
{
    checkBuilder();

    if (!m_aBuilder.removeNode(aName))
        raiseNodeChangedBeforeException("LayerUpdateHandler: Cannot remove node - node has already been changed.");
}
// -----------------------------------------------------------------------------

void SAL_CALL
    LayerUpdateHandler:: modifyProperty( const OUString& aName, sal_Int16 aAttributes, sal_Int16 aAttributeMask, const uno::Type & aType )
        throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)
{
    checkBuilder(false);

    if (!m_aBuilder.modifyProperty(aName,aAttributes,aAttributeMask, aType))
        raisePropChangedBeforeException("LayerUpdateHandler: Cannot start property modification - property has already been changed.");
}
// -----------------------------------------------------------------------------

void SAL_CALL
    LayerUpdateHandler:: setPropertyValue( const uno::Any& aValue )
        throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)
{
    checkBuilder(true); // already checks for open property

    OSL_VERIFY( m_aBuilder.setPropertyValue(aValue) );
}
// -----------------------------------------------------------------------------

void SAL_CALL
    LayerUpdateHandler:: setPropertyValueForLocale( const uno::Any& aValue, const OUString& aLocale )
        throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)
{
    checkBuilder(true); // already checks for open property

    OSL_VERIFY( m_aBuilder.setPropertyValueForLocale(aValue,aLocale) );
}
// -----------------------------------------------------------------------------

void SAL_CALL
    LayerUpdateHandler::resetPropertyValue( )
        throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)
{
    checkBuilder(true); // already checks for open property

    OSL_VERIFY( m_aBuilder.resetPropertyValue() );
}
// -----------------------------------------------------------------------------

void SAL_CALL
    LayerUpdateHandler::resetPropertyValueForLocale( const OUString& aLocale )
        throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)
{
    checkBuilder(true); // already checks for open property

    OSL_VERIFY( m_aBuilder.resetPropertyValueForLocale(aLocale) );
}
// -----------------------------------------------------------------------------

void SAL_CALL
    LayerUpdateHandler::endProperty(  )
        throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)
{
    checkBuilder(true); // already checks for open property

    OSL_VERIFY ( m_aBuilder.finishProperty() );
}
// -----------------------------------------------------------------------------

void SAL_CALL
    LayerUpdateHandler::resetProperty( const OUString& aName )
        throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)
{
    if (!m_aBuilder.resetProperty(aName))
        raisePropChangedBeforeException("LayerUpdateHandler: Cannot reset property - property has already been changed.");
}
// -----------------------------------------------------------------------------

void SAL_CALL
    LayerUpdateHandler::addOrReplaceProperty( const OUString& aName, sal_Int16 aAttributes, const uno::Type& aType )
        throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)
{
    if (!m_aBuilder.addNullProperty(aName,aAttributes,aType))
        raisePropExistsException("LayerUpdateHandler: Cannot add property - property exists (and has already been changed).");
}
// -----------------------------------------------------------------------------

void SAL_CALL
    LayerUpdateHandler::addOrReplacePropertyWithValue( const OUString& aName, sal_Int16 aAttributes, const uno::Any& aValue )
        throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)
{
    if (!m_aBuilder.addProperty(aName,aAttributes,aValue))
        raisePropExistsException("LayerUpdateHandler: Cannot add property - property exists (and has already been changed).");
}
// -----------------------------------------------------------------------------

void SAL_CALL
    LayerUpdateHandler::removeProperty( const OUString& aName )
        throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)
{
    // treat 'remove' as 'reset'. (Note: does not verify that this actually amounts to dropping the property)
    if (!m_aBuilder.resetProperty(aName))
        raisePropChangedBeforeException("LayerUpdateHandler: Cannot remove property - property has already been changed.");
}
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
    } // namespace

// -----------------------------------------------------------------------------
} // namespace

<|endoftext|>


<commit_before>#include "types.h"
#include "amd64.h"
#include "bits.hh"
#include "kernel.hh"
#include "traps.h"
#include "cpu.hh"
#include "apic.hh"
#include "kstream.hh"
#include "bitset.hh"

#define ID      0x802   // ID
#define VER     0x803   // Version
#define TPR     0x808   // Task Priority
#define PPR     0x80a   // Processor Priority
#define EOI     0x80b   // EOI
#define LDR     0x80d   // Logical Destination
#define SVR     0x80f   // Spurious Interrupt Vector
  #define ENABLE     0x00000100   // Unit Enable
#define ISR     0x810
  #define ISR_NR     0x8
#define TMR     0x818
#define IRR     0x820
#define ESR     0x828ull   // Error Status
#define ICR     0x830ull   // Interrupt Command
  #define INIT       0x00000500ull   // INIT/RESET
  #define STARTUP    0x00000600   // Startup IPI
  #define BCAST      0x00080000   // Send to all APICs, including self.
  #define LEVEL      0x00008000ull   // Level triggered
  #define ASSERT     0x00004000   // Assert interrupt (vs deassert)
  #define DEASSERT   0x00000000
  #define FIXED      0x00000000
#define TIMER   0x832   // Local Vector Table 0 (TIMER)
  #define X1         0x0000000B   // divide counts by 1
  #define PERIODIC   0x00020000   // Periodic
#define THERM   0x833   // Thermal sensor LVT
#define PCINT   0x834   // Performance Counter LVT
#define LINT0   0x835   // Local Vector Table 1 (LINT0)
#define LINT1   0x836   // Local Vector Table 2 (LINT1)
#define ERROR   0x837   // Local Vector Table 3 (ERROR)
  #define MASKED     0x00010000   // Interrupt masked
  #define MT_EXTINT  0x00000500
  #define MT_NMI     0x00000400   // NMI message type
  #define MT_FIX     0x00000000   // Fixed message type
#define TICR    0x838   // Timer Initial Count
#define TCCR    0x839   // Timer Current Count
#define TDCR    0x83e   // Timer Divide Configuration

static console_stream verbose(true);

static u64 x2apichz;

class x2apic_lapic : public abstract_lapic
{
public:
  void cpu_init();
  hwid_t id();
  void eoi();
  void send_ipi(struct cpu *c, int ino);
  void mask_pc(bool mask);
  void start_ap(struct cpu *c, u32 addr);
  bool is_x2apic();
  void dump();
  void dumpall();
private:
  void clearintr();
};

static int
x2apicmaxlvt(void)
{
  unsigned int v;

  v = readmsr(VER);
  return (((v) >> 16) & 0xFFu);
}

void
x2apic_lapic::eoi()
{
  writemsr(EOI, 0);
}

static int
x2apicwait(void)
{
  // Do nothing on x2apic
  return 0;
}

// Code closely follows native_cpu_up, do_boot_cpu,
// and wakeup_secondary_cpu_via_init in Linux v3.3
void
x2apic_lapic::start_ap(struct cpu *c, u32 addr)
{
  int i;

  // Be paranoid about clearing APIC errors
  writemsr(ESR, 0);
  readmsr(ESR);

  unsigned long accept_status;
  int maxlvt = x2apicmaxlvt();

  if (maxlvt > 3)
    writemsr(ESR, 0);
  readmsr(ESR);

  // "Universal startup algorithm."
  // Send INIT (level-triggered) interrupt to reset other CPU.
  // Asserting INIT
  writemsr(ICR, (((u64)c->hwid.num)<<32) | INIT | LEVEL | ASSERT);
  microdelay(10000);
  // Deasserting INIT
  writemsr(ICR, (((u64)c->hwid.num)<<32) | INIT | LEVEL);
  x2apicwait();

  // Send startup IPI (twice!) to enter bootstrap code.
  // Regular hardware is supposed to only accept a STARTUP
  // when it is in the halted state due to an INIT.  So the second
  // should be ignored, but it is part of the official Intel algorithm.
  for(i = 0; i < 2; i++){
    writemsr(ESR, 0);
    readmsr(ESR);

    // Kick the target chip
    writemsr(ICR, (((u64)c->hwid.num)<<32) | STARTUP | (addr>>12));
    // Linux gives 300 usecs to accept the IPI..
    microdelay(300);
    x2apicwait();
    // ..then it gives some more time
    microdelay(200);

    if (maxlvt > 3)
      writemsr(ESR, 0);

    accept_status = (readmsr(ESR) & 0xEF);
    if (accept_status)
      panic("x2apicstartap: accept status %lx", accept_status);
  }
}

void
x2apic_lapic::mask_pc(bool mask)
{
  writemsr(PCINT, mask ? MASKED : MT_NMI);
}

void
x2apic_lapic::send_ipi(struct cpu *c, int ino)
{
  // Unlike other MSR writes, x2apic writes are NOT serializing and
  // hence an IPI may be received before local writes become visible.
  // Prevent this by first performing an mfence.
  asm volatile("mfence");
  writemsr(ICR, (((u64)c->hwid.num)<<32) | FIXED | DEASSERT | ino);
}

hwid_t
x2apic_lapic::id()
{
  u64 id = readmsr(ID);
  return HWID((u32)id);
}

bool
x2apic_lapic::is_x2apic()
{
  return true;
}

void
x2apic_lapic::clearintr()
{
  // Clear any pending interrupts.  Linux does this.
  unsigned int value, queued;
  int i, j, acked = 0;
  unsigned long long tsc = 0, ntsc;
  long long max_loops = 2400000;

  tsc = rdtsc();
  do {
    queued = 0;
    for (i = ISR_NR - 1; i >= 0; i--)
      queued |= readmsr(IRR + i*0x1);

    for (i = ISR_NR - 1; i >= 0; i--) {
      value = readmsr(ISR + i*0x1);
      for (j = 31; j >= 0; j--) {
        if (value & (1<<j)) {
          eoi();
          acked++;
        }
      }
    }
    if (acked > 256) {
      cprintf("x2apic pending interrupts after %d EOI\n",
              acked);
      break;
    }
    ntsc = rdtsc();
    max_loops = (2400000 << 10) - (ntsc - tsc);
  } while (queued && max_loops > 0);
}

// Code closely follows setup_local_APIC in Linux v3.3
void
x2apic_lapic::cpu_init()
{
  u64 count;
  u32 value;
  int maxlvt;

  verbose.println("x2apic: Initializing LAPIC (CPU ", myid(), ")");

  // Enable performance counter overflow interrupts for sampler.cc
  mask_pc(false);

  // Enable interrupts on the APIC (but not on the processor).
  value = readmsr(TPR);
  value &= ~0xffU;
  writemsr(TPR, value);

  clearintr();

  // Enable local APIC; set spurious interrupt vector.
  value = readmsr(SVR);
  value &= ~0x000FF;
  value |= ENABLE;
  value |= T_IRQ0 + IRQ_SPURIOUS;
  writemsr(SVR, value);

  writemsr(LINT0, MT_EXTINT | MASKED);
  if (readmsr(ID) == 0)
    writemsr(LINT1, MT_NMI);
  else
    writemsr(LINT1, MT_NMI | MASKED);

  maxlvt = x2apicmaxlvt();
  if (maxlvt > 3)
    writemsr(ESR, 0);

  // enables sending errors
  value = T_IRQ0 + IRQ_ERROR;
  writemsr(ERROR, value);

  if (maxlvt > 3)
    writemsr(ESR, 0);
  readmsr(ESR);

  // Send an Init Level De-Assert to synchronise arbitration ID's.
  writemsr(ICR, BCAST | INIT | LEVEL);

  if (x2apichz == 0) {
    // Measure the TICR frequency
    writemsr(TDCR, X1);
    writemsr(TICR, 0xffffffff);
    u64 ccr0 = readmsr(TCCR);
    microdelay(10 * 1000);    // 1/100th of a second
    u64 ccr1 = readmsr(TCCR);
    x2apichz = 100 * (ccr0 - ccr1);
  }

  count = (QUANTUM*x2apichz) / 1000;
  if (count > 0xffffffff)
    panic("initx2apic: QUANTUM too large");

  // The timer repeatedly counts down at bus frequency
  // from xapic[TICR] and then issues an interrupt.
  writemsr(TDCR, X1);
  writemsr(TIMER, PERIODIC | (T_IRQ0 + IRQ_TIMER));
  writemsr(TICR, count);

  // Clear error status register (requires back-to-back writes).
  writemsr(ESR, 0);
  writemsr(ESR, 0);

  // Ack any outstanding interrupts.
  writemsr(EOI, 0);

  return;
}

void
x2apic_lapic::dump()
{
  bitset<256> isr, irr, tmr;
  scoped_cli cli();
  for (int word = 0; word < ISR_NR; ++word) {
    isr.setword(word * 32, readmsr(ISR + word));
    irr.setword(word * 32, readmsr(IRR + word));
    tmr.setword(word * 32, readmsr(TMR + word));
  }
  if (isr.any() || irr.any() || tmr.any())
    // Fixed-mode interrupt vectors that are awaiting EOI (ISR), that
    // are pending delivery (IRR), and are level-triggered and will
    // trigger an IOAPIC EOI when acknowledged (TMR).
    console.println("LAPIC INT  ISR ", isr, " IRR ", irr, " TMR ", tmr);
}

void
x2apic_lapic::dumpall()
{
  scoped_cli cli();
  console.println("LAPIC CPU ", myid());
#define SHOW(reg) console.println("  " #reg "\t", shex(readmsr(reg)).width(10).pad())
  SHOW(ID);
  SHOW(VER);
  SHOW(TPR);
  SHOW(PPR);
  SHOW(LDR);
  SHOW(SVR);
  SHOW(ESR);
  SHOW(ICR);
  SHOW(TIMER);
  SHOW(THERM);
  SHOW(PCINT);
  SHOW(LINT0);
  SHOW(LINT1);
  SHOW(ERROR);
  SHOW(TICR);
  SHOW(TCCR);
  SHOW(TDCR);
#undef SHOW
}

bool
initlapic_x2apic(void)
{
  u32 edx;
  cpuid(CPUID_FEATURES, nullptr, nullptr, nullptr, &edx);
  if (!(edx & FEATURE_ECX_X2APIC))
    return false;

  // According to [Intel SDM 3A 10.12.8.1], if the BIOS initializes
  // logical processors with APIC IDs greater than 255, then it should
  // enable the x2APIC.
  u64 apic_bar = readmsr(MSR_APIC_BAR);
  if (!(apic_bar & APIC_BAR_X2APIC_EN) || !(apic_bar & APIC_BAR_XAPIC_EN))
    return false;

  verbose.println("x2apic: Using x2APIC LAPIC");
  static x2apic_lapic apic;
  lapic = &apic;
  return true;
}
<commit_msg>x2apic: Fix detection process<commit_after>#include "types.h"
#include "amd64.h"
#include "bits.hh"
#include "kernel.hh"
#include "traps.h"
#include "cpu.hh"
#include "apic.hh"
#include "kstream.hh"
#include "bitset.hh"

#define ID      0x802   // ID
#define VER     0x803   // Version
#define TPR     0x808   // Task Priority
#define PPR     0x80a   // Processor Priority
#define EOI     0x80b   // EOI
#define LDR     0x80d   // Logical Destination
#define SVR     0x80f   // Spurious Interrupt Vector
  #define ENABLE     0x00000100   // Unit Enable
#define ISR     0x810
  #define ISR_NR     0x8
#define TMR     0x818
#define IRR     0x820
#define ESR     0x828ull   // Error Status
#define ICR     0x830ull   // Interrupt Command
  #define INIT       0x00000500ull   // INIT/RESET
  #define STARTUP    0x00000600   // Startup IPI
  #define BCAST      0x00080000   // Send to all APICs, including self.
  #define LEVEL      0x00008000ull   // Level triggered
  #define ASSERT     0x00004000   // Assert interrupt (vs deassert)
  #define DEASSERT   0x00000000
  #define FIXED      0x00000000
#define TIMER   0x832   // Local Vector Table 0 (TIMER)
  #define X1         0x0000000B   // divide counts by 1
  #define PERIODIC   0x00020000   // Periodic
#define THERM   0x833   // Thermal sensor LVT
#define PCINT   0x834   // Performance Counter LVT
#define LINT0   0x835   // Local Vector Table 1 (LINT0)
#define LINT1   0x836   // Local Vector Table 2 (LINT1)
#define ERROR   0x837   // Local Vector Table 3 (ERROR)
  #define MASKED     0x00010000   // Interrupt masked
  #define MT_EXTINT  0x00000500
  #define MT_NMI     0x00000400   // NMI message type
  #define MT_FIX     0x00000000   // Fixed message type
#define TICR    0x838   // Timer Initial Count
#define TCCR    0x839   // Timer Current Count
#define TDCR    0x83e   // Timer Divide Configuration

static console_stream verbose(true);

static u64 x2apichz;

class x2apic_lapic : public abstract_lapic
{
public:
  void cpu_init();
  hwid_t id();
  void eoi();
  void send_ipi(struct cpu *c, int ino);
  void mask_pc(bool mask);
  void start_ap(struct cpu *c, u32 addr);
  bool is_x2apic();
  void dump();
  void dumpall();
private:
  void clearintr();
};

static int
x2apicmaxlvt(void)
{
  unsigned int v;

  v = readmsr(VER);
  return (((v) >> 16) & 0xFFu);
}

void
x2apic_lapic::eoi()
{
  writemsr(EOI, 0);
}

static int
x2apicwait(void)
{
  // Do nothing on x2apic
  return 0;
}

// Code closely follows native_cpu_up, do_boot_cpu,
// and wakeup_secondary_cpu_via_init in Linux v3.3
void
x2apic_lapic::start_ap(struct cpu *c, u32 addr)
{
  int i;

  // Be paranoid about clearing APIC errors
  writemsr(ESR, 0);
  readmsr(ESR);

  unsigned long accept_status;
  int maxlvt = x2apicmaxlvt();

  if (maxlvt > 3)
    writemsr(ESR, 0);
  readmsr(ESR);

  // "Universal startup algorithm."
  // Send INIT (level-triggered) interrupt to reset other CPU.
  // Asserting INIT
  writemsr(ICR, (((u64)c->hwid.num)<<32) | INIT | LEVEL | ASSERT);
  microdelay(10000);
  // Deasserting INIT
  writemsr(ICR, (((u64)c->hwid.num)<<32) | INIT | LEVEL);
  x2apicwait();

  // Send startup IPI (twice!) to enter bootstrap code.
  // Regular hardware is supposed to only accept a STARTUP
  // when it is in the halted state due to an INIT.  So the second
  // should be ignored, but it is part of the official Intel algorithm.
  for(i = 0; i < 2; i++){
    writemsr(ESR, 0);
    readmsr(ESR);

    // Kick the target chip
    writemsr(ICR, (((u64)c->hwid.num)<<32) | STARTUP | (addr>>12));
    // Linux gives 300 usecs to accept the IPI..
    microdelay(300);
    x2apicwait();
    // ..then it gives some more time
    microdelay(200);

    if (maxlvt > 3)
      writemsr(ESR, 0);

    accept_status = (readmsr(ESR) & 0xEF);
    if (accept_status)
      panic("x2apicstartap: accept status %lx", accept_status);
  }
}

void
x2apic_lapic::mask_pc(bool mask)
{
  writemsr(PCINT, mask ? MASKED : MT_NMI);
}

void
x2apic_lapic::send_ipi(struct cpu *c, int ino)
{
  // Unlike other MSR writes, x2apic writes are NOT serializing and
  // hence an IPI may be received before local writes become visible.
  // Prevent this by first performing an mfence.
  asm volatile("mfence");
  writemsr(ICR, (((u64)c->hwid.num)<<32) | FIXED | DEASSERT | ino);
}

hwid_t
x2apic_lapic::id()
{
  u64 id = readmsr(ID);
  return HWID((u32)id);
}

bool
x2apic_lapic::is_x2apic()
{
  return true;
}

void
x2apic_lapic::clearintr()
{
  // Clear any pending interrupts.  Linux does this.
  unsigned int value, queued;
  int i, j, acked = 0;
  unsigned long long tsc = 0, ntsc;
  long long max_loops = 2400000;

  tsc = rdtsc();
  do {
    queued = 0;
    for (i = ISR_NR - 1; i >= 0; i--)
      queued |= readmsr(IRR + i*0x1);

    for (i = ISR_NR - 1; i >= 0; i--) {
      value = readmsr(ISR + i*0x1);
      for (j = 31; j >= 0; j--) {
        if (value & (1<<j)) {
          eoi();
          acked++;
        }
      }
    }
    if (acked > 256) {
      cprintf("x2apic pending interrupts after %d EOI\n",
              acked);
      break;
    }
    ntsc = rdtsc();
    max_loops = (2400000 << 10) - (ntsc - tsc);
  } while (queued && max_loops > 0);
}

// Code closely follows setup_local_APIC in Linux v3.3
void
x2apic_lapic::cpu_init()
{
  u64 count;
  u32 value;
  int maxlvt;

  verbose.println("x2apic: Initializing LAPIC (CPU ", myid(), ")");

  // Enable performance counter overflow interrupts for sampler.cc
  mask_pc(false);

  // Enable interrupts on the APIC (but not on the processor).
  value = readmsr(TPR);
  value &= ~0xffU;
  writemsr(TPR, value);

  clearintr();

  // Enable local APIC; set spurious interrupt vector.
  value = readmsr(SVR);
  value &= ~0x000FF;
  value |= ENABLE;
  value |= T_IRQ0 + IRQ_SPURIOUS;
  writemsr(SVR, value);

  writemsr(LINT0, MT_EXTINT | MASKED);
  if (readmsr(ID) == 0)
    writemsr(LINT1, MT_NMI);
  else
    writemsr(LINT1, MT_NMI | MASKED);

  maxlvt = x2apicmaxlvt();
  if (maxlvt > 3)
    writemsr(ESR, 0);

  // enables sending errors
  value = T_IRQ0 + IRQ_ERROR;
  writemsr(ERROR, value);

  if (maxlvt > 3)
    writemsr(ESR, 0);
  readmsr(ESR);

  // Send an Init Level De-Assert to synchronise arbitration ID's.
  writemsr(ICR, BCAST | INIT | LEVEL);

  if (x2apichz == 0) {
    // Measure the TICR frequency
    writemsr(TDCR, X1);
    writemsr(TICR, 0xffffffff);
    u64 ccr0 = readmsr(TCCR);
    microdelay(10 * 1000);    // 1/100th of a second
    u64 ccr1 = readmsr(TCCR);
    x2apichz = 100 * (ccr0 - ccr1);
  }

  count = (QUANTUM*x2apichz) / 1000;
  if (count > 0xffffffff)
    panic("initx2apic: QUANTUM too large");

  // The timer repeatedly counts down at bus frequency
  // from xapic[TICR] and then issues an interrupt.
  writemsr(TDCR, X1);
  writemsr(TIMER, PERIODIC | (T_IRQ0 + IRQ_TIMER));
  writemsr(TICR, count);

  // Clear error status register (requires back-to-back writes).
  writemsr(ESR, 0);
  writemsr(ESR, 0);

  // Ack any outstanding interrupts.
  writemsr(EOI, 0);

  return;
}

void
x2apic_lapic::dump()
{
  bitset<256> isr, irr, tmr;
  scoped_cli cli();
  for (int word = 0; word < ISR_NR; ++word) {
    isr.setword(word * 32, readmsr(ISR + word));
    irr.setword(word * 32, readmsr(IRR + word));
    tmr.setword(word * 32, readmsr(TMR + word));
  }
  if (isr.any() || irr.any() || tmr.any())
    // Fixed-mode interrupt vectors that are awaiting EOI (ISR), that
    // are pending delivery (IRR), and are level-triggered and will
    // trigger an IOAPIC EOI when acknowledged (TMR).
    console.println("LAPIC INT  ISR ", isr, " IRR ", irr, " TMR ", tmr);
}

void
x2apic_lapic::dumpall()
{
  scoped_cli cli();
  console.println("LAPIC CPU ", myid());
#define SHOW(reg) console.println("  " #reg "\t", shex(readmsr(reg)).width(10).pad())
  SHOW(ID);
  SHOW(VER);
  SHOW(TPR);
  SHOW(PPR);
  SHOW(LDR);
  SHOW(SVR);
  SHOW(ESR);
  SHOW(ICR);
  SHOW(TIMER);
  SHOW(THERM);
  SHOW(PCINT);
  SHOW(LINT0);
  SHOW(LINT1);
  SHOW(ERROR);
  SHOW(TICR);
  SHOW(TCCR);
  SHOW(TDCR);
#undef SHOW
}

bool
initlapic_x2apic(void)
{
  u32 ecx;
  cpuid(CPUID_FEATURES, nullptr, nullptr, &ecx, nullptr);
  if (!(ecx & FEATURE_ECX_X2APIC))
    return false;

  // According to [Intel SDM 3A 10.12.8.1], if the BIOS initializes
  // logical processors with APIC IDs greater than 255, then it should
  // enable the x2APIC.
  u64 apic_bar = readmsr(MSR_APIC_BAR);
  if (!(apic_bar & APIC_BAR_X2APIC_EN) || !(apic_bar & APIC_BAR_XAPIC_EN))
    return false;

  verbose.println("x2apic: Using x2APIC LAPIC");
  static x2apic_lapic apic;
  lapic = &apic;
  return true;
}
<|endoftext|>