<commit_before>// Copyright (c) 2012 Nezametdinov E. Ildus
// Licensed under the MIT License (see LICENSE.txt for details)

#include "D3D9Shader.h"

#include "../../../../../Engine/Core/FileManager/FileManager.h"
#include "../../../../../Engine/Core/Helpers/Array.h"
#include "../D3D9Renderer.h"

namespace selene
{

        D3d9Shader::D3d9Shader(const char* sourceCode, const char* version, DWORD flags, uint8_t libraryType,
                               const D3d9Capabilities& capabilities): code_(nullptr)
        {
                static const char* pixelShaderPositionDecodingFromR32f =
                        "float4 encodePosition(float4 position, float4 projectionParameters)"
                        "{"
                        "        return (position.z / projectionParameters.w).xxxx;"
                        "}"
                        "float decodeEyeZ(float4 encodedEyeZ, float4 projectionParameters)"
                        "{"
                        "        return encodedEyeZ.r * projectionParameters.w;"
                        "}";

                static const char* pixelShaderPositionDecodingFromRGBA8 =
                        "float4 encodePosition(float4 position, float4 projectionParameters)"
                        "{"
                        "        float4 result = float4(16777216.0, 65536.0, 256.0, 1.0) *"
                        "                        position.z / projectionParameters.w;"
                        "        result  = frac(result);"
                        "        result -= result.xxyz * float4(0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0);"
                        "        return result;"
                        "}"
                        "float decodeEyeZ(float4 encodedEyeZ, float4 projectionParameters)"
                        "{"
                        "        return dot(encodedEyeZ, float4(1.0 / (256.0 * 256.0 * 256.0),"
                        "                                       1.0 / (256.0 * 256.0),"
                        "                                       1.0 /  256.0, 1.0)) * projectionParameters.w;"
                        "}";

                std::string library;
                switch(libraryType)
                {
                        case LIBRARY_VERTEX_SHADER:
                                library =
                                        "float4 multiplyQuaternions(float4 quaternion0, float4 quaternion1)"
                                        "{"
                                        "        float3 v = quaternion0.w   * quaternion1.xyz +"
                                        "                   quaternion0.xyz * quaternion1.w   +"
                                        "                   cross(quaternion0.xyz, quaternion1.xyz);"
                                        "        float4 b = quaternion0 * quaternion1;"
                                        "        float  w = dot(b, float4(-1.0, -1.0, -1.0, 1.0));"
                                        "        return float4(v, w);"
                                        "}"
                                        "float4 rotateVector(float3 targetVector, float4 quaternion)"
                                        "{"
                                        "        float4 q = multiplyQuaternions(quaternion,"
                                        "                                       float4(targetVector, 0.0));"
                                        "        return multiplyQuaternions(q, float4(-quaternion.x, -quaternion.y,"
                                        "                                             -quaternion.z,  quaternion.w));"
                                        "}"
                                        "float3 transformPosition(float4 offset, float4 rotation, float3 position)"
                                        "{"
                                        "        return offset.xyz + rotateVector(position, rotation).xyz;"
                                        "}";
                                break;

                        case LIBRARY_PIXEL_SHADER:
                                if(capabilities.isR32fRenderTargetFormatSupported())
                                        library = pixelShaderPositionDecodingFromR32f;
                                else
                                        library = pixelShaderPositionDecodingFromRGBA8;

                                library +=
                                        "float3 decodePosition(float4 z, float2 xy, float4 projectionParameters,"
                                        "                      float4 unprojectionVector)"
                                        "{"
                                        "        float decodedEyeZ = decodeEyeZ(z, projectionParameters);"
                                        "        float4 p = float4(xy, 1.0, 0.0);"
                                        "        float4 result = p * unprojectionVector * decodedEyeZ.xxxx;"
                                        "        return result.xyz;"
                                        "}"
                                        "float3 encodeNormal(float3 normal)"
                                        "{"
                                        "        return 0.5 * normal + 0.5;"
                                        "}"
                                        "half3 decodeNormal(half3 encodedNormal)"
                                        "{"
                                        "        return 2.0 * encodedNormal - 1.0;"
                                        "}";
                                break;
                }

                std::string sourceCodeWithLibrary = library + sourceCode;

                if(FAILED(D3DXCompileShader(sourceCodeWithLibrary.c_str(),
                                            sourceCodeWithLibrary.length(),
                                            nullptr, nullptr, "main", version,
                                            flags, &code_, nullptr, nullptr)))
                        code_ = nullptr;
        }
        D3d9Shader::D3d9Shader(const D3d9Shader& other)
        {
                code_ = other.code_;

                if(code_ != nullptr)
                        code_->AddRef();
        }
        D3d9Shader::~D3d9Shader()
        {
                SAFE_RELEASE(code_);
        }
        D3d9Shader& D3d9Shader::operator =(const D3d9Shader& other)
        {
                SAFE_RELEASE(code_);
                code_ = other.code_;

                if(code_ != nullptr)
                        code_->AddRef();

                return *this;
        }

        //------------------------------------------------------------------------------------------------------------
        LPD3DXBUFFER D3d9Shader::getCode() const
        {
                return code_;
        }

        D3d9VertexShader::D3d9VertexShader(): d3dShader_(nullptr), d3dDevice_(nullptr) {}
        D3d9VertexShader::~D3d9VertexShader()
        {
                destroy();
        }

        //------------------------------------------------------------------------------------------------------------
        bool D3d9VertexShader::create(const D3d9Shader& shader)
        {
                d3dDevice_ = D3d9Renderer::getDevice();
                if(d3dDevice_ == nullptr)
                        return false;

                SAFE_RELEASE(d3dShader_);
                LPD3DXBUFFER code = shader.getCode();
                if(code == nullptr)
                        return false;

                if(FAILED(d3dDevice_->CreateVertexShader(reinterpret_cast<DWORD*>(code->GetBufferPointer()),
                                                         &d3dShader_)))
                {
                        d3dShader_ = nullptr;
                        return false;
                }

                return true;
        }

        //------------------------------------------------------------------------------------------------------------
        void D3d9VertexShader::destroy()
        {
                SAFE_RELEASE(d3dShader_);
                d3dDevice_ = nullptr;
        }

        //------------------------------------------------------------------------------------------------------------
        void D3d9VertexShader::set()
        {
                if(d3dDevice_ != nullptr)
                        d3dDevice_->SetVertexShader(d3dShader_);
        }

        D3d9PixelShader::D3d9PixelShader(): d3dShader_(nullptr), d3dDevice_(nullptr) {}
        D3d9PixelShader::~D3d9PixelShader()
        {
                destroy();
        }

        //------------------------------------------------------------------------------------------------------------
        bool D3d9PixelShader::create(const D3d9Shader& shader)
        {
                d3dDevice_ = D3d9Renderer::getDevice();
                if(d3dDevice_ == nullptr)
                        return false;

                SAFE_RELEASE(d3dShader_);
                LPD3DXBUFFER code = shader.getCode();
                if(code == nullptr)
                        return false;

                if(FAILED(d3dDevice_->CreatePixelShader(reinterpret_cast<DWORD*>(code->GetBufferPointer()),
                                                        &d3dShader_)))
                {
                        d3dShader_ = nullptr;
                        return false;
                }

                return true;
        }

        //------------------------------------------------------------------------------------------------------------
        void D3d9PixelShader::destroy()
        {
                SAFE_RELEASE(d3dShader_);
                d3dDevice_ = nullptr;
        }

        //------------------------------------------------------------------------------------------------------------
        void D3d9PixelShader::set()
        {
                if(d3dDevice_ != nullptr)
                        d3dDevice_->SetPixelShader(d3dShader_);
        }

}
<commit_msg>fix Direct3D 9 renderer<commit_after>// Copyright (c) 2012 Nezametdinov E. Ildus
// Licensed under the MIT License (see LICENSE.txt for details)

#include "D3D9Shader.h"

#include "../../../../../Engine/Core/FileManager/FileManager.h"
#include "../../../../../Engine/Core/Helpers/Array.h"
#include "../D3D9Renderer.h"

namespace selene
{

