<commit_before>#include "CollisionSkeleton.h"
#include "CollisionShapes.h"
#include "kinematics/Shape.h"
#include <cmath>
#include "utils/LoadOpengl.h"
#include "utils/UtilsMath.h"

using namespace std;
using namespace Eigen;
using namespace utils;

namespace collision_checking{

    CollisionSkeletonNode::CollisionSkeletonNode(kinematics::BodyNode* _bodyNode)
    {
        mBodyNode = _bodyNode;
        if (mBodyNode->getShape()->getShapeType() == kinematics::Shape::P_ELLIPSOID) {
            mMesh = createEllipsoid<fcl::OBBRSS>(mBodyNode->getShape()->getDim()[0], mBodyNode->getShape()->getDim()[1], mBodyNode->getShape()->getDim()[2]);
        } else if (mBodyNode->getShape()->getShapeType() == kinematics::Shape::P_CUBE) {
            mMesh = createCube<fcl::OBBRSS>(mBodyNode->getShape()->getDim()[0], mBodyNode->getShape()->getDim()[1], mBodyNode->getShape()->getDim()[2]);
        } else {
            mMesh = createMesh<fcl::OBBRSS>(mBodyNode->getShape()->getDim()[0], mBodyNode->getShape()->getDim()[1], mBodyNode->getShape()->getDim()[2], _bodyNode->getShape()->getVizMesh());
        }
    }
    CollisionSkeletonNode::~CollisionSkeletonNode()
    {
        delete mMesh;
    }

    int CollisionSkeletonNode::checkCollision(CollisionSkeletonNode* _otherNode, vector<ContactPoint>* _contactPoints, int _num_max_contact)
    {
        evalRT();
        _otherNode->evalRT();
        fcl::CollisionResult res;
        fcl::CollisionRequest req;

        req.enable_contact = _contactPoints; // only evaluate contact points if data structure for returning the contact points was provided
        req.num_max_contacts = _num_max_contact;
        fcl::collide(mMesh, mFclWorldTrans, _otherNode->mMesh, _otherNode->mFclWorldTrans, req, res);

        if(!_contactPoints) {
            return res.isCollision() ? 1 : 0;
        }

        int start, size;
        start = _contactPoints->size();
        size = 0;

        int numCoplanarContacts = 0;
        int numNoContacts = 0;
        int numContacts = 0;

        for(int i = 0; i < res.numContacts();i++) {
            // for each pair of intersecting triangles, we create two contact points
            ContactPoint pair1, pair2;
            pair1.bd1 = mBodyNode;
            pair1.bd2 = _otherNode->mBodyNode;
            pair1.bdID1 = this->mBodynodeID;
            pair1.bdID2 = _otherNode->mBodynodeID;
            pair1.collisionSkeletonNode1 = this;
            pair1.collisionSkeletonNode2 = _otherNode;
            fcl::Vec3f v;
            pair1.triID1 = res.getContact(i).b1;
            pair1.triID2 = res.getContact(i).b2;
            pair1.penetrationDepth = res.getContact(i).penetration_depth;
            pair2 = pair1;
            int contactResult = evalContactPosition(res, _otherNode, i, pair1.point, pair2.point, pair1.contactTri);
            pair2.contactTri = pair1.contactTri;
            if(contactResult == COPLANAR_CONTACT) {
                numCoplanarContacts++;
                //                if(numContacts != 0 || numCoplanarContacts > 1)
                if (numContacts > 2)
                  continue;
            } else if(contactResult == NO_CONTACT) {
                numNoContacts++;
                continue;
            } else {
                numContacts++;
            }
            v = res.getContact(i).normal;
            pair1.normal = Vector3d(v[0], v[1], v[2]);
            pair2.normal = Vector3d(v[0], v[1], v[2]);

            _contactPoints->push_back(pair1);
            _contactPoints->push_back(pair2);

            size+=2;
        }

        if(res.numContacts()==0)
            return 0;

        const double ZERO = 0.000001;
        const double ZERO2 = ZERO*ZERO;

        vector<int> deleteIDs;
        size = _contactPoints->size() - start;
        deleteIDs.clear();

        // mark all the repeated points
        for (int i = start; i < start + size; i++)
            for (int j = i + 1; j < start + size; j++) {
                Vector3d diff = (*_contactPoints)[i].point - (*_contactPoints)[j].point;
                if (diff.dot(diff) < 3 * ZERO2) {
                    deleteIDs.push_back(i);
                    break;
                }
            }
        // delete repeated points
        for (int i = deleteIDs.size() - 1; i >= 0; i--)
            _contactPoints->erase(_contactPoints->begin() + deleteIDs[i]);

        size = _contactPoints->size() - start;
        deleteIDs.clear();

        // remove all the co-linear contact points
        bool bremove;
        for (int i = start; i < start + size; i++) {
            bremove = false;
            for (int j = start; j < start + size; j++) {
                if (j == i)
                    continue;
                if (bremove)
                    break;
                for (int k = j + 1; k < start + size; k++) {
                    if (i == k)
                        continue;
                    Vector3d  v = ((*_contactPoints)[i].point - (*_contactPoints)[j].point).cross((*_contactPoints)[i].point - (*_contactPoints)[k].point);
                    if (v.dot(v) < ZERO2 && (((*_contactPoints)[i].point - (*_contactPoints)[j].point).dot((*_contactPoints)[i].point - (*_contactPoints)[k].point) < 0)) {
                        bremove = true;
                        break;
                    }
                }
            }
            if (bremove)
                deleteIDs.push_back(i);
        }

        for (int i = deleteIDs.size() - 1; i >= 0; i--)
            _contactPoints->erase(_contactPoints->begin() + deleteIDs[i]);

        int collisionNum = res.numContacts();
        //return numCoplanarContacts*100+numNoContacts;
        return collisionNum;
    }

    void CollisionSkeletonNode::evalRT() {
        mWorldTrans = mBodyNode->getWorldTransform();
        mFclWorldTrans = fcl::Transform3f(fcl::Matrix3f(mWorldTrans(0,0), mWorldTrans(0,1), mWorldTrans(0,2),
                                                        mWorldTrans(1,0), mWorldTrans(1,1), mWorldTrans(1,2),
                                                        mWorldTrans(2,0), mWorldTrans(2,1), mWorldTrans(2,2)),
                                          fcl::Vec3f(mWorldTrans(0,3), mWorldTrans(1,3), mWorldTrans(2,3)));
    }

    int CollisionSkeletonNode::evalContactPosition(fcl::CollisionResult& _result,  CollisionSkeletonNode* _other, int _idx, Vector3d& _contactPosition1, Vector3d& _contactPosition2, ContactTriangle& _contactTri ) {
        int id1, id2;
        fcl::Triangle tri1, tri2;
        CollisionSkeletonNode* node1 = this;
        CollisionSkeletonNode* node2 = _other;
        id1 = _result.getContact(_idx).b1;
        id2 = _result.getContact(_idx).b2;
        tri1 = node1->mMesh->tri_indices[id1];
        tri2 = node2->mMesh->tri_indices[id2];

        fcl::Vec3f v1, v2, v3, p1, p2, p3;
        v1 = node1->mMesh->vertices[tri1[0]];
        v2 = node1->mMesh->vertices[tri1[1]];
        v3 = node1->mMesh->vertices[tri1[2]];

        p1 = node2->mMesh->vertices[tri2[0]];
        p2 = node2->mMesh->vertices[tri2[1]];
        p3 = node2->mMesh->vertices[tri2[2]];

        fcl::Vec3f contact1, contact2;
        v1 = node1->TransformVertex(v1);
        v2 = node1->TransformVertex(v2);
        v3 = node1->TransformVertex(v3);
        p1 = node2->TransformVertex(p1);
        p2 = node2->TransformVertex(p2);
        p3 = node2->TransformVertex(p3);
        int testRes = FFtest(v1, v2, v3, p1, p2, p3, contact1, contact2);

        _contactTri.v1 = v1;
        _contactTri.v2 = v2;
        _contactTri.v3 = v3;
        _contactTri.u1 = p1;
        _contactTri.u2 = p2;
        _contactTri.u3 = p3;
        if (testRes == COPLANAR_CONTACT) {
            double area1 = triArea(v1, v2, v3);
            double area2 = triArea(p1, p2, p3);
            //            cout << "this node = " << this->mBodynodeID << " other node = " << _other->mBodynodeID << endl;
            if (area1 < area2)
                contact1 = v1 + v2 + v3;
            else
                contact1 = p1 + p2 + p3;
            contact1[0] /= 3.0;
            contact1[1] /= 3.0;
            contact1[2] /= 3.0;
            contact2 = contact1;
            //            cout << contact1[0] << " " << contact1[1] << " " << contact1[2] << endl;
        }
        _contactPosition1 = Vector3d(contact1[0], contact1[1], contact1[2]);
        _contactPosition2 = Vector3d(contact2[0], contact2[1], contact2[2]);
        return testRes;
    }

    void CollisionSkeletonNode::drawCollisionTriangle(int _tri) {
        fcl::Triangle Tri = mMesh->tri_indices[_tri];
        glVertex3f(mMesh->vertices[Tri[0]][0], mMesh->vertices[Tri[0]][1], mMesh->vertices[Tri[0]][2]);
        glVertex3f(mMesh->vertices[Tri[1]][0], mMesh->vertices[Tri[1]][1], mMesh->vertices[Tri[1]][2]);
        glVertex3f(mMesh->vertices[Tri[2]][0], mMesh->vertices[Tri[2]][1], mMesh->vertices[Tri[2]][2]);
    }

    void CollisionSkeletonNode::drawCollisionSkeletonNode(bool _bTrans) {
        evalRT();
        double M[16];
        for(int i=0;i<4;i++)
            for(int j=0;j<4;j++)
                M[j*4+i] = mWorldTrans(i, j);
        fcl::Vec3f v1, v2, v3;
        glPushMatrix();
        if(_bTrans)
            glMultMatrixd(M);
        glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
        glBegin(GL_TRIANGLES);
        for(int i = 0;i < mMesh->num_tris; i++) {
            fcl::Triangle tri = mMesh->tri_indices[i];
            glVertex3f(mMesh->vertices[tri[0]][0], mMesh->vertices[tri[0]][1], mMesh->vertices[tri[0]][2]);
            glVertex3f(mMesh->vertices[tri[1]][0], mMesh->vertices[tri[1]][1], mMesh->vertices[tri[1]][2]);
            glVertex3f(mMesh->vertices[tri[2]][0], mMesh->vertices[tri[2]][1], mMesh->vertices[tri[2]][2]);

        }
        glEnd();
        glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
        glPopMatrix();
    }

