<commit_before>#ifndef VEXCL_UTIL_HPP
#define VEXCL_UTIL_HPP

/*
The MIT License

Copyright (c) 2012-2013 Denis Demidov <ddemidov@ksu.ru>

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.
*/

/**
 * \file   vexcl/util.hpp
 * \author Denis Demidov <ddemidov@ksu.ru>
 * \brief  OpenCL general utilities.
 */

#ifdef WIN32
#  pragma warning(push)
#  pragma warning(disable : 4267 4290)
#  define NOMINMAX
#endif

#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
#include <type_traits>
#include <functional>
#include <climits>
#include <stdexcept>
#include <limits>
#include <boost/config.hpp>
#include <boost/type_traits/is_same.hpp>

#ifndef __CL_ENABLE_EXCEPTIONS
#  define __CL_ENABLE_EXCEPTIONS
#endif
#include <CL/cl.hpp>
#include <vexcl/types.hpp>

typedef unsigned int  uint;
typedef unsigned char uchar;

namespace vex {

/// Convert typename to string.
template <class T> inline std::string type_name() {
    throw std::logic_error("Trying to use an undefined type in a kernel.");
}

/// Declares a type as CL native, allows using it as a literal.
template <class T> struct is_cl_native : std::false_type {};

#define STRINGIFY(type) \
template <> inline std::string type_name<cl_##type>() { return #type; } \
template <> struct is_cl_native<cl_##type> : std::true_type {};

// enable use of OpenCL vector types as literals
#define CL_VEC_TYPE(type, len) \
template <> inline std::string type_name<cl_##type##len>() { return #type #len; } \
template <> struct is_cl_native<cl_##type##len> : std::true_type {};

#define CL_TYPES(type) \
STRINGIFY(type); \
CL_VEC_TYPE(type, 2); \
CL_VEC_TYPE(type, 4); \
CL_VEC_TYPE(type, 8); \
CL_VEC_TYPE(type, 16);

CL_TYPES(float);
CL_TYPES(double);
CL_TYPES(char);  CL_TYPES(uchar);
CL_TYPES(short); CL_TYPES(ushort);
CL_TYPES(int);   CL_TYPES(uint);
CL_TYPES(long);  CL_TYPES(ulong);
#undef CL_TYPES
#undef CL_VEC_TYPE
#undef STRINGIFY

#if defined(__clang__) && defined(__APPLE__)
template <> inline std::string type_name<size_t>() {
    return std::numeric_limits<std::size_t>::max() ==
        std::numeric_limits<uint>::max() ? "uint" : "ulong";
}
template <> struct is_cl_native<size_t> : std::true_type {};
#endif

const std::string standard_kernel_header = std::string(
        "#if defined(cl_khr_fp64)\n"
        "#  pragma OPENCL EXTENSION cl_khr_fp64: enable\n"
        "#elif defined(cl_amd_fp64)\n"
        "#  pragma OPENCL EXTENSION cl_amd_fp64: enable\n"
        "#endif\n"
        );

/// \cond INTERNAL

/// Binary operations with their traits.
namespace binop {
    enum kind {
        Add,
        Subtract,
        Multiply,
        Divide,
        Remainder,
        Greater,
        Less,
        GreaterEqual,
        LessEqual,
        Equal,
        NotEqual,
        BitwiseAnd,
        BitwiseOr,
        BitwiseXor,
        LogicalAnd,
        LogicalOr,
        RightShift,
        LeftShift
    };

    template <kind> struct traits {};

#define BOP_TRAITS(kind, op, nm)   \
    template <> struct traits<kind> {  \
        static std::string oper() { return op; } \
        static std::string name() { return nm; } \
    };

    BOP_TRAITS(Add,          "+",  "Add_")
    BOP_TRAITS(Subtract,     "-",  "Sub_")
    BOP_TRAITS(Multiply,     "*",  "Mul_")
    BOP_TRAITS(Divide,       "/",  "Div_")
    BOP_TRAITS(Remainder,    "%",  "Mod_")
    BOP_TRAITS(Greater,      ">",  "Gtr_")
    BOP_TRAITS(Less,         "<",  "Lss_")
    BOP_TRAITS(GreaterEqual, ">=", "Geq_")
    BOP_TRAITS(LessEqual,    "<=", "Leq_")
    BOP_TRAITS(Equal,        "==", "Equ_")
    BOP_TRAITS(NotEqual,     "!=", "Neq_")
    BOP_TRAITS(BitwiseAnd,   "&",  "BAnd_")
    BOP_TRAITS(BitwiseOr,    "|",  "BOr_")
    BOP_TRAITS(BitwiseXor,   "^",  "BXor_")
    BOP_TRAITS(LogicalAnd,   "&&", "LAnd_")
    BOP_TRAITS(LogicalOr,    "||", "LOr_")
    BOP_TRAITS(RightShift,   ">>", "Rsh_")
    BOP_TRAITS(LeftShift,    "<<", "Lsh_")

#undef BOP_TRAITS
}

/// \endcond

/// Return next power of 2.
inline size_t nextpow2(size_t x) {
    --x;
    x |= x >> 1U;
    x |= x >> 2U;
    x |= x >> 4U;
    x |= x >> 8U;
    x |= x >> 16U;
    return ++x;
}

/// Align n to the next multiple of m.
inline size_t alignup(size_t n, size_t m = 16U) {
    return n % m ? n - n % m + m : n;
}

/// Iterate over tuple elements.
template <size_t I, class Function, class Tuple>
typename std::enable_if<(I == std::tuple_size<Tuple>::value), void>::type
for_each(const Tuple &, Function &)
{ }

/// Iterate over tuple elements.
template <size_t I, class Function, class Tuple>
typename std::enable_if<(I < std::tuple_size<Tuple>::value), void>::type
for_each(const Tuple &v, Function &f)
{
    f( std::get<I>(v) );

    for_each<I + 1>(v, f);
}

/// Create and build a program from source string.
inline cl::Program build_sources(
        const cl::Context &context, const std::string &source
        )
{
    cl::Program program(context, cl::Program::Sources(
                1, std::make_pair(source.c_str(), source.size())
                ));

    auto device = context.getInfo<CL_CONTEXT_DEVICES>();

    try {
        program.build(device);
    } catch(const cl::Error&) {
        std::cerr << source
                  << std::endl
                  << program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(device[0])
                  << std::endl;
        throw;
    }

    return program;
}

/// Get maximum possible workgroup size for given kernel.
inline uint kernel_workgroup_size(
        const cl::Kernel &kernel,
        const cl::Device &device
        )
{
    size_t wgsz = 1024U;

    uint dev_wgsz = kernel.getWorkGroupInfo<CL_KERNEL_WORK_GROUP_SIZE>(device);
    while(wgsz > dev_wgsz) wgsz /= 2;

    return wgsz;
}

/// Shortcut for q.getInfo<CL_QUEUE_CONTEXT>()
inline cl::Context qctx(const cl::CommandQueue& q) {
    cl::Context ctx;
    q.getInfo(CL_QUEUE_CONTEXT, &ctx);
    return ctx;
}

/// Shortcut for q.getInfo<CL_QUEUE_DEVICE>()
inline cl::Device qdev(const cl::CommandQueue& q) {
    cl::Device dev;
    q.getInfo(CL_QUEUE_DEVICE, &dev);
    return dev;
}

struct column_owner {
    const std::vector<size_t> ∂

    column_owner(const std::vector<size_t> &part) : part(part) {}

    size_t operator()(size_t c) const {
        return std::upper_bound(part.begin(), part.end(), c)
            - part.begin() - 1;
    }
};

} // namespace vex

