<commit_before>/*  Sirikata
 *  Meshdata.hpp
 *
 *  Copyright (c) 2010, Daniel B. Miller
 *  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 Sirikata 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 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.
 */

#ifndef _SIRIKATA_MESH_MESHDATA_HPP_
#define _SIRIKATA_MESH_MESHDATA_HPP_

#include <sirikata/mesh/Platform.hpp>
#include <sirikata/core/util/Sha256.hpp>
#include "LightInfo.hpp"
#include <sirikata/core/util/UUID.hpp>
#include <stack>

namespace Sirikata {
namespace Mesh {

// Typedefs for NodeIndices, which refer to scene graph nodes in the model
typedef int32 NodeIndex;
extern SIRIKATA_MESH_EXPORT NodeIndex NullNodeIndex;
typedef std::vector<NodeIndex> NodeIndexList;

typedef std::vector<LightInfo> LightInfoList;
typedef std::vector<std::string> TextureList;

struct SIRIKATA_MESH_EXPORT Meshdata;
typedef std::tr1::shared_ptr<Meshdata> MeshdataPtr;

/** Represents a skinned animation. A skinned animation is directly associated
 *  with a SubMeshGeometry.
 */
struct SIRIKATA_MESH_EXPORT SkinController {
    // Joints for this controls Indexes into the Meshdata.joints array
    // (which indexes into Meshdata.nodes).
    std::vector<uint32> joints;

    Matrix4x4f bindShapeMatrix;
    ///n+1 elements where n is the number of vertices, so that we can do simple subtraction to find out how many joints influence each vertex
    std::vector<unsigned int> weightStartIndices;
    std::vector<float> weights;
    std::vector<unsigned int>jointIndices;
    std::vector<Matrix4x4f> inverseBindMatrices;
};
typedef std::vector<SkinController> SkinControllerList;

struct SIRIKATA_MESH_EXPORT SubMeshGeometry {
    std::string name;
    std::vector<Sirikata::Vector3f> positions;

    std::vector<Sirikata::Vector3f> normals;
    std::vector<Sirikata::Vector3f> tangents;
    std::vector<Sirikata::Vector4f> colors;
    std::vector<unsigned int> influenceStartIndex;//a list of where a given position's joint weights start
    std::vector<unsigned int> jointindices;
    std::vector<float> weights;

    std::vector<Sirikata::Matrix4x4f> inverseBindMatrices;

    struct TextureSet {
        unsigned int stride;
        std::vector<float> uvs;
    };
    std::vector<TextureSet>texUVs;
    struct Primitive {
        std::vector<unsigned short> indices;

        enum PrimitiveType {
            TRIANGLES,
            LINES,
            POINTS,
            LINESTRIPS,
            TRISTRIPS,
            TRIFANS
        }primitiveType;
        typedef size_t MaterialId;
        MaterialId materialId;
    };
    std::vector<Primitive> primitives;

    BoundingBox3f3f aabb;
    double radius;
    void recomputeBounds();

    SkinControllerList skinControllers;

    //used only during simplification
    std::vector< Matrix4x4f  > positionQs;
    uint32 numInstances;
    std::tr1::unordered_map<uint32, std::vector< std::pair<uint32, uint32> > > neighborPrimitives; // maps positionIdx to list of primitiveIdxes
    /////////////////////////////////

    /** Append the given SubMeshGeometry to the end of this one. Use the given
     *  transformation to transform the geometry before adding it.  This is a
     *  useful primitive when trying to merge/simplify geometry.
     */
    void append(const SubMeshGeometry& rhs, const Matrix4x4f& xform);
};
typedef std::vector<SubMeshGeometry> SubMeshGeometryList;

struct SIRIKATA_MESH_EXPORT GeometryInstance {
    typedef std::map<SubMeshGeometry::Primitive::MaterialId,size_t> MaterialBindingMap;
    MaterialBindingMap materialBindingMap;//maps materialIndex to offset in Meshdata's materials
    unsigned int geometryIndex; // Index in SubMeshGeometryList
    NodeIndex parentNode; // Index of node holding this instance

    /** Compute the bounds of this instance with the given transform. This is
     * more precise, and much more expensive, than transforming the
     * SubMeshGeometry's bounds.
     */
    BoundingBox3f3f computeTransformedBounds(MeshdataPtr parent, const Matrix4x4f& xform) const;
    BoundingBox3f3f computeTransformedBounds(const Meshdata& parent, const Matrix4x4f& xform) const;
    void computeTransformedBounds(MeshdataPtr parent, const Matrix4x4f& xform, BoundingBox3f3f* bounds_out, double* radius_out) const;
    void computeTransformedBounds(const Meshdata& parent, const Matrix4x4f& xform, BoundingBox3f3f* bounds_out, double* radius_out) const;
};
typedef std::vector<GeometryInstance> GeometryInstanceList;

struct SIRIKATA_MESH_EXPORT LightInstance {
    int lightIndex; // Index in LightInfoList
    NodeIndex parentNode; // Index of node holding this instance
};
typedef std::vector<LightInstance> LightInstanceList;

struct SIRIKATA_MESH_EXPORT MaterialEffectInfo {
    struct Texture {
        std::string uri;
        Vector4f color;//color while the texture is pulled in, or if the texture is 404'd
        size_t texCoord;
        enum Affecting {
            DIFFUSE,
            SPECULAR,
            EMISSION,
            AMBIENT,
            REFLECTIVE,
            OPACITY,

        }affecting;
        enum SamplerType
        {
			SAMPLER_TYPE_UNSPECIFIED,
			SAMPLER_TYPE_1D,
			SAMPLER_TYPE_2D,
			SAMPLER_TYPE_3D,
			SAMPLER_TYPE_CUBE,
			SAMPLER_TYPE_RECT,
			SAMPLER_TYPE_DEPTH,
			SAMPLER_TYPE_STATE
		} samplerType;
		enum SamplerFilter
		{
			SAMPLER_FILTER_UNSPECIFIED,
			SAMPLER_FILTER_NONE,
			SAMPLER_FILTER_NEAREST,
			SAMPLER_FILTER_LINEAR,
			SAMPLER_FILTER_NEAREST_MIPMAP_NEAREST,
			SAMPLER_FILTER_LINEAR_MIPMAP_NEAREST,
			SAMPLER_FILTER_NEAREST_MIPMAP_LINEAR,
			SAMPLER_FILTER_LINEAR_MIPMAP_LINEAR
		};
        SamplerFilter minFilter;
        SamplerFilter magFilter;
		enum WrapMode
		{
			WRAP_MODE_UNSPECIFIED=0,
			// NONE == GL_CLAMP_TO BORDER The defined behavior for NONE is
			// consistent with decal texturing where the border is black.
			// Mapping this calculation to GL_CLAMP_TO_BORDER is the best
			// approximation of this.
			WRAP_MODE_NONE,
 			// WRAP == GL_REPEAT Ignores the integer part of texture coordinates,
			// using only the fractional part.
			WRAP_MODE_WRAP,
			// MIRROR == GL_MIRRORED_REPEAT First mirrors the texture coordinate.
			// The mirrored coordinate is then clamped as described for CLAMP_TO_EDGE.
			WRAP_MODE_MIRROR,
			// CLAMP == GL_CLAMP_TO_EDGE Clamps texture coordinates at all
			// mipmap levels such that the texture filter never samples a
			// border texel. Note: GL_CLAMP takes any texels beyond the
			// sampling border and substitutes those texels with the border
			// color. So CLAMP_TO_EDGE is more appropriate. This also works
			// much better with OpenGL ES where the GL_CLAMP symbol was removed
			// from the OpenGL ES specification.
			WRAP_MODE_CLAMP,
			// BORDER GL_CLAMP_TO_BORDER Clamps texture coordinates at all
			// MIPmaps such that the texture filter always samples border
			// texels for fragments whose corresponding texture coordinate
			// is sufficiently far outside the range [0, 1].
			WRAP_MODE_BORDER
		};
        WrapMode wrapS,wrapT,wrapU;
        unsigned int maxMipLevel;
        float mipBias;

        bool operator==(const Texture& rhs) const;
        bool operator!=(const Texture& rhs) const;
    };
    typedef std::vector<Texture> TextureList;
    TextureList textures;
    float shininess;
    float reflectivity;

    bool operator==(const MaterialEffectInfo& rhs) const;
    bool operator!=(const MaterialEffectInfo& rhs) const;
};
typedef std::vector<MaterialEffectInfo> MaterialEffectInfoList;

struct  SIRIKATA_MESH_EXPORT InstanceSkinAnimation {
};

// A scene graph node. Contains a transformation, set of children nodes,
// camera instances, geometry instances, skin controller instances, light
// instances, and instances of other nodes.
struct SIRIKATA_MESH_EXPORT Node {
    Node();
    Node(NodeIndex par, const Matrix4x4f& xform);
    Node(const Matrix4x4f& xform);

    // Parent node in the actual hierarchy (not instantiated).
    NodeIndex parent;
    // Transformation to apply when traversing this node.
    Matrix4x4f transform;
    // Direct children, i.e. they are contained by this node directly and their
    // parent NodeIndex will reflect that.
    NodeIndexList children;
    // Instantiations of other nodes (and their children) into this
    // subtree. Because they are instantiations, their
    // instanceChildren[i]->parent != this node's index.
    NodeIndexList instanceChildren;
};
typedef std::vector<Node> NodeList;

struct SIRIKATA_MESH_EXPORT Meshdata {
    SubMeshGeometryList geometry;
    TextureList textures;
    LightInfoList lights;
    MaterialEffectInfoList materials;

    std::string uri;
    SHA256 hash;
    long id;

    GeometryInstanceList instances;
    LightInstanceList lightInstances;

    // The global transform should be applied to all nodes and instances
    Matrix4x4f globalTransform;
    // We track two sets of nodes: roots and the full list. (Obviously the roots
    // are a subset of the full list). The node list is just the full set,
    // usually only used to look up children/parents.  The roots list is just a
    // set of indices into the full list.
    NodeList nodes;
    NodeIndexList rootNodes;

    // Joints are tracked as indices of the nodes they are associated with.
    NodeIndexList joints;

    // Be careful using these methods. Since there are no "parent" links for
    // instance nodes (and even if there were, there could be more than one),
    // these methods cannot correctly compute the transform when instance_nodes
    // are involved.
    Matrix4x4f getTransform(NodeIndex index) const;