    SkeletonCollision::~SkeletonCollision() {
        for(int i=0;i<mCollisionSkeletonNodeList.size();i++)
            delete mCollisionSkeletonNodeList[i];
    }

    void SkeletonCollision::addCollisionSkeletonNode(kinematics::BodyNode *_bd, bool _bRecursive) {
        if (_bRecursive == false || _bd->getNumChildJoints() == 0) {
            CollisionSkeletonNode* csnode = new CollisionSkeletonNode(_bd);
            csnode->mBodynodeID = mCollisionSkeletonNodeList.size();
            mCollisionSkeletonNodeList.push_back(csnode);
            mBodyNodeHash[_bd] = csnode;
        } else {
            addCollisionSkeletonNode(_bd, false);
            for (int i = 0; i < _bd->getNumChildJoints(); i++)
                addCollisionSkeletonNode(_bd->getChildNode(i), true);
        }
    }

    bool SkeletonCollision::checkCollision(bool _calculateContactPoints) {
        int num_max_contact = 100;
        clearAllContacts();
        mNumTriIntersection = 0;
        for (int i = 0; i < mCollisionSkeletonNodeList.size(); i++) {
            for (int j = i + 1; j < mCollisionSkeletonNodeList.size(); j++) {
                if (mCollisionSkeletonNodeList[i]->mBodyNode->getParentNode() == mCollisionSkeletonNodeList[j]->mBodyNode || mCollisionSkeletonNodeList[j]->mBodyNode->getParentNode() == mCollisionSkeletonNodeList[i]->mBodyNode)
                    continue;
                if (mCollisionSkeletonNodeList[i]->mBodyNode->getSkel() == mCollisionSkeletonNodeList[j]->mBodyNode->getSkel())
                    continue;
                mNumTriIntersection += mCollisionSkeletonNodeList[i]->checkCollision(mCollisionSkeletonNodeList[j], _calculateContactPoints ? &mContactPointList : NULL, num_max_contact);
                if(!_calculateContactPoints && mNumTriIntersection > 0) {
                    return true;
                }
            }
        }
        return (mNumTriIntersection > 0);
    }

    void SkeletonCollision::draw() {
        for(int i=0;i<mCollisionSkeletonNodeList.size();i++)
            mCollisionSkeletonNodeList[i]->drawCollisionSkeletonNode();
    }
}
<commit_msg>Use collision mesh for collision checking.<commit_after>#include "CollisionSkeleton.h"
#include "CollisionShapes.h"
#include "kinematics/Shape.h"
#include <cmath>
#include "utils/LoadOpengl.h"
#include "utils/UtilsMath.h"

using namespace std;
using namespace Eigen;
using namespace utils;

namespace collision_checking{

    CollisionSkeletonNode::CollisionSkeletonNode(kinematics::BodyNode* _bodyNode)
    {
        mBodyNode = _bodyNode;
        if (mBodyNode->getShape()->getShapeType() == kinematics::Shape::P_ELLIPSOID) {
            mMesh = createEllipsoid<fcl::OBBRSS>(mBodyNode->getShape()->getDim()[0], mBodyNode->getShape()->getDim()[1], mBodyNode->getShape()->getDim()[2]);
        } else if (mBodyNode->getShape()->getShapeType() == kinematics::Shape::P_CUBE) {
            mMesh = createCube<fcl::OBBRSS>(mBodyNode->getShape()->getDim()[0], mBodyNode->getShape()->getDim()[1], mBodyNode->getShape()->getDim()[2]);
        } else {
            mMesh = createMesh<fcl::OBBRSS>(mBodyNode->getShape()->getDim()[0], mBodyNode->getShape()->getDim()[1], mBodyNode->getShape()->getDim()[2], _bodyNode->getShape()->getCollisionMesh());
        }
    }
    CollisionSkeletonNode::~CollisionSkeletonNode()
    {
        delete mMesh;
    }

    int CollisionSkeletonNode::checkCollision(CollisionSkeletonNode* _otherNode, vector<ContactPoint>* _contactPoints, int _num_max_contact)
    {
        evalRT();
        _otherNode->evalRT();
        fcl::CollisionResult res;
        fcl::CollisionRequest req;

        req.enable_contact = _contactPoints; // only evaluate contact points if data structure for returning the contact points was provided
        req.num_max_contacts = _num_max_contact;
        fcl::collide(mMesh, mFclWorldTrans, _otherNode->mMesh, _otherNode->mFclWorldTrans, req, res);

        if(!_contactPoints) {
            return res.isCollision() ? 1 : 0;
        }

        int start, size;
        start = _contactPoints->size();
        size = 0;

        int numCoplanarContacts = 0;
        int numNoContacts = 0;
        int numContacts = 0;

        for(int i = 0; i < res.numContacts();i++) {
            // for each pair of intersecting triangles, we create two contact points
            ContactPoint pair1, pair2;
            pair1.bd1 = mBodyNode;
            pair1.bd2 = _otherNode->mBodyNode;
            pair1.bdID1 = this->mBodynodeID;
            pair1.bdID2 = _otherNode->mBodynodeID;
            pair1.collisionSkeletonNode1 = this;
            pair1.collisionSkeletonNode2 = _otherNode;
            fcl::Vec3f v;
            pair1.triID1 = res.getContact(i).b1;
            pair1.triID2 = res.getContact(i).b2;
            pair1.penetrationDepth = res.getContact(i).penetration_depth;
            pair2 = pair1;
            int contactResult = evalContactPosition(res, _otherNode, i, pair1.point, pair2.point, pair1.contactTri);
            pair2.contactTri = pair1.contactTri;
            if(contactResult == COPLANAR_CONTACT) {
                numCoplanarContacts++;
                //                if(numContacts != 0 || numCoplanarContacts > 1)
                if (numContacts > 2)
                  continue;
            } else if(contactResult == NO_CONTACT) {
                numNoContacts++;
                continue;
            } else {
                numContacts++;
            }
            v = res.getContact(i).normal;
            pair1.normal = Vector3d(v[0], v[1], v[2]);
            pair2.normal = Vector3d(v[0], v[1], v[2]);

            _contactPoints->push_back(pair1);
            _contactPoints->push_back(pair2);

            size+=2;
        }

        if(res.numContacts()==0)
            return 0;

        const double ZERO = 0.000001;
        const double ZERO2 = ZERO*ZERO;

        vector<int> deleteIDs;
        size = _contactPoints->size() - start;
        deleteIDs.clear();

        // mark all the repeated points
        for (int i = start; i < start + size; i++)
            for (int j = i + 1; j < start + size; j++) {
                Vector3d diff = (*_contactPoints)[i].point - (*_contactPoints)[j].point;
                if (diff.dot(diff) < 3 * ZERO2) {
                    deleteIDs.push_back(i);
                    break;
                }
            }
        // delete repeated points
        for (int i = deleteIDs.size() - 1; i >= 0; i--)
            _contactPoints->erase(_contactPoints->begin() + deleteIDs[i]);

        size = _contactPoints->size() - start;
        deleteIDs.clear();

        // remove all the co-linear contact points
        bool bremove;
        for (int i = start; i < start + size; i++) {
            bremove = false;
            for (int j = start; j < start + size; j++) {
                if (j == i)
                    continue;
                if (bremove)
                    break;
                for (int k = j + 1; k < start + size; k++) {
                    if (i == k)
                        continue;
                    Vector3d  v = ((*_contactPoints)[i].point - (*_contactPoints)[j].point).cross((*_contactPoints)[i].point - (*_contactPoints)[k].point);
                    if (v.dot(v) < ZERO2 && (((*_contactPoints)[i].point - (*_contactPoints)[j].point).dot((*_contactPoints)[i].point - (*_contactPoints)[k].point) < 0)) {
                        bremove = true;
                        break;
                    }
                }
            }
            if (bremove)
                deleteIDs.push_back(i);
        }

        for (int i = deleteIDs.size() - 1; i >= 0; i--)
            _contactPoints->erase(_contactPoints->begin() + deleteIDs[i]);

        int collisionNum = res.numContacts();
        //return numCoplanarContacts*100+numNoContacts;
        return collisionNum;
    }

    void CollisionSkeletonNode::evalRT() {
        mWorldTrans = mBodyNode->getWorldTransform();
        mFclWorldTrans = fcl::Transform3f(fcl::Matrix3f(mWorldTrans(0,0), mWorldTrans(0,1), mWorldTrans(0,2),
                                                        mWorldTrans(1,0), mWorldTrans(1,1), mWorldTrans(1,2),
                                                        mWorldTrans(2,0), mWorldTrans(2,1), mWorldTrans(2,2)),
                                          fcl::Vec3f(mWorldTrans(0,3), mWorldTrans(1,3), mWorldTrans(2,3)));
    }

    int CollisionSkeletonNode::evalContactPosition(fcl::CollisionResult& _result,  CollisionSkeletonNode* _other, int _idx, Vector3d& _contactPosition1, Vector3d& _contactPosition2, ContactTriangle& _contactTri ) {
        int id1, id2;
        fcl::Triangle tri1, tri2;
        CollisionSkeletonNode* node1 = this;
        CollisionSkeletonNode* node2 = _other;
        id1 = _result.getContact(_idx).b1;
        id2 = _result.getContact(_idx).b2;
        tri1 = node1->mMesh->tri_indices[id1];
        tri2 = node2->mMesh->tri_indices[id2];

        fcl::Vec3f v1, v2, v3, p1, p2, p3;
        v1 = node1->mMesh->vertices[tri1[0]];
        v2 = node1->mMesh->vertices[tri1[1]];
        v3 = node1->mMesh->vertices[tri1[2]];

        p1 = node2->mMesh->vertices[tri2[0]];
        p2 = node2->mMesh->vertices[tri2[1]];
        p3 = node2->mMesh->vertices[tri2[2]];

        fcl::Vec3f contact1, contact2;
        v1 = node1->TransformVertex(v1);
        v2 = node1->TransformVertex(v2);
        v3 = node1->TransformVertex(v3);
        p1 = node2->TransformVertex(p1);
        p2 = node2->TransformVertex(p2);
        p3 = node2->TransformVertex(p3);
        int testRes = FFtest(v1, v2, v3, p1, p2, p3, contact1, contact2);

        _contactTri.v1 = v1;
        _contactTri.v2 = v2;
        _contactTri.v3 = v3;
        _contactTri.u1 = p1;
        _contactTri.u2 = p2;
        _contactTri.u3 = p3;
        if (testRes == COPLANAR_CONTACT) {
            double area1 = triArea(v1, v2, v3);
            double area2 = triArea(p1, p2, p3);
            //            cout << "this node = " << this->mBodynodeID << " other node = " << _other->mBodynodeID << endl;
            if (area1 < area2)
                contact1 = v1 + v2 + v3;
            else
                contact1 = p1 + p2 + p3;
            contact1[0] /= 3.0;
            contact1[1] /= 3.0;
            contact1[2] /= 3.0;
            contact2 = contact1;
            //            cout << contact1[0] << " " << contact1[1] << " " << contact1[2] << endl;
        }
        _contactPosition1 = Vector3d(contact1[0], contact1[1], contact1[2]);
        _contactPosition2 = Vector3d(contact2[0], contact2[1], contact2[2]);
        return testRes;
    }