/// Output description of an OpenCL error to a stream.
inline std::ostream& operator<<(std::ostream &os, const cl::Error &e) {
    os << e.what() << "(";

    switch (e.err()) {
        case 0:
            os << "Success";
            break;
        case -1:
            os << "Device not found";
            break;
        case -2:
            os << "Device not available";
            break;
        case -3:
            os << "Compiler not available";
            break;
        case -4:
            os << "Mem object allocation failure";
            break;
        case -5:
            os << "Out of resources";
            break;
        case -6:
            os << "Out of host memory";
            break;
        case -7:
            os << "Profiling info not available";
            break;
        case -8:
            os << "Mem copy overlap";
            break;
        case -9:
            os << "Image format mismatch";
            break;
        case -10:
            os << "Image format not supported";
            break;
        case -11:
            os << "Build program failure";
            break;
        case -12:
            os << "Map failure";
            break;
        case -13:
            os << "Misaligned sub buffer offset";
            break;
        case -14:
            os << "Exec status error for events in wait list";
            break;
        case -30:
            os << "Invalid value";
            break;
        case -31:
            os << "Invalid device type";
            break;
        case -32:
            os << "Invalid platform";
            break;
        case -33:
            os << "Invalid device";
            break;
        case -34:
            os << "Invalid context";
            break;
        case -35:
            os << "Invalid queue properties";
            break;
        case -36:
            os << "Invalid command queue";
            break;
        case -37:
            os << "Invalid host ptr";
            break;
        case -38:
            os << "Invalid mem object";
            break;
        case -39:
            os << "Invalid image format descriptor";
            break;
        case -40:
            os << "Invalid image size";
            break;
        case -41:
            os << "Invalid sampler";
            break;
        case -42:
            os << "Invalid binary";
            break;
        case -43:
            os << "Invalid build options";
            break;
        case -44:
            os << "Invalid program";
            break;
        case -45:
            os << "Invalid program executable";
            break;
        case -46:
            os << "Invalid kernel name";
            break;
        case -47:
            os << "Invalid kernel definition";
            break;
        case -48:
            os << "Invalid kernel";
            break;
        case -49:
            os << "Invalid arg index";
            break;
        case -50:
            os << "Invalid arg value";
            break;
        case -51:
            os << "Invalid arg size";
            break;
        case -52:
            os << "Invalid kernel args";
            break;
        case -53:
            os << "Invalid work dimension";
            break;
        case -54:
            os << "Invalid work group size";
            break;
        case -55:
            os << "Invalid work item size";
            break;
        case -56:
            os << "Invalid global offset";
            break;
        case -57:
            os << "Invalid event wait list";
            break;
        case -58:
            os << "Invalid event";
            break;
        case -59:
            os << "Invalid operation";
            break;
        case -60:
            os << "Invalid gl object";
            break;
        case -61:
            os << "Invalid buffer size";
            break;
        case -62:
            os << "Invalid mip level";
            break;
        case -63:
            os << "Invalid global work size";
            break;
        case -64:
            os << "Invalid property";
            break;
        default:
            os << "Unknown error";
            break;
    }

    return os << ")";
}

#ifdef WIN32
#  pragma warning(pop)
#endif

// vim: et
#endif
<commit_msg>Add ptrdiff_t specialization for Apple's clang<commit_after>#ifndef VEXCL_UTIL_HPP
#define VEXCL_UTIL_HPP

/*
The MIT License

Copyright (c) 2012-2013 Denis Demidov <ddemidov@ksu.ru>

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.
*/

/**
 * \file   vexcl/util.hpp
 * \author Denis Demidov <ddemidov@ksu.ru>
 * \brief  OpenCL general utilities.
 */

#ifdef WIN32
#  pragma warning(push)
#  pragma warning(disable : 4267 4290)
#  define NOMINMAX
#endif

#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
#include <type_traits>
#include <functional>
#include <climits>
#include <stdexcept>
#include <limits>
#include <boost/config.hpp>
#include <boost/type_traits/is_same.hpp>

#ifndef __CL_ENABLE_EXCEPTIONS
#  define __CL_ENABLE_EXCEPTIONS
#endif
#include <CL/cl.hpp>
#include <vexcl/types.hpp>

typedef unsigned int  uint;
typedef unsigned char uchar;

namespace vex {

/// Convert typename to string.
template <class T> inline std::string type_name() {
    throw std::logic_error("Trying to use an undefined type in a kernel.");
}

/// Declares a type as CL native, allows using it as a literal.
template <class T> struct is_cl_native : std::false_type {};

#define STRINGIFY(type) \
template <> inline std::string type_name<cl_##type>() { return #type; } \
template <> struct is_cl_native<cl_##type> : std::true_type {};

// enable use of OpenCL vector types as literals
#define CL_VEC_TYPE(type, len) \
template <> inline std::string type_name<cl_##type##len>() { return #type #len; } \
template <> struct is_cl_native<cl_##type##len> : std::true_type {};

#define CL_TYPES(type) \
STRINGIFY(type); \
CL_VEC_TYPE(type, 2); \
CL_VEC_TYPE(type, 4); \
CL_VEC_TYPE(type, 8); \
CL_VEC_TYPE(type, 16);

CL_TYPES(float);
CL_TYPES(double);
CL_TYPES(char);  CL_TYPES(uchar);
CL_TYPES(short); CL_TYPES(ushort);
CL_TYPES(int);   CL_TYPES(uint);
CL_TYPES(long);  CL_TYPES(ulong);
#undef CL_TYPES
#undef CL_VEC_TYPE
#undef STRINGIFY

#if defined(__clang__) && defined(__APPLE__)
template <> inline std::string type_name<size_t>() {
    return std::numeric_limits<std::size_t>::max() ==
        std::numeric_limits<uint>::max() ? "uint" : "ulong";
}
template <> struct is_cl_native<size_t> : std::true_type {};
template <> inline std::string type_name<ptrdiff_t>() {
    return std::numeric_limits<std::ptrdiff_t>::max() ==
        std::numeric_limits<int>::max() ? "int" : "long";
}
template <> struct is_cl_native<ptrdiff_t> : std::true_type {};
#endif

const std::string standard_kernel_header = std::string(
        "#if defined(cl_khr_fp64)\n"
        "#  pragma OPENCL EXTENSION cl_khr_fp64: enable\n"
        "#elif defined(cl_amd_fp64)\n"
        "#  pragma OPENCL EXTENSION cl_amd_fp64: enable\n"
        "#endif\n"
        );

/// \cond INTERNAL

/// Binary operations with their traits.
namespace binop {
    enum kind {
        Add,
        Subtract,
        Multiply,
        Divide,
        Remainder,
        Greater,
        Less,
        GreaterEqual,
        LessEqual,
        Equal,
        NotEqual,
        BitwiseAnd,
        BitwiseOr,
        BitwiseXor,
        LogicalAnd,
        LogicalOr,
        RightShift,
        LeftShift
    };

    template <kind> struct traits {};

#define BOP_TRAITS(kind, op, nm)   \
    template <> struct traits<kind> {  \
        static std::string oper() { return op; } \
        static std::string name() { return nm; } \
    };

    BOP_TRAITS(Add,          "+",  "Add_")
    BOP_TRAITS(Subtract,     "-",  "Sub_")
    BOP_TRAITS(Multiply,     "*",  "Mul_")
    BOP_TRAITS(Divide,       "/",  "Div_")
    BOP_TRAITS(Remainder,    "%",  "Mod_")
    BOP_TRAITS(Greater,      ">",  "Gtr_")
    BOP_TRAITS(Less,         "<",  "Lss_")
    BOP_TRAITS(GreaterEqual, ">=", "Geq_")
    BOP_TRAITS(LessEqual,    "<=", "Leq_")
    BOP_TRAITS(Equal,        "==", "Equ_")
    BOP_TRAITS(NotEqual,     "!=", "Neq_")
    BOP_TRAITS(BitwiseAnd,   "&",  "BAnd_")
    BOP_TRAITS(BitwiseOr,    "|",  "BOr_")
    BOP_TRAITS(BitwiseXor,   "^",  "BXor_")
    BOP_TRAITS(LogicalAnd,   "&&", "LAnd_")
    BOP_TRAITS(LogicalOr,    "||", "LOr_")
    BOP_TRAITS(RightShift,   ">>", "Rsh_")
    BOP_TRAITS(LeftShift,    "<<", "Lsh_")

#undef BOP_TRAITS
}

/// \endcond

/// Return next power of 2.
inline size_t nextpow2(size_t x) {
    --x;
    x |= x >> 1U;
    x |= x >> 2U;
    x |= x >> 4U;
    x |= x >> 8U;
    x |= x >> 16U;
    return ++x;
}

/// Align n to the next multiple of m.
inline size_t alignup(size_t n, size_t m = 16U) {
    return n % m ? n - n % m + m : n;
}

/// Iterate over tuple elements.
template <size_t I, class Function, class Tuple>
typename std::enable_if<(I == std::tuple_size<Tuple>::value), void>::type
for_each(const Tuple &, Function &)
{ }

/// Iterate over tuple elements.
template <size_t I, class Function, class Tuple>
typename std::enable_if<(I < std::tuple_size<Tuple>::value), void>::type
for_each(const Tuple &v, Function &f)
{
    f( std::get<I>(v) );

    for_each<I + 1>(v, f);
}

/// Create and build a program from source string.
inline cl::Program build_sources(
        const cl::Context &context, const std::string &source
        )
{
    cl::Program program(context, cl::Program::Sources(
                1, std::make_pair(source.c_str(), source.size())
                ));

    auto device = context.getInfo<CL_CONTEXT_DEVICES>();

    try {
        program.build(device);
    } catch(const cl::Error&) {
        std::cerr << source
                  << std::endl
                  << program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(device[0])
                  << std::endl;
        throw;
    }

    return program;
}

/// Get maximum possible workgroup size for given kernel.
inline uint kernel_workgroup_size(
        const cl::Kernel &kernel,
        const cl::Device &device
        )
{
    size_t wgsz = 1024U;

    uint dev_wgsz = kernel.getWorkGroupInfo<CL_KERNEL_WORK_GROUP_SIZE>(device);
    while(wgsz > dev_wgsz) wgsz /= 2;

    return wgsz;
}

/// Shortcut for q.getInfo<CL_QUEUE_CONTEXT>()
inline cl::Context qctx(const cl::CommandQueue& q) {
    cl::Context ctx;
    q.getInfo(CL_QUEUE_CONTEXT, &ctx);
    return ctx;
}

/// Shortcut for q.getInfo<CL_QUEUE_DEVICE>()
inline cl::Device qdev(const cl::CommandQueue& q) {
    cl::Device dev;
    q.getInfo(CL_QUEUE_DEVICE, &dev);
    return dev;
}

struct column_owner {
    const std::vector<size_t> ∂