  private:

    // A stack of NodeState is used to track the current traversal state for
    // instance iterators
    struct SIRIKATA_MESH_EXPORT NodeState {
        enum Step {
            Nodes,
            InstanceNodes,
            InstanceGeometries,
            InstanceLights,
            Done
        };

        NodeIndex index;
        Matrix4x4f transform;
        Step step;
        int32 currentChild;
    };

  public:

    // Allows you to generate a list of GeometryInstances with their transformations.
    class SIRIKATA_MESH_EXPORT GeometryInstanceIterator {
    public:
        GeometryInstanceIterator(const Meshdata* const mesh);
        // Get the next GeometryInstance and its transform. Returns true if
        // values were set, false if there were no more instances. The index
        // returned is of the geometry instance.
        bool next(uint32* geoinst_idx, Matrix4x4f* xform);
    private:
        const Meshdata* mMesh;

        int32 mRoot;
        std::stack<NodeState> mStack;
    };
    GeometryInstanceIterator getGeometryInstanceIterator() const;
    /** Get count of instanced geometry. This can differ from instances.size()
     * because many nodes may refer to the same InstanceGeometry.
     */
    uint32 getInstancedGeometryCount() const;

    // Allows you to generate a list of GeometryInstances with their transformations.
    class SIRIKATA_MESH_EXPORT LightInstanceIterator {
    public:
        LightInstanceIterator(const Meshdata* const mesh);
        // Get the next LightInstance and its transform. Returns true if
        // values were set, false if there were no more instances. The index
        // returned is of the light instance.
        bool next(uint32* lightinst_idx, Matrix4x4f* xform);
    private:
        const Meshdata* mMesh;

        int32 mRoot;
        std::stack<NodeState> mStack;
    };
    LightInstanceIterator getLightInstanceIterator() const;
    /** Get count of instanced lights. This can differ from
     * lightInstances.size() because many nodes may refer to the same
     * InstanceLight.
     */
    uint32 getInstancedLightCount() const;
};

} // namespace Mesh
} // namespace Sirikata

#endif //_SIRIKATA_MESH_MESHDATA_HPP_
<commit_msg>Fix warning about extraneous SIRIKATA_MESH_EXPORT on Meshdata forward declaration.<commit_after>/*  Sirikata
 *  Meshdata.hpp
 *
 *  Copyright (c) 2010, Daniel B. Miller
 *  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 Sirikata 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 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.
 */

#ifndef _SIRIKATA_MESH_MESHDATA_HPP_
#define _SIRIKATA_MESH_MESHDATA_HPP_

#include <sirikata/mesh/Platform.hpp>
#include <sirikata/core/util/Sha256.hpp>
#include "LightInfo.hpp"
#include <sirikata/core/util/UUID.hpp>
#include <stack>

namespace Sirikata {
namespace Mesh {

// Typedefs for NodeIndices, which refer to scene graph nodes in the model
typedef int32 NodeIndex;
extern SIRIKATA_MESH_EXPORT NodeIndex NullNodeIndex;
typedef std::vector<NodeIndex> NodeIndexList;

typedef std::vector<LightInfo> LightInfoList;
typedef std::vector<std::string> TextureList;

struct Meshdata;
typedef std::tr1::shared_ptr<Meshdata> MeshdataPtr;

/** Represents a skinned animation. A skinned animation is directly associated
 *  with a SubMeshGeometry.
 */
struct SIRIKATA_MESH_EXPORT SkinController {
    // Joints for this controls Indexes into the Meshdata.joints array
    // (which indexes into Meshdata.nodes).
    std::vector<uint32> joints;

    Matrix4x4f bindShapeMatrix;
    ///n+1 elements where n is the number of vertices, so that we can do simple subtraction to find out how many joints influence each vertex
    std::vector<unsigned int> weightStartIndices;
    std::vector<float> weights;
    std::vector<unsigned int>jointIndices;
    std::vector<Matrix4x4f> inverseBindMatrices;
};
typedef std::vector<SkinController> SkinControllerList;

struct SIRIKATA_MESH_EXPORT SubMeshGeometry {
    std::string name;
    std::vector<Sirikata::Vector3f> positions;

    std::vector<Sirikata::Vector3f> normals;
    std::vector<Sirikata::Vector3f> tangents;
    std::vector<Sirikata::Vector4f> colors;
    std::vector<unsigned int> influenceStartIndex;//a list of where a given position's joint weights start
    std::vector<unsigned int> jointindices;
    std::vector<float> weights;

    std::vector<Sirikata::Matrix4x4f> inverseBindMatrices;

    struct TextureSet {
        unsigned int stride;
        std::vector<float> uvs;
    };
    std::vector<TextureSet>texUVs;
    struct Primitive {
        std::vector<unsigned short> indices;

        enum PrimitiveType {
            TRIANGLES,
            LINES,
            POINTS,
            LINESTRIPS,
            TRISTRIPS,
            TRIFANS
        }primitiveType;
        typedef size_t MaterialId;
        MaterialId materialId;
    };
    std::vector<Primitive> primitives;

    BoundingBox3f3f aabb;
    double radius;
    void recomputeBounds();

    SkinControllerList skinControllers;

    //used only during simplification
    std::vector< Matrix4x4f  > positionQs;
    uint32 numInstances;
    std::tr1::unordered_map<uint32, std::vector< std::pair<uint32, uint32> > > neighborPrimitives; // maps positionIdx to list of primitiveIdxes
    /////////////////////////////////

    /** Append the given SubMeshGeometry to the end of this one. Use the given
     *  transformation to transform the geometry before adding it.  This is a
     *  useful primitive when trying to merge/simplify geometry.
     */
    void append(const SubMeshGeometry& rhs, const Matrix4x4f& xform);
};
typedef std::vector<SubMeshGeometry> SubMeshGeometryList;

struct SIRIKATA_MESH_EXPORT GeometryInstance {
    typedef std::map<SubMeshGeometry::Primitive::MaterialId,size_t> MaterialBindingMap;
    MaterialBindingMap materialBindingMap;//maps materialIndex to offset in Meshdata's materials
    unsigned int geometryIndex; // Index in SubMeshGeometryList
    NodeIndex parentNode; // Index of node holding this instance

    /** Compute the bounds of this instance with the given transform. This is
     * more precise, and much more expensive, than transforming the
     * SubMeshGeometry's bounds.
     */
    BoundingBox3f3f computeTransformedBounds(MeshdataPtr parent, const Matrix4x4f& xform) const;
    BoundingBox3f3f computeTransformedBounds(const Meshdata& parent, const Matrix4x4f& xform) const;
    void computeTransformedBounds(MeshdataPtr parent, const Matrix4x4f& xform, BoundingBox3f3f* bounds_out, double* radius_out) const;
    void computeTransformedBounds(const Meshdata& parent, const Matrix4x4f& xform, BoundingBox3f3f* bounds_out, double* radius_out) const;
};
typedef std::vector<GeometryInstance> GeometryInstanceList;

struct SIRIKATA_MESH_EXPORT LightInstance {
    int lightIndex; // Index in LightInfoList
    NodeIndex parentNode; // Index of node holding this instance
};
typedef std::vector<LightInstance> LightInstanceList;

struct SIRIKATA_MESH_EXPORT MaterialEffectInfo {
    struct Texture {
        std::string uri;
        Vector4f color;//color while the texture is pulled in, or if the texture is 404'd
        size_t texCoord;
        enum Affecting {
            DIFFUSE,
            SPECULAR,
            EMISSION,
            AMBIENT,
            REFLECTIVE,
            OPACITY,

        }affecting;
        enum SamplerType
        {
			SAMPLER_TYPE_UNSPECIFIED,
			SAMPLER_TYPE_1D,
			SAMPLER_TYPE_2D,
			SAMPLER_TYPE_3D,
			SAMPLER_TYPE_CUBE,
			SAMPLER_TYPE_RECT,
			SAMPLER_TYPE_DEPTH,
			SAMPLER_TYPE_STATE
		} samplerType;
		enum SamplerFilter
		{
			SAMPLER_FILTER_UNSPECIFIED,
			SAMPLER_FILTER_NONE,
			SAMPLER_FILTER_NEAREST,
			SAMPLER_FILTER_LINEAR,
			SAMPLER_FILTER_NEAREST_MIPMAP_NEAREST,
			SAMPLER_FILTER_LINEAR_MIPMAP_NEAREST,
			SAMPLER_FILTER_NEAREST_MIPMAP_LINEAR,
			SAMPLER_FILTER_LINEAR_MIPMAP_LINEAR
		};
        SamplerFilter minFilter;
        SamplerFilter magFilter;
		enum WrapMode
		{
			WRAP_MODE_UNSPECIFIED=0,
			// NONE == GL_CLAMP_TO BORDER The defined behavior for NONE is
			// consistent with decal texturing where the border is black.
			// Mapping this calculation to GL_CLAMP_TO_BORDER is the best
			// approximation of this.
			WRAP_MODE_NONE,
 			// WRAP == GL_REPEAT Ignores the integer part of texture coordinates,
			// using only the fractional part.
			WRAP_MODE_WRAP,
			// MIRROR == GL_MIRRORED_REPEAT First mirrors the texture coordinate.
			// The mirrored coordinate is then clamped as described for CLAMP_TO_EDGE.
			WRAP_MODE_MIRROR,
			// CLAMP == GL_CLAMP_TO_EDGE Clamps texture coordinates at all
			// mipmap levels such that the texture filter never samples a
			// border texel. Note: GL_CLAMP takes any texels beyond the
			// sampling border and substitutes those texels with the border
			// color. So CLAMP_TO_EDGE is more appropriate. This also works
			// much better with OpenGL ES where the GL_CLAMP symbol was removed
			// from the OpenGL ES specification.
			WRAP_MODE_CLAMP,
			// BORDER GL_CLAMP_TO_BORDER Clamps texture coordinates at all
			// MIPmaps such that the texture filter always samples border
			// texels for fragments whose corresponding texture coordinate
			// is sufficiently far outside the range [0, 1].
			WRAP_MODE_BORDER
		};
        WrapMode wrapS,wrapT,wrapU;
        unsigned int maxMipLevel;
        float mipBias;

        bool operator==(const Texture& rhs) const;
        bool operator!=(const Texture& rhs) const;
    };
    typedef std::vector<Texture> TextureList;
    TextureList textures;
    float shininess;
    float reflectivity;