    void CollisionSkeletonNode::drawCollisionTriangle(int _tri) {
        fcl::Triangle Tri = mMesh->tri_indices[_tri];
        glVertex3f(mMesh->vertices[Tri[0]][0], mMesh->vertices[Tri[0]][1], mMesh->vertices[Tri[0]][2]);
        glVertex3f(mMesh->vertices[Tri[1]][0], mMesh->vertices[Tri[1]][1], mMesh->vertices[Tri[1]][2]);
        glVertex3f(mMesh->vertices[Tri[2]][0], mMesh->vertices[Tri[2]][1], mMesh->vertices[Tri[2]][2]);
    }

    void CollisionSkeletonNode::drawCollisionSkeletonNode(bool _bTrans) {
        evalRT();
        double M[16];
        for(int i=0;i<4;i++)
            for(int j=0;j<4;j++)
                M[j*4+i] = mWorldTrans(i, j);
        fcl::Vec3f v1, v2, v3;
        glPushMatrix();
        if(_bTrans)
            glMultMatrixd(M);
        glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
        glBegin(GL_TRIANGLES);
        for(int i = 0;i < mMesh->num_tris; i++) {
            fcl::Triangle tri = mMesh->tri_indices[i];
            glVertex3f(mMesh->vertices[tri[0]][0], mMesh->vertices[tri[0]][1], mMesh->vertices[tri[0]][2]);
            glVertex3f(mMesh->vertices[tri[1]][0], mMesh->vertices[tri[1]][1], mMesh->vertices[tri[1]][2]);
            glVertex3f(mMesh->vertices[tri[2]][0], mMesh->vertices[tri[2]][1], mMesh->vertices[tri[2]][2]);

        }
        glEnd();
        glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
        glPopMatrix();
    }

    SkeletonCollision::~SkeletonCollision() {
        for(int i=0;i<mCollisionSkeletonNodeList.size();i++)
            delete mCollisionSkeletonNodeList[i];
    }

    void SkeletonCollision::addCollisionSkeletonNode(kinematics::BodyNode *_bd, bool _bRecursive) {
        if (_bRecursive == false || _bd->getNumChildJoints() == 0) {
            CollisionSkeletonNode* csnode = new CollisionSkeletonNode(_bd);
            csnode->mBodynodeID = mCollisionSkeletonNodeList.size();
            mCollisionSkeletonNodeList.push_back(csnode);
            mBodyNodeHash[_bd] = csnode;
        } else {
            addCollisionSkeletonNode(_bd, false);
            for (int i = 0; i < _bd->getNumChildJoints(); i++)
                addCollisionSkeletonNode(_bd->getChildNode(i), true);
        }
    }

    bool SkeletonCollision::checkCollision(bool _calculateContactPoints) {
        int num_max_contact = 100;
        clearAllContacts();
        mNumTriIntersection = 0;
        for (int i = 0; i < mCollisionSkeletonNodeList.size(); i++) {
            for (int j = i + 1; j < mCollisionSkeletonNodeList.size(); j++) {
                if (mCollisionSkeletonNodeList[i]->mBodyNode->getParentNode() == mCollisionSkeletonNodeList[j]->mBodyNode || mCollisionSkeletonNodeList[j]->mBodyNode->getParentNode() == mCollisionSkeletonNodeList[i]->mBodyNode)
                    continue;
                if (mCollisionSkeletonNodeList[i]->mBodyNode->getSkel() == mCollisionSkeletonNodeList[j]->mBodyNode->getSkel())
                    continue;
                mNumTriIntersection += mCollisionSkeletonNodeList[i]->checkCollision(mCollisionSkeletonNodeList[j], _calculateContactPoints ? &mContactPointList : NULL, num_max_contact);
                if(!_calculateContactPoints && mNumTriIntersection > 0) {
                    return true;
                }
            }
        }
        return (mNumTriIntersection > 0);
    }

    void SkeletonCollision::draw() {
        for(int i=0;i<mCollisionSkeletonNodeList.size();i++)
            mCollisionSkeletonNodeList[i]->drawCollisionSkeletonNode();
    }
}
<|endoftext|>


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

#include "src/traced/probes/ftrace/atrace_hal_wrapper.h"

#include "perfetto/base/build_config.h"
#include "src/android_internal/atrace_hal.h"
#include "src/android_internal/lazy_library_loader.h"

namespace perfetto {

namespace {
constexpr size_t kMaxNumCategories = 64;
}

struct AtraceHalWrapper::DynamicLibLoader {
  PERFETTO_LAZY_LOAD(android_internal::ForgetService, forget_service_);
  PERFETTO_LAZY_LOAD(android_internal::ListCategories, list_categories_);
  PERFETTO_LAZY_LOAD(android_internal::EnableCategories, enable_categories_);
  PERFETTO_LAZY_LOAD(android_internal::DisableAllCategories,
                     disable_all_categories_);

  std::vector<std::string> ListCategories() {
    std::vector<std::string> results;
    if (!list_categories_)
      return results;

    std::vector<android_internal::TracingVendorCategory> categories(
        kMaxNumCategories);
    size_t num_cat = categories.size();
    bool success = list_categories_(&categories[0], &num_cat);
    if (!success)
      return results;
    categories.resize(num_cat);

    for (const auto& category : categories) {
      results.push_back(category.name);
    }

    return results;
  }

  bool EnableCategories(const std::vector<std::string>& categories) {
    if (!enable_categories_)
      return false;
    std::vector<const char*> args;
    for (const std::string& category : categories) {
      args.push_back(category.c_str());
    }
    return enable_categories_(&args[0], args.size());
  }

  bool DisableAllCategories() {
    if (!disable_all_categories_)
      return false;
    return disable_all_categories_();
  }

  void ForgetService() {
    if (!forget_service_)
      return;
    forget_service_();
  }
};

AtraceHalWrapper::AtraceHalWrapper() {
#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
  lib_.reset(new DynamicLibLoader());
#endif
}

AtraceHalWrapper::~AtraceHalWrapper() {
  if (lib_)
    lib_->ForgetService();
};

std::vector<std::string> AtraceHalWrapper::ListCategories() {
  if (!lib_)
    return {};
  return lib_->ListCategories();
}

bool AtraceHalWrapper::EnableCategories(
    const std::vector<std::string>& categories) {
  if (!lib_)
    return true;
  return lib_->EnableCategories(categories);
}

bool AtraceHalWrapper::DisableAllCategories() {
  if (!lib_)
    return true;
  return lib_->DisableAllCategories();
}

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

#include "src/traced/probes/ftrace/atrace_hal_wrapper.h"

#include "perfetto/base/build_config.h"
#include "src/android_internal/atrace_hal.h"
#include "src/android_internal/lazy_library_loader.h"

namespace perfetto {

namespace {
constexpr size_t kMaxNumCategories = 64;
}

struct AtraceHalWrapper::DynamicLibLoader {
  PERFETTO_LAZY_LOAD(android_internal::ForgetService, forget_service_);
  PERFETTO_LAZY_LOAD(android_internal::ListCategories, list_categories_);
  PERFETTO_LAZY_LOAD(android_internal::EnableCategories, enable_categories_);
  PERFETTO_LAZY_LOAD(android_internal::DisableAllCategories,
                     disable_all_categories_);

  std::vector<std::string> ListCategories() {
    std::vector<std::string> results;
    if (!list_categories_)
      return results;

    std::vector<android_internal::TracingVendorCategory> categories(
        kMaxNumCategories);
    size_t num_cat = categories.size();
    bool success = list_categories_(&categories[0], &num_cat);
    if (!success)
      return results;
    categories.resize(num_cat);

    for (const auto& category : categories) {
      results.push_back(category.name);
    }

    return results;
  }

  bool EnableCategories(const std::vector<std::string>& categories) {
    if (!enable_categories_)
      return false;
    std::vector<const char*> args;
    for (const std::string& category : categories) {
      args.push_back(category.c_str());
    }
    return enable_categories_(&args[0], args.size());
  }

  bool DisableAllCategories() {
    if (!disable_all_categories_)
      return false;
    return disable_all_categories_();
  }