    column_owner(const std::vector<size_t> &part) : part(part) {}

    size_t operator()(size_t c) const {
        return std::upper_bound(part.begin(), part.end(), c)
            - part.begin() - 1;
    }
};

} // namespace vex

/// Output description of an OpenCL error to a stream.
inline std::ostream& operator<<(std::ostream &os, const cl::Error &e) {
    os << e.what() << "(";

    switch (e.err()) {
        case 0:
            os << "Success";
            break;
        case -1:
            os << "Device not found";
            break;
        case -2:
            os << "Device not available";
            break;
        case -3:
            os << "Compiler not available";
            break;
        case -4:
            os << "Mem object allocation failure";
            break;
        case -5:
            os << "Out of resources";
            break;
        case -6:
            os << "Out of host memory";
            break;
        case -7:
            os << "Profiling info not available";
            break;
        case -8:
            os << "Mem copy overlap";
            break;
        case -9:
            os << "Image format mismatch";
            break;
        case -10:
            os << "Image format not supported";
            break;
        case -11:
            os << "Build program failure";
            break;
        case -12:
            os << "Map failure";
            break;
        case -13:
            os << "Misaligned sub buffer offset";
            break;
        case -14:
            os << "Exec status error for events in wait list";
            break;
        case -30:
            os << "Invalid value";
            break;
        case -31:
            os << "Invalid device type";
            break;
        case -32:
            os << "Invalid platform";
            break;
        case -33:
            os << "Invalid device";
            break;
        case -34:
            os << "Invalid context";
            break;
        case -35:
            os << "Invalid queue properties";
            break;
        case -36:
            os << "Invalid command queue";
            break;
        case -37:
            os << "Invalid host ptr";
            break;
        case -38:
            os << "Invalid mem object";
            break;
        case -39:
            os << "Invalid image format descriptor";
            break;
        case -40:
            os << "Invalid image size";
            break;
        case -41:
            os << "Invalid sampler";
            break;
        case -42:
            os << "Invalid binary";
            break;
        case -43:
            os << "Invalid build options";
            break;
        case -44:
            os << "Invalid program";
            break;
        case -45:
            os << "Invalid program executable";
            break;
        case -46:
            os << "Invalid kernel name";
            break;
        case -47:
            os << "Invalid kernel definition";
            break;
        case -48:
            os << "Invalid kernel";
            break;
        case -49:
            os << "Invalid arg index";
            break;
        case -50:
            os << "Invalid arg value";
            break;
        case -51:
            os << "Invalid arg size";
            break;
        case -52:
            os << "Invalid kernel args";
            break;
        case -53:
            os << "Invalid work dimension";
            break;
        case -54:
            os << "Invalid work group size";
            break;
        case -55:
            os << "Invalid work item size";
            break;
        case -56:
            os << "Invalid global offset";
            break;
        case -57:
            os << "Invalid event wait list";
            break;
        case -58:
            os << "Invalid event";
            break;
        case -59:
            os << "Invalid operation";
            break;
        case -60:
            os << "Invalid gl object";
            break;
        case -61:
            os << "Invalid buffer size";
            break;
        case -62:
            os << "Invalid mip level";
            break;
        case -63:
            os << "Invalid global work size";
            break;
        case -64:
            os << "Invalid property";
            break;
        default:
            os << "Unknown error";
            break;
    }

    return os << ")";
}

#ifdef WIN32
#  pragma warning(pop)
#endif

// vim: et
#endif
<|endoftext|>