    bool operator==(const MaterialEffectInfo& rhs) const;
    bool operator!=(const MaterialEffectInfo& rhs) const;
};
typedef std::vector<MaterialEffectInfo> MaterialEffectInfoList;

struct  SIRIKATA_MESH_EXPORT InstanceSkinAnimation {
};

// A scene graph node. Contains a transformation, set of children nodes,
// camera instances, geometry instances, skin controller instances, light
// instances, and instances of other nodes.
struct SIRIKATA_MESH_EXPORT Node {
    Node();
    Node(NodeIndex par, const Matrix4x4f& xform);
    Node(const Matrix4x4f& xform);

    // Parent node in the actual hierarchy (not instantiated).
    NodeIndex parent;
    // Transformation to apply when traversing this node.
    Matrix4x4f transform;
    // Direct children, i.e. they are contained by this node directly and their
    // parent NodeIndex will reflect that.
    NodeIndexList children;
    // Instantiations of other nodes (and their children) into this
    // subtree. Because they are instantiations, their
    // instanceChildren[i]->parent != this node's index.
    NodeIndexList instanceChildren;
};
typedef std::vector<Node> NodeList;

struct SIRIKATA_MESH_EXPORT Meshdata {
    SubMeshGeometryList geometry;
    TextureList textures;
    LightInfoList lights;
    MaterialEffectInfoList materials;

    std::string uri;
    SHA256 hash;
    long id;

    GeometryInstanceList instances;
    LightInstanceList lightInstances;

    // The global transform should be applied to all nodes and instances
    Matrix4x4f globalTransform;
    // We track two sets of nodes: roots and the full list. (Obviously the roots
    // are a subset of the full list). The node list is just the full set,
    // usually only used to look up children/parents.  The roots list is just a
    // set of indices into the full list.
    NodeList nodes;
    NodeIndexList rootNodes;

    // Joints are tracked as indices of the nodes they are associated with.
    NodeIndexList joints;

    // Be careful using these methods. Since there are no "parent" links for
    // instance nodes (and even if there were, there could be more than one),
    // these methods cannot correctly compute the transform when instance_nodes
    // are involved.
    Matrix4x4f getTransform(NodeIndex index) const;

  private:

    // A stack of NodeState is used to track the current traversal state for
    // instance iterators
    struct SIRIKATA_MESH_EXPORT NodeState {
        enum Step {
            Nodes,
            InstanceNodes,
            InstanceGeometries,
            InstanceLights,
            Done
        };

        NodeIndex index;
        Matrix4x4f transform;
        Step step;
        int32 currentChild;
    };

  public:

    // Allows you to generate a list of GeometryInstances with their transformations.
    class SIRIKATA_MESH_EXPORT GeometryInstanceIterator {
    public:
        GeometryInstanceIterator(const Meshdata* const mesh);
        // Get the next GeometryInstance and its transform. Returns true if
        // values were set, false if there were no more instances. The index
        // returned is of the geometry instance.
        bool next(uint32* geoinst_idx, Matrix4x4f* xform);
    private:
        const Meshdata* mMesh;

        int32 mRoot;
        std::stack<NodeState> mStack;
    };
    GeometryInstanceIterator getGeometryInstanceIterator() const;
    /** Get count of instanced geometry. This can differ from instances.size()
     * because many nodes may refer to the same InstanceGeometry.
     */
    uint32 getInstancedGeometryCount() const;

    // Allows you to generate a list of GeometryInstances with their transformations.
    class SIRIKATA_MESH_EXPORT LightInstanceIterator {
    public:
        LightInstanceIterator(const Meshdata* const mesh);
        // Get the next LightInstance and its transform. Returns true if
        // values were set, false if there were no more instances. The index
        // returned is of the light instance.
        bool next(uint32* lightinst_idx, Matrix4x4f* xform);
    private:
        const Meshdata* mMesh;

        int32 mRoot;
        std::stack<NodeState> mStack;
    };
    LightInstanceIterator getLightInstanceIterator() const;
    /** Get count of instanced lights. This can differ from
     * lightInstances.size() because many nodes may refer to the same
     * InstanceLight.
     */
    uint32 getInstancedLightCount() const;
};

} // namespace Mesh
} // namespace Sirikata

#endif //_SIRIKATA_MESH_MESHDATA_HPP_
<|endoftext|>


<commit_before><commit_msg>gtk: Fix a typo that breaks tab dragging when another gtk window is minimized.<commit_after><|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.

// This is a file for random testcases that we run into that at one point or
// another have crashed the program.

#include "chrome/test/ui/ui_test.h"

#include "base/basictypes.h"
#include "base/file_path.h"
#include "base/platform_thread.h"
#include "chrome/common/chrome_switches.h"

class GoogleTest : public UITest {
 protected:
  GoogleTest() : UITest() {
    FilePath test_file(test_data_directory_);
    test_file = test_file.AppendASCII("google");
    test_file = test_file.AppendASCII("google.html");
    homepage_ = test_file.ToWStringHack();
  }
};

TEST_F(GoogleTest, Crash) {
  std::wstring page_title = L"Google";

  // Make sure the navigation succeeded.
  EXPECT_EQ(page_title, GetActiveTabTitle());

  // UITest will check if this crashed.
}

class ColumnLayout : public UITest {
 protected:
  ColumnLayout() : UITest() {
    FilePath test_file(test_data_directory_);
    test_file = test_file.AppendASCII("columns.html");
    homepage_ = test_file.ToWStringHack();
  }
};

TEST_F(ColumnLayout, Crash) {
  std::wstring page_title = L"Column test";

  // Make sure the navigation succeeded.
  EXPECT_EQ(page_title, GetActiveTabTitle());

  // UITest will check if this crashed.
}

// By passing kTryChromeAgain with a magic value > 10000 we cause chrome
// to exit fairly early. This was the cause of crashes. See bug 34799.
class EarlyReturnTest : public UITest {
 public:
  EarlyReturnTest() {
    wait_for_initial_loads_ = false;
    // We don't depend on these timeouts, they are set to the minimum so
    // the automation server waits the minimun amount possible for the
    // handshake that will never come.
    set_command_execution_timeout_ms(1);
    set_action_timeout_ms(1);
    launch_arguments_.AppendSwitchWithValue(switches::kTryChromeAgain, "10001");
  }
};

TEST_F(EarlyReturnTest, ToastCrasher) {
  // UITest will check if this crashed.
}
<commit_msg>Marking EarlyReturnTest.ToastCrasher as flaky<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.

// This is a file for random testcases that we run into that at one point or
// another have crashed the program.

#include "chrome/test/ui/ui_test.h"

#include "base/basictypes.h"
#include "base/file_path.h"
#include "base/platform_thread.h"
#include "chrome/common/chrome_switches.h"

class GoogleTest : public UITest {
 protected:
  GoogleTest() : UITest() {
    FilePath test_file(test_data_directory_);
    test_file = test_file.AppendASCII("google");
    test_file = test_file.AppendASCII("google.html");
    homepage_ = test_file.ToWStringHack();
  }
};

TEST_F(GoogleTest, Crash) {
  std::wstring page_title = L"Google";

  // Make sure the navigation succeeded.
  EXPECT_EQ(page_title, GetActiveTabTitle());

  // UITest will check if this crashed.
}

class ColumnLayout : public UITest {
 protected:
  ColumnLayout() : UITest() {
    FilePath test_file(test_data_directory_);
    test_file = test_file.AppendASCII("columns.html");
    homepage_ = test_file.ToWStringHack();
  }
};

TEST_F(ColumnLayout, Crash) {
  std::wstring page_title = L"Column test";

  // Make sure the navigation succeeded.
  EXPECT_EQ(page_title, GetActiveTabTitle());

  // UITest will check if this crashed.
}

// By passing kTryChromeAgain with a magic value > 10000 we cause chrome
// to exit fairly early. This was the cause of crashes. See bug 34799.
class EarlyReturnTest : public UITest {
 public:
  EarlyReturnTest() {
    wait_for_initial_loads_ = false;
    // We don't depend on these timeouts, they are set to the minimum so
    // the automation server waits the minimun amount possible for the
    // handshake that will never come.
    set_command_execution_timeout_ms(1);
    set_action_timeout_ms(1);
    launch_arguments_.AppendSwitchWithValue(switches::kTryChromeAgain, "10001");
  }
};

// Flaky: http://crbug.com/45115
TEST_F(EarlyReturnTest, FLAKEY_ToastCrasher) {
  // UITest will check if this crashed.
}
<|endoftext|>


<commit_before>//
//  Mach7: Pattern Matching Library for C++
//
//  Copyright 2011-2013, Texas A&M University.
//  Copyright 2014 Yuriy Solodkyy.
//  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 names of Mach7 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 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 HOLDERS 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.

///
/// \file
///
/// A minimal version of the XTL library definitions required to support subtyping.
///
/// \author Yuriy Solodkyy <yuriy.solodkyy@gmail.com>
///
/// \see https://parasol.tamu.edu/xtl/
/// \see https://parasol.tamu.edu/mach7/
/// \see https://github.com/solodon4/Mach7
/// \see https://github.com/solodon4/SELL
///

#pragma once

#include <type_traits>
#include "config.hpp"	// To emulate some of the language features on old compilers

namespace xtl
{
    template <class T, class U, class C = void> struct is_subtype : std::is_same<T,U> {};

    template <class T, class S> struct is_subtype<const S*, const T*> : is_subtype<S,T> {};
    template <class T, class S> struct is_subtype<      S*, const T*> : is_subtype<S,T> {};
    template <class T, class S> struct is_subtype<const S*,       T*> : std::false_type {};
    template <class T, class S> struct is_subtype<      S*,       T*> : is_subtype<S,T> {};

    // Derived class is a subtype of a base class
    template <class D, class B>
    struct is_subtype <D, B, typename std::enable_if<std::is_base_of<B,D>::value>::type> : std::true_type {};

    template <typename T>
    struct is_poly_morphic // Ignore weirdness in name for now, workaround of a Visual C++ 2010 compiler bug.
    {
        static const bool value = false; // Most of the types do not exhibit polymorphic behavior, those that do will have to specialize
    };

    template <typename T>
    struct is_poly_morphic<const T> // Constness does not affect whether type is polymorphic
    {
        static const bool value = is_poly_morphic<T>::value;
    };

    template <typename T>
    struct is_poly_morphic<volatile T> // Volatility does not affect whether type is polymorphic
    {
        static const bool value = is_poly_morphic<T>::value;
    };