        D3d9Shader::D3d9Shader(const char* sourceCode, const char* version, DWORD flags, uint8_t libraryType,
                               const D3d9Capabilities& capabilities): code_(nullptr)
        {
                static const char* pixelShaderPositionDecodingFromR32f =
                        "float4 encodePosition(float4 position, float4 projectionParameters)"
                        "{"
                        "        return (position.z / projectionParameters.w).xxxx;"
                        "}"
                        "float decodeEyeZ(float4 encodedEyeZ, float4 projectionParameters)"
                        "{"
                        "        return encodedEyeZ.r * projectionParameters.w;"
                        "}";

                static const char* pixelShaderPositionDecodingFromRGBA8 =
                        "float4 encodePosition(float4 position, float4 projectionParameters)"
                        "{"
                        "        float4 result = float4(16777216.0, 65536.0, 256.0, 1.0) *"
                        "                        position.z / projectionParameters.w;"
                        "        result  = frac(result);"
                        "        result -= result.xxyz * float4(0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0);"
                        "        return result;"
                        "}"
                        "float decodeEyeZ(float4 encodedEyeZ, float4 projectionParameters)"
                        "{"
                        "        return dot(encodedEyeZ, float4(1.0 / (256.0 * 256.0 * 256.0),"
                        "                                       1.0 / (256.0 * 256.0),"
                        "                                       1.0 /  256.0, 1.0)) * projectionParameters.w;"
                        "}";

                std::string library;
                switch(libraryType)
                {
                        case LIBRARY_VERTEX_SHADER:
                                library =
                                        "float4 multiplyQuaternions(float4 quaternion0, float4 quaternion1)"
                                        "{"
                                        "        float3 v = quaternion0.w   * quaternion1.xyz +"
                                        "                   quaternion0.xyz * quaternion1.w   +"
                                        "                   cross(quaternion0.xyz, quaternion1.xyz);"
                                        "        float4 b = quaternion0 * quaternion1;"
                                        "        float  w = dot(b, float4(-1.0, -1.0, -1.0, 1.0));"
                                        "        return float4(v, w);"
                                        "}"
                                        "float4 rotateVector(float3 targetVector, float4 quaternion)"
                                        "{"
                                        "        float4 q = multiplyQuaternions(quaternion,"
                                        "                                       float4(targetVector, 0.0));"
                                        "        return multiplyQuaternions(q, float4(-quaternion.x, -quaternion.y,"
                                        "                                             -quaternion.z,  quaternion.w));"
                                        "}"
                                        "float3 transformPosition(float4 offset, float4 rotation, float3 position)"
                                        "{"
                                        "        return offset.xyz + rotateVector(position, rotation).xyz;"
                                        "}";
                                break;

                        case LIBRARY_PIXEL_SHADER:
                                if(capabilities.isR32fRenderTargetFormatSupported())
                                        library = pixelShaderPositionDecodingFromR32f;
                                else
                                        library = pixelShaderPositionDecodingFromRGBA8;

                                library +=
                                        "float3 decodePosition(float4 z, float2 xy, float4 projectionParameters,"
                                        "                      float4 unprojectionVector)"
                                        "{"
                                        "        float decodedEyeZ = decodeEyeZ(z, projectionParameters);"
                                        "        float4 p = float4(xy, 1.0, 0.0);"
                                        "        float4 result = p * unprojectionVector * decodedEyeZ.xxxx;"
                                        "        return result.xyz;"
                                        "}"
                                        "float3 encodeNormal(float3 normal)"
                                        "{"
                                        "        return 0.5 * normal + 0.5;"
                                        "}"
                                        "half3 decodeNormal(half3 encodedNormal)"
                                        "{"
                                        "        return 2.0 * encodedNormal - 1.0;"
                                        "}";
                                break;
                }

                std::string sourceCodeWithLibrary = library + sourceCode;

                if(FAILED(D3DXCompileShader(sourceCodeWithLibrary.c_str(),
                                            sourceCodeWithLibrary.length(),
                                            nullptr, nullptr, "main", version,
                                            flags, &code_, nullptr, nullptr)))
                        code_ = nullptr;
        }
        D3d9Shader::D3d9Shader(const D3d9Shader& other): code_(nullptr)
        {
                code_ = other.code_;

                if(code_ != nullptr)
                        code_->AddRef();
        }
        D3d9Shader::~D3d9Shader()
        {
                SAFE_RELEASE(code_);
        }
        D3d9Shader& D3d9Shader::operator =(const D3d9Shader& other)
        {
                SAFE_RELEASE(code_);
                code_ = other.code_;

                if(code_ != nullptr)
                        code_->AddRef();

                return *this;
        }

        //------------------------------------------------------------------------------------------------------------
        LPD3DXBUFFER D3d9Shader::getCode() const
        {
                return code_;
        }

        D3d9VertexShader::D3d9VertexShader(): d3dShader_(nullptr), d3dDevice_(nullptr) {}
        D3d9VertexShader::~D3d9VertexShader()
        {
                destroy();
        }

        //------------------------------------------------------------------------------------------------------------
        bool D3d9VertexShader::create(const D3d9Shader& shader)
        {
                d3dDevice_ = D3d9Renderer::getDevice();
                if(d3dDevice_ == nullptr)
                        return false;

                SAFE_RELEASE(d3dShader_);
                LPD3DXBUFFER code = shader.getCode();
                if(code == nullptr)
                        return false;

                if(FAILED(d3dDevice_->CreateVertexShader(reinterpret_cast<DWORD*>(code->GetBufferPointer()),
                                                         &d3dShader_)))
                {
                        d3dShader_ = nullptr;
                        return false;
                }

                return true;
        }

        //------------------------------------------------------------------------------------------------------------
        void D3d9VertexShader::destroy()
        {
                SAFE_RELEASE(d3dShader_);
                d3dDevice_ = nullptr;
        }

        //------------------------------------------------------------------------------------------------------------
        void D3d9VertexShader::set()
        {
                if(d3dDevice_ != nullptr)
                        d3dDevice_->SetVertexShader(d3dShader_);
        }

        D3d9PixelShader::D3d9PixelShader(): d3dShader_(nullptr), d3dDevice_(nullptr) {}
        D3d9PixelShader::~D3d9PixelShader()
        {
                destroy();
        }

        //------------------------------------------------------------------------------------------------------------
        bool D3d9PixelShader::create(const D3d9Shader& shader)
        {
                d3dDevice_ = D3d9Renderer::getDevice();
                if(d3dDevice_ == nullptr)
                        return false;

                SAFE_RELEASE(d3dShader_);
                LPD3DXBUFFER code = shader.getCode();
                if(code == nullptr)
                        return false;

                if(FAILED(d3dDevice_->CreatePixelShader(reinterpret_cast<DWORD*>(code->GetBufferPointer()),
                                                        &d3dShader_)))
                {
                        d3dShader_ = nullptr;
                        return false;
                }

                return true;
        }

        //------------------------------------------------------------------------------------------------------------
        void D3d9PixelShader::destroy()
        {
                SAFE_RELEASE(d3dShader_);
                d3dDevice_ = nullptr;
        }

        //------------------------------------------------------------------------------------------------------------
        void D3d9PixelShader::set()
        {
                if(d3dDevice_ != nullptr)
                        d3dDevice_->SetPixelShader(d3dShader_);
        }

}
<|endoftext|>


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

#include <Network/XmlRPCServer/Configurator/Base/ConfiguratorBase.hpp>
#include <boost/lexical_cast.hpp>

ConfiguratorBase::ConfiguratorBase(
    IConfiguratorShrPtr const a_configurator
)
    : m_configurator(a_configurator)
{
    configure();
}

bool ConfiguratorBase::configure()
{
    if (!loadXml())
    {
        return false;
    }

    if (!parseXml())
    {
        return false;
    }

    return true;
}

unsigned short int ConfiguratorBase::getHumanExperienceFactor() const
{
    return m_human_experience_factor;
}

bool ConfiguratorBase::loadXml()
{
    std::string path_base_xml =
        m_configurator->getConfigurationPath() + m_configurator->getConfigurationSelected() + "/Base/base.xml";

    return m_base_xml.load_file(path_base_xml.c_str());
}