<commit_before>/****************************************************************************

 This file is part of the GLC-lib library.
 Copyright (C) 2005-2006 Laurent Ribon (laumaya@users.sourceforge.net)
 Version 0.9.6, packaged on June, 2006.

 http://glc-lib.sourceforge.net

 GLC-lib is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; either version 2 of the License, or
 (at your option) any later version.

 GLC-lib 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 General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with GLC-lib; if not, write to the Free Software
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

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

//! \file glc_light.cpp implementation of the GLC_Light class.

#include <QtDebug>
#include "glc_light.h"
#include "glc_openglexception.h"

//////////////////////////////////////////////////////////////////////
// Constructor Destructor
//////////////////////////////////////////////////////////////////////
GLC_Light::GLC_Light()
:GLC_Object("Light")
, m_LightID(GL_LIGHT1)	// Default Light ID
, m_ListID(0)			// By default display list ID= 0
, m_ListIsValid(false)	// By default display list is not valid
, m_AmbientColor()		// Ambient color will be set in the constructor
, m_DiffuseColor(Qt::white)		// By default diffuse color is set to white
, m_SpecularColor(Qt::white)	// By default specular color is set to white
, m_Position()
{
	//! \todo modify class to support multi light
	m_AmbientColor.setRgbF(0.2, 0.2, 0.2, 1.0); // By default light's color is dark grey
}

GLC_Light::GLC_Light(const QColor& color)
:GLC_Object("Light")
, m_LightID(GL_LIGHT1)	// Default Light ID
, m_ListID(0)			// By default display list ID= 0
, m_ListIsValid(false)	// By default display list is not valid
, m_AmbientColor(color) // the ambiant color of the light
, m_DiffuseColor(Qt::white)		// By default diffuse color is set to white
, m_SpecularColor(Qt::white)	// By default specular color is set to white
, m_Position()
{
	//! \todo modify class to support multi light
}

GLC_Light::~GLC_Light(void)
{
	deleteList();
}

/////////////////////////////////////////////////////////////////////
// Set Functions
//////////////////////////////////////////////////////////////////////

// Set the lihgt position by a 4D vector
void GLC_Light::setPosition(const GLC_Vector4d &vectPos)
{
	m_Position= vectPos;
	m_ListIsValid = false;
}

// Set the lihgt position by a 3 GLfloat
void GLC_Light::setPosition(GLfloat x, GLfloat y, GLfloat z)
{
	m_Position.setX(x);
	m_Position.setY(y);
	m_Position.setZ(z);
	m_ListIsValid = false;
}

// Set light's ambiant color by a QColor
void GLC_Light::setAmbientColor(const QColor& color)
{
	m_AmbientColor= color;
	m_ListIsValid = false;
}

// Set light's diffuse color by a QColor
void GLC_Light::setDiffuseColor(const QColor& color)
{
	m_DiffuseColor= color;
	m_ListIsValid = false;
}

// Set light's specular color by a QColor
void GLC_Light::setSpecularColor(const QColor& color)
{
	m_SpecularColor= color;
	m_ListIsValid = false;
}

//////////////////////////////////////////////////////////////////////
// OpenGL Functions
//////////////////////////////////////////////////////////////////////

// Create light's OpenGL list
void GLC_Light::creationList(GLenum Mode)
{
	if(!m_ListID)		// OpenGL list not created
	{
		m_ListID= glGenLists(1);

		if (!m_ListID)	// OpenGL List Id not get
		{
			glDraw();
			qDebug("GLC_Lumiere::CreationListe Display list not create");
		}
	}
	// OpenGL list creation and execution
	glNewList(m_ListID, Mode);

	// Light execution
	glDraw();

	glEndList();

	// Indicateur de la validit de la liste
	m_ListIsValid= true;

	// OpenGL error handler
	GLenum error= glGetError();
	if (error != GL_NO_ERROR)
	{
		GLC_OpenGlException OpenGlException("GLC_Light::CreationList ", error);
		throw(OpenGlException);
	}
}

// Execute OpenGL light
void GLC_Light::glExecute(GLenum Mode)
{
	// Object Name
	glLoadName(getID());

	if (!m_ListIsValid)
	{
		// OpenGL list is not valid

		creationList(Mode);
	}
	else
	{
		glCallList(m_ListID);
	}

	// OpenGL error handler
	GLenum error= glGetError();
	if (error != GL_NO_ERROR)
	{
		GLC_OpenGlException OpenGlException("GLC_Light::GlExecute ", error);
		throw(OpenGlException);
	}

}

// OpenGL light set up
void GLC_Light::glDraw(void)
{
	// Color
	GLfloat setArray[4]= {static_cast<GLfloat>(m_AmbientColor.redF()),
									static_cast<GLfloat>(m_AmbientColor.greenF()),
									static_cast<GLfloat>(m_AmbientColor.blueF()),
									static_cast<GLfloat>(m_AmbientColor.alphaF())};
	glLightfv(m_LightID, GL_AMBIENT, setArray);		// Setup The Ambient Light

	setArray[0]= static_cast<GLfloat>(m_DiffuseColor.redF());
	setArray[1]= static_cast<GLfloat>(m_DiffuseColor.greenF());
	setArray[2]= static_cast<GLfloat>(m_DiffuseColor.blueF());
	setArray[3]= static_cast<GLfloat>(m_DiffuseColor.alphaF());
	glLightfv(m_LightID, GL_DIFFUSE, setArray);		// Setup The Diffuse Light

	setArray[0]= static_cast<GLfloat>(m_SpecularColor.redF());
	setArray[1]= static_cast<GLfloat>(m_SpecularColor.greenF());
	setArray[2]= static_cast<GLfloat>(m_SpecularColor.blueF());
	setArray[3]= static_cast<GLfloat>(m_SpecularColor.alphaF());
	glLightfv(m_LightID, GL_SPECULAR, setArray);	// Setup The specular Light

	// Position
	setArray[0]= static_cast<GLfloat>(m_Position.getX());
	setArray[1]= static_cast<GLfloat>(m_Position.getY());
	setArray[2]= static_cast<GLfloat>(m_Position.getZ());
	setArray[3]= static_cast<GLfloat>(m_Position.getW());

	glLightfv(m_LightID, GL_POSITION, setArray);	// Position The Light

	// OpenGL error handler
	GLenum error= glGetError();
	if (error != GL_NO_ERROR)
	{
		GLC_OpenGlException OpenGlException("GLC_Light::GlDraw ", error);
		throw(OpenGlException);
	}

}

//////////////////////////////////////////////////////////////////////
// Private services Functions
//////////////////////////////////////////////////////////////////////

// Delete OpenGL Display list
void GLC_Light::deleteList(void)
{
	//! if the list is valid, the list is deleted
	if (glIsList(m_ListID))
	{
		glDeleteLists(m_ListID, 1);
	}
}
<commit_msg>modification off the default light color<commit_after>/****************************************************************************

 This file is part of the GLC-lib library.
 Copyright (C) 2005-2006 Laurent Ribon (laumaya@users.sourceforge.net)
 Version 0.9.6, packaged on June, 2006.

 http://glc-lib.sourceforge.net

 GLC-lib is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; either version 2 of the License, or
 (at your option) any later version.

 GLC-lib 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 General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with GLC-lib; if not, write to the Free Software
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

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

//! \file glc_light.cpp implementation of the GLC_Light class.

#include <QtDebug>
#include "glc_light.h"
#include "glc_openglexception.h"

//////////////////////////////////////////////////////////////////////
// Constructor Destructor
//////////////////////////////////////////////////////////////////////
GLC_Light::GLC_Light()
:GLC_Object("Light")
, m_LightID(GL_LIGHT1)	// Default Light ID
, m_ListID(0)			// By default display list ID= 0
, m_ListIsValid(false)	// By default display list is not valid
, m_AmbientColor(Qt::black)		// By default diffuse color is set to black
, m_DiffuseColor(Qt::white)		// By default diffuse color is set to white
, m_SpecularColor(Qt::white)	// By default specular color is set to white
, m_Position()
{
	//! \todo modify class to support multi light
}

GLC_Light::GLC_Light(const QColor& color)
:GLC_Object("Light")
, m_LightID(GL_LIGHT1)	// Default Light ID
, m_ListID(0)			// By default display list ID= 0
, m_ListIsValid(false)	// By default display list is not valid
, m_AmbientColor(Qt::black)		// By default diffuse color is set to black
, m_DiffuseColor(color)			// Diffuse color is set to color
, m_SpecularColor(Qt::white)	// By default specular color is set to white
, m_Position()
{
	//! \todo modify class to support multi light
}

GLC_Light::~GLC_Light(void)
{
	deleteList();
}

/////////////////////////////////////////////////////////////////////
// Set Functions
//////////////////////////////////////////////////////////////////////

// Set the lihgt position by a 4D vector
void GLC_Light::setPosition(const GLC_Vector4d &vectPos)
{
	m_Position= vectPos;
	m_ListIsValid = false;
}

// Set the lihgt position by a 3 GLfloat
void GLC_Light::setPosition(GLfloat x, GLfloat y, GLfloat z)
{
	m_Position.setX(x);
	m_Position.setY(y);
	m_Position.setZ(z);
	m_ListIsValid = false;
}

// Set light's ambiant color by a QColor
void GLC_Light::setAmbientColor(const QColor& color)
{
	m_AmbientColor= color;
	m_ListIsValid = false;
}

// Set light's diffuse color by a QColor
void GLC_Light::setDiffuseColor(const QColor& color)
{
	m_DiffuseColor= color;
	m_ListIsValid = false;
}

// Set light's specular color by a QColor
void GLC_Light::setSpecularColor(const QColor& color)
{
	m_SpecularColor= color;
	m_ListIsValid = false;
}

//////////////////////////////////////////////////////////////////////
// OpenGL Functions
//////////////////////////////////////////////////////////////////////

// Create light's OpenGL list
void GLC_Light::creationList(GLenum Mode)
{
	if(!m_ListID)		// OpenGL list not created
	{
		m_ListID= glGenLists(1);

		if (!m_ListID)	// OpenGL List Id not get
		{
			glDraw();
			qDebug("GLC_Lumiere::CreationListe Display list not create");
		}
	}
	// OpenGL list creation and execution
	glNewList(m_ListID, Mode);

	// Light execution
	glDraw();

	glEndList();

	// Indicateur de la validit de la liste
	m_ListIsValid= true;

	// OpenGL error handler
	GLenum error= glGetError();
	if (error != GL_NO_ERROR)
	{
		GLC_OpenGlException OpenGlException("GLC_Light::CreationList ", error);
		throw(OpenGlException);
	}
}

// Execute OpenGL light
void GLC_Light::glExecute(GLenum Mode)
{
	// Object Name
	glLoadName(getID());

	if (!m_ListIsValid)
	{
		// OpenGL list is not valid

		creationList(Mode);
	}
	else
	{
		glCallList(m_ListID);
	}

	// OpenGL error handler
	GLenum error= glGetError();
	if (error != GL_NO_ERROR)
	{
		GLC_OpenGlException OpenGlException("GLC_Light::GlExecute ", error);
		throw(OpenGlException);
	}

}

// OpenGL light set up
void GLC_Light::glDraw(void)
{
	// Color
	GLfloat setArray[4]= {static_cast<GLfloat>(m_AmbientColor.redF()),
									static_cast<GLfloat>(m_AmbientColor.greenF()),
									static_cast<GLfloat>(m_AmbientColor.blueF()),
									static_cast<GLfloat>(m_AmbientColor.alphaF())};
	glLightfv(m_LightID, GL_AMBIENT, setArray);		// Setup The Ambient Light

	setArray[0]= static_cast<GLfloat>(m_DiffuseColor.redF());
	setArray[1]= static_cast<GLfloat>(m_DiffuseColor.greenF());
	setArray[2]= static_cast<GLfloat>(m_DiffuseColor.blueF());
	setArray[3]= static_cast<GLfloat>(m_DiffuseColor.alphaF());
	glLightfv(m_LightID, GL_DIFFUSE, setArray);		// Setup The Diffuse Light

	setArray[0]= static_cast<GLfloat>(m_SpecularColor.redF());
	setArray[1]= static_cast<GLfloat>(m_SpecularColor.greenF());
	setArray[2]= static_cast<GLfloat>(m_SpecularColor.blueF());
	setArray[3]= static_cast<GLfloat>(m_SpecularColor.alphaF());
	glLightfv(m_LightID, GL_SPECULAR, setArray);	// Setup The specular Light

	// Position
	setArray[0]= static_cast<GLfloat>(m_Position.getX());
	setArray[1]= static_cast<GLfloat>(m_Position.getY());
	setArray[2]= static_cast<GLfloat>(m_Position.getZ());
	setArray[3]= static_cast<GLfloat>(m_Position.getW());

	glLightfv(m_LightID, GL_POSITION, setArray);	// Position The Light

	// OpenGL error handler
	GLenum error= glGetError();
	if (error != GL_NO_ERROR)
	{
		GLC_OpenGlException OpenGlException("GLC_Light::GlDraw ", error);
		throw(OpenGlException);
	}

}

//////////////////////////////////////////////////////////////////////
// Private services Functions
//////////////////////////////////////////////////////////////////////

// Delete OpenGL Display list
void GLC_Light::deleteList(void)
{
	//! if the list is valid, the list is deleted
	if (glIsList(m_ListID))
	{
		glDeleteLists(m_ListID, 1);
	}
}
<|endoftext|>


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

#include "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"

#if defined(TOOLKIT_VIEWS)
#define MAYBE_Infobars Infobars
#else
// Need to finish port to Linux. See http://crbug.com/39916 for details.
// Temporarily marked as DISABLED on OSX too. See http://crbug.com/60990 for details.
#define MAYBE_Infobars DISABLED_Infobars
#endif

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Infobars) {
  // TODO(finnur): Remove once infobars are no longer experimental (bug 39511).
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

  ASSERT_TRUE(RunExtensionTest("infobars")) << message_;
}
<commit_msg>Marking ExtensionApiTest, Infobars as DISABLED on everything but Windows.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"

#if defined(OS_WIN)
#define MAYBE_Infobars Infobars
#else
// Need to finish port to Linux. See http://crbug.com/39916 for details.
// Temporarily marked as DISABLED on OSX too. See http://crbug.com/60990 for details.
#define MAYBE_Infobars DISABLED_Infobars
#endif

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Infobars) {
  // TODO(finnur): Remove once infobars are no longer experimental (bug 39511).
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

  ASSERT_TRUE(RunExtensionTest("infobars")) << message_;
}
<|endoftext|>


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

#include "chrome/browser/safe_browsing/safe_browsing_database.h"

#include "base/file_util.h"
#include "base/logging.h"
#include "base/sha2.h"
#include "chrome/browser/safe_browsing/safe_browsing_database_impl.h"
#include "chrome/browser/safe_browsing/safe_browsing_database_bloom.h"
#include "googleurl/src/gurl.h"

// Filename suffix for the bloom filter.
static const wchar_t kBloomFilterFile[] = L" Filter";

// Factory method.
SafeBrowsingDatabase* SafeBrowsingDatabase::Create() {
  return new SafeBrowsingDatabaseImpl;
}

bool SafeBrowsingDatabase::NeedToCheckUrl(const GURL& url) {
  if (!bloom_filter_.get())
    return true;

  IncrementBloomFilterReadCount();

  std::vector<std::string> hosts;
  safe_browsing_util::GenerateHostsToCheck(url, &hosts);
  if (hosts.size() == 0)
    return false;  // Could be about:blank.

  SBPrefix host_key;
  if (url.HostIsIPAddress()) {
    base::SHA256HashString(url.host() + "/", &host_key, sizeof(SBPrefix));
    if (bloom_filter_->Exists(host_key))
      return true;
  } else {
    base::SHA256HashString(hosts[0] + "/", &host_key, sizeof(SBPrefix));
    if (bloom_filter_->Exists(host_key))
      return true;

    if (hosts.size() > 1) {
      base::SHA256HashString(hosts[1] + "/", &host_key, sizeof(SBPrefix));
      if (bloom_filter_->Exists(host_key))
        return true;
    }
  }
  return false;
}

std::wstring SafeBrowsingDatabase::BloomFilterFilename(
    const std::wstring& db_filename) {
  return db_filename + kBloomFilterFile;
}

void SafeBrowsingDatabase::LoadBloomFilter() {
  DCHECK(!bloom_filter_filename_.empty());

  int64 size_64;
  if (!file_util::GetFileSize(bloom_filter_filename_, &size_64) ||
      size_64 == 0) {
    BuildBloomFilter();
    return;
  }

  int size = static_cast<int>(size_64);
  char* data = new char[size];
  CHECK(data);

  Time before = Time::Now();
  file_util::ReadFile(bloom_filter_filename_, data, size);
  SB_DLOG(INFO) << "SafeBrowsingDatabase read bloom filter in " <<
        (Time::Now() - before).InMilliseconds() << " ms";

  bloom_filter_.reset(new BloomFilter(data, size));
}

void SafeBrowsingDatabase::DeleteBloomFilter() {
  file_util::Delete(bloom_filter_filename_, false);
}

void SafeBrowsingDatabase::WriteBloomFilter() {
  if (!bloom_filter_.get())
    return;

  Time before = Time::Now();
  file_util::WriteFile(bloom_filter_filename_,
                       bloom_filter_->data(),
                       bloom_filter_->size());
  SB_DLOG(INFO) << "SafeBrowsingDatabase wrote bloom filter in " <<
      (Time::Now() - before).InMilliseconds() << " ms";
}

<commit_msg>Provide an option to turn on the new SafeBrowsing storage system via a command line flag ("--new-safe-browsing").<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/safe_browsing/safe_browsing_database.h"

#include "base/command_line.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/sha2.h"
#include "chrome/browser/safe_browsing/safe_browsing_database_impl.h"
#include "chrome/browser/safe_browsing/safe_browsing_database_bloom.h"
#include "chrome/common/chrome_switches.h"
#include "googleurl/src/gurl.h"

// Filename suffix for the bloom filter.
static const wchar_t kBloomFilterFile[] = L" Filter";

// Factory method.
SafeBrowsingDatabase* SafeBrowsingDatabase::Create() {
  if (CommandLine().HasSwitch(switches::kUseNewSafeBrowsing))
    return new SafeBrowsingDatabaseBloom;
  return new SafeBrowsingDatabaseImpl;
}

bool SafeBrowsingDatabase::NeedToCheckUrl(const GURL& url) {
  if (!bloom_filter_.get())
    return true;

  IncrementBloomFilterReadCount();

  std::vector<std::string> hosts;
  safe_browsing_util::GenerateHostsToCheck(url, &hosts);
  if (hosts.size() == 0)
    return false;  // Could be about:blank.

  SBPrefix host_key;
  if (url.HostIsIPAddress()) {
    base::SHA256HashString(url.host() + "/", &host_key, sizeof(SBPrefix));
    if (bloom_filter_->Exists(host_key))
      return true;
  } else {
    base::SHA256HashString(hosts[0] + "/", &host_key, sizeof(SBPrefix));
    if (bloom_filter_->Exists(host_key))
      return true;

    if (hosts.size() > 1) {
      base::SHA256HashString(hosts[1] + "/", &host_key, sizeof(SBPrefix));
      if (bloom_filter_->Exists(host_key))
        return true;
    }
  }
  return false;
}

std::wstring SafeBrowsingDatabase::BloomFilterFilename(
    const std::wstring& db_filename) {
  return db_filename + kBloomFilterFile;
}

void SafeBrowsingDatabase::LoadBloomFilter() {
  DCHECK(!bloom_filter_filename_.empty());

  int64 size_64;
  if (!file_util::GetFileSize(bloom_filter_filename_, &size_64) ||
      size_64 == 0) {
    BuildBloomFilter();
    return;
  }

  int size = static_cast<int>(size_64);
  char* data = new char[size];
  CHECK(data);

  Time before = Time::Now();
  file_util::ReadFile(bloom_filter_filename_, data, size);
  SB_DLOG(INFO) << "SafeBrowsingDatabase read bloom filter in " <<
        (Time::Now() - before).InMilliseconds() << " ms";

  bloom_filter_.reset(new BloomFilter(data, size));
}

void SafeBrowsingDatabase::DeleteBloomFilter() {
  file_util::Delete(bloom_filter_filename_, false);
}

void SafeBrowsingDatabase::WriteBloomFilter() {
  if (!bloom_filter_.get())
    return;

  Time before = Time::Now();
  file_util::WriteFile(bloom_filter_filename_,
                       bloom_filter_->data(),
                       bloom_filter_->size());
  SB_DLOG(INFO) << "SafeBrowsingDatabase wrote bloom filter in " <<
      (Time::Now() - before).InMilliseconds() << " ms";
}

<|endoftext|>


<commit_before>/*
Copyright (c) 2015 - present Advanced Micro Devices, Inc. All rights reserved.

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.
*/