    //==============================================================================
    // target class definition
    //==============================================================================

    /// Helper qualifier to overcome problems with overload resolution when only
    /// several argument types are deduced and others are explicitly specified.
    /// This class will be used to wrap explicitly given arguments. Overloaded
    /// subtype_cast_impl have to use this qualifier to match target type T that was
    /// specified by the user in subtype_cast<T>(val).
    template <class T>
    struct target
    {
        /// Type that actually has to be returned by a subtype_cast. Most of the
        /// time it will be the same as target type T, however in some cases it may
        /// be different. An example of such is the result type of casting array
        /// array types, which is T* instead of T[N].By default, result type matches T.
        typedef T type;
    };

    //==============================================================================
    // Forward declarations
    //==============================================================================

    template <class T, class S>
    typename std::enable_if<is_subtype<typename std::remove_reference<S>::type, T>::value, typename target<T>::type>::type
    subtype_cast(S&& s);

    //==============================================================================
    // subtype_cast_impl definition
    //==============================================================================

    /// Helper function to overcome problems with overload resolution when only
    /// several arguments types are deduced and others are explicitly specified.
    /// This function has all of the types in deducible context, so that explicitly
    /// given arguments will be passed through dummy null-pointers.
    /// Default implementation just tries to cast one type to another.
    template <class T, class S>
    inline T subtype_cast_impl(target<T>, const S& s)
    {
        return (T)s;
    }

    //==============================================================================
    // subtype_cast definition
    //==============================================================================

    /// Routine to cast sub-type T to its super-type S.
    /// Extra level of indirection with impl was made to overcome the problem that
    /// when S is not among the arguments generic and more specific specialization
    /// are the same for compiler and it reports ambiguity.
//    template <class T, class S>
//    typename std::enable_if<is_subtype<S, T>::value, typename target<T>::type>::type
//    subtype_cast(const S& s)
//    {
//        // We create a dedicated variable with result because some classes may provide
//        // copy constructors that don't bind to temporaries (e.g. auto_ptr<T>).
//        typename target<T>::type result(subtype_cast_impl(target<T>(), s));
//        std::cout << "subtype_cast<" << typeid(T).name() << ">(" << typeid(S).name() << ") = " << std::endl;
//        return result;
//    }
    template <class T, class S>
    inline typename std::enable_if<is_subtype<typename std::remove_reference<S>::type, T>::value, typename target<T>::type>::type
    subtype_cast(S&& s)
    {
        return subtype_cast_impl(target<T>(), std::forward<S>(s));
    }

    //==============================================================================
    // subtype_dynamic_cast definition
    //==============================================================================

    template <class T>
    inline T* subtype_dynamic_cast_impl(target<T*>, T* p) noexcept
    {
        return p;
    }

    inline std::nullptr_t subtype_dynamic_cast_impl(...) noexcept
    {
        return nullptr;
    }

    template <class D, class B>
    inline typename std::enable_if<std::is_base_of<B, D>::value, D*>::type
    subtype_dynamic_cast_impl(target<D*>, B* p) noexcept
    {
        return dynamic_cast<D*>(p);
    }

    template <class S, class T>
    //inline typename std::enable_if<is_subtype<S, T>::value, S*>::type
    inline S subtype_dynamic_cast(T* t) noexcept
    {
        typename target<S>::type result = subtype_dynamic_cast_impl(target<S>(), t);
        //std::cout << "subtype_dynamic_cast<" << typeid(S).name() << ">(" << typeid(t).name() << ") = " << result << std::endl;
        return result;
    }

} // of namespace xtl

<commit_msg>include header <utility><commit_after>//
//  Mach7: Pattern Matching Library for C++
//
//  Copyright 2011-2013, Texas A&M University.
//  Copyright 2014 Yuriy Solodkyy.
//  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 names of Mach7 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 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 HOLDERS 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.

///
/// \file
///
/// A minimal version of the XTL library definitions required to support subtyping.
///
/// \author Yuriy Solodkyy <yuriy.solodkyy@gmail.com>
///
/// \see https://parasol.tamu.edu/xtl/
/// \see https://parasol.tamu.edu/mach7/
/// \see https://github.com/solodon4/Mach7
/// \see https://github.com/solodon4/SELL
///

#pragma once

#include <type_traits>
#include <utility>
#include "config.hpp"	// To emulate some of the language features on old compilers

namespace xtl
{
    template <class T, class U, class C = void> struct is_subtype : std::is_same<T,U> {};

    template <class T, class S> struct is_subtype<const S*, const T*> : is_subtype<S,T> {};
    template <class T, class S> struct is_subtype<      S*, const T*> : is_subtype<S,T> {};
    template <class T, class S> struct is_subtype<const S*,       T*> : std::false_type {};
    template <class T, class S> struct is_subtype<      S*,       T*> : is_subtype<S,T> {};

    // Derived class is a subtype of a base class
    template <class D, class B>
    struct is_subtype <D, B, typename std::enable_if<std::is_base_of<B,D>::value>::type> : std::true_type {};

    template <typename T>
    struct is_poly_morphic // Ignore weirdness in name for now, workaround of a Visual C++ 2010 compiler bug.
    {
        static const bool value = false; // Most of the types do not exhibit polymorphic behavior, those that do will have to specialize
    };

    template <typename T>
    struct is_poly_morphic<const T> // Constness does not affect whether type is polymorphic
    {
        static const bool value = is_poly_morphic<T>::value;
    };

    template <typename T>
    struct is_poly_morphic<volatile T> // Volatility does not affect whether type is polymorphic
    {
        static const bool value = is_poly_morphic<T>::value;
    };

    //==============================================================================
    // target class definition
    //==============================================================================

    /// Helper qualifier to overcome problems with overload resolution when only
    /// several argument types are deduced and others are explicitly specified.
    /// This class will be used to wrap explicitly given arguments. Overloaded
    /// subtype_cast_impl have to use this qualifier to match target type T that was
    /// specified by the user in subtype_cast<T>(val).
    template <class T>
    struct target
    {
        /// Type that actually has to be returned by a subtype_cast. Most of the
        /// time it will be the same as target type T, however in some cases it may
        /// be different. An example of such is the result type of casting array
        /// array types, which is T* instead of T[N].By default, result type matches T.
        typedef T type;
    };

    //==============================================================================
    // Forward declarations
    //==============================================================================

    template <class T, class S>
    typename std::enable_if<is_subtype<typename std::remove_reference<S>::type, T>::value, typename target<T>::type>::type
    subtype_cast(S&& s);

    //==============================================================================
    // subtype_cast_impl definition
    //==============================================================================

    /// Helper function to overcome problems with overload resolution when only
    /// several arguments types are deduced and others are explicitly specified.
    /// This function has all of the types in deducible context, so that explicitly
    /// given arguments will be passed through dummy null-pointers.
    /// Default implementation just tries to cast one type to another.
    template <class T, class S>
    inline T subtype_cast_impl(target<T>, const S& s)
    {
        return (T)s;
    }

    //==============================================================================
    // subtype_cast definition
    //==============================================================================

    /// Routine to cast sub-type T to its super-type S.
    /// Extra level of indirection with impl was made to overcome the problem that
    /// when S is not among the arguments generic and more specific specialization
    /// are the same for compiler and it reports ambiguity.
//    template <class T, class S>
//    typename std::enable_if<is_subtype<S, T>::value, typename target<T>::type>::type
//    subtype_cast(const S& s)
//    {
//        // We create a dedicated variable with result because some classes may provide
//        // copy constructors that don't bind to temporaries (e.g. auto_ptr<T>).
//        typename target<T>::type result(subtype_cast_impl(target<T>(), s));
//        std::cout << "subtype_cast<" << typeid(T).name() << ">(" << typeid(S).name() << ") = " << std::endl;
//        return result;
//    }
    template <class T, class S>
    inline typename std::enable_if<is_subtype<typename std::remove_reference<S>::type, T>::value, typename target<T>::type>::type
    subtype_cast(S&& s)
    {
        return subtype_cast_impl(target<T>(), std::forward<S>(s));
    }

    //==============================================================================
    // subtype_dynamic_cast definition
    //==============================================================================

    template <class T>
    inline T* subtype_dynamic_cast_impl(target<T*>, T* p) noexcept
    {
        return p;
    }

    inline std::nullptr_t subtype_dynamic_cast_impl(...) noexcept
    {
        return nullptr;
    }

    template <class D, class B>
    inline typename std::enable_if<std::is_base_of<B, D>::value, D*>::type
    subtype_dynamic_cast_impl(target<D*>, B* p) noexcept
    {
        return dynamic_cast<D*>(p);
    }

    template <class S, class T>
    //inline typename std::enable_if<is_subtype<S, T>::value, S*>::type
    inline S subtype_dynamic_cast(T* t) noexcept
    {
        typename target<S>::type result = subtype_dynamic_cast_impl(target<S>(), t);
        //std::cout << "subtype_dynamic_cast<" << typeid(S).name() << ">(" << typeid(t).name() << ") = " << result << std::endl;
        return result;
    }

} // of namespace xtl

<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2014, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under the BSD-style license found in the
 *  LICENSE file in the root directory of this source tree. An additional grant
 *  of patent rights can be found in the PATENTS file in the same directory.
 *
 */

#include <string>

#include <boost/regex.hpp>
#include <boost/xpressive/xpressive.hpp>

#include <osquery/filesystem.h>
#include <osquery/sql.h>
#include <osquery/tables.h>

namespace xp = boost::xpressive;