bool ConfiguratorBase::parseXml()
{
    // TODO: Add verification here.

    pugi::xml_node base = m_base_xml.child("base");

    m_human_experience_factor = boost::lexical_cast<unsigned short int>(base.child_value("humanexperiencefactor"));

    std::cout << m_human_experience_factor << std::endl;

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

#include <Network/XmlRPCServer/Configurator/Base/ConfiguratorBase.hpp>
#include <boost/lexical_cast.hpp>

ConfiguratorBase::ConfiguratorBase(
    IConfiguratorShrPtr const a_configurator
)
    : m_configurator(a_configurator)
{
    configure();
}

bool ConfiguratorBase::configure()
{
    if (!loadXml())
    {
        return false;
    }

    if (!parseXml())
    {
        return false;
    }

    return true;
}

unsigned short int ConfiguratorBase::getHumanExperienceFactor() const
{
    return m_human_experience_factor;
}

bool ConfiguratorBase::loadXml()
{
    std::string path_base_xml =
        m_configurator->getConfigurationPath() + m_configurator->getConfigurationSelected() + "/Base/base.xml";

    return m_base_xml.load_file(path_base_xml.c_str());
}

bool ConfiguratorBase::parseXml()
{
    // TODO: Add verification here.

    pugi::xml_node base = m_base_xml.child("base");

    m_human_experience_factor = boost::lexical_cast<unsigned short int>(base.child_value("humanexperiencefactor"));

    return true;
}
<|endoftext|>


<commit_before>/*******************************************************************************
 *
 * MIT License
 *
 * Copyright (c) 2019 Advanced Micro Devices, Inc.
 *
 * 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 OR COPYRIGHT HOLDERS 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.
 *
 *******************************************************************************/

#pragma once

#include <Tensile/Predicates.hpp>
#include <Tensile/ContractionProblem.hpp>

#include <array>
#include <cstddef>
#include <vector>

namespace Tensile
{
    namespace Predicates
    {
        /**
         * \addtogroup Predicates
         * @{
         */
        /**
         * @brief ContractionProblem predicates
         */
        namespace Contraction
        {
            struct FreeSizeAMultiple: public Predicate_CRTP<FreeSizeAMultiple, ContractionProblem>
            {
                enum { HasIndex = true, HasValue = true };
                size_t index;
                size_t value;

                FreeSizeAMultiple() = default;
                FreeSizeAMultiple(size_t index, size_t value): index(index), value(value) {}

                static std::string Type() { return "FreeSizeAMultiple"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    return problem.freeSizeA(index) % value == 0;
                }
            };

            struct FreeSizeBMultiple: public Predicate_CRTP<FreeSizeBMultiple, ContractionProblem>
            {
                enum { HasIndex = true, HasValue = true };
                size_t index;
                size_t value;

                FreeSizeBMultiple() = default;
                FreeSizeBMultiple(size_t index, size_t value): index(index), value(value) {}

                static std::string Type() { return "FreeSizeBMultiple"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    return problem.freeSizeA(index) % value == 0;
                }
            };

            struct BatchSizeMultiple: public Predicate_CRTP<BatchSizeMultiple, ContractionProblem>
            {
                enum { HasIndex = true, HasValue = true };
                size_t index;
                size_t value;

                BatchSizeMultiple() = default;
                BatchSizeMultiple(size_t index, size_t value): index(index), value(value) {}

                static std::string Type() { return "BatchSizeMultiple"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    return problem.batchSize(index) % value == 0;
                }
            };

            struct BatchSizeEqual: public Predicate_CRTP<BatchSizeEqual, ContractionProblem>
            {
                enum { HasIndex = true, HasValue = true };
                size_t index;
                size_t value;

                BatchSizeEqual() = default;
                BatchSizeEqual(size_t index, size_t value): index(index), value(value) {}

                static std::string Type() { return "BatchSizeEqual"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    return problem.batchSize(index) == value;
                }
            };

            struct BoundSizeMultiple: public Predicate_CRTP<BoundSizeMultiple, ContractionProblem>
            {
                enum { HasIndex = true, HasValue = true };
                int64_t index;
                size_t value;

                BoundSizeMultiple() = default;
                BoundSizeMultiple(size_t index, size_t value): index(index), value(value) {}

                static std::string Type() { return "BoundSizeMultiple"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    if (index < 0)
                        return problem.boundSize(problem.boundIndices().size()+index) % value == 0;
                    else
                        return problem.boundSize(index) % value == 0;
                }
            };

            struct ProblemSizeEqual: public Predicate_CRTP<ProblemSizeEqual, ContractionProblem>
            {
                enum { HasIndex = true, HasValue = true };
                size_t index;
                size_t value;

                ProblemSizeEqual() = default;
                ProblemSizeEqual(size_t index, size_t value): index(index), value(value) {}

                static std::string Type() { return "ProblemSizeEqual"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    return problem.problemSizes()[index] == value;
                }
            };

            struct MaxProblemSizeGreaterThan: public Predicate_CRTP<MaxProblemSizeGreaterThan, ContractionProblem>
            {
                enum { HasIndex = false, HasValue = true };
                size_t value;

                MaxProblemSizeGreaterThan() = default;
                MaxProblemSizeGreaterThan(size_t value): value(value) {}

                static std::string Type() { return "MaxProblemSizeGreaterThan"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    return problem.maxProblemSize() > value;
                }

                virtual bool debugEval(ContractionProblem const& problem, std::ostream & stream) const override
                {
                    bool rv = (*this)(problem);

                    stream << *this << ": (" << problem.maxProblemSize() << " > " << value << ") == " << rv;

                    return rv;
                }
            };

            struct LeadingFreeSizesGreaterOrEqual: public Predicate_CRTP<LeadingFreeSizesGreaterOrEqual, ContractionProblem>
            {
                enum { HasIndex = false, HasValue = true };
                size_t value;

                LeadingFreeSizesGreaterOrEqual() = default;
                LeadingFreeSizesGreaterOrEqual(size_t value): value(value) {}

                static std::string Type() { return "LeadingFreeSizesGreaterOrEqual"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    // TODO: this is not quite right since it assumes batchSize(0) is lowest order in index assignments
                    //   If tensor contains multiple batch dims this may not be true.
                    //   Really should modify Contractions.py to select SizeN >= value, based on desired index requirement
                    return (problem.freeIndicesA().size() ? problem.freeSizeA(0) >= value : problem.batchSize(0) >= value)
                        && (problem.freeIndicesB().size() ? problem.freeSizeB(0) >= value : problem.batchSize(0) >= value);
                }
            };

            struct SizeEqual: public Predicate_CRTP<SizeEqual, ContractionProblem>
            {
                enum { HasIndex = true, HasValue = true };
                size_t index;
                size_t value;

                SizeEqual() = default;
                SizeEqual(size_t index, size_t value): index(index), value(value) {}

                static std::string Type() { return "SizeEqual"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    return problem.size(index) == value;
                }

                virtual bool debugEval(ContractionProblem const& problem, std::ostream & stream) const override
                {
                    bool rv = (*this)(problem);

                    stream << *this << ": (" << problem.size(index) << " == " << value << ") == " << rv;

                    return rv;
                }
            };

            struct StrideAEqual: public Predicate_CRTP<StrideAEqual, ContractionProblem>
            {
                enum { HasIndex = true, HasValue = true };
                size_t index;
                size_t value;

                StrideAEqual() = default;
                StrideAEqual(size_t index, size_t value): index(index), value(value) {}

                static std::string Type() { return "StrideAEqual"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    return problem.a().strides()[index] == value ;
                }

                virtual bool debugEval(ContractionProblem const& problem, std::ostream & stream) const override
                {
                    bool rv = (*this)(problem);

                    stream << *this << ": (" << problem.a().strides()[index] << " == " << value << ") == " << rv;

                    return rv;
                }
            };

            struct StrideBEqual: public Predicate_CRTP<StrideBEqual, ContractionProblem>
            {
                enum { HasIndex = true, HasValue = true };
                size_t index;
                size_t value;

                StrideBEqual() = default;
                StrideBEqual(size_t index, size_t value): index(index), value(value) {}

                static std::string Type() { return "StrideBEqual"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    return problem.b().strides()[index] == value ;
                }

                virtual bool debugEval(ContractionProblem const& problem, std::ostream & stream) const override
                {
                    bool rv = (*this)(problem);

                    stream << *this << ": (" << problem.b().strides()[index] << " == " << value << ") == " << rv;

                    return rv;
                }
            };

            struct CDStridesEqual: public Predicate_CRTP<CDStridesEqual, ContractionProblem>
            {
                enum { HasIndex = false, HasValue = false };
                static std::string Type() { return "CDStridesEqual"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    return problem.c().strides() == problem.d().strides();
                }
            };

            struct LDCEqualsLDD: public Predicate_CRTP<LDCEqualsLDD, ContractionProblem>
            {
                enum { HasIndex = false, HasValue = false };
                static std::string Type() { return "LDCEqualsLDD"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    return problem.c().strides()[1] == problem.d().strides()[1];
                }
            };

            struct BetaZero: public Predicate_CRTP<BetaZero, ContractionProblem>
            {
                enum { HasIndex = false, HasValue = false };
                BetaZero() = default;

                static std::string Type() { return "BetaZero"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    return problem.beta() == 0.0;
                }
            };

            struct BetaOne: public Predicate_CRTP<BetaOne, ContractionProblem>
            {
                enum { HasIndex = false, HasValue = false };
                BetaOne() = default;

                static std::string Type() { return "BetaOne"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    return problem.beta() == 1.0;
                }
            };

            struct HighPrecisionAccumulateEqual: public Predicate_CRTP<HighPrecisionAccumulateEqual, ContractionProblem>
            {
                enum { HasIndex = false, HasValue = true };
                bool value;

                HighPrecisionAccumulateEqual() = default;
                HighPrecisionAccumulateEqual(bool value): value(value) {}

                static std::string Type() { return "HighPrecisionAccumulate"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    return problem.highPrecisionAccumulate() == value;
                }
            };

            struct TypesEqual: public Predicate_CRTP<TypesEqual, ContractionProblem>
            {
                enum { HasIndex = false, HasValue = true };
                TypesEqual() = default;

                std::array<DataType, 4> value;

                static std::string Type() { return "TypesEqual"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    return problem.a().dataType() == value[0]
                        && problem.b().dataType() == value[1]
                        && problem.c().dataType() == value[2]
                        && problem.d().dataType() == value[3];
                }

                virtual std::string toString() const override
                {
                    return concatenate(this->type(),
                                       "(a:",  value[0],
                                       ", b:", value[1],
                                       ", c:", value[2],
                                       ", d:", value[3],
                                       ")");
                }

                virtual bool debugEval(ContractionProblem const& problem, std::ostream & stream) const override
                {
                    bool rv = (*this)(problem);

                    stream << this->type()
                           <<   "(a:" << problem.a().dataType() << " == " << value[0]
                           << "&& b:" << problem.b().dataType() << " == " << value[1]
                           << "&& c:" << problem.c().dataType() << " == " << value[2]
                           << "&& d:" << problem.d().dataType() << " == " << value[3]
                           << "): " << rv;

                    return rv;
                }
            };

            struct OperationIdentifierEqual: public Predicate_CRTP<OperationIdentifierEqual, ContractionProblem>
            {
                enum { HasIndex = false, HasValue = true };
                OperationIdentifierEqual() = default;

                std::string value;

                static std::string Type() { return "OperationIdentifierEqual"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    return problem.operationIdentifier() == value;
                }
            };
        }

        /**
         * @}
         */
    }
}

<commit_msg>Add comments and debug for LeadingFreeSizesGreaterOrEqual<commit_after>/*******************************************************************************
 *
 * MIT License
 *
 * Copyright (c) 2019 Advanced Micro Devices, Inc.
 *
 * 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 OR COPYRIGHT HOLDERS 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.
 *
 *******************************************************************************/

#pragma once

#include <Tensile/Predicates.hpp>
#include <Tensile/ContractionProblem.hpp>

#include <array>
#include <cstddef>
#include <vector>

namespace Tensile
{
    namespace Predicates
    {
        /**
         * \addtogroup Predicates
         * @{
         */
        /**
         * @brief ContractionProblem predicates
         */
        namespace Contraction
        {
            struct FreeSizeAMultiple: public Predicate_CRTP<FreeSizeAMultiple, ContractionProblem>
            {
                enum { HasIndex = true, HasValue = true };
                size_t index;
                size_t value;

                FreeSizeAMultiple() = default;
                FreeSizeAMultiple(size_t index, size_t value): index(index), value(value) {}

                static std::string Type() { return "FreeSizeAMultiple"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    return problem.freeSizeA(index) % value == 0;
                }
            };

            struct FreeSizeBMultiple: public Predicate_CRTP<FreeSizeBMultiple, ContractionProblem>
            {
                enum { HasIndex = true, HasValue = true };
                size_t index;
                size_t value;

                FreeSizeBMultiple() = default;
                FreeSizeBMultiple(size_t index, size_t value): index(index), value(value) {}

                static std::string Type() { return "FreeSizeBMultiple"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    return problem.freeSizeA(index) % value == 0;
                }
            };

            struct BatchSizeMultiple: public Predicate_CRTP<BatchSizeMultiple, ContractionProblem>
            {
                enum { HasIndex = true, HasValue = true };
                size_t index;
                size_t value;

                BatchSizeMultiple() = default;
                BatchSizeMultiple(size_t index, size_t value): index(index), value(value) {}

                static std::string Type() { return "BatchSizeMultiple"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    return problem.batchSize(index) % value == 0;
                }
            };

            struct BatchSizeEqual: public Predicate_CRTP<BatchSizeEqual, ContractionProblem>
            {
                enum { HasIndex = true, HasValue = true };
                size_t index;
                size_t value;

                BatchSizeEqual() = default;
                BatchSizeEqual(size_t index, size_t value): index(index), value(value) {}

                static std::string Type() { return "BatchSizeEqual"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    return problem.batchSize(index) == value;
                }
            };

            struct BoundSizeMultiple: public Predicate_CRTP<BoundSizeMultiple, ContractionProblem>
            {
                enum { HasIndex = true, HasValue = true };
                int64_t index;
                size_t value;

                BoundSizeMultiple() = default;
                BoundSizeMultiple(size_t index, size_t value): index(index), value(value) {}

                static std::string Type() { return "BoundSizeMultiple"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    if (index < 0)
                        return problem.boundSize(problem.boundIndices().size()+index) % value == 0;
                    else
                        return problem.boundSize(index) % value == 0;
                }
            };

            struct ProblemSizeEqual: public Predicate_CRTP<ProblemSizeEqual, ContractionProblem>
            {
                enum { HasIndex = true, HasValue = true };
                size_t index;
                size_t value;

                ProblemSizeEqual() = default;
                ProblemSizeEqual(size_t index, size_t value): index(index), value(value) {}

                static std::string Type() { return "ProblemSizeEqual"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    return problem.problemSizes()[index] == value;
                }
            };

            struct MaxProblemSizeGreaterThan: public Predicate_CRTP<MaxProblemSizeGreaterThan, ContractionProblem>
            {
                enum { HasIndex = false, HasValue = true };
                size_t value;

                MaxProblemSizeGreaterThan() = default;
                MaxProblemSizeGreaterThan(size_t value): value(value) {}

                static std::string Type() { return "MaxProblemSizeGreaterThan"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    return problem.maxProblemSize() > value;
                }

                virtual bool debugEval(ContractionProblem const& problem, std::ostream & stream) const override
                {
                    bool rv = (*this)(problem);

                    stream << *this << ": (" << problem.maxProblemSize() << " > " << value << ") == " << rv;

                    return rv;
                }
            };

            // If the tensor contains no free dimensions, then the first batch dimension serves as the leading free size
            struct LeadingFreeSizesGreaterOrEqual: public Predicate_CRTP<LeadingFreeSizesGreaterOrEqual, ContractionProblem>
            {
                enum { HasIndex = false, HasValue = true };
                size_t value;

                LeadingFreeSizesGreaterOrEqual() = default;
                LeadingFreeSizesGreaterOrEqual(size_t value): value(value) {}

                static std::string Type() { return "LeadingFreeSizesGreaterOrEqual"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    assert(problem.batchIndices().size() <= 1);
                    // TODO: this is not quite right since it assumes batchSize(0) is lowest order in index assignments
                    //   If tensor contains multiple batch dims this may not be true.
                    //   Really should modify Contractions.py to select SizeN >= value, based on desired index requirement
                    return (problem.freeIndicesA().size() ? problem.freeSizeA(0) >= value : problem.batchSize(0) >= value)
                        && (problem.freeIndicesB().size() ? problem.freeSizeB(0) >= value : problem.batchSize(0) >= value);
                }
                virtual bool debugEval(ContractionProblem const& problem, std::ostream & stream) const override
                {
                    bool rv = (*this)(problem);

                    stream << *this << ": ("
                        << (problem.freeIndicesA().size() ? "freeA0:":"batchA0:")
                        << (problem.freeIndicesA().size() ? problem.freeSizeA(0) : problem.batchSize(0)) << " >= " << value << " && "
                        << (problem.freeIndicesB().size() ? "freeB0:":"batchB0:")
                        << (problem.freeIndicesB().size() ? problem.freeSizeB(0) : problem.batchSize(0)) << " >= " << value
                        << ") == " << rv;

                    return rv;
                }
            };

            struct SizeEqual: public Predicate_CRTP<SizeEqual, ContractionProblem>
            {
                enum { HasIndex = true, HasValue = true };
                size_t index;
                size_t value;

                SizeEqual() = default;
                SizeEqual(size_t index, size_t value): index(index), value(value) {}

                static std::string Type() { return "SizeEqual"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    return problem.size(index) == value;
                }

                virtual bool debugEval(ContractionProblem const& problem, std::ostream & stream) const override
                {
                    bool rv = (*this)(problem);

                    stream << *this << ": (" << problem.size(index) << " == " << value << ") == " << rv;

                    return rv;
                }
            };

            struct StrideAEqual: public Predicate_CRTP<StrideAEqual, ContractionProblem>
            {
                enum { HasIndex = true, HasValue = true };
                size_t index;
                size_t value;

                StrideAEqual() = default;
                StrideAEqual(size_t index, size_t value): index(index), value(value) {}

                static std::string Type() { return "StrideAEqual"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    return problem.a().strides()[index] == value ;
                }

                virtual bool debugEval(ContractionProblem const& problem, std::ostream & stream) const override
                {
                    bool rv = (*this)(problem);

                    stream << *this << ": (" << problem.a().strides()[index] << " == " << value << ") == " << rv;

                    return rv;
                }
            };

            struct StrideBEqual: public Predicate_CRTP<StrideBEqual, ContractionProblem>
            {
                enum { HasIndex = true, HasValue = true };
                size_t index;
                size_t value;

                StrideBEqual() = default;
                StrideBEqual(size_t index, size_t value): index(index), value(value) {}

                static std::string Type() { return "StrideBEqual"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    return problem.b().strides()[index] == value ;
                }

                virtual bool debugEval(ContractionProblem const& problem, std::ostream & stream) const override
                {
                    bool rv = (*this)(problem);

                    stream << *this << ": (" << problem.b().strides()[index] << " == " << value << ") == " << rv;

                    return rv;
                }
            };

            struct CDStridesEqual: public Predicate_CRTP<CDStridesEqual, ContractionProblem>
            {
                enum { HasIndex = false, HasValue = false };
                static std::string Type() { return "CDStridesEqual"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    return problem.c().strides() == problem.d().strides();
                }
            };

            struct LDCEqualsLDD: public Predicate_CRTP<LDCEqualsLDD, ContractionProblem>
            {
                enum { HasIndex = false, HasValue = false };
                static std::string Type() { return "LDCEqualsLDD"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    return problem.c().strides()[1] == problem.d().strides()[1];
                }
            };

            struct BetaZero: public Predicate_CRTP<BetaZero, ContractionProblem>
            {
                enum { HasIndex = false, HasValue = false };
                BetaZero() = default;

                static std::string Type() { return "BetaZero"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    return problem.beta() == 0.0;
                }
            };

            struct BetaOne: public Predicate_CRTP<BetaOne, ContractionProblem>
            {
                enum { HasIndex = false, HasValue = false };
                BetaOne() = default;

                static std::string Type() { return "BetaOne"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    return problem.beta() == 1.0;
                }
            };

            struct HighPrecisionAccumulateEqual: public Predicate_CRTP<HighPrecisionAccumulateEqual, ContractionProblem>
            {
                enum { HasIndex = false, HasValue = true };
                bool value;

                HighPrecisionAccumulateEqual() = default;
                HighPrecisionAccumulateEqual(bool value): value(value) {}

                static std::string Type() { return "HighPrecisionAccumulate"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    return problem.highPrecisionAccumulate() == value;
                }
            };

            struct TypesEqual: public Predicate_CRTP<TypesEqual, ContractionProblem>
            {
                enum { HasIndex = false, HasValue = true };
                TypesEqual() = default;

                std::array<DataType, 4> value;

                static std::string Type() { return "TypesEqual"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    return problem.a().dataType() == value[0]
                        && problem.b().dataType() == value[1]
                        && problem.c().dataType() == value[2]
                        && problem.d().dataType() == value[3];
                }

                virtual std::string toString() const override
                {
                    return concatenate(this->type(),
                                       "(a:",  value[0],
                                       ", b:", value[1],
                                       ", c:", value[2],
                                       ", d:", value[3],
                                       ")");
                }

                virtual bool debugEval(ContractionProblem const& problem, std::ostream & stream) const override
                {
                    bool rv = (*this)(problem);

                    stream << this->type()
                           <<   "(a:" << problem.a().dataType() << " == " << value[0]
                           << "&& b:" << problem.b().dataType() << " == " << value[1]
                           << "&& c:" << problem.c().dataType() << " == " << value[2]
                           << "&& d:" << problem.d().dataType() << " == " << value[3]
                           << "): " << rv;

                    return rv;
                }
            };

            struct OperationIdentifierEqual: public Predicate_CRTP<OperationIdentifierEqual, ContractionProblem>
            {
                enum { HasIndex = false, HasValue = true };
                OperationIdentifierEqual() = default;

                std::string value;

                static std::string Type() { return "OperationIdentifierEqual"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    return problem.operationIdentifier() == value;
                }
            };
        }

        /**
         * @}
         */
    }
}

<|endoftext|>


<commit_before>#ifndef __dispatchkit_hpp__
#define __dispatchkit_hpp__

#include <typeinfo>
#include <string>
#include <map>
#include <boost/shared_ptr.hpp>
#include <boost/lexical_cast.hpp>
#include <stdexcept>
#include <vector>
#include <iostream>
#include <deque>

#include "boxed_value.hpp"
#include "type_info.hpp"
#include "proxy_functions.hpp"
#include "proxy_constructors.hpp"

namespace dispatchkit
{
  class Dispatch_Engine
  {
    public:
      typedef std::multimap<std::string, boost::shared_ptr<Proxy_Function> > Function_Map;
      typedef std::map<std::string, Type_Info> Type_Name_Map;
      typedef std::map<std::string, Boxed_Value> Scope;
      typedef std::deque<Scope> Stack;

      Dispatch_Engine()
      {
        m_scopes.push_back(Scope());
      }

      bool register_function(const boost::shared_ptr<Proxy_Function> &f, const std::string &name)
      {
        return add_function(f, name);
      }

      template<typename Function>
        bool register_function(const Function &func, const std::string &name)
        {
          return add_function(boost::shared_ptr<Proxy_Function>(new Proxy_Function_Impl<Function>(func)), name);
        }

      template<typename Class>
        void set_object(const std::string &name, const Class &obj)
        {
          for (int i = m_scopes.size()-1; i >= 0; --i)
          {
            std::map<std::string, Boxed_Value>::const_iterator itr = m_scopes[i].find(name);
            if (itr != m_scopes[i].end())
            {
              m_scopes[i][name] = Boxed_Value(obj);
              return;
            }
          }

          add_object(name, obj);
        }

      template<typename Class>
        void add_object(const std::string &name, const Class &obj)
        {
          m_scopes.back()[name] = Boxed_Value(obj);
        }

      void new_scope()
      {
        m_scopes.push_back(Scope());
      }

      void pop_scope()
      {
        if (m_scopes.size() > 1)
        {
          m_scopes.pop_back();
        } else {
          throw std::range_error("Unable to pop global stack");
        }
      }

      Stack get_stack()
      {
        return m_scopes;
      }

      Stack set_stack(Stack s)
      {
        swap(s, m_scopes);
        return s;
      }

      Boxed_Value get_object(const std::string &name) const
      {
        for (int i = m_scopes.size()-1; i >= 0; --i)
        {
          std::map<std::string, Boxed_Value>::const_iterator itr = m_scopes[i].find(name);
          if (itr != m_scopes[i].end())
          {
            return itr->second;
          }
        }

        throw std::range_error("Object not known: " + name);
      }

      template<typename Type>
        void register_type(const std::string &name)
        {
          m_types.insert(std::make_pair(name, Get_Type_Info<Type>::get()));
        }

      std::vector<Type_Name_Map::value_type> get_types() const
      {
        return std::vector<Type_Name_Map::value_type>(m_types.begin(), m_types.end());
      }

      std::vector<std::pair<std::string, Function_Map::mapped_type> >
        get_function(const std::string &t_name) const
      {
        std::vector<std::pair<std::string, Function_Map::mapped_type> > funcs;

        try {
          funcs.insert(funcs.end(),
              Function_Map::value_type(
                t_name,
                boxed_cast<Function_Map::mapped_type>(get_object(t_name)))
              );
        } catch (const std::bad_cast &) {
        } catch (const std::range_error &) {
        }

        std::pair<Function_Map::const_iterator, Function_Map::const_iterator> range
          = m_functions.equal_range(t_name);

        funcs.insert(funcs.end(), range.first, range.second);
        return funcs;
      }

      std::vector<Function_Map::value_type> get_functions() const
      {
        return std::vector<Function_Map::value_type>(m_functions.begin(), m_functions.end());
      }

    private:
      bool add_function(const boost::shared_ptr<Proxy_Function> &f, const std::string &t_name)
      {
        std::pair<Function_Map::const_iterator, Function_Map::const_iterator> range
          = m_functions.equal_range(t_name);

        while (range.first != range.second)
        {
          if ((*f) == *(range.first->second))
          {
            return false;
          }
          ++range.first;
        }

        m_functions.insert(std::make_pair(t_name, f));
        return true;
      }

      std::deque<Scope> m_scopes;

      Function_Map m_functions;
      Type_Name_Map m_types;
  };

  void dump_object(Boxed_Value o)
  {
    std::cout << o.get_type_info().m_type_info->name() << std::endl;
  }

  void dump_type(const Type_Info &type)
  {
    std::cout << type.m_bare_type_info->name();
  }

  void dump_function(const Dispatch_Engine::Function_Map::value_type &f)
  {
    std::vector<Type_Info> params = f.second->get_param_types();

    dump_type(params.front());
    std::cout << " " << f.first << "(";

    for (std::vector<Type_Info>::const_iterator itr = params.begin() + 1;
         itr != params.end();
         ++itr)
    {
      dump_type(*itr);
      std::cout << ", ";
    }

    std::cout << ")" << std::endl;
  }

  void dump_system(const Dispatch_Engine &s)
  {
    std::cout << "Registered Types: " << std::endl;
    std::vector<Dispatch_Engine::Type_Name_Map::value_type> types = s.get_types();
    for (std::vector<Dispatch_Engine::Type_Name_Map::value_type>::const_iterator itr = types.begin();
         itr != types.end();
         ++itr)
    {
      std::cout << itr->first << ": ";
      dump_type(itr->second);
      std::cout << std::endl;
    }

    std::cout << std::endl;  std::vector<Dispatch_Engine::Function_Map::value_type> funcs = s.get_functions();

    std::cout << "Functions: " << std::endl;
    for (std::vector<Dispatch_Engine::Function_Map::value_type>::const_iterator itr = funcs.begin();
         itr != funcs.end();
         ++itr)
    {
      dump_function(*itr);
    }
    std::cout << std::endl;
  }

}

#endif

<commit_msg>Return matching named functions when a get_object query finds no matching name object<commit_after>#ifndef __dispatchkit_hpp__
#define __dispatchkit_hpp__

#include <typeinfo>
#include <string>
#include <map>
#include <boost/shared_ptr.hpp>
#include <boost/lexical_cast.hpp>
#include <stdexcept>
#include <vector>
#include <iostream>
#include <deque>

#include "boxed_value.hpp"
#include "type_info.hpp"
#include "proxy_functions.hpp"
#include "proxy_constructors.hpp"

namespace dispatchkit
{
  class Dispatch_Function : public Proxy_Function
  {
    public:
      Dispatch_Function(const std::vector<std::pair<std::string, boost::shared_ptr<Proxy_Function> > > &t_funcs)
        : m_funcs(t_funcs)
      {
      }

      bool operator==(const Proxy_Function &f) const
      {
        return false;
      }

      virtual ~Dispatch_Function() {}

      virtual Boxed_Value operator()(const std::vector<Boxed_Value> &params)
      {
        return dispatch(m_funcs, params);
      }

      virtual std::vector<Type_Info> get_param_types()
      {
        return std::vector<Type_Info>();
      }

    private:
      std::vector<std::pair<std::string, boost::shared_ptr<Proxy_Function> > > m_funcs;
  };

  class Dispatch_Engine
  {
    public:
      typedef std::multimap<std::string, boost::shared_ptr<Proxy_Function> > Function_Map;
      typedef std::map<std::string, Type_Info> Type_Name_Map;
      typedef std::map<std::string, Boxed_Value> Scope;
      typedef std::deque<Scope> Stack;

      Dispatch_Engine()
      {
        m_scopes.push_back(Scope());
      }

      bool register_function(const boost::shared_ptr<Proxy_Function> &f, const std::string &name)
      {
        return add_function(f, name);
      }

      template<typename Function>
        bool register_function(const Function &func, const std::string &name)
        {
          return add_function(boost::shared_ptr<Proxy_Function>(new Proxy_Function_Impl<Function>(func)), name);
        }

      template<typename Class>
        void set_object(const std::string &name, const Class &obj)
        {
          for (int i = m_scopes.size()-1; i >= 0; --i)
          {
            std::map<std::string, Boxed_Value>::const_iterator itr = m_scopes[i].find(name);
            if (itr != m_scopes[i].end())
            {
              m_scopes[i][name] = Boxed_Value(obj);
              return;
            }
          }

          add_object(name, obj);
        }

      template<typename Class>
        void add_object(const std::string &name, const Class &obj)
        {
          m_scopes.back()[name] = Boxed_Value(obj);
        }

      void new_scope()
      {
        m_scopes.push_back(Scope());
      }

      void pop_scope()
      {
        if (m_scopes.size() > 1)
        {
          m_scopes.pop_back();
        } else {
          throw std::range_error("Unable to pop global stack");
        }
      }

      Stack get_stack()
      {
        return m_scopes;
      }

      Stack set_stack(Stack s)
      {
        swap(s, m_scopes);
        return s;
      }

      Boxed_Value get_object(const std::string &name) const
      {
        for (int i = m_scopes.size()-1; i >= 0; --i)
        {
          std::map<std::string, Boxed_Value>::const_iterator itr = m_scopes[i].find(name);
          if (itr != m_scopes[i].end())
          {
            return itr->second;
          }
        }

        std::vector<std::pair<std::string, Function_Map::mapped_type> > funcs = get_function_impl(name, false);

        if (funcs.empty())
        {
          throw std::range_error("Object not known: " + name);
        } else {
          return Boxed_Value(boost::shared_ptr<Proxy_Function>(new Dispatch_Function(funcs)));
        }
      }

      template<typename Type>
        void register_type(const std::string &name)
        {
          m_types.insert(std::make_pair(name, Get_Type_Info<Type>::get()));
        }

      std::vector<Type_Name_Map::value_type> get_types() const
      {
        return std::vector<Type_Name_Map::value_type>(m_types.begin(), m_types.end());
      }

      std::vector<std::pair<std::string, Function_Map::mapped_type> >
        get_function_impl(const std::string &t_name, bool include_objects) const
      {
        std::vector<std::pair<std::string, Function_Map::mapped_type> > funcs;

        if (include_objects)
        {
          try {
            funcs.insert(funcs.end(),
                Function_Map::value_type(
                  t_name,
                  boxed_cast<Function_Map::mapped_type>(get_object(t_name)))
                );
          } catch (const bad_boxed_cast &) {
          } catch (const std::range_error &) {
          }
        }

        std::pair<Function_Map::const_iterator, Function_Map::const_iterator> range
          = m_functions.equal_range(t_name);

        funcs.insert(funcs.end(), range.first, range.second);
        return funcs;
      }

      std::vector<std::pair<std::string, Function_Map::mapped_type> >
        get_function(const std::string &t_name) const
      {
        return get_function_impl(t_name, true);
      }

      std::vector<Function_Map::value_type> get_functions() const
      {
        return std::vector<Function_Map::value_type>(m_functions.begin(), m_functions.end());
      }

    private:
      bool add_function(const boost::shared_ptr<Proxy_Function> &f, const std::string &t_name)
      {
        std::pair<Function_Map::const_iterator, Function_Map::const_iterator> range
          = m_functions.equal_range(t_name);

        while (range.first != range.second)
        {
          if ((*f) == *(range.first->second))
          {
            return false;
          }
          ++range.first;
        }

        m_functions.insert(std::make_pair(t_name, f));
        return true;
      }

      std::deque<Scope> m_scopes;

      Function_Map m_functions;
      Type_Name_Map m_types;
  };

  void dump_object(Boxed_Value o)
  {
    std::cout << o.get_type_info().m_type_info->name() << std::endl;
  }

  void dump_type(const Type_Info &type)
  {
    std::cout << type.m_bare_type_info->name();
  }

  void dump_function(const Dispatch_Engine::Function_Map::value_type &f)
  {
    std::vector<Type_Info> params = f.second->get_param_types();

    dump_type(params.front());
    std::cout << " " << f.first << "(";

    for (std::vector<Type_Info>::const_iterator itr = params.begin() + 1;
         itr != params.end();
         ++itr)
    {
      dump_type(*itr);
      std::cout << ", ";
    }

    std::cout << ")" << std::endl;
  }

  void dump_system(const Dispatch_Engine &s)
  {
    std::cout << "Registered Types: " << std::endl;
    std::vector<Dispatch_Engine::Type_Name_Map::value_type> types = s.get_types();
    for (std::vector<Dispatch_Engine::Type_Name_Map::value_type>::const_iterator itr = types.begin();
         itr != types.end();
         ++itr)
    {
      std::cout << itr->first << ": ";
      dump_type(itr->second);
      std::cout << std::endl;
    }

    std::cout << std::endl;  std::vector<Dispatch_Engine::Function_Map::value_type> funcs = s.get_functions();

    std::cout << "Functions: " << std::endl;
    for (std::vector<Dispatch_Engine::Function_Map::value_type>::const_iterator itr = funcs.begin();
         itr != funcs.end();
         ++itr)
    {
      dump_function(*itr);
    }
    std::cout << std::endl;
  }

}

#endif

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: toolbarwrapper.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: kz $ $Date: 2004-10-04 18:07:15 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________

#ifndef __FRAMEWORK_UIELEMENT_TOOLBARWRAPPER_HXX_
#include <uielement/toolbarwrapper.hxx>
#endif

#ifndef __FRAMEWORK_THREADHELP_RESETABLEGUARD_HXX_
#include <threadhelp/resetableguard.hxx>
#endif

#ifndef __FRAMEWORK_HELPER_ACTIONTRIGGERHELPER_HXX_
#include <helper/actiontriggerhelper.hxx>
#endif

#ifndef __FRAMEWORK_UIELEMENT_CONSTITEMCONTAINER_HXX_
#include <uielement/constitemcontainer.hxx>
#endif

#ifndef __FRAMEWORK_UIELEMENT_ROOTITEMCONTAINER_HXX_
#include <uielement/rootitemcontainer.hxx>
#endif

#ifndef __FRAMEWORK_UIELEMENT_TOOLBARMANAGER_HXX_
#include <uielement/toolbarmanager.hxx>
#endif

#ifndef __FRAMEWORK_UIELEMENT_TOOLBARW_HXX_
#include <uielement/toolbar.hxx>
#endif

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif

#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif

#ifndef _COM_SUN_STAR_AWT_XSYSTEMDEPENDENTMENUPEER_HPP_
#include <com/sun/star/awt/XSystemDependentMenuPeer.hpp>
#endif

#ifndef _COM_SUN_STAR_AWT_XMENUBAR_HPP_
#include <com/sun/star/awt/XMenuBar.hpp>
#endif

#ifndef _COM_SUN_STAR_CONTAINER_XINDEXCONTAINER_HPP_
#include <com/sun/star/container/XIndexContainer.hpp>
#endif

#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif

#ifndef _DRAFTS_COM_SUN_STAR_UI_UIELEMENTTYPE_HPP_
#include <drafts/com/sun/star/ui/UIElementType.hpp>
#endif

//_________________________________________________________________________________________________________________
//  other includes
//_________________________________________________________________________________________________________________

#ifndef _TOOLKIT_HELPER_VCLUNOHELPER_HXX_
#include <toolkit/unohlp.hxx>
#endif
#ifndef _TOOLKIT_AWT_VCLXWINDOW_HXX_
#include <toolkit/awt/vclxwindow.hxx>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif

#include <svtools/miscopt.hxx>
#include <vcl/svapp.hxx>
#include <vcl/toolbox.hxx>
#include <rtl/logfile.hxx>

using namespace rtl;
using namespace com::sun::star::uno;
using namespace com::sun::star::beans;
using namespace com::sun::star::frame;
using namespace com::sun::star::lang;
using namespace com::sun::star::container;
using namespace com::sun::star::awt;
using namespace drafts::com::sun::star::ui;

namespace framework
{

ToolBarWrapper::ToolBarWrapper( const Reference< XMultiServiceFactory >& xServiceManager ) :
    UIConfigElementWrapperBase( UIElementType::TOOLBAR ),
    m_xServiceManager( xServiceManager )
{
}

ToolBarWrapper::~ToolBarWrapper()
{
}

// XComponent
void SAL_CALL ToolBarWrapper::dispose() throw ( RuntimeException )
{
    Reference< XComponent > xThis( static_cast< OWeakObject* >(this), UNO_QUERY );

    {
        ResetableGuard aLock( m_aLock );
        if ( m_bDisposed )
            return;
    }

    com::sun::star::lang::EventObject aEvent( xThis );
    m_aListenerContainer.disposeAndClear( aEvent );

    ResetableGuard aLock( m_aLock );

    if ( m_xToolBarManager.is() )
        m_xToolBarManager->dispose();
    m_xToolBarManager.clear();
    m_xConfigSource.clear();
    m_xConfigData.clear();
    m_xToolBarWindow.clear();

    m_bDisposed = sal_True;
}

// XInitialization
void SAL_CALL ToolBarWrapper::initialize( const Sequence< Any >& aArguments ) throw ( Exception, RuntimeException )
{
    ResetableGuard aLock( m_aLock );

    if ( m_bDisposed )
        throw DisposedException();

    if ( !m_bInitialized )
    {
        UIConfigElementWrapperBase::initialize( aArguments );

        Reference< XFrame > xFrame( m_xWeakFrame );
        if ( xFrame.is() && m_xConfigSource.is() )
        {
            // Create VCL based toolbar which will be filled with settings data
            ToolBar* pToolBar = 0;
            ToolBarManager* pToolBarManager = 0;
            {
                vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );
                Window* pWindow = VCLUnoHelper::GetWindow( xFrame->getContainerWindow() );
                if ( pWindow )
                {
                    ULONG nStyles = WB_LINESPACING | WB_BORDER | WB_SCROLL | WB_MOVEABLE | WB_3DLOOK | WB_DOCKABLE | WB_SIZEABLE | WB_CLOSEABLE;

                    pToolBar = new ToolBar( pWindow, nStyles );
                    m_xToolBarWindow = VCLUnoHelper::GetInterface( pToolBar );
                    pToolBarManager = new ToolBarManager( m_xServiceManager, xFrame, m_aResourceURL, pToolBar );
                    pToolBar->SetToolBarManager( pToolBarManager );
                    m_xToolBarManager = Reference< XComponent >( static_cast< OWeakObject *>( pToolBarManager ), UNO_QUERY );
                }
            }

            try
            {
                m_xConfigData = m_xConfigSource->getSettings( m_aResourceURL, sal_False );
                if ( m_xConfigData.is() && pToolBar && pToolBarManager )
                {
                    // Fill toolbar with container contents
                    pToolBarManager->FillToolbar( m_xConfigData );
                    pToolBar->SetOutStyle( SvtMiscOptions().GetToolboxStyle() );
                    pToolBar->EnableCustomize( TRUE );
                    ::Size aActSize( pToolBar->GetSizePixel() );
                    ::Size aSize( pToolBar->CalcWindowSizePixel() );
                    aSize.Width() = aActSize.Width();
                    pToolBar->SetOutputSizePixel( aSize );
                }
            }
            catch ( NoSuchElementException& )
            {
            }
        }
    }
}

// XUpdatable
void SAL_CALL ToolBarWrapper::update() throw (::com::sun::star::uno::RuntimeException)
{
    ResetableGuard aLock( m_aLock );

    if ( m_bDisposed )
        throw DisposedException();

    ToolBarManager* pToolBarManager = static_cast< ToolBarManager *>( m_xToolBarManager.get() );
    if ( pToolBarManager )
        pToolBarManager->CheckAndUpdateImages();
}

// XUIElementSettings
void SAL_CALL ToolBarWrapper::updateSettings() throw (::com::sun::star::uno::RuntimeException)
{
    ResetableGuard aLock( m_aLock );

    if ( m_bDisposed )
        throw DisposedException();

    if ( m_bPersistent &&
         m_xConfigSource.is() &&
         m_xToolBarManager.is() )
    {
        try
        {
            ToolBarManager* pToolBarManager = static_cast< ToolBarManager *>( m_xToolBarManager.get() );

            m_xConfigData = m_xConfigSource->getSettings( m_aResourceURL, sal_False );
            if ( m_xConfigData.is() )
                pToolBarManager->FillToolbar( m_xConfigData );
        }
        catch ( NoSuchElementException& )
        {
        }
    }
}

Reference< XIndexAccess > SAL_CALL ToolBarWrapper::getSettings( sal_Bool bWriteable ) throw (::com::sun::star::uno::RuntimeException)
{
    ResetableGuard aLock( m_aLock );

    if ( m_bDisposed )
        throw DisposedException();

    if ( bWriteable )
        return Reference< XIndexAccess >( static_cast< OWeakObject * >( new RootItemContainer( m_xConfigData ) ), UNO_QUERY );
    else
        return m_xConfigData;
}

void SAL_CALL ToolBarWrapper::setSettings( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess >& xSettings ) throw (::com::sun::star::uno::RuntimeException)
{
    ResetableGuard aLock( m_aLock );

    if ( m_bDisposed )
        throw DisposedException();

    if ( xSettings.is() )
    {
        // Create a copy of the data if the container is not const
        Reference< XIndexReplace > xReplace( xSettings, UNO_QUERY );
        if ( xReplace.is() )
            m_xConfigData = Reference< XIndexAccess >( static_cast< OWeakObject * >( new ConstItemContainer( xSettings ) ), UNO_QUERY );
        else
            m_xConfigData = xSettings;

        if ( m_xConfigSource.is() && m_bPersistent )
        {
            OUString aResourceURL( m_aResourceURL );
            Reference< XUIConfigurationManager > xUICfgMgr( m_xConfigSource );

            aLock.unlock();

            try
            {
                xUICfgMgr->replaceSettings( aResourceURL, m_xConfigData );
            }
            catch( NoSuchElementException& )
            {
            }
        }
    }
}

//  XUIConfigurationListener
void SAL_CALL ToolBarWrapper::elementInserted( const ::drafts::com::sun::star::ui::ConfigurationEvent& Event ) throw (::com::sun::star::uno::RuntimeException)
{
}

void SAL_CALL ToolBarWrapper::elementRemoved( const ::drafts::com::sun::star::ui::ConfigurationEvent& Event ) throw (::com::sun::star::uno::RuntimeException)
{
}

void SAL_CALL ToolBarWrapper::elementReplaced( const ::drafts::com::sun::star::ui::ConfigurationEvent& Event ) throw (::com::sun::star::uno::RuntimeException)
{
}

// XUIElement interface
Reference< XInterface > SAL_CALL ToolBarWrapper::getRealInterface(  ) throw (::com::sun::star::uno::RuntimeException)
{
    ResetableGuard aLock( m_aLock );

    if ( m_xToolBarManager.is() )
    {
        ToolBarManager* pToolBarManager = static_cast< ToolBarManager *>( m_xToolBarManager.get() );
        if ( pToolBarManager )
        {
            Window* pWindow = (Window *)pToolBarManager->GetToolBar();
            return Reference< XInterface >( VCLUnoHelper::GetInterface( pWindow ), UNO_QUERY );
        }
    }

    return Reference< XInterface >();
}

} // namespace framework
<commit_msg>INTEGRATION: CWS docking4 (1.4.6); FILE MERGED 2004/10/25 09:36:13 cd 1.4.6.2: #i10000# Build problems with gcc fixed 2004/10/22 15:27:58 cd 1.4.6.1: #i34077# Support for toolbar button/sub-toolbar behavior<commit_after>/*************************************************************************
 *
 *  $RCSfile: toolbarwrapper.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: obo $ $Date: 2004-11-16 14:56:46 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________