#include <hip/hip_runtime.h>

#include "hip_internal.hpp"

hipError_t hipMalloc(void** ptr, size_t sizeBytes)
{
    HIP_INIT_API(ptr, sizeBytes);

    amd::Context* context = as_amd(g_currentCtx);

    if (sizeBytes == 0) {
        *ptr = nullptr;
        return hipSuccess;
    }
    else if (!is_valid(context) || !ptr) {
        return hipErrorInvalidValue;
    }

    auto deviceHandle = as_amd(g_deviceArray[0]);
    if ((deviceHandle->info().maxMemAllocSize_ < size)) {
        return hipErrorOutOfMemory;
    }

    amd::Memory* mem = new (*context) amd::Buffer(*context, 0, sizeBytes);
    if (!mem) {
        return hipErrorOutOfMemory;
    }

    if (!mem->create(nullptr)) {
        return hipErrorMemoryAllocation;
    }

    *ptr = reinterpret_cast<void*>(as_cl(mem));

    return hipSuccess;
}

hipError_t hipFree(void* ptr)
{
    if (!is_valid(reinterpret_cast<cl_mem>(ptr))) {
        return hipErrorInvalidValue;
    }
    as_amd(reinterpret_cast<cl_mem>(ptr))->release();
    return hipSuccess;
}

<commit_msg>P4 to Git Change 1516173 by skudchad@skudchad_rocm on 2018/02/14 15:02:45<commit_after>/*
Copyright (c) 2015 - present Advanced Micro Devices, Inc. All rights reserved.

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.
*/

#include <hip/hip_runtime.h>

#include "hip_internal.hpp"