namespace osquery {
namespace tables {

#ifdef CENTOS
const std::string kLinuxOSRelease = "/etc/redhat-release";
const std::string kLinuxOSRegex =
    "(?P<name>\\w+) .* "
    "(?P<major>[0-9]+).(?P<minor>[0-9]+)[\\.]{0,1}(?P<patch>[0-9]+)";
#else
const std::string kLinuxOSRelease = "/etc/os-release";
const std::string kLinuxOSRegex =
    "VERSION=\"(?P<major>[0-9]+)\\.(?P<minor>[0-9]+)[\\.]{0,1}(?P<patch>[0-9]+)"
    "?, (?P<name>[\\w ]*)\"$";
#endif

QueryData genOSVersion(QueryContext& context) {
  std::string content;
  if (!readFile(kLinuxOSRelease, content).ok()) {
    return {};
  }

  Row r;
  auto rx = xp::sregex::compile(kLinuxOSRegex);
  xp::smatch matches;
  for (const auto& line : osquery::split(content, "\n")) {
    if (xp::regex_search(line, matches, rx)) {
      r["major"] = INTEGER(matches["major"]);
      r["minor"] = INTEGER(matches["minor"]);
      r["patch"] =
          (matches["patch"].length() > 0) ? INTEGER(matches["patch"]) : "0";
      r["name"] = matches["name"];
      break;
    }
  }

  // No build name.
  r["build"] = "";
  return {r};
}
}
}
<commit_msg>Fix Ubuntu-version regex<commit_after>/*
 *  Copyright (c) 2014, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under the BSD-style license found in the
 *  LICENSE file in the root directory of this source tree. An additional grant
 *  of patent rights can be found in the PATENTS file in the same directory.
 *
 */

#include <string>

#include <boost/regex.hpp>
#include <boost/xpressive/xpressive.hpp>

#include <osquery/filesystem.h>
#include <osquery/sql.h>
#include <osquery/tables.h>

namespace xp = boost::xpressive;

namespace osquery {
namespace tables {

#ifdef CENTOS
const std::string kLinuxOSRelease = "/etc/redhat-release";
const std::string kLinuxOSRegex =
    "(?P<name>\\w+) .* "
    "(?P<major>[0-9]+).(?P<minor>[0-9]+)[\\.]{0,1}(?P<patch>[0-9]+)";
#else
const std::string kLinuxOSRelease = "/etc/os-release";
const std::string kLinuxOSRegex =
    "VERSION=\"(?P<major>[0-9]+)\\.(?P<minor>[0-9]+)[\\.]{0,1}(?P<patch>[0-9]+)"
    "?.*, (?P<name>[\\w ]*)\"$";
#endif

QueryData genOSVersion(QueryContext& context) {
  std::string content;
  if (!readFile(kLinuxOSRelease, content).ok()) {
    return {};
  }

  Row r;
  auto rx = xp::sregex::compile(kLinuxOSRegex);
  xp::smatch matches;
  for (const auto& line : osquery::split(content, "\n")) {
    if (xp::regex_search(line, matches, rx)) {
      r["major"] = INTEGER(matches["major"]);
      r["minor"] = INTEGER(matches["minor"]);
      r["patch"] =
          (matches["patch"].length() > 0) ? INTEGER(matches["patch"]) : "0";
      r["name"] = matches["name"];
      break;
    }
  }

  // No build name.
  r["build"] = "";
  return {r};
}
}
}
<|endoftext|>


<commit_before>/*
 * Heap.cpp
 *
 *  Created on: Oct 27, 2013
 */

#include "Heap.h"

Location Heap::getLocation(Priority key)
{
	Location ret;
	if ( keyToAddress.count(key)>0 ) {
		// found
		ret = keyToAddress[key];
	} else {
		//not found
		ret = NULL;
	}
	return ret;
}

bool Heap::setLocation(Location address,Priority key)
{
	if(address == NULL)
		return false;
	keyToAddress[key] = address;
	return true;
}

bool Heap::deleteLocation(Priority key)
{
	if(keyToAddress.count(key)>0)
	{
		keyToAddress.erase (key);
		return true;
	}
	else
		return false;
}
<commit_msg>Minor change<commit_after>/*
 * Heap.cpp
 *
 *  Created on: Oct 27, 2013
 */

#include "Heap.h"

Location Heap::getLocation(Priority key)
{
	Location ret;
	if ( keyToAddress.count(key)>0 ) {
		// found
		ret = keyToAddress[key];
	} else {
		//not found
		ret = NULL;
	}
	return ret;
}

bool Heap::setLocation(Location address,Priority key)
{
	if(address == NULL)
		return false;
	keyToAddress[key] = address;
	return true;
}

bool Heap::deleteLocation(Priority key)
{
	if(keyToAddress.count(key)>0)
	{
		keyToAddress.erase (key);
		return true;
	}
	else
		return false;
}
<|endoftext|>


<commit_before>#include "MPU6050.h"
#include <stdint.h>

using namespace flyhero;

void IMU_Data_Ready_Callback();
void IMU_Data_Read_Callback();

MPU6050& mpu = MPU6050::Instance();

extern "C" void app_main(void)
{
	if (mpu.Init() || mpu.Calibrate()) {
		while (true) {
			/*LEDs::Toggle(LEDs::Green);
			Timer::Delay_ms(500);*/
		}
	}

	printf("init complete\n");

	//mpu.Data_Ready_Callback = &IMU_Data_Ready_Callback;
	//mpu.Data_Read_Callback = &IMU_Data_Read_Callback;
	MPU6050::Raw_Data accel, gyro;

	while (true) {
		mpu.Read_Raw(accel, gyro);

		printf("%d %d %d %d %d %d\n", accel.x, accel.y, accel.z, gyro.x, gyro.y, gyro.z);

		vTaskDelay(1000 / portTICK_RATE_MS);
	}
}

void IMU_Data_Ready_Callback() {
	// 160 us
	/*if (mpu.Start_Read() != HAL_OK)
		LEDs::TurnOn(LEDs::Orange);*/
}

// IMU_Data_Ready_Callback() -> 340 us -> IMU_Data_Read_Callback()

void IMU_Data_Read_Callback() {
	mpu.Complete_Read();

	// 200 us
	mpu.Compute_Mahony();
	//mpu.Compute_Euler();
}
<commit_msg>(main): Test MPU9250 code<commit_after>#include "MPU9250.h"

using namespace flyhero;

extern "C" void app_main(void) {
	MPU9250::Instance().Init();
}

/*#include "MPU6050.h"
#include <stdint.h>

using namespace flyhero;

void IMU_Data_Ready_Callback();
void IMU_Data_Read_Callback();

MPU6050& mpu = MPU6050::Instance();

extern "C" void app_main(void)
{
	if (mpu.Init() || mpu.Calibrate()) {
		while (true) {
			//LEDs::Toggle(LEDs::Green);
			//Timer::Delay_ms(500);
		}
	}

	printf("init complete\n");

	//mpu.Data_Ready_Callback = &IMU_Data_Ready_Callback;
	//mpu.Data_Read_Callback = &IMU_Data_Read_Callback;
	MPU6050::Raw_Data accel, gyro;

	while (true) {
		mpu.Read_Raw(accel, gyro);

		printf("%d %d %d %d %d %d\n", accel.x, accel.y, accel.z, gyro.x, gyro.y, gyro.z);

		vTaskDelay(1000 / portTICK_RATE_MS);
	}
}

void IMU_Data_Ready_Callback() {
	// 160 us
	//if (mpu.Start_Read() != HAL_OK)
	//	LEDs::TurnOn(LEDs::Orange);
}

// IMU_Data_Ready_Callback() -> 340 us -> IMU_Data_Read_Callback()

void IMU_Data_Read_Callback() {
	mpu.Complete_Read();

	// 200 us
	mpu.Compute_Mahony();
	//mpu.Compute_Euler();
}*/
<|endoftext|>


<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Copyright (c) 2015-2016 The Bitcoin Unlimited developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "pow.h"

#include "arith_uint256.h"
#include "chain.h"
#include "primitives/block.h"
#include "uint256.h"
#include "util.h"
#include "mvf-core.h"  // MVF-Core added

unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params)
{
    unsigned int nProofOfWorkLimit = UintToArith256(params.powLimit).GetCompact();
    static bool force_retarget=GetBoolArg("-force-retarget", false);  //MVF-Core added

    // Genesis block
    if (pindexLast == NULL)
        return nProofOfWorkLimit;

    // MVF-Core begin difficulty re-targeting reset
	if (pindexLast->nHeight == FinalActivateForkHeight)
	{
        LogPrintf("MVF: FORK BLOCK DIFFICULTY RESET  %08x  \n", pindexLast->nBits);
		return pindexLast->nBits;
	}
	LogPrintf("MVF DEBUG DifficultyAdjInterval = %d , TimeSpan = %d \n", params.DifficultyAdjustmentInterval(pindexLast->nHeight), params.MVFPowTargetTimespan(pindexLast->nHeight));
    // MVF-Core end

	// Only change once per difficulty adjustment interval
	if ((pindexLast->nHeight+1) % params.DifficultyAdjustmentInterval(pindexLast->nHeight) != 0)  // MVF-Core
	{
		if (params.fPowAllowMinDifficultyBlocks && !force_retarget)  // MVF-Core
		{
			// Special difficulty rule for testnet:
			// If the new block's timestamp is more than 2* 10 minutes
			// then allow mining of a min-difficulty block.
			if (pblock->GetBlockTime() > pindexLast->GetBlockTime() + params.nPowTargetSpacing*2)
				return nProofOfWorkLimit;
			else
			{
				// Return the last non-special-min-difficulty-rules-block
				const CBlockIndex* pindex = pindexLast;
				while (pindex->pprev && pindex->nHeight % params.DifficultyAdjustmentInterval(pindexLast->nHeight) != 0 && pindex->nBits == nProofOfWorkLimit)  // MVF-Core
					pindex = pindex->pprev;
				return pindex->nBits;
			}
		}
		return pindexLast->nBits;
    }

	// Go back by what we want to be 14 days worth of blocks
    // MVF-Core begin adjust nHeightFirst
	int nHeightFirst = pindexLast->nHeight - (params.DifficultyAdjustmentInterval(pindexLast->nHeight)-1);
	if (params.MVFisWithinRetargetPeriod(pindexLast->nHeight))
		nHeightFirst = pindexLast->nHeight - params.DifficultyAdjustmentInterval(pindexLast->nHeight);
    // MVF-Core end
	assert(nHeightFirst >= 0);
	const CBlockIndex* pindexFirst = pindexLast->GetAncestor(nHeightFirst);
	assert(pindexFirst);

	return CalculateNextWorkRequired(pindexLast, pindexFirst->GetBlockTime(), params);

}