  void ForgetService() {
    if (!forget_service_)
      return;
    forget_service_();
  }
};

AtraceHalWrapper::AtraceHalWrapper() {
#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
  lib_.reset(new DynamicLibLoader());
#endif
}

AtraceHalWrapper::~AtraceHalWrapper() {
  if (lib_)
    lib_->ForgetService();
}

std::vector<std::string> AtraceHalWrapper::ListCategories() {
  if (!lib_)
    return {};
  return lib_->ListCategories();
}

bool AtraceHalWrapper::EnableCategories(
    const std::vector<std::string>& categories) {
  if (!lib_)
    return true;
  return lib_->EnableCategories(categories);
}

bool AtraceHalWrapper::DisableAllCategories() {
  if (!lib_)
    return true;
  return lib_->DisableAllCategories();
}

}  // namespace perfetto
<|endoftext|>


<commit_before>#include "../stdafx.h"

#include "crl.h"

void CRL::read(Handle<Bio> in, DataFormat::DATA_FORMAT format) {
	LOGGER_FN();

	try{
		if (in.isEmpty()){
			THROW_EXCEPTION(0, CRL, NULL, ERROR_PARAMETER_NULL, 1);
		}

		X509_CRL *crl = NULL;

		switch (format){
		case DataFormat::BASE64:
			LOGGER_OPENSSL("PEM_read_bio_X509_CRL");
			crl = PEM_read_bio_X509_CRL(in->internal(), NULL, NULL, NULL);
			if (!crl){
				THROW_EXCEPTION(0, CRL, NULL, ERROR_CRL_BAD_PEM_INPUT_DATA);
			}
			break;
		case DataFormat::DER:
			LOGGER_OPENSSL("d2i_X509_CRL_bio");
			crl = d2i_X509_CRL_bio(in->internal(), NULL);
			if (!crl){
				THROW_EXCEPTION(0, CRL, NULL, ERROR_CRL_BAD_DIR_INPUT_DATA);
			}
			break;
		default:
			THROW_EXCEPTION(0, CRL, NULL, ERROR_DATA_FORMAT_UNKNOWN_FORMAT, format);
		}
		this->setData(crl);
	}
	catch (Handle<Exception> e){
		THROW_EXCEPTION(0, CRL, e, "Error read CRL");
	}
}

void CRL::write(Handle<Bio> out, DataFormat::DATA_FORMAT format) {
	LOGGER_FN();

	try{
		if (out.isEmpty()){
			THROW_EXCEPTION(0, CRL, NULL, ERROR_PARAMETER_NULL, 1);
		}

		switch (format){
		case DataFormat::DER:
			LOGGER_OPENSSL(i2d_X509_CRL_bio);
			if (!i2d_X509_CRL_bio(out->internal(), this->internal())){
				THROW_OPENSSL_EXCEPTION(0, CRL, NULL, "i2d_X509_CRL_bio");
			}
			break;
		case DataFormat::BASE64:
			LOGGER_OPENSSL(PEM_write_bio_X509_CRL);
			if (!PEM_write_bio_X509_CRL(out->internal(), this->internal())){
				THROW_OPENSSL_EXCEPTION(0, CRL, NULL, "PEM_write_bio_X509_CRL");
			}
			break;
		}
		out->flush();
	}
	catch (Handle<Exception> e){
		THROW_EXCEPTION(0, CRL, e, "Error write CRL to file");
	}

}

Handle<CRL> CRL::duplicate(){
	LOGGER_FN();
	try{
		X509_CRL *crl = NULL;
		LOGGER_OPENSSL(X509_CRL_dup);
		crl = X509_CRL_dup(this->internal());
		if (!crl){
			THROW_OPENSSL_EXCEPTION(0, CRL, NULL, "X509_CRL_dup");
		}
		return new CRL(crl);
	}
	catch (Handle<Exception> e){
		THROW_EXCEPTION(0, CRL, e, "Eror duplicate CRL");
	}
}

int CRL::equals(Handle<CRL> crl){
	LOGGER_FN();
	try{
		LOGGER_OPENSSL(X509_CRL_cmp);
		if (X509_CRL_cmp(this->internal(), crl->internal()) == 0){
			return 0;
		}
		else{
			return -1;
		}
	}
	catch (Handle<Exception> e){
		THROW_EXCEPTION(0, CRL, e, "Error compare CRL");
	}
}

int CRL::compare(Handle<CRL> crl){
	LOGGER_FN();

	LOGGER_OPENSSL(X509_CRL_cmp);
	int res = X509_CRL_cmp(this->internal(), crl->internal());

	return res;
}

Handle<std::string> CRL::getThumbprint()
{
	LOGGER_FN();

	return this->hash(EVP_sha1());
}

Handle<std::string> CRL::hash(Handle<std::string> algorithm){
	LOGGER_FN();

	LOGGER_OPENSSL(EVP_get_digestbyname);
	const EVP_MD *md = EVP_get_digestbyname(algorithm->c_str());
	if (!md) {
		THROW_OPENSSL_EXCEPTION(0, CRL, NULL, "EVP_get_digestbyname");
	}

	return this->hash(md);
}

Handle<std::string> CRL::hash(const EVP_MD *md) {
	LOGGER_FN();

	unsigned char hash[EVP_MAX_MD_SIZE] = { 0 };
	unsigned int hashlen = 0;

	LOGGER_OPENSSL(X509_CRL_digest);
	if (!X509_CRL_digest(this->internal(), md, hash, &hashlen)) {
		THROW_OPENSSL_EXCEPTION(0, CRL, NULL, "X509_CRL_digest");
	}

	Handle<std::string> res = new std::string((char *)hash, hashlen);

	return res;
}

long CRL::getVersion()
{
	LOGGER_FN();
	std::string strBuf;

	LOGGER_OPENSSL(X509_CRL_get_version);
	long ver = X509_CRL_get_version(this->internal());

	return ver;
}

Handle<std::string> CRL::getSigAlgName(){
	LOGGER_FN();

	try{
		LOGGER_OPENSSL(OBJ_obj2nid);
		int pkey_nid = OBJ_obj2nid(this->internal()->sig_alg->algorithm);

		if (pkey_nid == NID_undef) {
			THROW_EXCEPTION(0, CRL, NULL, "Can not get key nid");
		}

		LOGGER_OPENSSL(OBJ_nid2ln);
		std::string sslbuf = OBJ_nid2ln(pkey_nid);

		Handle<std::string> res = new std::string(sslbuf.c_str(), sslbuf.length());

		return res;
	}
	catch (Handle<Exception> e){
		THROW_EXCEPTION(0, CRL, e, "Error get CRL signature algorithm long name");
	}
}

Handle<std::string> CRL::getSigAlgShortName(){
	LOGGER_FN();

	try{
		LOGGER_OPENSSL(OBJ_obj2nid);
		int pkey_nid = OBJ_obj2nid(this->internal()->sig_alg->algorithm);
		if (pkey_nid == NID_undef) {
			THROW_EXCEPTION(0, CRL, NULL, "Can not get key nid");
		}

		LOGGER_OPENSSL(OBJ_nid2ln);
		std::string sslbuf = OBJ_nid2sn(pkey_nid);

		Handle<std::string> res = new std::string(sslbuf.c_str(), sslbuf.length());

		return res;
	}
	catch (Handle<Exception> e){
		THROW_EXCEPTION(0, CRL, e, "Error get CRL signature algorithm short name");
	}
}

Handle<std::string> CRL::getSigAlgOID(){
	LOGGER_FN();

	try{
		char buf[100];
		LOGGER_OPENSSL(OBJ_obj2txt);
		int bufLen = 0;
		if ((bufLen = OBJ_obj2txt(buf, 100, this->internal()->sig_alg->algorithm, 1)) <= 0){
			THROW_OPENSSL_EXCEPTION(0, Algorithm, NULL, "OBJ_obj2txt");
		}

		std::string *res = new std::string(buf, bufLen);

		return res;
	}
	catch (Handle<Exception> e){
		THROW_EXCEPTION(0, CRL, e, "Error get CRL signature OID");
	}
}
Handle<std::string> CRL::issuerName()
{
	LOGGER_FN();

	LOGGER_OPENSSL(X509_CRL_get_issuer);
	X509_NAME *name = X509_CRL_get_issuer(this->internal());
	if (!name)
		THROW_EXCEPTION(1, CRL, NULL, "X509_NAME is NULL");

	LOGGER_OPENSSL(X509_NAME_oneline);
	char *str_name = X509_NAME_oneline(name, NULL, 0);
	if (!str_name)
		THROW_EXCEPTION(1, CRL, NULL, "X509_NAME_oneline");

	Handle<std::string> res = new std::string(str_name);
	OPENSSL_free(str_name);

	return res;
}

Handle<std::string> CRL::issuerFriendlyName()
{
	LOGGER_FN();

	LOGGER_OPENSSL(X509_get_issuer_name);
	return GetCommonName(X509_CRL_get_issuer(this->internal()));
}

Handle<std::string> CRL::GetCommonName(X509_NAME *a){
	LOGGER_FN();

	Handle<std::string> name = new std::string("");
	if (a == NULL)
		THROW_EXCEPTION(0, Certificate, NULL, "Parameter 1 can not be NULL");

	int nid = NID_commonName;
	LOGGER_OPENSSL(X509_NAME_get_index_by_NID);
	int index = X509_NAME_get_index_by_NID(a, nid, -1);
	if (index >= 0) {
		LOGGER_OPENSSL(X509_NAME_get_entry);
		X509_NAME_ENTRY *issuerNameCommonName = X509_NAME_get_entry(a, index);

		if (issuerNameCommonName) {
			LOGGER_OPENSSL(X509_NAME_ENTRY_get_data);
			ASN1_STRING *issuerCNASN1 = X509_NAME_ENTRY_get_data(issuerNameCommonName);

			if (issuerCNASN1 != NULL) {
				unsigned char *utf = NULL;
				LOGGER_OPENSSL(ASN1_STRING_to_UTF8);
				ASN1_STRING_to_UTF8(&utf, issuerCNASN1);
				name = new std::string((char *)utf);
				OPENSSL_free(utf);
			}
		}
	}
	else {
		return new std::string("No common name");
	}
	return name;
}

Handle<std::string> CRL::getEncoded(){
	LOGGER_FN();

	try{
		LOGGER_OPENSSL(BIO_new);
		BIO * bio_out = BIO_new(BIO_s_mem());
		LOGGER_OPENSSL(i2d_X509_CRL_bio);
		if (!i2d_X509_CRL_bio(bio_out, this->internal())){
			THROW_OPENSSL_EXCEPTION(0, CRL, NULL, "i2d_X509_CRL_bio");
		}
		BUF_MEM *bio_buf;
		LOGGER_OPENSSL(BIO_get_mem_ptr);
		BIO_get_mem_ptr(bio_out, &bio_buf);
		Handle<std::string> res = new std::string(bio_buf->data, bio_buf->length);
		LOGGER_OPENSSL(BIO_free);
		BIO_free(bio_out);

		return res;
	}
	catch (Handle<Exception> e){
		THROW_EXCEPTION(0, CRL, e, "Error get encoded CRL");
	}
}

Handle<std::string> CRL::getSignature(){
	LOGGER_FN();

	try{
		std::string sslbuf = std::string((char *)(this->internal()->signature)->data, (this->internal()->signature)->length);
		Handle<std::string> res = new std::string(sslbuf.c_str(), sslbuf.length());

		return res;
	}
	catch (Handle<Exception> e){
		THROW_EXCEPTION(0, CRL, e, "Error get signature CRL");
	}
}

Handle<std::string> CRL::getNextUpdate(){
	LOGGER_FN();

	LOGGER_OPENSSL(X509_CRL_get_nextUpdate);
	ASN1_TIME *time = X509_CRL_get_nextUpdate(this->internal());
	return ASN1_TIME_toString(time);
}

Handle<std::string> CRL::getThisUpdate(){
	LOGGER_FN();

	LOGGER_OPENSSL(X509_CRL_get_lastUpdate);
	ASN1_TIME *time = X509_CRL_get_lastUpdate(this->internal());
	return ASN1_TIME_toString(time);
}

Handle<RevokedCertificate> CRL::getRevokedCertificate(Handle<Certificate> cert){
	LOGGER_FN();

	if (cert.isEmpty()){
		THROW_EXCEPTION(0, CRL, NULL, ERROR_PARAMETER_NULL, 1);
	}
	X509_REVOKED *rc = NULL;
	LOGGER_OPENSSL(X509_CRL_get0_by_cert);
	if (X509_CRL_get0_by_cert(this->internal(), &rc, cert->internal())){
		return new RevokedCertificate(rc, this->handle());
	}
	else{
		return NULL;
	}
}

Handle<RevokedCertificate> CRL::getRevokedCertificate(Handle<std::string> serial){
	LOGGER_FN();

	if (serial.isEmpty()){
		THROW_EXCEPTION(0, CRL, NULL, ERROR_PARAMETER_NULL, 1);
	}

	BIGNUM* bn = BN_new();
	BN_bin2bn((const unsigned char *)serial->data(), serial->length(), bn);

	ASN1_INTEGER* asnInt = ASN1_INTEGER_new();
	BN_to_ASN1_INTEGER(bn, asnInt);

	X509_REVOKED *rc = NULL;
	LOGGER_OPENSSL(X509_CRL_get0_by_serial);
	if (X509_CRL_get0_by_serial(this->internal(), &rc, asnInt)){
		return new RevokedCertificate(rc, this->handle());
	}
	else{
		return NULL;
	}
}

Handle<std::string> RevokedCertificate::revocationDate()
{
	LOGGER_FN();

	ASN1_TIME *time = this->internal()->revocationDate;
	return ASN1_TIME_toString(time);
}

int RevokedCertificate::reason()
{
	LOGGER_FN();

	return this->internal()->reason;
}
<commit_msg>Del unusable variable<commit_after>#include "../stdafx.h"

#include "crl.h"

void CRL::read(Handle<Bio> in, DataFormat::DATA_FORMAT format) {
	LOGGER_FN();

	try{
		if (in.isEmpty()){
			THROW_EXCEPTION(0, CRL, NULL, ERROR_PARAMETER_NULL, 1);
		}

		X509_CRL *crl = NULL;

		switch (format){
		case DataFormat::BASE64:
			LOGGER_OPENSSL("PEM_read_bio_X509_CRL");
			crl = PEM_read_bio_X509_CRL(in->internal(), NULL, NULL, NULL);
			if (!crl){
				THROW_EXCEPTION(0, CRL, NULL, ERROR_CRL_BAD_PEM_INPUT_DATA);
			}
			break;
		case DataFormat::DER:
			LOGGER_OPENSSL("d2i_X509_CRL_bio");
			crl = d2i_X509_CRL_bio(in->internal(), NULL);
			if (!crl){
				THROW_EXCEPTION(0, CRL, NULL, ERROR_CRL_BAD_DIR_INPUT_DATA);
			}
			break;
		default:
			THROW_EXCEPTION(0, CRL, NULL, ERROR_DATA_FORMAT_UNKNOWN_FORMAT, format);
		}
		this->setData(crl);
	}
	catch (Handle<Exception> e){
		THROW_EXCEPTION(0, CRL, e, "Error read CRL");
	}
}

void CRL::write(Handle<Bio> out, DataFormat::DATA_FORMAT format) {
	LOGGER_FN();

	try{
		if (out.isEmpty()){
			THROW_EXCEPTION(0, CRL, NULL, ERROR_PARAMETER_NULL, 1);
		}

		switch (format){
		case DataFormat::DER:
			LOGGER_OPENSSL(i2d_X509_CRL_bio);
			if (!i2d_X509_CRL_bio(out->internal(), this->internal())){
				THROW_OPENSSL_EXCEPTION(0, CRL, NULL, "i2d_X509_CRL_bio");
			}
			break;
		case DataFormat::BASE64:
			LOGGER_OPENSSL(PEM_write_bio_X509_CRL);
			if (!PEM_write_bio_X509_CRL(out->internal(), this->internal())){
				THROW_OPENSSL_EXCEPTION(0, CRL, NULL, "PEM_write_bio_X509_CRL");
			}
			break;
		}
		out->flush();
	}
	catch (Handle<Exception> e){
		THROW_EXCEPTION(0, CRL, e, "Error write CRL to file");
	}

}

Handle<CRL> CRL::duplicate(){
	LOGGER_FN();
	try{
		X509_CRL *crl = NULL;
		LOGGER_OPENSSL(X509_CRL_dup);
		crl = X509_CRL_dup(this->internal());
		if (!crl){
			THROW_OPENSSL_EXCEPTION(0, CRL, NULL, "X509_CRL_dup");
		}
		return new CRL(crl);
	}
	catch (Handle<Exception> e){
		THROW_EXCEPTION(0, CRL, e, "Eror duplicate CRL");
	}
}

int CRL::equals(Handle<CRL> crl){
	LOGGER_FN();
	try{
		LOGGER_OPENSSL(X509_CRL_cmp);
		if (X509_CRL_cmp(this->internal(), crl->internal()) == 0){
			return 0;
		}
		else{
			return -1;
		}
	}
	catch (Handle<Exception> e){
		THROW_EXCEPTION(0, CRL, e, "Error compare CRL");
	}
}

int CRL::compare(Handle<CRL> crl){
	LOGGER_FN();

	LOGGER_OPENSSL(X509_CRL_cmp);
	int res = X509_CRL_cmp(this->internal(), crl->internal());

	return res;
}

Handle<std::string> CRL::getThumbprint()
{
	LOGGER_FN();

	return this->hash(EVP_sha1());
}

Handle<std::string> CRL::hash(Handle<std::string> algorithm){
	LOGGER_FN();

	LOGGER_OPENSSL(EVP_get_digestbyname);
	const EVP_MD *md = EVP_get_digestbyname(algorithm->c_str());
	if (!md) {
		THROW_OPENSSL_EXCEPTION(0, CRL, NULL, "EVP_get_digestbyname");
	}

	return this->hash(md);
}

Handle<std::string> CRL::hash(const EVP_MD *md) {
	LOGGER_FN();

	unsigned char hash[EVP_MAX_MD_SIZE] = { 0 };
	unsigned int hashlen = 0;

	LOGGER_OPENSSL(X509_CRL_digest);
	if (!X509_CRL_digest(this->internal(), md, hash, &hashlen)) {
		THROW_OPENSSL_EXCEPTION(0, CRL, NULL, "X509_CRL_digest");
	}

	Handle<std::string> res = new std::string((char *)hash, hashlen);

	return res;
}

long CRL::getVersion()
{
	LOGGER_FN();

	LOGGER_OPENSSL(X509_CRL_get_version);
	long ver = X509_CRL_get_version(this->internal());

	return ver;
}

Handle<std::string> CRL::getSigAlgName(){
	LOGGER_FN();

	try{
		LOGGER_OPENSSL(OBJ_obj2nid);
		int pkey_nid = OBJ_obj2nid(this->internal()->sig_alg->algorithm);

		if (pkey_nid == NID_undef) {
			THROW_EXCEPTION(0, CRL, NULL, "Can not get key nid");
		}

		LOGGER_OPENSSL(OBJ_nid2ln);
		std::string sslbuf = OBJ_nid2ln(pkey_nid);

		Handle<std::string> res = new std::string(sslbuf.c_str(), sslbuf.length());

		return res;
	}
	catch (Handle<Exception> e){
		THROW_EXCEPTION(0, CRL, e, "Error get CRL signature algorithm long name");
	}
}

Handle<std::string> CRL::getSigAlgShortName(){
	LOGGER_FN();

	try{
		LOGGER_OPENSSL(OBJ_obj2nid);
		int pkey_nid = OBJ_obj2nid(this->internal()->sig_alg->algorithm);
		if (pkey_nid == NID_undef) {
			THROW_EXCEPTION(0, CRL, NULL, "Can not get key nid");
		}

		LOGGER_OPENSSL(OBJ_nid2ln);
		std::string sslbuf = OBJ_nid2sn(pkey_nid);

		Handle<std::string> res = new std::string(sslbuf.c_str(), sslbuf.length());

		return res;
	}
	catch (Handle<Exception> e){
		THROW_EXCEPTION(0, CRL, e, "Error get CRL signature algorithm short name");
	}
}

Handle<std::string> CRL::getSigAlgOID(){
	LOGGER_FN();

	try{
		char buf[100];
		LOGGER_OPENSSL(OBJ_obj2txt);
		int bufLen = 0;
		if ((bufLen = OBJ_obj2txt(buf, 100, this->internal()->sig_alg->algorithm, 1)) <= 0){
			THROW_OPENSSL_EXCEPTION(0, Algorithm, NULL, "OBJ_obj2txt");
		}

		std::string *res = new std::string(buf, bufLen);

		return res;
	}
	catch (Handle<Exception> e){
		THROW_EXCEPTION(0, CRL, e, "Error get CRL signature OID");
	}
}
Handle<std::string> CRL::issuerName()
{
	LOGGER_FN();

	LOGGER_OPENSSL(X509_CRL_get_issuer);
	X509_NAME *name = X509_CRL_get_issuer(this->internal());
	if (!name)
		THROW_EXCEPTION(1, CRL, NULL, "X509_NAME is NULL");

	LOGGER_OPENSSL(X509_NAME_oneline);
	char *str_name = X509_NAME_oneline(name, NULL, 0);
	if (!str_name)
		THROW_EXCEPTION(1, CRL, NULL, "X509_NAME_oneline");

	Handle<std::string> res = new std::string(str_name);
	OPENSSL_free(str_name);

	return res;
}

Handle<std::string> CRL::issuerFriendlyName()
{
	LOGGER_FN();

	LOGGER_OPENSSL(X509_get_issuer_name);
	return GetCommonName(X509_CRL_get_issuer(this->internal()));
}

Handle<std::string> CRL::GetCommonName(X509_NAME *a){
	LOGGER_FN();

	Handle<std::string> name = new std::string("");
	if (a == NULL)
		THROW_EXCEPTION(0, Certificate, NULL, "Parameter 1 can not be NULL");

	int nid = NID_commonName;
	LOGGER_OPENSSL(X509_NAME_get_index_by_NID);
	int index = X509_NAME_get_index_by_NID(a, nid, -1);
	if (index >= 0) {
		LOGGER_OPENSSL(X509_NAME_get_entry);
		X509_NAME_ENTRY *issuerNameCommonName = X509_NAME_get_entry(a, index);

		if (issuerNameCommonName) {
			LOGGER_OPENSSL(X509_NAME_ENTRY_get_data);
			ASN1_STRING *issuerCNASN1 = X509_NAME_ENTRY_get_data(issuerNameCommonName);

			if (issuerCNASN1 != NULL) {
				unsigned char *utf = NULL;
				LOGGER_OPENSSL(ASN1_STRING_to_UTF8);
				ASN1_STRING_to_UTF8(&utf, issuerCNASN1);
				name = new std::string((char *)utf);
				OPENSSL_free(utf);
			}
		}
	}
	else {
		return new std::string("No common name");
	}
	return name;
}

Handle<std::string> CRL::getEncoded(){
	LOGGER_FN();

	try{
		LOGGER_OPENSSL(BIO_new);
		BIO * bio_out = BIO_new(BIO_s_mem());
		LOGGER_OPENSSL(i2d_X509_CRL_bio);
		if (!i2d_X509_CRL_bio(bio_out, this->internal())){
			THROW_OPENSSL_EXCEPTION(0, CRL, NULL, "i2d_X509_CRL_bio");
		}
		BUF_MEM *bio_buf;
		LOGGER_OPENSSL(BIO_get_mem_ptr);
		BIO_get_mem_ptr(bio_out, &bio_buf);
		Handle<std::string> res = new std::string(bio_buf->data, bio_buf->length);
		LOGGER_OPENSSL(BIO_free);
		BIO_free(bio_out);

		return res;
	}
	catch (Handle<Exception> e){
		THROW_EXCEPTION(0, CRL, e, "Error get encoded CRL");
	}
}

Handle<std::string> CRL::getSignature(){
	LOGGER_FN();

	try{
		std::string sslbuf = std::string((char *)(this->internal()->signature)->data, (this->internal()->signature)->length);
		Handle<std::string> res = new std::string(sslbuf.c_str(), sslbuf.length());

		return res;
	}
	catch (Handle<Exception> e){
		THROW_EXCEPTION(0, CRL, e, "Error get signature CRL");
	}
}

Handle<std::string> CRL::getNextUpdate(){
	LOGGER_FN();

	LOGGER_OPENSSL(X509_CRL_get_nextUpdate);
	ASN1_TIME *time = X509_CRL_get_nextUpdate(this->internal());
	return ASN1_TIME_toString(time);
}

Handle<std::string> CRL::getThisUpdate(){
	LOGGER_FN();

	LOGGER_OPENSSL(X509_CRL_get_lastUpdate);
	ASN1_TIME *time = X509_CRL_get_lastUpdate(this->internal());
	return ASN1_TIME_toString(time);
}

Handle<RevokedCertificate> CRL::getRevokedCertificate(Handle<Certificate> cert){
	LOGGER_FN();

	if (cert.isEmpty()){
		THROW_EXCEPTION(0, CRL, NULL, ERROR_PARAMETER_NULL, 1);
	}
	X509_REVOKED *rc = NULL;
	LOGGER_OPENSSL(X509_CRL_get0_by_cert);
	if (X509_CRL_get0_by_cert(this->internal(), &rc, cert->internal())){
		return new RevokedCertificate(rc, this->handle());
	}
	else{
		return NULL;
	}
}

Handle<RevokedCertificate> CRL::getRevokedCertificate(Handle<std::string> serial){
	LOGGER_FN();

	if (serial.isEmpty()){
		THROW_EXCEPTION(0, CRL, NULL, ERROR_PARAMETER_NULL, 1);
	}

	BIGNUM* bn = BN_new();
	BN_bin2bn((const unsigned char *)serial->data(), serial->length(), bn);

	ASN1_INTEGER* asnInt = ASN1_INTEGER_new();
	BN_to_ASN1_INTEGER(bn, asnInt);

	X509_REVOKED *rc = NULL;
	LOGGER_OPENSSL(X509_CRL_get0_by_serial);
	if (X509_CRL_get0_by_serial(this->internal(), &rc, asnInt)){
		return new RevokedCertificate(rc, this->handle());
	}
	else{
		return NULL;
	}
}

Handle<std::string> RevokedCertificate::revocationDate()
{
	LOGGER_FN();

	ASN1_TIME *time = this->internal()->revocationDate;
	return ASN1_TIME_toString(time);
}

int RevokedCertificate::reason()
{
	LOGGER_FN();

	return this->internal()->reason;
}
<|endoftext|>


<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libdui.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include "duipositionindicatorview.h"
#include "duipositionindicatorview_p.h"

#include <QString>
#include <QTimer>
#include <QStyleOptionGraphicsItem>

#include "duipositionindicator_p.h"  // For the member indexes of the model
#include "duitheme.h"
#include "duiviewcreator.h"
#include "duipositionindicator.h"
#include "duiabstractwidgetanimation.h"
#define NODEBUG

DuiPositionIndicatorViewPrivate::DuiPositionIndicatorViewPrivate()
    : controller(0),
      hideTimer(new QTimer()),
      visible(false)
{
}

DuiPositionIndicatorViewPrivate::~DuiPositionIndicatorViewPrivate()
{
    delete this->hideTimer;
}

DuiPositionIndicatorView::DuiPositionIndicatorView(DuiPositionIndicator *controller) :
    DuiWidgetView(* new DuiPositionIndicatorViewPrivate, controller)
{
    Q_D(DuiPositionIndicatorView);
    d->controller = controller;

    connect(d->hideTimer, SIGNAL(timeout()), this, SLOT(hide()));
    d->hideTimer->setSingleShot(true);
}

DuiPositionIndicatorView::~DuiPositionIndicatorView()
{
    Q_D(DuiPositionIndicatorView);
    d->controller = 0;
}

void DuiPositionIndicatorView::drawContents(QPainter *painter, const QStyleOptionGraphicsItem *option) const
{
    /*
        Q_D(const DuiPositionIndicatorView);
    */
    Q_UNUSED(option);
    Q_UNUSED(painter);

    /*
        if(d->visible) {
    */
    /*
    int dotDist = style()->pixmapDistance();
    QSize dotSize = style()->onPixmap()->size();
    QSizeF vpSize = model()->viewportSize();
    QRectF pRange = model()->pannedRange();
    QPointF pPos = model()->pannedPos();
    const QPixmap *pixOff = style()->offPixmap();
    const QPixmap *pixOn = style()->onPixmap();

    int dotsX = size().width() / dotDist;
    int onDotsX = (2 * dotsX * vpSize.width() + pRange.width()) / pRange.width() / 2;
    onDotsX = qMax(onDotsX,
                   style()->minIndicatorDots());
    int onPosX = (2 * dotsX * pPos.x() + pRange.width()) / pRange.width() / 2;
    QPoint barPosH = QPoint(size().width() - dotsX * dotDist + (dotDist - dotSize.width()) / 2,
                            size().height() - dotDist + (dotDist - dotSize.height()) / 2);

    int dotsY = size().height() / dotDist;
    int onDotsY = (2 * dotsY * vpSize.height() + pRange.height()) / pRange.height() / 2;
    onDotsY = qMax(onDotsY,
                   style()->minIndicatorDots());
    int onPosY = (2 * dotsY * pPos.y() + pRange.height()) / pRange.height() / 2;
    QPoint barPosV = QPoint(size().width() - dotDist + (dotDist - dotSize.width()) / 2,
                            size().height() - dotsY * dotDist + (dotDist - dotSize.height()) / 2);

    int effPosX = qMax(0, onPosX);
    int effPosY = qMax(0, onPosY);

    if (pRange.width() > vpSize.width()) {
        QPointF currPos(barPosH);
        QPointF posAdd(dotDist, 0);
        bool pixState;

        for (int i = 0; i < dotsX; ++i) {
            pixState = (i < effPosX || i >= onPosX + onDotsX) ? false : true;
            painter->drawPixmap(currPos, pixState ? *pixOn : *pixOff);

            currPos += posAdd;
        }
    }

    if (pRange.height() > vpSize.height()) {
        QPointF currPos(barPosV);
        QPointF posAdd(0, dotDist);
        bool pixState;

        for (int i = 0; i < dotsY; ++i) {
            pixState = (i < effPosY || i >= onPosY + onDotsY) ? false : true;
            painter->drawPixmap(currPos, pixState ? *pixOn : *pixOff);

            currPos += posAdd;
        }
    }
    */
    /*
        }
    */
}

void DuiPositionIndicatorView::updateData(const QList<const char *>& modifications)
{
    DuiWidgetView::updateData(modifications);

    resetHideTimer();
    update();
}

void DuiPositionIndicatorView::setupModel()
{
    DuiWidgetView::setupModel();

    resetHideTimer();
    update();
}

void DuiPositionIndicatorView::resizeEvent(QGraphicsSceneResizeEvent *event)
{
    DuiWidgetView::resizeEvent(event);
    update();
}

void DuiPositionIndicatorView::hide()
{
    Q_D(DuiPositionIndicatorView);
    d->visible = false;
    if (showAnimation())
        showAnimation()->stop();
    if (hideAnimation())
        hideAnimation()->start();
    update();
}

void DuiPositionIndicatorView::resetHideTimer()
{
    Q_D(DuiPositionIndicatorView);
    if (!d->visible) {
        if (hideAnimation())
            hideAnimation()->stop();
        if (showAnimation())
            showAnimation()->start();
        d->visible = true;
    }
    d->hideTimer->stop();
    d->hideTimer->start(style()->hideTimeout());
}

DUI_REGISTER_VIEW_NEW(DuiPositionIndicatorView, DuiPositionIndicator)
<commit_msg>Changes: Reverting "Not painting position indicator for tests."<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libdui.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include "duipositionindicatorview.h"
#include "duipositionindicatorview_p.h"

#include <QString>
#include <QTimer>
#include <QStyleOptionGraphicsItem>

#include "duipositionindicator_p.h"  // For the member indexes of the model
#include "duitheme.h"
#include "duiviewcreator.h"
#include "duipositionindicator.h"
#include "duiabstractwidgetanimation.h"
#define NODEBUG

DuiPositionIndicatorViewPrivate::DuiPositionIndicatorViewPrivate()
    : controller(0),
      hideTimer(new QTimer()),
      visible(false)
{
}

DuiPositionIndicatorViewPrivate::~DuiPositionIndicatorViewPrivate()
{
    delete this->hideTimer;
}

DuiPositionIndicatorView::DuiPositionIndicatorView(DuiPositionIndicator *controller) :
    DuiWidgetView(* new DuiPositionIndicatorViewPrivate, controller)
{
    Q_D(DuiPositionIndicatorView);
    d->controller = controller;

    connect(d->hideTimer, SIGNAL(timeout()), this, SLOT(hide()));
    d->hideTimer->setSingleShot(true);
}

DuiPositionIndicatorView::~DuiPositionIndicatorView()
{
    Q_D(DuiPositionIndicatorView);
    d->controller = 0;
}

void DuiPositionIndicatorView::drawContents(QPainter *painter, const QStyleOptionGraphicsItem *option) const
{
    /*
        Q_D(const DuiPositionIndicatorView);
    */
    Q_UNUSED(option);
    /*
        if(d->visible) {
    */
    int dotDist = style()->pixmapDistance();
    QSize dotSize = style()->onPixmap()->size();
    QSizeF vpSize = model()->viewportSize();
    QRectF pRange = model()->pannedRange();
    QPointF pPos = model()->pannedPos();
    const QPixmap *pixOff = style()->offPixmap();
    const QPixmap *pixOn = style()->onPixmap();

    int dotsX = size().width() / dotDist;
    int onDotsX = (2 * dotsX * vpSize.width() + pRange.width()) / pRange.width() / 2;
    onDotsX = qMax(onDotsX,
                   style()->minIndicatorDots());
    int onPosX = (2 * dotsX * pPos.x() + pRange.width()) / pRange.width() / 2;
    QPoint barPosH = QPoint(size().width() - dotsX * dotDist + (dotDist - dotSize.width()) / 2,
                            size().height() - dotDist + (dotDist - dotSize.height()) / 2);

    int dotsY = size().height() / dotDist;
    int onDotsY = (2 * dotsY * vpSize.height() + pRange.height()) / pRange.height() / 2;
    onDotsY = qMax(onDotsY,
                   style()->minIndicatorDots());
    int onPosY = (2 * dotsY * pPos.y() + pRange.height()) / pRange.height() / 2;
    QPoint barPosV = QPoint(size().width() - dotDist + (dotDist - dotSize.width()) / 2,
                            size().height() - dotsY * dotDist + (dotDist - dotSize.height()) / 2);

    int effPosX = qMax(0, onPosX);
    int effPosY = qMax(0, onPosY);

    if (pRange.width() > vpSize.width()) {
        QPointF currPos(barPosH);
        QPointF posAdd(dotDist, 0);
        bool pixState;

        for (int i = 0; i < dotsX; ++i) {
            pixState = (i < effPosX || i >= onPosX + onDotsX) ? false : true;
            painter->drawPixmap(currPos, pixState ? *pixOn : *pixOff);

            currPos += posAdd;
        }
    }

    if (pRange.height() > vpSize.height()) {
        QPointF currPos(barPosV);
        QPointF posAdd(0, dotDist);
        bool pixState;

        for (int i = 0; i < dotsY; ++i) {
            pixState = (i < effPosY || i >= onPosY + onDotsY) ? false : true;
            painter->drawPixmap(currPos, pixState ? *pixOn : *pixOff);

            currPos += posAdd;
        }
    }
    /*
        }
    */
}

void DuiPositionIndicatorView::updateData(const QList<const char *>& modifications)
{
    DuiWidgetView::updateData(modifications);

    resetHideTimer();
    update();
}

void DuiPositionIndicatorView::setupModel()
{
    DuiWidgetView::setupModel();

    resetHideTimer();
    update();
}

void DuiPositionIndicatorView::resizeEvent(QGraphicsSceneResizeEvent *event)
{
    DuiWidgetView::resizeEvent(event);
    update();
}

void DuiPositionIndicatorView::hide()
{
    Q_D(DuiPositionIndicatorView);
    d->visible = false;
    if (showAnimation())
        showAnimation()->stop();
    if (hideAnimation())
        hideAnimation()->start();
    update();
}

void DuiPositionIndicatorView::resetHideTimer()
{
    Q_D(DuiPositionIndicatorView);
    if (!d->visible) {
        if (hideAnimation())
            hideAnimation()->stop();
        if (showAnimation())
            showAnimation()->start();
        d->visible = true;
    }
    d->hideTimer->stop();
    d->hideTimer->start(style()->hideTimeout());
}

DUI_REGISTER_VIEW_NEW(DuiPositionIndicatorView, DuiPositionIndicator)
<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * $Id$
 */

#if !defined(XERCESC_INCLUDE_GUARD_DOMIMPLEMENTATIONIMPL_HPP)
#define XERCESC_INCLUDE_GUARD_DOMIMPLEMENTATIONIMPL_HPP

//
//  This file is part of the internal implementation of the C++ XML DOM.
//  It should NOT be included or used directly by application programs.
//
//  Applications should include the file <xercesc/dom/DOM.hpp> for the entire
//  DOM API, or xercesc/dom/DOM*.hpp for individual DOM classes, where the class
//  name is substituded for the *.
//

#include <xercesc/util/XercesDefs.hpp>
#include <xercesc/dom/DOMImplementation.hpp>
#include <xercesc/dom/DOMImplementationSource.hpp>

XERCES_CPP_NAMESPACE_BEGIN

class XMLMsgLoader;

class DOMImplementationImpl: public XMemory,
                             public DOMImplementation,
                             public DOMImplementationSource
{
private:
    DOMImplementationImpl(const DOMImplementationImpl &);
    DOMImplementationImpl & operator = (const DOMImplementationImpl &);
    friend class XMLInitializer;

protected:
    DOMImplementationImpl() {};

public:
    virtual ~DOMImplementationImpl() {};
    static DOMImplementationImpl*   getDOMImplementationImpl();
    static XMLMsgLoader* getMsgLoader4DOM();

    // ------------------------------------------------------------
    // DOMImplementation Virtual interface
    // ------------------------------------------------------------
    virtual bool                hasFeature(const  XMLCh * feature,  const  XMLCh * version) const;

    // Introduced in DOM Level 2
    virtual DOMDocumentType*    createDocumentType(const XMLCh *qualifiedName,
                                                   const XMLCh * publicId,
                                                   const XMLCh *systemId);
    virtual DOMDocument*        createDocument(const XMLCh *namespaceURI,
                                               const XMLCh *qualifiedName,
                                               DOMDocumentType *doctype,
                                               MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager);

    // DOM Level 3
    virtual void* getFeature(const XMLCh* feature, const XMLCh* version) const;

    // Non-standard extension
    virtual DOMDocument*        createDocument(MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager);

    // ------------------------------------------------------------
    // DOMImplementationLS Virtual interface
    // ------------------------------------------------------------
    // Introduced in DOM Level 3
    virtual DOMLSParser* createLSParser(const DOMImplementationLSMode mode,
                                        const XMLCh* const     schemaType,
                                        MemoryManager* const   manager = XMLPlatformUtils::fgMemoryManager,
                                        XMLGrammarPool*  const gramPool = 0);
    virtual DOMLSSerializer* createLSSerializer(MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager);
    virtual DOMLSInput* createLSInput(MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager);
    virtual DOMLSOutput* createLSOutput(MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager);

    // ------------------------------------------------------------
    // DOMImplementationSource Virtual interface
    // ------------------------------------------------------------
    virtual DOMImplementation* getDOMImplementation(const XMLCh* features) const;
    virtual DOMImplementationList* getDOMImplementationList(const XMLCh* features) const;

};

XERCES_CPP_NAMESPACE_END

#endif
<commit_msg>XERCESC-2062 - DOMImplementationImpl class declaration is missing CDOM_EXPORT<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * $Id$
 */

#if !defined(XERCESC_INCLUDE_GUARD_DOMIMPLEMENTATIONIMPL_HPP)
#define XERCESC_INCLUDE_GUARD_DOMIMPLEMENTATIONIMPL_HPP

//
//  This file is part of the internal implementation of the C++ XML DOM.
//  It should NOT be included or used directly by application programs.
//
//  Applications should include the file <xercesc/dom/DOM.hpp> for the entire
//  DOM API, or xercesc/dom/DOM*.hpp for individual DOM classes, where the class
//  name is substituded for the *.
//

#include <xercesc/util/XercesDefs.hpp>
#include <xercesc/dom/DOMImplementation.hpp>
#include <xercesc/dom/DOMImplementationSource.hpp>

XERCES_CPP_NAMESPACE_BEGIN

class XMLMsgLoader;

class CDOM_EXPORT DOMImplementationImpl: public XMemory,
                             public DOMImplementation,
                             public DOMImplementationSource
{
private:
    DOMImplementationImpl(const DOMImplementationImpl &);
    DOMImplementationImpl & operator = (const DOMImplementationImpl &);
    friend class XMLInitializer;

protected:
    DOMImplementationImpl() {};

public:
    virtual ~DOMImplementationImpl() {};
    static DOMImplementationImpl*   getDOMImplementationImpl();
    static XMLMsgLoader* getMsgLoader4DOM();

    // ------------------------------------------------------------
    // DOMImplementation Virtual interface
    // ------------------------------------------------------------
    virtual bool                hasFeature(const  XMLCh * feature,  const  XMLCh * version) const;

    // Introduced in DOM Level 2
    virtual DOMDocumentType*    createDocumentType(const XMLCh *qualifiedName,
                                                   const XMLCh * publicId,
                                                   const XMLCh *systemId);
    virtual DOMDocument*        createDocument(const XMLCh *namespaceURI,
                                               const XMLCh *qualifiedName,
                                               DOMDocumentType *doctype,
                                               MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager);

    // DOM Level 3
    virtual void* getFeature(const XMLCh* feature, const XMLCh* version) const;

    // Non-standard extension
    virtual DOMDocument*        createDocument(MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager);

    // ------------------------------------------------------------
    // DOMImplementationLS Virtual interface
    // ------------------------------------------------------------
    // Introduced in DOM Level 3
    virtual DOMLSParser* createLSParser(const DOMImplementationLSMode mode,
                                        const XMLCh* const     schemaType,
                                        MemoryManager* const   manager = XMLPlatformUtils::fgMemoryManager,
                                        XMLGrammarPool*  const gramPool = 0);
    virtual DOMLSSerializer* createLSSerializer(MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager);
    virtual DOMLSInput* createLSInput(MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager);
    virtual DOMLSOutput* createLSOutput(MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager);

    // ------------------------------------------------------------
    // DOMImplementationSource Virtual interface
    // ------------------------------------------------------------
    virtual DOMImplementation* getDOMImplementation(const XMLCh* features) const;
    virtual DOMImplementationList* getDOMImplementationList(const XMLCh* features) const;

};

XERCES_CPP_NAMESPACE_END

#endif
<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 1999-2000 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xerces" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache\@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
 * ITS 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.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation, and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com .  For more information
 * on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

// ---------------------------------------------------------------------------
//  Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/BinFileInputStream.hpp>
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/util/XMLString.hpp>
#include <xercesc/util/XMLUniDefs.hpp>
#include <xercesc/framework/LocalFileInputSource.hpp>

XERCES_CPP_NAMESPACE_BEGIN

/***
 *
 * Originated by Chris larsson
 *
 * Issue:
 *
 * There is an inconsistency in URI resolution in the case where the file itself is a
 * symbolic link to another path (or the path has path segment which is a symbolic
 * link to another path). So, is the base path the directory where the symbolic link resides
 * or the directory where the real file resides? I'm sure one could argue either way,
 * but I think that having the base path be the directory where the symbolic link resides
 * is more intuitive.
 *
 * Defining it this way would then make the behavior consistent with using an absolute
 * path as well as with the java behavior.
 *
 * Proposal:
 *
 * The URI is resolved within the parser code, and is somewhat independant of the OS.
 *
 * A relative path is resolved by querying the current directory and appending the
 * relative part onto the returned current directory string to obtain the base URI.
 * An absolute path is simply used as the base URI.
 * Then remove all "./" and "../" path segments using an algorithm like weavepath to obtain
 * the resolved base URI.
 *
 * When you need to access another file such as a dtd, use the resolved base URI and add on
 * the relative URI of the dtd file. Then resolve it using the same weavepath algorithm.
 *
 * Note:
 *
 *   Java parser behaves differently for a path containning symbolic path segment. When
 *   it is given an absolute path, it can locate the primary instance document, while given
 *   relative path, it might not.
 *
 *   It is because Java parser uses URI solution where "/segment/../" is required to be removed
 *   from the resultant path if a relative URI is merged to a baseURI. While this is NOT required
 *   for an absolute URI.
 *
 *   So if a path segment, which is symbolic link, happen to be followed by the '/../', it is
 *   NOT removed from the path if it is given in absolute form, and the underlying file system
 *   will locate the file, if in relative form, that symbolic link path segment together with
 *   '../' is removed from the resultant path, and the file system may NOT be able to locate
 *   the file, if there is a one, it is definitely not the one expected, in fact by accident.
 *
 *   Therefore, to keep consistent with Java parser, for now, we do not apply removeDotDotSlash()
 *   for absolute path.
 *
 ***/

// ---------------------------------------------------------------------------
//  LocalFileInputSource: Constructors and Destructor
// ---------------------------------------------------------------------------
LocalFileInputSource::LocalFileInputSource( const XMLCh* const basePath
                                          , const XMLCh* const relativePath)
{
    //
    //  If the relative part is really relative, then weave it together
    //  with the base path. If not, just take the relative path as the
    //  entire path.
    //
    if (XMLPlatformUtils::isRelative(relativePath))
    {
        XMLCh* tmpBuf = XMLPlatformUtils::weavePaths(basePath, relativePath);
        setSystemId(tmpBuf);
        delete [] tmpBuf;
    }
    else
    {
        XMLCh* tmpBuf = XMLString::replicate(relativePath);
        XMLPlatformUtils::removeDotSlash(tmpBuf);
        setSystemId(tmpBuf);
        delete [] tmpBuf;
    }

}

LocalFileInputSource::LocalFileInputSource(const XMLCh* const filePath)
{

    //
    //  If the path is relative, then complete it acording to the current
    //  working directory rules of the current platform. Else, just take
    //  it as is.
    //
    if (XMLPlatformUtils::isRelative(filePath))
    {
        XMLCh* curDir = XMLPlatformUtils::getCurrentDirectory();

        int    curDirLen = XMLString::stringLen(curDir);
        int    filePathLen = XMLString::stringLen(filePath);
        XMLCh* fullDir = new XMLCh [ curDirLen + filePathLen + 2];

        fullDir[0] = 0;
        XMLString::copyString(fullDir, curDir);
        fullDir[curDirLen] = chForwardSlash;
        fullDir[curDirLen+1] = 0;
        XMLString::catString(&fullDir[curDirLen+1], filePath);
        fullDir[curDirLen+filePathLen+1] = 0;

        XMLPlatformUtils::removeDotSlash(fullDir);
        XMLPlatformUtils::removeDotDotSlash(fullDir);

        setSystemId(fullDir);

        delete [] curDir;
        delete [] fullDir;
    }
     else
    {
        XMLCh* tmpBuf = XMLString::replicate(filePath);
        XMLPlatformUtils::removeDotSlash(tmpBuf);
        setSystemId(tmpBuf);
        delete [] tmpBuf;
    }

}

LocalFileInputSource::~LocalFileInputSource()
{
}

// ---------------------------------------------------------------------------
//  LocalFileInputSource: InputSource interface implementation
// ---------------------------------------------------------------------------
BinInputStream* LocalFileInputSource::makeStream() const
{
    BinFileInputStream* retStrm = new BinFileInputStream(getSystemId());
    if (!retStrm->getIsOpen())
    {
        delete retStrm;
        return 0;
    }
    return retStrm;
}

XERCES_CPP_NAMESPACE_END

<commit_msg>remove unnecessary assignment<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 1999-2000 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xerces" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache\@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
 * ITS 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.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation, and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com .  For more information
 * on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

// ---------------------------------------------------------------------------
//  Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/BinFileInputStream.hpp>
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/util/XMLString.hpp>
#include <xercesc/util/XMLUniDefs.hpp>
#include <xercesc/framework/LocalFileInputSource.hpp>

XERCES_CPP_NAMESPACE_BEGIN

/***
 *
 * Originated by Chris larsson
 *
 * Issue:
 *
 * There is an inconsistency in URI resolution in the case where the file itself is a
 * symbolic link to another path (or the path has path segment which is a symbolic
 * link to another path). So, is the base path the directory where the symbolic link resides
 * or the directory where the real file resides? I'm sure one could argue either way,
 * but I think that having the base path be the directory where the symbolic link resides
 * is more intuitive.
 *
 * Defining it this way would then make the behavior consistent with using an absolute
 * path as well as with the java behavior.
 *
 * Proposal:
 *
 * The URI is resolved within the parser code, and is somewhat independant of the OS.
 *
 * A relative path is resolved by querying the current directory and appending the
 * relative part onto the returned current directory string to obtain the base URI.
 * An absolute path is simply used as the base URI.
 * Then remove all "./" and "../" path segments using an algorithm like weavepath to obtain
 * the resolved base URI.
 *
 * When you need to access another file such as a dtd, use the resolved base URI and add on
 * the relative URI of the dtd file. Then resolve it using the same weavepath algorithm.
 *
 * Note:
 *
 *   Java parser behaves differently for a path containning symbolic path segment. When
 *   it is given an absolute path, it can locate the primary instance document, while given
 *   relative path, it might not.
 *
 *   It is because Java parser uses URI solution where "/segment/../" is required to be removed
 *   from the resultant path if a relative URI is merged to a baseURI. While this is NOT required
 *   for an absolute URI.
 *
 *   So if a path segment, which is symbolic link, happen to be followed by the '/../', it is
 *   NOT removed from the path if it is given in absolute form, and the underlying file system
 *   will locate the file, if in relative form, that symbolic link path segment together with
 *   '../' is removed from the resultant path, and the file system may NOT be able to locate
 *   the file, if there is a one, it is definitely not the one expected, in fact by accident.
 *
 *   Therefore, to keep consistent with Java parser, for now, we do not apply removeDotDotSlash()
 *   for absolute path.
 *
 ***/

// ---------------------------------------------------------------------------
//  LocalFileInputSource: Constructors and Destructor
// ---------------------------------------------------------------------------
LocalFileInputSource::LocalFileInputSource( const XMLCh* const basePath
                                          , const XMLCh* const relativePath)
{
    //
    //  If the relative part is really relative, then weave it together
    //  with the base path. If not, just take the relative path as the
    //  entire path.
    //
    if (XMLPlatformUtils::isRelative(relativePath))
    {
        XMLCh* tmpBuf = XMLPlatformUtils::weavePaths(basePath, relativePath);
        setSystemId(tmpBuf);
        delete [] tmpBuf;
    }
    else
    {
        XMLCh* tmpBuf = XMLString::replicate(relativePath);
        XMLPlatformUtils::removeDotSlash(tmpBuf);
        setSystemId(tmpBuf);
        delete [] tmpBuf;
    }

}

LocalFileInputSource::LocalFileInputSource(const XMLCh* const filePath)
{

    //
    //  If the path is relative, then complete it acording to the current
    //  working directory rules of the current platform. Else, just take
    //  it as is.
    //
    if (XMLPlatformUtils::isRelative(filePath))
    {
        XMLCh* curDir = XMLPlatformUtils::getCurrentDirectory();

        int    curDirLen = XMLString::stringLen(curDir);
        int    filePathLen = XMLString::stringLen(filePath);
        XMLCh* fullDir = new XMLCh [ curDirLen + filePathLen + 2];

        XMLString::copyString(fullDir, curDir);
        fullDir[curDirLen] = chForwardSlash;
        XMLString::copyString(&fullDir[curDirLen+1], filePath);

        XMLPlatformUtils::removeDotSlash(fullDir);
        XMLPlatformUtils::removeDotDotSlash(fullDir);

        setSystemId(fullDir);

        delete [] curDir;
        delete [] fullDir;
    }
     else
    {
        XMLCh* tmpBuf = XMLString::replicate(filePath);
        XMLPlatformUtils::removeDotSlash(tmpBuf);
        setSystemId(tmpBuf);
        delete [] tmpBuf;
    }

}

LocalFileInputSource::~LocalFileInputSource()
{
}

// ---------------------------------------------------------------------------
//  LocalFileInputSource: InputSource interface implementation
// ---------------------------------------------------------------------------
BinInputStream* LocalFileInputSource::makeStream() const
{
    BinFileInputStream* retStrm = new BinFileInputStream(getSystemId());
    if (!retStrm->getIsOpen())
    {
        delete retStrm;
        return 0;
    }
    return retStrm;
}

XERCES_CPP_NAMESPACE_END

<|endoftext|>