hipError_t hipMalloc(void** ptr, size_t sizeBytes)
{
    HIP_INIT_API(ptr, sizeBytes);

    amd::Context* context = as_amd(g_currentCtx);

    if (sizeBytes == 0) {
        *ptr = nullptr;
        return hipSuccess;
    }
    else if (!is_valid(context) || !ptr) {
        return hipErrorInvalidValue;
    }

    auto deviceHandle = as_amd(g_deviceArray[0]);
    if ((deviceHandle->info().maxMemAllocSize_ < size)) {
        return hipErrorOutOfMemory;
    }

    amd::Memory* mem = new (*context) amd::Buffer(*context, 0, sizeBytes);
    if (!mem) {
        return hipErrorOutOfMemory;
    }

    if (!mem->create(nullptr)) {
        return hipErrorMemoryAllocation;
    }

    *ptr = reinterpret_cast<void*>(as_cl(mem));

    return hipSuccess;
}

hipError_t hipFree(void* ptr)
{
    if (!is_valid(reinterpret_cast<cl_mem>(ptr))) {
        return hipErrorInvalidValue;
    }
    as_amd(reinterpret_cast<cl_mem>(ptr))->release();
    return hipSuccess;
}

hipError_t hipMemcpy(void* dst, const void* src, size_t sizeBytes, hipMemcpyKind kind)
{
    HIP_INIT_API(dst, src, sizeBytes, kind);

    amd::Context* context = as_amd(g_currentCtx);
    amd::Device* device = context->devices()[0];

    // FIXME : Do we create a queue here or create at init and just reuse
    amd::HostQueue* queue = new amd::HostQueue(*context, *device, 0,
                                                amd::CommandQueue::RealTimeDisabled,
                                                amd::CommandQueue::Priority::Normal);
    if (!queue) {
        return hipErrorOutOfMemory;
    }

    amd::Buffer* srcBuffer = as_amd(reinterpret_cast<cl_mem>(const_cast<void*>(src)))->asBuffer();
    amd::Buffer* dstBuffer = as_amd(reinterpret_cast<cl_mem>(const_cast<void*>(dst)))->asBuffer();

    amd::Command* command;
    amd::Command::EventWaitList waitList;

    switch (kind) {
    case hipMemcpyDeviceToHost:
    command = new amd::ReadMemoryCommand(*queue, CL_COMMAND_READ_BUFFER, waitList,
        srcBuffer, 0, sizeBytes, dst);
    break;
    case hipMemcpyHostToDevice:
    command = new amd::WriteMemoryCommand(*queue, CL_COMMAND_WRITE_BUFFER, waitList,
        dstBuffer, 0, sizeBytes, src);
    break;
    default:
        assert(!"Shouldn't reach here");
    break;
    }
    if (!command) {
        return hipErrorOutOfMemory;
    }

    // Make sure we have memory for the command execution
    if (CL_SUCCESS != command->validateMemory()) {
        delete command;
        return hipErrorMemoryAllocation;
    }

    command->enqueue();
    command->awaitCompletion();
    command->release();

    queue->release();

    return hipSuccess;
}

<|endoftext|>


<commit_before>// This file is part of Poseidon.
// Copyleft 2020, LH_Mouse. All wrongs reserved.

#ifndef POSEIDON_HTTP_ENUMS_HPP_
#define POSEIDON_HTTP_ENUMS_HPP_

#include "../fwd.hpp"

namespace poseidon {

// These are HTTP version numbers.
// At the moment only 1.0 and 1.1 are supported.
enum HTTP_Version : uint16_t
  {
    http_version_0_0  =      0,
    http_version_1_0  = 0x0100,  // HTTP/1.0
    http_version_1_1  = 0x0101,  // HTTP/1.1
  };

// Converts an HTTP version to a string such as `HTTP/1.1`.
ROCKET_CONST_FUNCTION
const char*
format_http_version(HTTP_Version ver)
  noexcept;

// Parses a version number from plain text.
// `http_version_0_0` is returned if the string is not valid.
ROCKET_PURE_FUNCTION
HTTP_Version
parse_http_version(const char* bptr, const char* eptr)
  noexcept;

// These are HTTP methods a.k.a. verbs.
enum HTTP_Method : uint8_t
  {
    http_method_null     = 0,
    http_method_get      = 1,
    http_method_head     = 2,
    http_method_post     = 3,
    http_method_put      = 4,
    http_method_delete   = 5,
    http_method_connect  = 6,
    http_method_options  = 7,
    http_method_trace    = 8,
  };

// Converts an HTTP method to a string such as `GET`.
// If the method is invalid, the invalid string `NULL` is returned.
ROCKET_CONST_FUNCTION
const char*
format_http_method(HTTP_Method method)
  noexcept;

// Parses a method from plain text.
// `http_method_null` is returned if the string is not valid.
ROCKET_PURE_FUNCTION
HTTP_Method
parse_http_method(const char* bptr, const char* eptr)
  noexcept;

// These are HTTP status codes.
// This list is not exhaustive. Custom values may be used.
enum HTTP_Status : uint16_t
  {
    http_status_null                    =   0,  // Null
    http_status_class_information       = 100,
    http_status_continue                = 100,  // Continue
    http_status_switching_protocol      = 101,  // Switching Protocol
    http_status_processing              = 102,  // Processing
    http_status_early_hints             = 103,  // Early Hints
    http_status_class_success           = 200,
    http_status_ok                      = 200,  // OK
    http_status_created                 = 201,  // Created
    http_status_accepted                = 202,  // Accepted
    http_status_nonauthoritative        = 203,  // Non-authoritative Information
    http_status_no_content              = 204,  // No Content
    http_status_reset_content           = 205,  // Reset Content
    http_status_partial_content         = 206,  // Partial Content
    http_status_multistatus             = 207,  // Multi-status
    http_status_already_reported        = 208,  // Already Reported
    http_status_im_used                 = 226,  // IM Used
    http_status_connection_established  = 299,  // Connection Established [x]
    http_status_class_redirection       = 300,
    http_status_multiple_choice         = 300,  // Multiple Choice
    http_status_moved_permanently       = 301,  // Moved Permanently
    http_status_found                   = 302,  // Found
    http_status_see_other               = 303,  // See Other
    http_status_not_modified            = 304,  // Not Modified
    http_status_use_proxy               = 305,  // Use Proxy
    http_status_temporary_redirect      = 307,  // Temporary Redirect
    http_status_permanent_redirect      = 308,  // Permanent Redirect
    http_status_class_client_error      = 400,
    http_status_bad_request             = 400,  // Bad Request
    http_status_unauthorized            = 401,  // Unauthorized
    http_status_forbidden               = 403,  // Forbidden
    http_status_not_found               = 404,  // Not Found
    http_status_method_not_allowed      = 405,  // Method Not Allowed
    http_status_not_acceptable          = 406,  // Not Acceptable
    http_status_proxy_unauthorized      = 407,  // Proxy Authentication Required
    http_status_request_timeout         = 408,  // Request Timeout
    http_status_conflict                = 409,  // Conflict
    http_status_gone                    = 410,  // Gone
    http_status_length_required         = 411,  // Length Required
    http_status_precondition_failed     = 412,  // Precondition Failed
    http_status_payload_too_large       = 413,  // Payload Too Large
    http_status_uri_too_long            = 414,  // URI Too Long
    http_status_unsupported_media_type  = 415,  // Unsupported Media Type
    http_status_range_not_satisfiable   = 416,  // Range Not Satisfiable
    http_status_expectation_failed      = 417,  // Expectation Failed
    http_status_misdirected_request     = 421,  // Misdirected Request
    http_status_unprocessable_entity    = 422,  // Unprocessable Entity
    http_status_locked                  = 423,  // Locked
    http_status_failed_dependency       = 424,  // Failed Dependency
    http_status_too_early               = 425,  // Too Early
    http_status_upgrade_required        = 426,  // Upgrade Required
    http_status_precondition_required   = 428,  // Precondition Required
    http_status_too_many_requests       = 429,  // Too Many Requests
    http_status_headers_too_large       = 431,  // Request Header Fields Too Large
    http_status_class_server_error      = 500,
    http_status_internal_server_error   = 500,  // Internal Server Error
    http_status_not_implemented         = 501,  // Not Implemented
    http_status_bad_gateway             = 502,  // Bad Gateway
    http_status_service_unavailable     = 503,  // Service Unavailable
    http_status_gateway_timeout         = 504,  // Gateway Timeout
    http_status_version_not_supported   = 505,  // HTTP Version Not Supported
    http_status_insufficient_storage    = 507,  // Insufficient Storage
    http_status_loop_detected           = 508,  // Loop Detected
    http_status_not_extended            = 510,  // Not Extended
    http_status_network_unauthorized    = 511,  // Network Authentication Required
  };

// Converts an HTTP status code to a string such as `Bad Request`.
// If the status code is unknown, `Unknown Status` is returned.
ROCKET_CONST_FUNCTION
const char*
describe_http_status(HTTP_Status stat)
  noexcept;

// Classifies a status code.
constexpr
HTTP_Status
classify_http_status(HTTP_Status stat)
  noexcept
  { return static_cast<HTTP_Status>(static_cast<uint32_t>(stat) / 100 * 100);  }

// These are values for `Connection:` headers.
enum HTTP_Connection : uint8_t
  {
    http_connection_keep_alive  = 0,
    http_connection_close       = 1,
    http_connection_upgrade     = 2,  // special value for pending upgrades
    http_connection_tunnel      = 3,  // special value for CONNECT method
    http_connection_websocket   = 4,  // WebSocket
  };

// These are WebSocket opcodes.
// This list is exhaustive according to RFC 6455.
enum WebSocket_Opcode : uint8_t
  {
    websocket_opcode_class_data     = 0b0000,
    websocket_opcode_continuation   = 0b0000,
    websocket_opcode_text           = 0b0001,
    websocket_opcode_binary         = 0b0010,
    websocket_opcode_class_control  = 0b1000,
    websocket_opcode_close          = 0b1000,
    websocket_opcode_ping           = 0b1001,
    websocket_opcode_pong           = 0b1010,
  };

// Classifies an opcode.
constexpr
WebSocket_Opcode
classify_websocket_opcode(WebSocket_Opcode opcode)
  noexcept
  { return static_cast<WebSocket_Opcode>(opcode & 0b1000);  }

// These are WebSocket status codes.
// This list is not exhaustive. Custom values may be used.
enum WebSocket_Status : uint16_t
  {
    websocket_status_null                =    0,
    websocket_status_class_rfc6455       = 1000,
    websocket_status_normal_closure      = 1000,
    websocket_status_going_away          = 1001,
    websocket_status_protocol_error      = 1002,
    websocket_status_not_acceptable      = 1003,
    websocket_status_no_status           = 1005,  // reserved
    websocket_status_abnormal            = 1006,  // reserved
    websocket_status_data_error          = 1007,
    websocket_status_forbidden           = 1008,
    websocket_status_too_large           = 1009,
    websocket_status_extension_required  = 1010,  // reserved
    websocket_status_server_error        = 1011,
    websocket_status_tls_error           = 1015,  // reserved
    websocket_status_class_iana          = 3000,
    websocket_status_class_private_use   = 4000,
  };

// Classifies a status code.
constexpr
WebSocket_Status
classify_websocket_status(WebSocket_Status stat)
  noexcept
  {
    uint32_t cls = static_cast<uint32_t>(stat) / 1000 * 1000;
    return (cls == 2000) ? websocket_status_class_rfc6455
                         : static_cast<WebSocket_Status>(cls);
  }

}  // namespace poseidon