#ifndef __FRAMEWORK_UIELEMENT_TOOLBARWRAPPER_HXX_
#include <uielement/toolbarwrapper.hxx>
#endif

#ifndef __FRAMEWORK_THREADHELP_RESETABLEGUARD_HXX_
#include <threadhelp/resetableguard.hxx>
#endif

#ifndef __FRAMEWORK_HELPER_ACTIONTRIGGERHELPER_HXX_
#include <helper/actiontriggerhelper.hxx>
#endif

#ifndef __FRAMEWORK_UIELEMENT_CONSTITEMCONTAINER_HXX_
#include <uielement/constitemcontainer.hxx>
#endif

#ifndef __FRAMEWORK_UIELEMENT_ROOTITEMCONTAINER_HXX_
#include <uielement/rootitemcontainer.hxx>
#endif

#ifndef __FRAMEWORK_UIELEMENT_TOOLBARMANAGER_HXX_
#include <uielement/toolbarmanager.hxx>
#endif

#ifndef __FRAMEWORK_UIELEMENT_TOOLBARW_HXX_
#include <uielement/toolbar.hxx>
#endif

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif

#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif

#ifndef _COM_SUN_STAR_AWT_XSYSTEMDEPENDENTMENUPEER_HPP_
#include <com/sun/star/awt/XSystemDependentMenuPeer.hpp>
#endif