unsigned int CalculateNextWorkRequired(const CBlockIndex* pindexLast, int64_t nFirstBlockTime, const Consensus::Params& params)
{
    static bool force_retarget=GetBoolArg("-force-retarget", false);  // MVF-Core added to test retargeting
    const arith_uint256 bnPowLimit = UintToArith256(params.powLimit); // MVF-Core moved here

    if (params.fPowNoRetargeting && !force_retarget)  // MVF-Core
        return pindexLast->nBits;

    // Limit adjustment step
    int64_t nActualTimespan = pindexLast->GetBlockTime() - nFirstBlockTime;
    // MVF-Core begin check for abnormal condition
    // This actually occurred during testing, resulting in new target == 0
    // which could never be met
    if (nActualTimespan == 0) {
        LogPrintf("  MVF: nActualTimespan == 0, returning bnPowLimit\n");
        return bnPowLimit.GetCompact();
    }
    // MVF-Core end
    LogPrintf("  nActualTimespan = %d  before bounds\n", nActualTimespan);

    // MVF-Core begin target time span while within the re-target period
    int64_t nTargetTimespan = params.nPowTargetTimespan; // the original 14 days
    if (params.MVFisWithinRetargetPeriod(pindexLast->nHeight))
        nTargetTimespan = params.MVFPowTargetTimespan(pindexLast->nHeight);

    // permit abrupt changes for a few blocks after the fork i.e. when nTargetTimespan is < 30 minutes
    if (nTargetTimespan >= params.nPowTargetSpacing * 3)
    {
        // prevent abrupt changes to target
        if (nActualTimespan < nTargetTimespan/4)
            nActualTimespan = nTargetTimespan/4;
        if (nActualTimespan > nTargetTimespan*4)
            nActualTimespan = nTargetTimespan*4;
    }
    else LogPrintf("Abrupt RETARGET permitted.\n");
    // MVF-Core end

    // Retarget
    arith_uint256 bnNew;
    arith_uint256 bnOld;
    bnNew.SetCompact(pindexLast->nBits);
    bnOld = bnNew;
    // MVF-Core begin: move division before multiplication
    // at regtest difficulty, the multiplication is prone to overflowing
    bnNew /= nTargetTimespan;
    bnNew *= nActualTimespan;
    // MVF-Core end

    if (bnNew > bnPowLimit)
        bnNew = bnPowLimit;

    /// debug print
    LogPrintf("GetNextWorkRequired RETARGET\n");
    LogPrintf("nTargetTimespan = %d    nActualTimespan = %d\n", nTargetTimespan, nActualTimespan);  // MVF-Core
    LogPrintf("Before: %08x  %s\n", pindexLast->nBits, bnOld.ToString());
    LogPrintf("After:  %08x  %s\n", bnNew.GetCompact(), bnNew.ToString());

    return bnNew.GetCompact();
}

bool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params& params)
{
    bool fNegative;
    bool fOverflow;
    arith_uint256 bnTarget;
    static bool force_retarget=GetBoolArg("-force-retarget", false);  // MVF-Core

    bnTarget.SetCompact(nBits, &fNegative, &fOverflow);

    // Check range
    // MVF-Core begin suppress trace output to enable faster test runs when
    // -force-retarget is used for retargeting tests
    if (fNegative || bnTarget == 0 || fOverflow || bnTarget > UintToArith256(params.powLimit)) {
        if (!force_retarget)
            return error("CheckProofOfWork(): nBits below minimum work");
        else
            return false;
    }

    // Check proof of work matches claimed amount
    // if retargeting is enforced on testnets, suppress this warning
    // because it would flood the logs when lots of hashing going on
    if (UintToArith256(hash) > bnTarget) {
        if (!force_retarget)
            return error("CheckProofOfWork(): hash %s doesn't match nBits 0x%x",hash.ToString(),nBits);
        else
            return false;
    }
    // MVF-Core end

    return true;
}

arith_uint256 GetBlockProof(const CBlockIndex& block)
{
    arith_uint256 bnTarget;
    bool fNegative;
    bool fOverflow;
    bnTarget.SetCompact(block.nBits, &fNegative, &fOverflow);
    if (fNegative || fOverflow || bnTarget == 0)
        return 0;
    // We need to compute 2**256 / (bnTarget+1), but we can't represent 2**256
    // as it's too large for a arith_uint256. However, as 2**256 is at least as large
    // as bnTarget+1, it is equal to ((2**256 - bnTarget - 1) / (bnTarget+1)) + 1,
    // or ~bnTarget / (nTarget+1) + 1.
    return (~bnTarget / (bnTarget + 1)) + 1;
}

int64_t GetBlockProofEquivalentTime(const CBlockIndex& to, const CBlockIndex& from, const CBlockIndex& tip, const Consensus::Params& params)
{
    arith_uint256 r;
    int sign = 1;
    if (to.nChainWork > from.nChainWork) {
        r = to.nChainWork - from.nChainWork;
    } else {
        r = from.nChainWork - to.nChainWork;
        sign = -1;
    }
    r = r * arith_uint256(params.nPowTargetSpacing) / GetBlockProof(tip);
    if (r.bits() > 63) {
        return sign * std::numeric_limits<int64_t>::max();
    }
    return sign * r.GetLow64();
}
<commit_msg>test version with overflow detection<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Copyright (c) 2015-2016 The Bitcoin Unlimited developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "pow.h"

#include "arith_uint256.h"
#include "chain.h"
#include "primitives/block.h"
#include "uint256.h"
#include "util.h"
#include "mvf-core.h"  // MVF-Core added

unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params)
{
    unsigned int nProofOfWorkLimit = UintToArith256(params.powLimit).GetCompact();
    static bool force_retarget=GetBoolArg("-force-retarget", false);  //MVF-Core added

    // Genesis block
    if (pindexLast == NULL)
        return nProofOfWorkLimit;

    // MVF-Core begin difficulty re-targeting reset
	if (pindexLast->nHeight == FinalActivateForkHeight)
	{
        LogPrintf("MVF: FORK BLOCK DIFFICULTY RESET  %08x  \n", pindexLast->nBits);
		return pindexLast->nBits;
	}
	LogPrintf("MVF DEBUG DifficultyAdjInterval = %d , TimeSpan = %d \n", params.DifficultyAdjustmentInterval(pindexLast->nHeight), params.MVFPowTargetTimespan(pindexLast->nHeight));
    // MVF-Core end

	// Only change once per difficulty adjustment interval
	if ((pindexLast->nHeight+1) % params.DifficultyAdjustmentInterval(pindexLast->nHeight) != 0)  // MVF-Core
	{
		if (params.fPowAllowMinDifficultyBlocks && !force_retarget)  // MVF-Core
		{
			// Special difficulty rule for testnet:
			// If the new block's timestamp is more than 2* 10 minutes
			// then allow mining of a min-difficulty block.
			if (pblock->GetBlockTime() > pindexLast->GetBlockTime() + params.nPowTargetSpacing*2)
				return nProofOfWorkLimit;
			else
			{
				// Return the last non-special-min-difficulty-rules-block
				const CBlockIndex* pindex = pindexLast;
				while (pindex->pprev && pindex->nHeight % params.DifficultyAdjustmentInterval(pindexLast->nHeight) != 0 && pindex->nBits == nProofOfWorkLimit)  // MVF-Core
					pindex = pindex->pprev;
				return pindex->nBits;
			}
		}
		return pindexLast->nBits;
    }

	// Go back by what we want to be 14 days worth of blocks
    // MVF-Core begin adjust nHeightFirst
	int nHeightFirst = pindexLast->nHeight - (params.DifficultyAdjustmentInterval(pindexLast->nHeight)-1);
	if (params.MVFisWithinRetargetPeriod(pindexLast->nHeight))
		nHeightFirst = pindexLast->nHeight - params.DifficultyAdjustmentInterval(pindexLast->nHeight);
    // MVF-Core end
	assert(nHeightFirst >= 0);
	const CBlockIndex* pindexFirst = pindexLast->GetAncestor(nHeightFirst);
	assert(pindexFirst);

	return CalculateNextWorkRequired(pindexLast, pindexFirst->GetBlockTime(), params);

}

unsigned int CalculateNextWorkRequired(const CBlockIndex* pindexLast, int64_t nFirstBlockTime, const Consensus::Params& params)
{
    static bool force_retarget=GetBoolArg("-force-retarget", false);  // MVF-Core added to test retargeting
    const arith_uint256 bnPowLimit = UintToArith256(params.powLimit); // MVF-Core moved here

    if (params.fPowNoRetargeting && !force_retarget)  // MVF-Core
        return pindexLast->nBits;

    // Limit adjustment step
    int64_t nActualTimespan = pindexLast->GetBlockTime() - nFirstBlockTime;
    // MVF-Core begin check for abnormal condition
    // This actually occurred during testing, resulting in new target == 0
    // which could never be met
    if (nActualTimespan == 0) {
        LogPrintf("  MVF: nActualTimespan == 0, returning bnPowLimit\n");
        return bnPowLimit.GetCompact();
    }
    // MVF-Core end
    LogPrintf("  nActualTimespan = %d  before bounds\n", nActualTimespan);

    // MVF-Core begin target time span while within the re-target period
    int64_t nTargetTimespan = params.nPowTargetTimespan; // the original 14 days
    if (params.MVFisWithinRetargetPeriod(pindexLast->nHeight))
        nTargetTimespan = params.MVFPowTargetTimespan(pindexLast->nHeight);

    // permit abrupt changes for a few blocks after the fork i.e. when nTargetTimespan is < 30 minutes
    if (nTargetTimespan >= params.nPowTargetSpacing * 3)
    {
        // prevent abrupt changes to target
        if (nActualTimespan < nTargetTimespan/4)
            nActualTimespan = nTargetTimespan/4;
        if (nActualTimespan > nTargetTimespan*4)
            nActualTimespan = nTargetTimespan*4;
    }
    else LogPrintf("Abrupt RETARGET permitted.\n");
    // MVF-Core end

    // Retarget
    arith_uint256 bnNew, bnNew1, bnNew2;
    arith_uint256 bnOld;
    bnNew.SetCompact(pindexLast->nBits);
    bnOld = bnNew;
    // MVF-Core begin: do division before multiplication
    // at regtest difficulty, the multiplication is prone to overflowing.
    // we use some more variables to detect and report on such overflows,
    // at least during testing.
    // MVF-Core TODO: remove temporary overflow checks when no longer needed
    bnNew1 = bnNew / nTargetTimespan;
    bnNew2 = bnNew1 * nActualTimespan;
    bnNew = bnNew2;
    if (bnNew > bnPowLimit) {
        bnNew = bnPowLimit;
        LogPrintf("MVF GetNextWorkRequired exceeded POWLIMIT, RESET\n");
    }
    if (bnNew2 / nActualTimespan != bnNew1) {
        if  (nActualTimespan >= nTargetTimespan) {
            bnNew = bnPowLimit;
            LogPrintf("MVF GetNextWorkRequired overflow detected, RESET to POW LIMIT\n");
        }
        else {
            // this case would be very unexpected - timespan shorter but
            // still overflow... this is what we want to watch for during
            // testing.
            // in this case we take half the previous target, to increase
            // difficulty to increase targets, returning the calculation to
            // non-overflow conditions on next round...
            bnNew = bnOld / 2;
            LogPrintf("MVF GetNextWorkRequired overflow detected, set to bnOld / 2\n");
        }
    }
    // MVF-Core end

    /// debug print
    LogPrintf("GetNextWorkRequired RETARGET\n");
    LogPrintf("nTargetTimespan = %d    nActualTimespan = %d\n", nTargetTimespan, nActualTimespan);  // MVF-Core
    LogPrintf("Before: %08x  %s\n", pindexLast->nBits, bnOld.ToString());
    LogPrintf("After:  %08x  %s\n", bnNew.GetCompact(), bnNew.ToString());

    return bnNew.GetCompact();
}