#endif
<commit_msg>http/enums: Update `HTTP_Connection`<commit_after>// This file is part of Poseidon.
// Copyleft 2020, LH_Mouse. All wrongs reserved.

#ifndef POSEIDON_HTTP_ENUMS_HPP_
#define POSEIDON_HTTP_ENUMS_HPP_

#include "../fwd.hpp"

namespace poseidon {

// These are HTTP version numbers.
// At the moment only 1.0 and 1.1 are supported.
enum HTTP_Version : uint16_t
  {
    http_version_0_0  =      0,
    http_version_1_0  = 0x0100,  // HTTP/1.0
    http_version_1_1  = 0x0101,  // HTTP/1.1
  };

// Converts an HTTP version to a string such as `HTTP/1.1`.
ROCKET_CONST_FUNCTION
const char*
format_http_version(HTTP_Version ver)
  noexcept;

// Parses a version number from plain text.
// `http_version_0_0` is returned if the string is not valid.
ROCKET_PURE_FUNCTION
HTTP_Version
parse_http_version(const char* bptr, const char* eptr)
  noexcept;

// These are HTTP methods a.k.a. verbs.
enum HTTP_Method : uint8_t
  {
    http_method_null     = 0,
    http_method_get      = 1,
    http_method_head     = 2,
    http_method_post     = 3,
    http_method_put      = 4,
    http_method_delete   = 5,
    http_method_connect  = 6,
    http_method_options  = 7,
    http_method_trace    = 8,
  };

// Converts an HTTP method to a string such as `GET`.
// If the method is invalid, the invalid string `NULL` is returned.
ROCKET_CONST_FUNCTION
const char*
format_http_method(HTTP_Method method)
  noexcept;

// Parses a method from plain text.
// `http_method_null` is returned if the string is not valid.
ROCKET_PURE_FUNCTION
HTTP_Method
parse_http_method(const char* bptr, const char* eptr)
  noexcept;

// These are HTTP status codes.
// This list is not exhaustive. Custom values may be used.
enum HTTP_Status : uint16_t
  {
    http_status_null                    =   0,  // Null
    http_status_class_information       = 100,
    http_status_continue                = 100,  // Continue
    http_status_switching_protocol      = 101,  // Switching Protocol
    http_status_processing              = 102,  // Processing
    http_status_early_hints             = 103,  // Early Hints
    http_status_class_success           = 200,
    http_status_ok                      = 200,  // OK
    http_status_created                 = 201,  // Created
    http_status_accepted                = 202,  // Accepted
    http_status_nonauthoritative        = 203,  // Non-authoritative Information
    http_status_no_content              = 204,  // No Content
    http_status_reset_content           = 205,  // Reset Content
    http_status_partial_content         = 206,  // Partial Content
    http_status_multistatus             = 207,  // Multi-status
    http_status_already_reported        = 208,  // Already Reported
    http_status_im_used                 = 226,  // IM Used
    http_status_connection_established  = 299,  // Connection Established [x]
    http_status_class_redirection       = 300,
    http_status_multiple_choice         = 300,  // Multiple Choice
    http_status_moved_permanently       = 301,  // Moved Permanently
    http_status_found                   = 302,  // Found
    http_status_see_other               = 303,  // See Other
    http_status_not_modified            = 304,  // Not Modified
    http_status_use_proxy               = 305,  // Use Proxy
    http_status_temporary_redirect      = 307,  // Temporary Redirect
    http_status_permanent_redirect      = 308,  // Permanent Redirect
    http_status_class_client_error      = 400,
    http_status_bad_request             = 400,  // Bad Request
    http_status_unauthorized            = 401,  // Unauthorized
    http_status_forbidden               = 403,  // Forbidden
    http_status_not_found               = 404,  // Not Found
    http_status_method_not_allowed      = 405,  // Method Not Allowed
    http_status_not_acceptable          = 406,  // Not Acceptable
    http_status_proxy_unauthorized      = 407,  // Proxy Authentication Required
    http_status_request_timeout         = 408,  // Request Timeout
    http_status_conflict                = 409,  // Conflict
    http_status_gone                    = 410,  // Gone
    http_status_length_required         = 411,  // Length Required
    http_status_precondition_failed     = 412,  // Precondition Failed
    http_status_payload_too_large       = 413,  // Payload Too Large
    http_status_uri_too_long            = 414,  // URI Too Long
    http_status_unsupported_media_type  = 415,  // Unsupported Media Type
    http_status_range_not_satisfiable   = 416,  // Range Not Satisfiable
    http_status_expectation_failed      = 417,  // Expectation Failed
    http_status_misdirected_request     = 421,  // Misdirected Request
    http_status_unprocessable_entity    = 422,  // Unprocessable Entity
    http_status_locked                  = 423,  // Locked
    http_status_failed_dependency       = 424,  // Failed Dependency
    http_status_too_early               = 425,  // Too Early
    http_status_upgrade_required        = 426,  // Upgrade Required
    http_status_precondition_required   = 428,  // Precondition Required
    http_status_too_many_requests       = 429,  // Too Many Requests
    http_status_headers_too_large       = 431,  // Request Header Fields Too Large
    http_status_class_server_error      = 500,
    http_status_internal_server_error   = 500,  // Internal Server Error
    http_status_not_implemented         = 501,  // Not Implemented
    http_status_bad_gateway             = 502,  // Bad Gateway
    http_status_service_unavailable     = 503,  // Service Unavailable
    http_status_gateway_timeout         = 504,  // Gateway Timeout
    http_status_version_not_supported   = 505,  // HTTP Version Not Supported
    http_status_insufficient_storage    = 507,  // Insufficient Storage
    http_status_loop_detected           = 508,  // Loop Detected
    http_status_not_extended            = 510,  // Not Extended
    http_status_network_unauthorized    = 511,  // Network Authentication Required
  };

// Converts an HTTP status code to a string such as `Bad Request`.
// If the status code is unknown, `Unknown Status` is returned.
ROCKET_CONST_FUNCTION
const char*
describe_http_status(HTTP_Status stat)
  noexcept;

// Classifies a status code.
constexpr
HTTP_Status
classify_http_status(HTTP_Status stat)
  noexcept
  { return static_cast<HTTP_Status>(static_cast<uint32_t>(stat) / 100 * 100);  }

// These were designed for various options in the `Connection:` header, but
// now they denote [ method + connection + upgrade ] combinations.
enum HTTP_Connection : uint8_t
  {
    http_connection_keep_alive  = 0,
    http_connection_connect     = 1,  // special value for CONNECT method
    http_connection_head        = 2,  // special value for HEAD method
    http_connection_close       = 3,
    http_connection_upgrade     = 4,  // special value for pending upgrades
    http_connection_websocket   = 5,  // WebSocket
  };

// These are WebSocket opcodes.
// This list is exhaustive according to RFC 6455.
enum WebSocket_Opcode : uint8_t
  {
    websocket_opcode_class_data     = 0b0000,
    websocket_opcode_continuation   = 0b0000,
    websocket_opcode_text           = 0b0001,
    websocket_opcode_binary         = 0b0010,
    websocket_opcode_class_control  = 0b1000,
    websocket_opcode_close          = 0b1000,
    websocket_opcode_ping           = 0b1001,
    websocket_opcode_pong           = 0b1010,
  };

// Classifies an opcode.
constexpr
WebSocket_Opcode
classify_websocket_opcode(WebSocket_Opcode opcode)
  noexcept
  { return static_cast<WebSocket_Opcode>(opcode & 0b1000);  }

// These are WebSocket status codes.
// This list is not exhaustive. Custom values may be used.
enum WebSocket_Status : uint16_t
  {
    websocket_status_null                =    0,
    websocket_status_class_rfc6455       = 1000,
    websocket_status_normal_closure      = 1000,
    websocket_status_going_away          = 1001,
    websocket_status_protocol_error      = 1002,
    websocket_status_not_acceptable      = 1003,
    websocket_status_no_status           = 1005,  // reserved
    websocket_status_abnormal            = 1006,  // reserved
    websocket_status_data_error          = 1007,
    websocket_status_forbidden           = 1008,
    websocket_status_too_large           = 1009,
    websocket_status_extension_required  = 1010,  // reserved
    websocket_status_server_error        = 1011,
    websocket_status_tls_error           = 1015,  // reserved
    websocket_status_class_iana          = 3000,
    websocket_status_class_private_use   = 4000,
  };

// Classifies a status code.
constexpr
WebSocket_Status
classify_websocket_status(WebSocket_Status stat)
  noexcept
  {
    uint32_t cls = static_cast<uint32_t>(stat) / 1000 * 1000;
    return (cls == 2000) ? websocket_status_class_rfc6455
                         : static_cast<WebSocket_Status>(cls);
  }

}  // namespace poseidon