#ifndef _COM_SUN_STAR_AWT_XMENUBAR_HPP_
#include <com/sun/star/awt/XMenuBar.hpp>
#endif

#ifndef _COM_SUN_STAR_CONTAINER_XINDEXCONTAINER_HPP_
#include <com/sun/star/container/XIndexContainer.hpp>
#endif

#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif

#ifndef _DRAFTS_COM_SUN_STAR_UI_UIELEMENTTYPE_HPP_
#include <drafts/com/sun/star/ui/UIElementType.hpp>
#endif

//_________________________________________________________________________________________________________________
//  other includes
//_________________________________________________________________________________________________________________

#ifndef _TOOLKIT_HELPER_VCLUNOHELPER_HXX_
#include <toolkit/unohlp.hxx>
#endif
#ifndef _TOOLKIT_AWT_VCLXWINDOW_HXX_
#include <toolkit/awt/vclxwindow.hxx>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif

#include <svtools/miscopt.hxx>
#include <vcl/svapp.hxx>
#include <vcl/toolbox.hxx>
#include <rtl/logfile.hxx>

using namespace rtl;
using namespace com::sun::star;
using namespace com::sun::star::uno;
using namespace com::sun::star::beans;
using namespace com::sun::star::frame;
using namespace com::sun::star::lang;
using namespace com::sun::star::container;
using namespace com::sun::star::awt;
using namespace drafts::com::sun::star::ui;