bool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params& params)
{
    bool fNegative;
    bool fOverflow;
    arith_uint256 bnTarget;
    static bool force_retarget=GetBoolArg("-force-retarget", false);  // MVF-Core

    bnTarget.SetCompact(nBits, &fNegative, &fOverflow);

    // Check range
    // MVF-Core begin suppress trace output to enable faster test runs when
    // -force-retarget is used for retargeting tests
    if (fNegative || bnTarget == 0 || fOverflow || bnTarget > UintToArith256(params.powLimit)) {
        if (!force_retarget)
            return error("CheckProofOfWork(): nBits below minimum work");
        else
            return false;
    }

    // Check proof of work matches claimed amount
    // if retargeting is enforced on testnets, suppress this warning
    // because it would flood the logs when lots of hashing going on
    if (UintToArith256(hash) > bnTarget) {
        if (!force_retarget)
            return error("CheckProofOfWork(): hash %s doesn't match nBits 0x%x",hash.ToString(),nBits);
        else
            return false;
    }
    // MVF-Core end

    return true;
}

arith_uint256 GetBlockProof(const CBlockIndex& block)
{
    arith_uint256 bnTarget;
    bool fNegative;
    bool fOverflow;
    bnTarget.SetCompact(block.nBits, &fNegative, &fOverflow);
    if (fNegative || fOverflow || bnTarget == 0)
        return 0;
    // We need to compute 2**256 / (bnTarget+1), but we can't represent 2**256
    // as it's too large for a arith_uint256. However, as 2**256 is at least as large
    // as bnTarget+1, it is equal to ((2**256 - bnTarget - 1) / (bnTarget+1)) + 1,
    // or ~bnTarget / (nTarget+1) + 1.
    return (~bnTarget / (bnTarget + 1)) + 1;
}

int64_t GetBlockProofEquivalentTime(const CBlockIndex& to, const CBlockIndex& from, const CBlockIndex& tip, const Consensus::Params& params)
{
    arith_uint256 r;
    int sign = 1;
    if (to.nChainWork > from.nChainWork) {
        r = to.nChainWork - from.nChainWork;
    } else {
        r = from.nChainWork - to.nChainWork;
        sign = -1;
    }
    r = r * arith_uint256(params.nPowTargetSpacing) / GetBlockProof(tip);
    if (r.bits() > 63) {
        return sign * std::numeric_limits<int64_t>::max();
    }
    return sign * r.GetLow64();
}
<|endoftext|>


<commit_before>// Copyright (c) 2009 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 "app/gtk_dnd_util.h"

#include "base/logging.h"
#include "base/pickle.h"
#include "base/utf_string_conversions.h"
#include "googleurl/src/gurl.h"

static const int kBitsPerByte = 8;

using WebKit::WebDragOperationsMask;
using WebKit::WebDragOperation;
using WebKit::WebDragOperationNone;
using WebKit::WebDragOperationCopy;
using WebKit::WebDragOperationLink;
using WebKit::WebDragOperationMove;

namespace {

void AddTargetToList(GtkTargetList* targets, int target_code) {
  switch (target_code) {
    case gtk_dnd_util::TEXT_PLAIN:
      gtk_target_list_add_text_targets(targets, gtk_dnd_util::TEXT_PLAIN);
      break;

    case gtk_dnd_util::TEXT_URI_LIST:
      gtk_target_list_add_uri_targets(targets, gtk_dnd_util::TEXT_URI_LIST);
      break;

    case gtk_dnd_util::TEXT_HTML:
      gtk_target_list_add(
          targets, gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::TEXT_PLAIN),
          0, gtk_dnd_util::TEXT_HTML);
      break;

    case gtk_dnd_util::NETSCAPE_URL:
      gtk_target_list_add(targets,
          gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::NETSCAPE_URL),
          0, gtk_dnd_util::NETSCAPE_URL);
      break;

    case gtk_dnd_util::CHROME_TAB:
    case gtk_dnd_util::CHROME_BOOKMARK_ITEM:
    case gtk_dnd_util::CHROME_NAMED_URL:
      gtk_target_list_add(targets, gtk_dnd_util::GetAtomForTarget(target_code),
                          GTK_TARGET_SAME_APP, target_code);
      break;

    case gtk_dnd_util::DIRECT_SAVE_FILE:
      gtk_target_list_add(targets,
          gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::DIRECT_SAVE_FILE),
          0, gtk_dnd_util::DIRECT_SAVE_FILE);
      break;

    default:
      NOTREACHED() << " Unexpected target code: " << target_code;
  }
}

}  // namespace

namespace gtk_dnd_util {

GdkAtom GetAtomForTarget(int target) {
  switch (target) {
    case CHROME_TAB:
      static GdkAtom tab_atom = gdk_atom_intern(
          const_cast<char*>("application/x-chrome-tab"), false);
      return tab_atom;

    case TEXT_HTML:
      static GdkAtom html_atom = gdk_atom_intern(
          const_cast<char*>("text/html"), false);
      return html_atom;

    case CHROME_BOOKMARK_ITEM:
      static GdkAtom bookmark_atom = gdk_atom_intern(
          const_cast<char*>("application/x-chrome-bookmark-item"), false);
      return bookmark_atom;

    case TEXT_PLAIN:
      static GdkAtom text_atom = gdk_atom_intern(
          const_cast<char*>("text/plain;charset=utf-8"), false);
      return text_atom;

    case TEXT_URI_LIST:
      static GdkAtom uris_atom = gdk_atom_intern(
          const_cast<char*>("text/uri-list"), false);
      return uris_atom;

    case CHROME_NAMED_URL:
      static GdkAtom named_url = gdk_atom_intern(
          const_cast<char*>("application/x-chrome-named-url"), false);
      return named_url;

    case NETSCAPE_URL:
      static GdkAtom netscape_url = gdk_atom_intern(
          const_cast<char*>("_NETSCAPE_URL"), false);
      return netscape_url;

    case TEXT_PLAIN_NO_CHARSET:
      static GdkAtom text_no_charset_atom = gdk_atom_intern(
          const_cast<char*>("text/plain"), false);
      return text_no_charset_atom;

    case DIRECT_SAVE_FILE:
      static GdkAtom xds_atom = gdk_atom_intern(
          const_cast<char*>("XdndDirectSave0"), false);
      return xds_atom;

    default:
      NOTREACHED();
  }

  return NULL;
}

GtkTargetList* GetTargetListFromCodeMask(int code_mask) {
  GtkTargetList* targets = gtk_target_list_new(NULL, 0);

  for (size_t i = 1; i < INVALID_TARGET; i = i << 1) {
    if (i == CHROME_WEBDROP_FILE_CONTENTS)
      continue;

    if (i & code_mask)
      AddTargetToList(targets, i);
  }

  return targets;
}

void SetSourceTargetListFromCodeMask(GtkWidget* source, int code_mask) {
  GtkTargetList* targets = GetTargetListFromCodeMask(code_mask);
  gtk_drag_source_set_target_list(source, targets);
  gtk_target_list_unref(targets);
}

void SetDestTargetList(GtkWidget* dest, const int* target_codes) {
  GtkTargetList* targets = gtk_target_list_new(NULL, 0);

  for (size_t i = 0; target_codes[i] != -1; ++i) {
    AddTargetToList(targets, target_codes[i]);
  }

  gtk_drag_dest_set_target_list(dest, targets);
  gtk_target_list_unref(targets);
}

void WriteURLWithName(GtkSelectionData* selection_data,
                      const GURL& url,
                      const string16& title,
                      int type) {
  switch (type) {
    case TEXT_PLAIN: {
      gtk_selection_data_set_text(selection_data, url.spec().c_str(),
                                  url.spec().length());
      break;
    }
    case TEXT_URI_LIST: {
      gchar* uri_array[2];
      uri_array[0] = strdup(url.spec().c_str());
      uri_array[1] = NULL;
      gtk_selection_data_set_uris(selection_data, uri_array);
      free(uri_array[0]);
      break;
    }
    case CHROME_NAMED_URL: {
      Pickle pickle;
      pickle.WriteString(UTF16ToUTF8(title));
      pickle.WriteString(url.spec());
      gtk_selection_data_set(
          selection_data,
          GetAtomForTarget(gtk_dnd_util::CHROME_NAMED_URL),
          kBitsPerByte,
          reinterpret_cast<const guchar*>(pickle.data()),
          pickle.size());
      break;
    }
    case NETSCAPE_URL: {
      // _NETSCAPE_URL format is URL + \n + title.
      std::string utf8_text = url.spec() + "\n" + UTF16ToUTF8(title);
      gtk_selection_data_set(selection_data,
                             selection_data->target,
                             kBitsPerByte,
                             reinterpret_cast<const guchar*>(utf8_text.c_str()),
                             utf8_text.length());
      break;
    }

    default: {
      NOTREACHED();
      break;
    }
  }
}

bool ExtractNamedURL(GtkSelectionData* selection_data,
                     GURL* url,
                     string16* title) {
  Pickle data(reinterpret_cast<char*>(selection_data->data),
              selection_data->length);
  void* iter = NULL;
  std::string title_utf8, url_utf8;
  if (!data.ReadString(&iter, &title_utf8) ||
      !data.ReadString(&iter, &url_utf8)) {
    return false;
  }

  GURL gurl(url_utf8);
  if (!gurl.is_valid())
    return false;

  *url = gurl;
  *title = UTF8ToUTF16(title_utf8);
  return true;
}

bool ExtractURIList(GtkSelectionData* selection_data, std::vector<GURL>* urls) {
  gchar** uris = gtk_selection_data_get_uris(selection_data);
  if (!uris)
    return false;

  for (size_t i = 0; uris[i] != NULL; ++i) {
    GURL url(uris[i]);
    if (url.is_valid())
      urls->push_back(url);
  }

  g_strfreev(uris);
  return true;
}

GdkDragAction WebDragOpToGdkDragAction(WebDragOperationsMask op) {
  GdkDragAction action = static_cast<GdkDragAction>(0);
  if (op & WebDragOperationCopy)
    action = static_cast<GdkDragAction>(action | GDK_ACTION_COPY);
  if (op & WebDragOperationLink)
    action = static_cast<GdkDragAction>(action | GDK_ACTION_LINK);
  if (op & WebDragOperationMove)
    action = static_cast<GdkDragAction>(action | GDK_ACTION_MOVE);
  return action;
}

WebDragOperationsMask GdkDragActionToWebDragOp(GdkDragAction action) {
  WebDragOperationsMask op = WebDragOperationNone;
  if (action & GDK_ACTION_COPY)
    op = static_cast<WebDragOperationsMask>(op | WebDragOperationCopy);
  if (action & GDK_ACTION_LINK)
    op = static_cast<WebDragOperationsMask>(op | WebDragOperationLink);
  if (action & GDK_ACTION_MOVE)
    op = static_cast<WebDragOperationsMask>(op | WebDragOperationMove);
  return op;
}

}  // namespace gtk_dnd_util
<commit_msg>We DnD shouldn't provide text/html if it claims to provide text/text/plain;charset=utf-8.<commit_after>// Copyright (c) 2009 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 "app/gtk_dnd_util.h"