#endif
<|endoftext|>


<commit_before>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2011, John Haddon. All rights reserved.
//  Copyright (c) 2011-2013, Image Engine Design Inc. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are
//  met:
//
//      * Redistributions of source code must retain the above
//        copyright notice, this list of conditions and the following
//        disclaimer.
//
//      * Redistributions in binary form must reproduce the above
//        copyright notice, this list of conditions and the following
//        disclaimer in the documentation and/or other materials provided with
//        the distribution.
//
//      * Neither the name of John Haddon nor the names of
//        any other contributors to this software may be used to endorse or
//        promote products derived from this software without specific prior
//        written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT OWNER 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 "boost/python.hpp"

#include <fstream>

#include "boost/filesystem.hpp"

#include "IECorePython/ScopedGILLock.h"
#include "IECorePython/RunTimeTypedBinding.h"
#include "IECorePython/Wrapper.h"

#include "Gaffer/ApplicationRoot.h"
#include "Gaffer/CompoundPlug.h"
#include "Gaffer/Preferences.h"

#include "GafferBindings/ApplicationRootBinding.h"
#include "GafferBindings/Serialisation.h"
#include "GafferBindings/ValuePlugBinding.h"

using namespace boost::python;
using namespace GafferBindings;
using namespace Gaffer;

class ApplicationRootWrapper : public ApplicationRoot, public IECorePython::Wrapper<ApplicationRoot>
{

	public :

		ApplicationRootWrapper( PyObject *self, const std::string &name = staticTypeName() )
			:	ApplicationRoot( name ), IECorePython::Wrapper<ApplicationRoot>( self, this )
		{
		}

		virtual void savePreferences( const std::string &fileName ) const
		{
			IECorePython::ScopedGILLock gilLock;

			// serialise everything
			Serialisation s( preferences(), "application.root()[\"preferences\"]" );

			// make the directory for the preferences file if it doesn't exist yet
			boost::filesystem::path path( fileName );
			path.remove_filename();
			boost::filesystem::create_directories( path );

			// then make the file and write the serialisation into it
			std::ofstream f;
			f.open( fileName.c_str() );
			if( !f.is_open() )
			{
				throw IECore::Exception( "Unable to open file \"" + fileName + "\"" );
			}

			f << "# This file was automatically generated by Gaffer.\n";
			f << "# Do not edit this file - it will be overwritten.\n\n";
			f << s.result() << std::endl;

			if( !f.good() )
			{
				throw IECore::Exception( "Error while writing file \"" + fileName + "\"" );
			}
		}

};

IE_CORE_DECLAREPTR( ApplicationRootWrapper )

static IECore::ObjectPtr getClipboardContents( ApplicationRoot &a )
{
	IECore::ConstObjectPtr o = a.getClipboardContents();
	if( o )
	{
		return o->copy();
	}
	return 0;
}

void GafferBindings::bindApplicationRoot()
{
	IECorePython::RunTimeTypedClass<ApplicationRoot, ApplicationRootWrapperPtr>()
		.def( init<>() )
		.def( init<const std::string &>() )
		.def( "getClipboardContents", &getClipboardContents )
		.def( "setClipboardContents", &ApplicationRoot::setClipboardContents )
		.def( "savePreferences", (void (ApplicationRoot::*)()const)&ApplicationRoot::savePreferences )
		.def( "savePreferences", (void (ApplicationRoot::*)( const std::string & )const)&ApplicationRoot::savePreferences )
		.def( "preferencesLocation", &ApplicationRoot::preferencesLocation )
	;
}
<commit_msg>Removing unused include.<commit_after>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2011, John Haddon. All rights reserved.
//  Copyright (c) 2011-2013, Image Engine Design Inc. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are
//  met:
//
//      * Redistributions of source code must retain the above
//        copyright notice, this list of conditions and the following
//        disclaimer.
//
//      * Redistributions in binary form must reproduce the above
//        copyright notice, this list of conditions and the following
//        disclaimer in the documentation and/or other materials provided with
//        the distribution.
//
//      * Neither the name of John Haddon nor the names of
//        any other contributors to this software may be used to endorse or
//        promote products derived from this software without specific prior
//        written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT OWNER 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 "boost/python.hpp"

#include <fstream>

#include "boost/filesystem.hpp"

#include "IECorePython/ScopedGILLock.h"
#include "IECorePython/RunTimeTypedBinding.h"
#include "IECorePython/Wrapper.h"

#include "Gaffer/ApplicationRoot.h"
#include "Gaffer/CompoundPlug.h"
#include "Gaffer/Preferences.h"

#include "GafferBindings/ApplicationRootBinding.h"
#include "GafferBindings/Serialisation.h"

using namespace boost::python;
using namespace GafferBindings;
using namespace Gaffer;

class ApplicationRootWrapper : public ApplicationRoot, public IECorePython::Wrapper<ApplicationRoot>
{

	public :

		ApplicationRootWrapper( PyObject *self, const std::string &name = staticTypeName() )
			:	ApplicationRoot( name ), IECorePython::Wrapper<ApplicationRoot>( self, this )
		{
		}

		virtual void savePreferences( const std::string &fileName ) const
		{
			IECorePython::ScopedGILLock gilLock;

			// serialise everything
			Serialisation s( preferences(), "application.root()[\"preferences\"]" );

			// make the directory for the preferences file if it doesn't exist yet
			boost::filesystem::path path( fileName );
			path.remove_filename();
			boost::filesystem::create_directories( path );

			// then make the file and write the serialisation into it
			std::ofstream f;
			f.open( fileName.c_str() );
			if( !f.is_open() )
			{
				throw IECore::Exception( "Unable to open file \"" + fileName + "\"" );
			}

			f << "# This file was automatically generated by Gaffer.\n";
			f << "# Do not edit this file - it will be overwritten.\n\n";
			f << s.result() << std::endl;

			if( !f.good() )
			{
				throw IECore::Exception( "Error while writing file \"" + fileName + "\"" );
			}
		}

};

IE_CORE_DECLAREPTR( ApplicationRootWrapper )

static IECore::ObjectPtr getClipboardContents( ApplicationRoot &a )
{
	IECore::ConstObjectPtr o = a.getClipboardContents();
	if( o )
	{
		return o->copy();
	}
	return 0;
}

void GafferBindings::bindApplicationRoot()
{
	IECorePython::RunTimeTypedClass<ApplicationRoot, ApplicationRootWrapperPtr>()
		.def( init<>() )
		.def( init<const std::string &>() )
		.def( "getClipboardContents", &getClipboardContents )
		.def( "setClipboardContents", &ApplicationRoot::setClipboardContents )
		.def( "savePreferences", (void (ApplicationRoot::*)()const)&ApplicationRoot::savePreferences )
		.def( "savePreferences", (void (ApplicationRoot::*)( const std::string & )const)&ApplicationRoot::savePreferences )
		.def( "preferencesLocation", &ApplicationRoot::preferencesLocation )
	;
}
<|endoftext|>