namespace framework
{

ToolBarWrapper::ToolBarWrapper( const Reference< XMultiServiceFactory >& xServiceManager ) :
    UIConfigElementWrapperBase( UIElementType::TOOLBAR ),
    m_xServiceManager( xServiceManager )
{
}

ToolBarWrapper::~ToolBarWrapper()
{
}

// XInterface
void SAL_CALL ToolBarWrapper::acquire() throw()
{
    UIConfigElementWrapperBase::acquire();
}

void SAL_CALL ToolBarWrapper::release() throw()
{
    UIConfigElementWrapperBase::release();
}

uno::Any SAL_CALL ToolBarWrapper::queryInterface( const uno::Type & rType )
throw( ::com::sun::star::uno::RuntimeException )
{
    Any a = ::cppu::queryInterface(
                rType ,
                SAL_STATIC_CAST( ::com::sun::star::ui::XUIFunctionListener*, this ) );

    if( a.hasValue() )
        return a;

    return UIConfigElementWrapperBase::queryInterface( rType );
}

// XComponent
void SAL_CALL ToolBarWrapper::dispose() throw ( RuntimeException )
{
    Reference< XComponent > xThis( static_cast< OWeakObject* >(this), UNO_QUERY );

    {
        ResetableGuard aLock( m_aLock );
        if ( m_bDisposed )
            return;
    }

    com::sun::star::lang::EventObject aEvent( xThis );
    m_aListenerContainer.disposeAndClear( aEvent );

    ResetableGuard aLock( m_aLock );

    if ( m_xToolBarManager.is() )
        m_xToolBarManager->dispose();
    m_xToolBarManager.clear();
    m_xConfigSource.clear();
    m_xConfigData.clear();
    m_xToolBarWindow.clear();

    m_bDisposed = sal_True;
}

// XInitialization
void SAL_CALL ToolBarWrapper::initialize( const Sequence< Any >& aArguments ) throw ( Exception, RuntimeException )
{
    ResetableGuard aLock( m_aLock );

    if ( m_bDisposed )
        throw DisposedException();

    if ( !m_bInitialized )
    {
        UIConfigElementWrapperBase::initialize( aArguments );

        Reference< XFrame > xFrame( m_xWeakFrame );
        if ( xFrame.is() && m_xConfigSource.is() )
        {
            // Create VCL based toolbar which will be filled with settings data
            ToolBar* pToolBar = 0;
            ToolBarManager* pToolBarManager = 0;
            {
                vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );
                Window* pWindow = VCLUnoHelper::GetWindow( xFrame->getContainerWindow() );
                if ( pWindow )
                {
                    ULONG nStyles = WB_LINESPACING | WB_BORDER | WB_SCROLL | WB_MOVEABLE | WB_3DLOOK | WB_DOCKABLE | WB_SIZEABLE | WB_CLOSEABLE;

                    pToolBar = new ToolBar( pWindow, nStyles );
                    m_xToolBarWindow = VCLUnoHelper::GetInterface( pToolBar );
                    pToolBarManager = new ToolBarManager( m_xServiceManager, xFrame, m_aResourceURL, pToolBar );
                    pToolBar->SetToolBarManager( pToolBarManager );
                    m_xToolBarManager = Reference< XComponent >( static_cast< OWeakObject *>( pToolBarManager ), UNO_QUERY );
                }
            }

            try
            {
                m_xConfigData = m_xConfigSource->getSettings( m_aResourceURL, sal_False );
                if ( m_xConfigData.is() && pToolBar && pToolBarManager )
                {
                    // Fill toolbar with container contents
                    pToolBarManager->FillToolbar( m_xConfigData );
                    pToolBar->SetOutStyle( SvtMiscOptions().GetToolboxStyle() );
                    pToolBar->EnableCustomize( TRUE );
                    ::Size aActSize( pToolBar->GetSizePixel() );
                    ::Size aSize( pToolBar->CalcWindowSizePixel() );
                    aSize.Width() = aActSize.Width();
                    pToolBar->SetOutputSizePixel( aSize );
                }
            }
            catch ( NoSuchElementException& )
            {
            }
        }
    }
}