#include "base/logging.h"
#include "base/pickle.h"
#include "base/utf_string_conversions.h"
#include "googleurl/src/gurl.h"

static const int kBitsPerByte = 8;

using WebKit::WebDragOperationsMask;
using WebKit::WebDragOperation;
using WebKit::WebDragOperationNone;
using WebKit::WebDragOperationCopy;
using WebKit::WebDragOperationLink;
using WebKit::WebDragOperationMove;

namespace {

void AddTargetToList(GtkTargetList* targets, int target_code) {
  switch (target_code) {
    case gtk_dnd_util::TEXT_PLAIN:
      gtk_target_list_add_text_targets(targets, gtk_dnd_util::TEXT_PLAIN);
      break;

    case gtk_dnd_util::TEXT_URI_LIST:
      gtk_target_list_add_uri_targets(targets, gtk_dnd_util::TEXT_URI_LIST);
      break;

    case gtk_dnd_util::TEXT_HTML:
      gtk_target_list_add(
          targets, gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::TEXT_HTML),
          0, gtk_dnd_util::TEXT_HTML);
      break;

    case gtk_dnd_util::NETSCAPE_URL:
      gtk_target_list_add(targets,
          gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::NETSCAPE_URL),
          0, gtk_dnd_util::NETSCAPE_URL);
      break;

    case gtk_dnd_util::CHROME_TAB:
    case gtk_dnd_util::CHROME_BOOKMARK_ITEM:
    case gtk_dnd_util::CHROME_NAMED_URL:
      gtk_target_list_add(targets, gtk_dnd_util::GetAtomForTarget(target_code),
                          GTK_TARGET_SAME_APP, target_code);
      break;

    case gtk_dnd_util::DIRECT_SAVE_FILE:
      gtk_target_list_add(targets,
          gtk_dnd_util::GetAtomForTarget(gtk_dnd_util::DIRECT_SAVE_FILE),
          0, gtk_dnd_util::DIRECT_SAVE_FILE);
      break;

    default:
      NOTREACHED() << " Unexpected target code: " << target_code;
  }
}

}  // namespace

namespace gtk_dnd_util {

GdkAtom GetAtomForTarget(int target) {
  switch (target) {
    case CHROME_TAB:
      static GdkAtom tab_atom = gdk_atom_intern(
          const_cast<char*>("application/x-chrome-tab"), false);
      return tab_atom;

    case TEXT_HTML:
      static GdkAtom html_atom = gdk_atom_intern(
          const_cast<char*>("text/html"), false);
      return html_atom;

    case CHROME_BOOKMARK_ITEM:
      static GdkAtom bookmark_atom = gdk_atom_intern(
          const_cast<char*>("application/x-chrome-bookmark-item"), false);
      return bookmark_atom;

    case TEXT_PLAIN:
      static GdkAtom text_atom = gdk_atom_intern(
          const_cast<char*>("text/plain;charset=utf-8"), false);
      return text_atom;

    case TEXT_URI_LIST:
      static GdkAtom uris_atom = gdk_atom_intern(
          const_cast<char*>("text/uri-list"), false);
      return uris_atom;

    case CHROME_NAMED_URL:
      static GdkAtom named_url = gdk_atom_intern(
          const_cast<char*>("application/x-chrome-named-url"), false);
      return named_url;

    case NETSCAPE_URL:
      static GdkAtom netscape_url = gdk_atom_intern(
          const_cast<char*>("_NETSCAPE_URL"), false);
      return netscape_url;

    case TEXT_PLAIN_NO_CHARSET:
      static GdkAtom text_no_charset_atom = gdk_atom_intern(
          const_cast<char*>("text/plain"), false);
      return text_no_charset_atom;

    case DIRECT_SAVE_FILE:
      static GdkAtom xds_atom = gdk_atom_intern(
          const_cast<char*>("XdndDirectSave0"), false);
      return xds_atom;

    default:
      NOTREACHED();
  }

  return NULL;
}

GtkTargetList* GetTargetListFromCodeMask(int code_mask) {
  GtkTargetList* targets = gtk_target_list_new(NULL, 0);

  for (size_t i = 1; i < INVALID_TARGET; i = i << 1) {
    if (i == CHROME_WEBDROP_FILE_CONTENTS)
      continue;

    if (i & code_mask)
      AddTargetToList(targets, i);
  }

  return targets;
}

void SetSourceTargetListFromCodeMask(GtkWidget* source, int code_mask) {
  GtkTargetList* targets = GetTargetListFromCodeMask(code_mask);
  gtk_drag_source_set_target_list(source, targets);
  gtk_target_list_unref(targets);
}

void SetDestTargetList(GtkWidget* dest, const int* target_codes) {
  GtkTargetList* targets = gtk_target_list_new(NULL, 0);

  for (size_t i = 0; target_codes[i] != -1; ++i) {
    AddTargetToList(targets, target_codes[i]);
  }

  gtk_drag_dest_set_target_list(dest, targets);
  gtk_target_list_unref(targets);
}

void WriteURLWithName(GtkSelectionData* selection_data,
                      const GURL& url,
                      const string16& title,
                      int type) {
  switch (type) {
    case TEXT_PLAIN: {
      gtk_selection_data_set_text(selection_data, url.spec().c_str(),
                                  url.spec().length());
      break;
    }
    case TEXT_URI_LIST: {
      gchar* uri_array[2];
      uri_array[0] = strdup(url.spec().c_str());
      uri_array[1] = NULL;
      gtk_selection_data_set_uris(selection_data, uri_array);
      free(uri_array[0]);
      break;
    }
    case CHROME_NAMED_URL: {
      Pickle pickle;
      pickle.WriteString(UTF16ToUTF8(title));
      pickle.WriteString(url.spec());
      gtk_selection_data_set(
          selection_data,
          GetAtomForTarget(gtk_dnd_util::CHROME_NAMED_URL),
          kBitsPerByte,
          reinterpret_cast<const guchar*>(pickle.data()),
          pickle.size());
      break;
    }
    case NETSCAPE_URL: {
      // _NETSCAPE_URL format is URL + \n + title.
      std::string utf8_text = url.spec() + "\n" + UTF16ToUTF8(title);
      gtk_selection_data_set(selection_data,
                             selection_data->target,
                             kBitsPerByte,
                             reinterpret_cast<const guchar*>(utf8_text.c_str()),
                             utf8_text.length());
      break;
    }

    default: {
      NOTREACHED();
      break;
    }
  }
}

bool ExtractNamedURL(GtkSelectionData* selection_data,
                     GURL* url,
                     string16* title) {
  Pickle data(reinterpret_cast<char*>(selection_data->data),
              selection_data->length);
  void* iter = NULL;
  std::string title_utf8, url_utf8;
  if (!data.ReadString(&iter, &title_utf8) ||
      !data.ReadString(&iter, &url_utf8)) {
    return false;
  }

  GURL gurl(url_utf8);
  if (!gurl.is_valid())
    return false;

  *url = gurl;
  *title = UTF8ToUTF16(title_utf8);
  return true;
}

bool ExtractURIList(GtkSelectionData* selection_data, std::vector<GURL>* urls) {
  gchar** uris = gtk_selection_data_get_uris(selection_data);
  if (!uris)
    return false;

  for (size_t i = 0; uris[i] != NULL; ++i) {
    GURL url(uris[i]);
    if (url.is_valid())
      urls->push_back(url);
  }

  g_strfreev(uris);
  return true;
}

GdkDragAction WebDragOpToGdkDragAction(WebDragOperationsMask op) {
  GdkDragAction action = static_cast<GdkDragAction>(0);
  if (op & WebDragOperationCopy)
    action = static_cast<GdkDragAction>(action | GDK_ACTION_COPY);
  if (op & WebDragOperationLink)
    action = static_cast<GdkDragAction>(action | GDK_ACTION_LINK);
  if (op & WebDragOperationMove)
    action = static_cast<GdkDragAction>(action | GDK_ACTION_MOVE);
  return action;
}

WebDragOperationsMask GdkDragActionToWebDragOp(GdkDragAction action) {
  WebDragOperationsMask op = WebDragOperationNone;
  if (action & GDK_ACTION_COPY)
    op = static_cast<WebDragOperationsMask>(op | WebDragOperationCopy);
  if (action & GDK_ACTION_LINK)
    op = static_cast<WebDragOperationsMask>(op | WebDragOperationLink);
  if (action & GDK_ACTION_MOVE)
    op = static_cast<WebDragOperationsMask>(op | WebDragOperationMove);
  return op;
}

}  // namespace gtk_dnd_util
<|endoftext|>