// XEventListener
void SAL_CALL ToolBarWrapper::disposing( const ::com::sun::star::lang::EventObject& aEvent ) throw (::com::sun::star::uno::RuntimeException)
{
    // nothing todo
}

// XUpdatable
void SAL_CALL ToolBarWrapper::update() throw (::com::sun::star::uno::RuntimeException)
{
    ResetableGuard aLock( m_aLock );

    if ( m_bDisposed )
        throw DisposedException();

    ToolBarManager* pToolBarManager = static_cast< ToolBarManager *>( m_xToolBarManager.get() );
    if ( pToolBarManager )
        pToolBarManager->CheckAndUpdateImages();
}

// XUIElementSettings
void SAL_CALL ToolBarWrapper::updateSettings() throw (::com::sun::star::uno::RuntimeException)
{
    ResetableGuard aLock( m_aLock );

    if ( m_bDisposed )
        throw DisposedException();

    if ( m_bPersistent &&
         m_xConfigSource.is() &&
         m_xToolBarManager.is() )
    {
        try
        {
            ToolBarManager* pToolBarManager = static_cast< ToolBarManager *>( m_xToolBarManager.get() );

            m_xConfigData = m_xConfigSource->getSettings( m_aResourceURL, sal_False );
            if ( m_xConfigData.is() )
                pToolBarManager->FillToolbar( m_xConfigData );
        }
        catch ( NoSuchElementException& )
        {
        }
    }
}

Reference< XIndexAccess > SAL_CALL ToolBarWrapper::getSettings( sal_Bool bWriteable ) throw (::com::sun::star::uno::RuntimeException)
{
    ResetableGuard aLock( m_aLock );

    if ( m_bDisposed )
        throw DisposedException();

    if ( bWriteable )
        return Reference< XIndexAccess >( static_cast< OWeakObject * >( new RootItemContainer( m_xConfigData ) ), UNO_QUERY );
    else
        return m_xConfigData;
}

void SAL_CALL ToolBarWrapper::setSettings( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess >& xSettings ) throw (::com::sun::star::uno::RuntimeException)
{
    ResetableGuard aLock( m_aLock );

    if ( m_bDisposed )
        throw DisposedException();

    if ( xSettings.is() )
    {
        // Create a copy of the data if the container is not const
        Reference< XIndexReplace > xReplace( xSettings, UNO_QUERY );
        if ( xReplace.is() )
            m_xConfigData = Reference< XIndexAccess >( static_cast< OWeakObject * >( new ConstItemContainer( xSettings ) ), UNO_QUERY );
        else
            m_xConfigData = xSettings;

        if ( m_xConfigSource.is() && m_bPersistent )
        {
            OUString aResourceURL( m_aResourceURL );
            Reference< XUIConfigurationManager > xUICfgMgr( m_xConfigSource );

            aLock.unlock();

            try
            {
                xUICfgMgr->replaceSettings( aResourceURL, m_xConfigData );
            }
            catch( NoSuchElementException& )
            {
            }
        }
    }
}

//  XUIConfigurationListener
void SAL_CALL ToolBarWrapper::elementInserted( const ::drafts::com::sun::star::ui::ConfigurationEvent& Event ) throw (::com::sun::star::uno::RuntimeException)
{
}

void SAL_CALL ToolBarWrapper::elementRemoved( const ::drafts::com::sun::star::ui::ConfigurationEvent& Event ) throw (::com::sun::star::uno::RuntimeException)
{
}

void SAL_CALL ToolBarWrapper::elementReplaced( const ::drafts::com::sun::star::ui::ConfigurationEvent& Event ) throw (::com::sun::star::uno::RuntimeException)
{
}

// XUIElement interface
Reference< XInterface > SAL_CALL ToolBarWrapper::getRealInterface(  ) throw (::com::sun::star::uno::RuntimeException)
{
    ResetableGuard aLock( m_aLock );

    if ( m_xToolBarManager.is() )
    {
        ToolBarManager* pToolBarManager = static_cast< ToolBarManager *>( m_xToolBarManager.get() );
        if ( pToolBarManager )
        {
            Window* pWindow = (Window *)pToolBarManager->GetToolBar();
            return Reference< XInterface >( VCLUnoHelper::GetInterface( pWindow ), UNO_QUERY );
        }
    }

    return Reference< XInterface >();
}

//XUIFunctionExecute
void SAL_CALL ToolBarWrapper::functionExecute(
    const ::rtl::OUString& aUIElementName,
    const ::rtl::OUString& aCommand )
throw (::com::sun::star::uno::RuntimeException)
{
    ResetableGuard aLock( m_aLock );

    if ( m_xToolBarManager.is() )
    {
        ToolBarManager* pToolBarManager = static_cast< ToolBarManager *>( m_xToolBarManager.get() );
        if ( pToolBarManager )
            pToolBarManager->notifyRegisteredControllers( aUIElementName, aCommand );
    }
}

} // namespace framework
<|endoftext|>