<commit_before>#include "wrap_body.hpp"

#include "wrap_vertex_array.hpp"

#include <boost/python.hpp>
#include <Box2D/Collision/Shapes/b2CircleShape.h>
#include <Box2D/Collision/Shapes/b2EdgeShape.h>
#include <Box2D/Collision/Shapes/b2LoopShape.h>
#include <Box2D/Collision/Shapes/b2PolygonShape.h>
#include <Box2D/Dynamics/b2Fixture.h>
#include <Box2D/Dynamics/b2Body.h>
#include <Box2D/Dynamics/b2World.h>
#include <Box2D/Dynamics/Contacts/b2Contact.h>
#include <Box2D/Dynamics/Joints/b2Joint.h>

using namespace boost::python;

namespace pysics {
    void wrap_body_type()
    {
        enum_<b2BodyType>("BodyType")
            .value("STATIC_BODY", b2_staticBody)
            .value("KINEMATIC_BODY", b2_kinematicBody)
            .value("DYNAMIC_BODY", b2_dynamicBody)
            .export_values()
        ;
    }

    b2Fixture *create_fixture(b2Body *body,
                              b2Shape *shape,
                              b2UserData user_data,
                              float32 friction,
                              float32 restitution,
                              float32 density,
                              bool sensor,
                              uint16 category_bits,
                              uint16 mask_bits,
                              uint16 group_index)
    {
        b2FixtureDef fixture_def;
        fixture_def.shape = shape;
        fixture_def.userData = user_data;
        fixture_def.friction = friction;
        fixture_def.restitution = restitution;
        fixture_def.density = density;
        fixture_def.isSensor = sensor;
        fixture_def.filter.categoryBits = category_bits;
        fixture_def.filter.maskBits = mask_bits;
        fixture_def.filter.groupIndex = group_index;
        return body->CreateFixture(&fixture_def);
    }

    b2Fixture *create_circle_fixture(b2Body *body,
                                     b2Vec2 position,
                                     float32 radius,
                                     b2UserData user_data,
                                     float32 friction,
                                     float32 restitution,
                                     float32 density,
                                     bool sensor,
                                     uint16 category_bits,
                                     uint16 mask_bits,
                                     uint16 group_index)
    {
        b2CircleShape circle_shape;
        circle_shape.m_p = position;
        circle_shape.m_radius = radius;

        b2FixtureDef fixture_def;
        fixture_def.shape = &circle_shape;
        fixture_def.userData = user_data;
        fixture_def.friction = friction;
        fixture_def.restitution = restitution;
        fixture_def.density = density;
        fixture_def.isSensor = sensor;
        fixture_def.filter.categoryBits = category_bits;
        fixture_def.filter.maskBits = mask_bits;
        fixture_def.filter.groupIndex = group_index;

        return body->CreateFixture(&fixture_def);
    }

    b2Fixture *create_edge_fixture(b2Body *body,
                                   b2Vec2 vertex_1,
                                   b2Vec2 vertex_2,
                                   b2UserData user_data,
                                   float32 friction,
                                   float32 restitution,
                                   float32 density,
                                   bool sensor,
                                   uint16 category_bits,
                                   uint16 mask_bits,
                                   uint16 group_index)
    {
        b2EdgeShape edge_shape;
        edge_shape.m_vertex1 = vertex_1;
        edge_shape.m_vertex2 = vertex_2;

        b2FixtureDef fixture_def;
        fixture_def.shape = &edge_shape;
        fixture_def.userData = user_data;
        fixture_def.friction = friction;
        fixture_def.restitution = restitution;
        fixture_def.density = density;
        fixture_def.isSensor = sensor;
        fixture_def.filter.categoryBits = category_bits;
        fixture_def.filter.maskBits = mask_bits;
        fixture_def.filter.groupIndex = group_index;

        return body->CreateFixture(&fixture_def);
    }

    namespace {
        void set_vertices(b2PolygonShape *polygon_shape, list vertices)
        {
            b2Vec2 arr[b2_maxPolygonVertices];
            long n = len(vertices);
            for (long i = 0; i != n; ++i) {
                arr[i] = extract<b2Vec2>(vertices[i]);
            }
            polygon_shape->Set(arr, n);
        }
    }

    b2Fixture *create_polygon_fixture(b2Body *body,
                                      list vertices,
                                      b2UserData user_data,
                                      float32 friction,
                                      float32 restitution,
                                      float32 density,
                                      bool sensor,
                                      uint16 category_bits,
                                      uint16 mask_bits,
                                      uint16 group_index)
    {
        b2PolygonShape polygon_shape;
        if (len(vertices)) {
            set_vertices(&polygon_shape, vertices);
        } else {
            polygon_shape.SetAsBox(1.0f, 1.0f);
        }

        b2FixtureDef fixture_def;
        fixture_def.shape = &polygon_shape;
        fixture_def.userData = user_data;
        fixture_def.friction = friction;
        fixture_def.restitution = restitution;
        fixture_def.density = density;
        fixture_def.isSensor = sensor;
        fixture_def.filter.categoryBits = category_bits;
        fixture_def.filter.maskBits = mask_bits;
        fixture_def.filter.groupIndex = group_index;

        return body->CreateFixture(&fixture_def);
    }

    b2Fixture *create_loop_fixture(b2Body *body,
                                   VertexArray vertices,
                                   b2UserData user_data,
                                   float32 friction,
                                   float32 restitution,
                                   float32 density,
                                   bool sensor,
                                   uint16 category_bits,
                                   uint16 mask_bits,
                                   uint16 group_index)
    {
        b2LoopShape loop_shape;
        loop_shape.m_vertices = vertices.ptr();
        loop_shape.m_count = vertices.size();

        b2FixtureDef fixture_def;
        fixture_def.shape = &loop_shape;
        fixture_def.userData = user_data;
        fixture_def.friction = friction;
        fixture_def.restitution = restitution;
        fixture_def.density = density;
        fixture_def.isSensor = sensor;
        fixture_def.filter.categoryBits = category_bits;
        fixture_def.filter.maskBits = mask_bits;
        fixture_def.filter.groupIndex = group_index;

        return body->CreateFixture(&fixture_def);
    }

    void wrap_body()
    {
        b2Fixture *(b2Body::*get_fixture_list)() = &b2Body::GetFixtureList;
        b2JointEdge *(b2Body::*get_joint_list)() = &b2Body::GetJointList;
        b2ContactEdge *(b2Body::*get_contact_list)() = &b2Body::GetContactList;
        b2Body *(b2Body::*get_next)() = &b2Body::GetNext;
        b2World *(b2Body::*get_world)() = &b2Body::GetWorld;

        class_<b2Body, boost::noncopyable>("Body", no_init)
            .def("create_fixture", &create_fixture, return_internal_reference<>(),
                 (arg("self"),
                  arg("shape"),
                  arg("user_data")=object(),
                  arg("friction")=0.2f,
                  arg("restitution")=0.0f,
                  arg("density")=1.0f,
                  arg("sensor")=false,
                  arg("category_bits")=0x0001,
                  arg("mask_bits")=0xffff,
                  arg("group_index")=0))
            .def("create_circle_fixture", &create_circle_fixture, return_internal_reference<>(),
                 (arg("self"),
                  arg("position")=b2Vec2(0.0f, 0.0f),
                  arg("radius")=1.0f,
                  arg("user_data")=object(),
                  arg("friction")=0.2f,
                  arg("restitution")=0.0f,
                  arg("density")=1.0f,
                  arg("sensor")=false,
                  arg("category_bits")=0x0001,
                  arg("mask_bits")=0xffff,
                  arg("group_index")=0))
            .def("create_edge_fixture", &create_edge_fixture, return_internal_reference<>(),
                 (arg("self"),
                  arg("vertex_1")=b2Vec2(0.0f, 0.0f),
                  arg("vertex_2")=b2Vec2(0.0f, 0.0f),
                  arg("user_data")=object(),
                  arg("friction")=0.2f,
                  arg("restitution")=0.0f,
                  arg("density")=1.0f,
                  arg("sensor")=false,
                  arg("category_bits")=0x0001,
                  arg("mask_bits")=0xffff,
                  arg("group_index")=0))
            .def("create_polygon_fixture", &create_polygon_fixture, return_internal_reference<>(),
                 (arg("self"),
                  arg("vertices")=list(),
                  arg("user_data")=object(),
                  arg("friction")=0.2f,
                  arg("restitution")=0.0f,
                  arg("density")=1.0f,
                  arg("sensor")=false,
                  arg("category_bits")=0x0001,
                  arg("mask_bits")=0xffff,
                  arg("group_index")=0))
            .def("create_loop_fixture", &create_loop_fixture, return_internal_reference<>(),
                 (arg("self"),
                  arg("vertices"),
                  arg("user_data")=object(),
                  arg("friction")=0.2f,
                  arg("restitution")=0.0f,
                  arg("density")=1.0f,
                  arg("sensor")=false,
                  arg("category_bits")=0x0001,
                  arg("mask_bits")=0xffff,
                  arg("group_index")=0))
            .def("destroy_fixture", &b2Body::DestroyFixture)
            .add_property("transform", make_function(&b2Body::GetTransform, return_value_policy<copy_const_reference>()), &b2Body::SetTransform)
            .add_property("position", make_function(&b2Body::GetPosition, return_value_policy<copy_const_reference>()))
            .add_property("angle", &b2Body::GetAngle)
            .add_property("world_center", make_function(&b2Body::GetWorldCenter, return_value_policy<copy_const_reference>()))
            .add_property("local_center", make_function(&b2Body::GetLocalCenter, return_value_policy<copy_const_reference>()))
            .add_property("linear_velocity", &b2Body::GetLinearVelocity, &b2Body::SetLinearVelocity)
            .add_property("angular_velocity", &b2Body::GetAngularVelocity, &b2Body::SetAngularVelocity)
            .def("apply_force", &b2Body::ApplyForce)
            .def("apply_torque", &b2Body::ApplyTorque)
            .def("apply_linear_impulse", &b2Body::ApplyLinearImpulse)
            .def("apply_angular_impulse", &b2Body::ApplyAngularImpulse)
            .add_property("mass", &b2Body::GetMass)
            .add_property("inertia", &b2Body::GetInertia)
            .add_property("mass_data", &b2Body::GetMassData, &b2Body::SetMassData)
            .def("reset_mass_data", &b2Body::ResetMassData)
            .def("get_world_point", &b2Body::GetWorldPoint)
            .def("get_world_vector", &b2Body::GetWorldVector)
            .def("get_local_point", &b2Body::GetLocalPoint)
            .def("get_local_vector", &b2Body::GetLocalVector)
            .def("get_linear_velocity_from_world_point", &b2Body::GetLinearVelocityFromWorldPoint)
            .def("get_linear_velocity_from_local_point", &b2Body::GetLinearVelocityFromLocalPoint)
            .add_property("linear_damping", &b2Body::GetLinearDamping, &b2Body::SetLinearDamping)
            .add_property("angular_damping", &b2Body::GetAngularDamping, &b2Body::SetAngularDamping)
            .add_property("type", &b2Body::GetType, &b2Body::SetType)
            .add_property("bullet", &b2Body::IsBullet, &b2Body::SetBullet)
            .add_property("sleeping_allowed", &b2Body::IsSleepingAllowed, &b2Body::SetSleepingAllowed)
            .add_property("awake", &b2Body::IsAwake, &b2Body::SetAwake)
            .add_property("active", &b2Body::IsActive, &b2Body::SetActive)
            .add_property("fixed_rotation", &b2Body::IsFixedRotation, &b2Body::SetFixedRotation)
            .add_property("fixture_list", make_function(get_fixture_list, return_internal_reference<>()))
            .add_property("joint_list", make_function(get_joint_list, return_internal_reference<>()))
            .add_property("contact_list", make_function(get_contact_list, return_internal_reference<>()))
            .add_property("next", make_function(get_next, return_internal_reference<>()))
            .add_property("user_data", &b2Body::GetUserData, &b2Body::SetUserData)
            .add_property("world", make_function(get_world, return_internal_reference<>()))
        ;
    }
}
<commit_msg>reverted default density to zero<commit_after>#include "wrap_body.hpp"

#include "wrap_vertex_array.hpp"

#include <boost/python.hpp>
#include <Box2D/Collision/Shapes/b2CircleShape.h>
#include <Box2D/Collision/Shapes/b2EdgeShape.h>
#include <Box2D/Collision/Shapes/b2LoopShape.h>
#include <Box2D/Collision/Shapes/b2PolygonShape.h>
#include <Box2D/Dynamics/b2Fixture.h>
#include <Box2D/Dynamics/b2Body.h>
#include <Box2D/Dynamics/b2World.h>
#include <Box2D/Dynamics/Contacts/b2Contact.h>
#include <Box2D/Dynamics/Joints/b2Joint.h>

using namespace boost::python;

namespace pysics {
    void wrap_body_type()
    {
        enum_<b2BodyType>("BodyType")
            .value("STATIC_BODY", b2_staticBody)
            .value("KINEMATIC_BODY", b2_kinematicBody)
            .value("DYNAMIC_BODY", b2_dynamicBody)
            .export_values()
        ;
    }

    b2Fixture *create_fixture(b2Body *body,
                              b2Shape *shape,
                              b2UserData user_data,
                              float32 friction,
                              float32 restitution,
                              float32 density,
                              bool sensor,
                              uint16 category_bits,
                              uint16 mask_bits,
                              uint16 group_index)
    {
        b2FixtureDef fixture_def;
        fixture_def.shape = shape;
        fixture_def.userData = user_data;
        fixture_def.friction = friction;
        fixture_def.restitution = restitution;
        fixture_def.density = density;
        fixture_def.isSensor = sensor;
        fixture_def.filter.categoryBits = category_bits;
        fixture_def.filter.maskBits = mask_bits;
        fixture_def.filter.groupIndex = group_index;
        return body->CreateFixture(&fixture_def);
    }

    b2Fixture *create_circle_fixture(b2Body *body,
                                     b2Vec2 position,
                                     float32 radius,
                                     b2UserData user_data,
                                     float32 friction,
                                     float32 restitution,
                                     float32 density,
                                     bool sensor,
                                     uint16 category_bits,
                                     uint16 mask_bits,
                                     uint16 group_index)
    {
        b2CircleShape circle_shape;
        circle_shape.m_p = position;
        circle_shape.m_radius = radius;

        b2FixtureDef fixture_def;
        fixture_def.shape = &circle_shape;
        fixture_def.userData = user_data;
        fixture_def.friction = friction;
        fixture_def.restitution = restitution;
        fixture_def.density = density;
        fixture_def.isSensor = sensor;
        fixture_def.filter.categoryBits = category_bits;
        fixture_def.filter.maskBits = mask_bits;
        fixture_def.filter.groupIndex = group_index;

        return body->CreateFixture(&fixture_def);
    }

    b2Fixture *create_edge_fixture(b2Body *body,
                                   b2Vec2 vertex_1,
                                   b2Vec2 vertex_2,
                                   b2UserData user_data,
                                   float32 friction,
                                   float32 restitution,
                                   float32 density,
                                   bool sensor,
                                   uint16 category_bits,
                                   uint16 mask_bits,
                                   uint16 group_index)
    {
        b2EdgeShape edge_shape;
        edge_shape.m_vertex1 = vertex_1;
        edge_shape.m_vertex2 = vertex_2;

        b2FixtureDef fixture_def;
        fixture_def.shape = &edge_shape;
        fixture_def.userData = user_data;
        fixture_def.friction = friction;
        fixture_def.restitution = restitution;
        fixture_def.density = density;
        fixture_def.isSensor = sensor;
        fixture_def.filter.categoryBits = category_bits;
        fixture_def.filter.maskBits = mask_bits;
        fixture_def.filter.groupIndex = group_index;

        return body->CreateFixture(&fixture_def);
    }

    namespace {
        void set_vertices(b2PolygonShape *polygon_shape, list vertices)
        {
            b2Vec2 arr[b2_maxPolygonVertices];
            long n = len(vertices);
            for (long i = 0; i != n; ++i) {
                arr[i] = extract<b2Vec2>(vertices[i]);
            }
            polygon_shape->Set(arr, n);
        }
    }

    b2Fixture *create_polygon_fixture(b2Body *body,
                                      list vertices,
                                      b2UserData user_data,
                                      float32 friction,
                                      float32 restitution,
                                      float32 density,
                                      bool sensor,
                                      uint16 category_bits,
                                      uint16 mask_bits,
                                      uint16 group_index)
    {
        b2PolygonShape polygon_shape;
        if (len(vertices)) {
            set_vertices(&polygon_shape, vertices);
        } else {
            polygon_shape.SetAsBox(1.0f, 1.0f);
        }

        b2FixtureDef fixture_def;
        fixture_def.shape = &polygon_shape;
        fixture_def.userData = user_data;
        fixture_def.friction = friction;
        fixture_def.restitution = restitution;
        fixture_def.density = density;
        fixture_def.isSensor = sensor;
        fixture_def.filter.categoryBits = category_bits;
        fixture_def.filter.maskBits = mask_bits;
        fixture_def.filter.groupIndex = group_index;

        return body->CreateFixture(&fixture_def);
    }

    b2Fixture *create_loop_fixture(b2Body *body,
                                   VertexArray vertices,
                                   b2UserData user_data,
                                   float32 friction,
                                   float32 restitution,
                                   float32 density,
                                   bool sensor,
                                   uint16 category_bits,
                                   uint16 mask_bits,
                                   uint16 group_index)
    {
        b2LoopShape loop_shape;
        loop_shape.m_vertices = vertices.ptr();
        loop_shape.m_count = vertices.size();

        b2FixtureDef fixture_def;
        fixture_def.shape = &loop_shape;
        fixture_def.userData = user_data;
        fixture_def.friction = friction;
        fixture_def.restitution = restitution;
        fixture_def.density = density;
        fixture_def.isSensor = sensor;
        fixture_def.filter.categoryBits = category_bits;
        fixture_def.filter.maskBits = mask_bits;
        fixture_def.filter.groupIndex = group_index;

        return body->CreateFixture(&fixture_def);
    }

    void wrap_body()
    {
        b2Fixture *(b2Body::*get_fixture_list)() = &b2Body::GetFixtureList;
        b2JointEdge *(b2Body::*get_joint_list)() = &b2Body::GetJointList;
        b2ContactEdge *(b2Body::*get_contact_list)() = &b2Body::GetContactList;
        b2Body *(b2Body::*get_next)() = &b2Body::GetNext;
        b2World *(b2Body::*get_world)() = &b2Body::GetWorld;

        class_<b2Body, boost::noncopyable>("Body", no_init)
            .def("create_fixture", &create_fixture, return_internal_reference<>(),
                 (arg("self"),
                  arg("shape"),
                  arg("user_data")=object(),
                  arg("friction")=0.2f,
                  arg("restitution")=0.0f,
                  arg("density")=0.0f,
                  arg("sensor")=false,
                  arg("category_bits")=0x0001,
                  arg("mask_bits")=0xffff,
                  arg("group_index")=0))
            .def("create_circle_fixture", &create_circle_fixture, return_internal_reference<>(),
                 (arg("self"),
                  arg("position")=b2Vec2(0.0f, 0.0f),
                  arg("radius")=1.0f,
                  arg("user_data")=object(),
                  arg("friction")=0.2f,
                  arg("restitution")=0.0f,
                  arg("density")=0.0f,
                  arg("sensor")=false,
                  arg("category_bits")=0x0001,
                  arg("mask_bits")=0xffff,
                  arg("group_index")=0))
            .def("create_edge_fixture", &create_edge_fixture, return_internal_reference<>(),
                 (arg("self"),
                  arg("vertex_1")=b2Vec2(0.0f, 0.0f),
                  arg("vertex_2")=b2Vec2(0.0f, 0.0f),
                  arg("user_data")=object(),
                  arg("friction")=0.2f,
                  arg("restitution")=0.0f,
                  arg("density")=0.0f,
                  arg("sensor")=false,
                  arg("category_bits")=0x0001,
                  arg("mask_bits")=0xffff,
                  arg("group_index")=0))
            .def("create_polygon_fixture", &create_polygon_fixture, return_internal_reference<>(),
                 (arg("self"),
                  arg("vertices")=list(),
                  arg("user_data")=object(),
                  arg("friction")=0.2f,
                  arg("restitution")=0.0f,
                  arg("density")=0.0f,
                  arg("sensor")=false,
                  arg("category_bits")=0x0001,
                  arg("mask_bits")=0xffff,
                  arg("group_index")=0))
            .def("create_loop_fixture", &create_loop_fixture, return_internal_reference<>(),
                 (arg("self"),
                  arg("vertices"),
                  arg("user_data")=object(),
                  arg("friction")=0.2f,
                  arg("restitution")=0.0f,
                  arg("density")=0.0f,
                  arg("sensor")=false,
                  arg("category_bits")=0x0001,
                  arg("mask_bits")=0xffff,
                  arg("group_index")=0))
            .def("destroy_fixture", &b2Body::DestroyFixture)
            .add_property("transform", make_function(&b2Body::GetTransform, return_value_policy<copy_const_reference>()), &b2Body::SetTransform)
            .add_property("position", make_function(&b2Body::GetPosition, return_value_policy<copy_const_reference>()))
            .add_property("angle", &b2Body::GetAngle)
            .add_property("world_center", make_function(&b2Body::GetWorldCenter, return_value_policy<copy_const_reference>()))
            .add_property("local_center", make_function(&b2Body::GetLocalCenter, return_value_policy<copy_const_reference>()))
            .add_property("linear_velocity", &b2Body::GetLinearVelocity, &b2Body::SetLinearVelocity)
            .add_property("angular_velocity", &b2Body::GetAngularVelocity, &b2Body::SetAngularVelocity)
            .def("apply_force", &b2Body::ApplyForce)
            .def("apply_torque", &b2Body::ApplyTorque)
            .def("apply_linear_impulse", &b2Body::ApplyLinearImpulse)
            .def("apply_angular_impulse", &b2Body::ApplyAngularImpulse)
            .add_property("mass", &b2Body::GetMass)
            .add_property("inertia", &b2Body::GetInertia)
            .add_property("mass_data", &b2Body::GetMassData, &b2Body::SetMassData)
            .def("reset_mass_data", &b2Body::ResetMassData)
            .def("get_world_point", &b2Body::GetWorldPoint)
            .def("get_world_vector", &b2Body::GetWorldVector)
            .def("get_local_point", &b2Body::GetLocalPoint)
            .def("get_local_vector", &b2Body::GetLocalVector)
            .def("get_linear_velocity_from_world_point", &b2Body::GetLinearVelocityFromWorldPoint)
            .def("get_linear_velocity_from_local_point", &b2Body::GetLinearVelocityFromLocalPoint)
            .add_property("linear_damping", &b2Body::GetLinearDamping, &b2Body::SetLinearDamping)
            .add_property("angular_damping", &b2Body::GetAngularDamping, &b2Body::SetAngularDamping)
            .add_property("type", &b2Body::GetType, &b2Body::SetType)
            .add_property("bullet", &b2Body::IsBullet, &b2Body::SetBullet)
            .add_property("sleeping_allowed", &b2Body::IsSleepingAllowed, &b2Body::SetSleepingAllowed)
            .add_property("awake", &b2Body::IsAwake, &b2Body::SetAwake)
            .add_property("active", &b2Body::IsActive, &b2Body::SetActive)
            .add_property("fixed_rotation", &b2Body::IsFixedRotation, &b2Body::SetFixedRotation)
            .add_property("fixture_list", make_function(get_fixture_list, return_internal_reference<>()))
            .add_property("joint_list", make_function(get_joint_list, return_internal_reference<>()))
            .add_property("contact_list", make_function(get_contact_list, return_internal_reference<>()))
            .add_property("next", make_function(get_next, return_internal_reference<>()))
            .add_property("user_data", &b2Body::GetUserData, &b2Body::SetUserData)
            .add_property("world", make_function(get_world, return_internal_reference<>()))
        ;
    }
}
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <cstdlib>
#include <fstream>
#include <vector>
#include <cmath>
#include <sstream>
#include <stdio.h>
#include <unistd.h>
using namespace std;

#include "Processes.h"
#include "Base.h"
#include "Command.h"
#include "Andand.h"
#include "Oror.h"

//Simple constructor
Processes::Processes()
{
    currCmds.resize(0);
}
//Simple destructor
Processes::~Processes()
{
    for(unsigned i = 0; i < currCmds.size(); ++i)
    {
        delete currCmds.at(i);
    }
}
//This executes all objects within the object's currCmds vector
int Processes::execute()
{
    int temp = 0;
    for(unsigned i = 0; i < currCmds.size(); ++i)
    {
        temp = currCmds.at(i)->execute();
    }
    return temp;
}
//Processes parses the code to split it into separate command lines
//should there be any semicolons present.
void Processes::parse(string input)
{
    vector<string> currCs;
    istringstream inSS(input);
    string currString;
    //Main loop for parsing input that contains semicolons
    while(input.find(";") != string::npos)
    {
        bool hashtag = false;
        bool semicolon = false;
        currCs.resize(0);
        while(!semicolon)
        {
            inSS >> currString;
            input.erase(0, currString.size() + 1);
            //Tests for hashtag/semicolon presence
            if(currString.find("#") != string::npos)
            {
                hashtag = true;
            }
            if(currString.find(";") != string::npos)
            {
                semicolon = true;
            }
            if(!hashtag)
            {
                if(!semicolon)
                {
                    currCs.push_back(currString);
                }
                else
                {
                    currString.erase(currString.size() - 1);
                    currCs.push_back(currString);
                }
            }
        }
        //Here, we detect the presence of connectors.
        bool detected = false;
        for(unsigned j = 0; j < currCs.size(); ++j)
        {
            if(currCs.at(j) == "||" || currCs.at(j) == "&&")
            {
                detected = true;
                break;
            }
        }
        //If it detects one, it sends the vector to a loop
        //that runs until the end of the current command string.
        //It stops at the next connector, looks at the previous connector,
        //and creates objects and links them correspondingly.
        if(detected)
        {
            string prevConnector;
            string nextConnector;
            vector<string> firstCommand;
            unsigned i = 0;
            while(currCs.at(i) != "&&" && currCs.at(i) != "||")
            {
                firstCommand.push_back(currCs.at(i));
                ++i;
            }
            prevConnector = currCs.at(i);
            Base *temp3 = new Command(firstCommand);
            currCmds.push_back(temp3);
            ++i;
            vector<string> currCommand;
            for(;i < currCs.size(); ++i)
            {
                currCommand.push_back(currCs.at(i));
                if(currCs.at(i) == "&&" || currCs.at(i) == "||")
                {
                    currCommand.pop_back();
                    Base *temp = new Command(currCommand);
                    nextConnector = currCs.at(i);
                    if(prevConnector == "&&")
                    {
                        Base *temp2 = new Andand(currCmds.at(currCmds.size() - 1), temp);
                        currCmds.pop_back();
                        currCmds.push_back(temp2);
                        currCommand.resize(0);
                    }
                    else
                    {
                        Base * temp2 = new Oror(currCmds.at(currCmds.size() - 1), temp);
                        currCmds.pop_back();
                        currCmds.push_back(temp2);
                        currCommand.resize(0);
                    }
                }
            }
        }
        //This runs if there no connectors left after semicolon detecting.
        else {
            vector<string> currCommand;
            for(unsigned k = 0; k < currCs.size(); ++k)
            {
                currCommand.push_back(currCs.at(k));
            }
            Base *temp = new Command(currCommand);
            currCmds.push_back(temp);
        }
    }
    //Second loop that parses the remaining part of the input
    //Also, if the input never contained any semicolons,
    //the parse will go straight to this part of the code.
    currCs.resize(0);
    while(inSS >> currString)
    {
        if(currString.find("#") != string::npos)
        {
            break;
        }
        currCs.push_back(currString);
    }
    //Again, detects whether the string has connectors.
    bool detected = false;
    for(unsigned j = 0; j < currCs.size(); ++j)
    {
        if(currCs.at(j) == "&&" || currCs.at(j) == "||")
        {
            detected = true;
            break;
        }
    }
    //If it detects them, it sends them to be parsed,
    //where connector objects are created after the first command is created
    //and subsequently linked until the end of parsing.
    if(detected)
    {
        string prevConnector;
        string nextConnector;
        vector<string> firstCommand;
        unsigned i = 0;
        while(currCs.at(i) != "&&" && currCs.at(i) != "||")
        {
            firstCommand.push_back(currCs.at(i));
            ++i;
        }
        prevConnector = currCs.at(i);
        Base *temp3 = new Command(firstCommand);
        currCmds.push_back(temp3);
        ++i;
        vector<string> currCommand;
        for(; i < currCs.size(); ++i)
        {
            currCommand.push_back(currCs.at(i));
            if(currCs.at(i) == "&&" || currCs.at(i) == "||")
            {
                currCommand.pop_back();
                Base *temp = new Command(currCommand);
                nextConnector = currCs.at(i);
                if(prevConnector == "&&")
                {
                    Base *temp2 = new Andand(currCmds.at(currCmds.size() - 1), temp);
                    currCmds.pop_back();
                    currCmds.push_back(temp2);
                    currCommand.resize(0);
                }
                else
                {
                    Base * temp2 = new Oror(currCmds.at(currCmds.size() - 1), temp);
                    currCmds.pop_back();
                    currCmds.push_back(temp2);
                    currCommand.resize(0);
                }
            }
        }
        Base * temp = new Command(currCommand);
        if(prevConnector == "&&")
            {
                Base *temp2 = new Andand(currCmds.at(currCmds.size() - 1), temp);
                currCmds.pop_back();
                currCmds.push_back(temp2);
                currCommand.resize(0);
            }
        else
        {
            Base * temp2 = new Oror(currCmds.at(currCmds.size() - 1), temp);
            currCmds.pop_back();
            currCmds.push_back(temp2);
        }
    }
    else {
        vector<string> currCommand;
        for(unsigned k = 0; k < currCs.size(); ++k)
        {
            currCommand.push_back(currCs.at(k));
        }
        Base *temp = new Command(currCommand);
        currCmds.push_back(temp);
    }
}
//This is used to clean up the Processes vector in order to gather further
//input from the user.
void Processes::reset()
{
    for(unsigned i = 0; i < currCmds.size(); ++i)
    {
        delete currCmds.at(i);
    }
    this->currCmds.resize(0);
}<commit_msg>styling issues resolved<commit_after>#include <iostream>
#include <string>
#include <cstdlib>
#include <fstream>
#include <vector>
#include <cmath>
#include <sstream>
#include <stdio.h>
#include <unistd.h>
using namespace std;

#include "Processes.h"
#include "Base.h"
#include "Command.h"
#include "Andand.h"
#include "Oror.h"

//Simple constructor
Processes::Processes()
{
    currCmds.resize(0);
}
//Simple destructor
Processes::~Processes()
{
    for(unsigned i = 0; i < currCmds.size(); ++i)
    {
        delete currCmds.at(i);
    }
}
//This executes all objects within the object's currCmds vector
int Processes::execute()
{
    int temp = 0;
    for(unsigned i = 0; i < currCmds.size(); ++i)
    {
        temp = currCmds.at(i)->execute();
    }
    return temp;
}
//Processes parses the code to split it into separate command lines
//should there be any semicolons present.
void Processes::parse(string input)
{
    vector<string> currCs;
    istringstream inSS(input);
    string currString;
    //Main loop for parsing input that contains semicolons
    while(input.find(";") != string::npos)
    {
        bool hashtag = false;
        bool semicolon = false;
        currCs.resize(0);
        while(!semicolon)
        {
            inSS >> currString;
            input.erase(0, currString.size() + 1);
            //Tests for hashtag/semicolon presence
            if(currString.find("#") != string::npos)
            {
                hashtag = true;
            }
            if(currString.find(";") != string::npos)
            {
                semicolon = true;
            }
            if(!hashtag)
            {
                if(!semicolon)
                {
                    currCs.push_back(currString);
                }
                else
                {
                    currString.erase(currString.size() - 1);
                    currCs.push_back(currString);
                }
            }
        }
        //Here, we detect the presence of connectors.
        bool detected = false;
        for(unsigned j = 0; j < currCs.size(); ++j)
        {
            if(currCs.at(j) == "||" || currCs.at(j) == "&&")
            {
                detected = true;
                break;
            }
        }
        //If it detects one, it sends the vector to a loop
        //that runs until the end of the current command string.
        //It stops at the next connector, looks at the previous connector,
        //and creates objects and links them correspondingly.
        if(detected)
        {
            string prevConnector;
            string nextConnector;
            vector<string> firstCommand;
            unsigned i = 0;
            while(currCs.at(i) != "&&" && currCs.at(i) != "||")
            {
                firstCommand.push_back(currCs.at(i));
                ++i;
            }
            prevConnector = currCs.at(i);
            Base *temp3 = new Command(firstCommand);
            currCmds.push_back(temp3);
            ++i;
            vector<string> currCommand;
            for(;i < currCs.size(); ++i)
            {
                currCommand.push_back(currCs.at(i));
                if(currCs.at(i) == "&&" || currCs.at(i) == "||")
                {
                    currCommand.pop_back();
                    Base *temp = new Command(currCommand);
                    nextConnector = currCs.at(i);
                    if(prevConnector == "&&")
                    {
                        Base *temp2 = new Andand(currCmds.at(
                            currCmds.size() - 1), temp);
                        currCmds.pop_back();
                        currCmds.push_back(temp2);
                        currCommand.resize(0);
                    }
                    else
                    {
                        Base * temp2 = new Oror(currCmds.at(
                            currCmds.size() - 1), temp);
                        currCmds.pop_back();
                        currCmds.push_back(temp2);
                        currCommand.resize(0);
                    }
                }
            }
        }
        //This runs if there no connectors left after semicolon detecting.
        else {
            vector<string> currCommand;
            for(unsigned k = 0; k < currCs.size(); ++k)
            {
                currCommand.push_back(currCs.at(k));
            }
            Base *temp = new Command(currCommand);
            currCmds.push_back(temp);
        }
    }
    //Second loop that parses the remaining part of the input
    //Also, if the input never contained any semicolons,
    //the parse will go straight to this part of the code.
    currCs.resize(0);
    while(inSS >> currString)
    {
        if(currString.find("#") != string::npos)
        {
            break;
        }
        currCs.push_back(currString);
    }
    //Again, detects whether the string has connectors.
    bool detected = false;
    for(unsigned j = 0; j < currCs.size(); ++j)
    {
        if(currCs.at(j) == "&&" || currCs.at(j) == "||")
        {
            detected = true;
            break;
        }
    }
    //If it detects them, it sends them to be parsed,
    //where connector objects are created after the first command is created
    //and subsequently linked until the end of parsing.
    if(detected)
    {
        string prevConnector;
        string nextConnector;
        vector<string> firstCommand;
        unsigned i = 0;
        while(currCs.at(i) != "&&" && currCs.at(i) != "||")
        {
            firstCommand.push_back(currCs.at(i));
            ++i;
        }
        prevConnector = currCs.at(i);
        Base *temp3 = new Command(firstCommand);
        currCmds.push_back(temp3);
        ++i;
        vector<string> currCommand;
        for(; i < currCs.size(); ++i)
        {
            currCommand.push_back(currCs.at(i));
            if(currCs.at(i) == "&&" || currCs.at(i) == "||")
            {
                currCommand.pop_back();
                Base *temp = new Command(currCommand);
                nextConnector = currCs.at(i);
                if(prevConnector == "&&")
                {
                    Base *temp2 = new Andand(currCmds.at(currCmds.size() - 1),
                        temp);
                    currCmds.pop_back();
                    currCmds.push_back(temp2);
                    currCommand.resize(0);
                }
                else
                {
                    Base * temp2 = new Oror(currCmds.at(currCmds.size() - 1),
                        temp);
                    currCmds.pop_back();
                    currCmds.push_back(temp2);
                    currCommand.resize(0);
                }
            }
        }
        Base * temp = new Command(currCommand);
        if(prevConnector == "&&")
            {
                Base *temp2 = new Andand(currCmds.at(currCmds.size() - 1),
                    temp);
                currCmds.pop_back();
                currCmds.push_back(temp2);
                currCommand.resize(0);
            }
        else
        {
            Base * temp2 = new Oror(currCmds.at(currCmds.size() - 1), temp);
            currCmds.pop_back();
            currCmds.push_back(temp2);
        }
    }
    else {
        vector<string> currCommand;
        for(unsigned k = 0; k < currCs.size(); ++k)
        {
            currCommand.push_back(currCs.at(k));
        }
        Base *temp = new Command(currCommand);
        currCmds.push_back(temp);
    }
}
//This is used to clean up the Processes vector in order to gather further
//input from the user.
void Processes::reset()
{
    for(unsigned i = 0; i < currCmds.size(); ++i)
    {
        delete currCmds.at(i);
    }
    this->currCmds.resize(0);
}<|endoftext|>


<commit_before>// @(#)root/gl:$Id$
// Author:  Timur Pocheptsov  03/08/2004
// NOTE: This code moved from obsoleted TGLSceneObject.h / .cxx - see these
// attic files for previous CVS history

/*************************************************************************
 * Copyright (C) 1995-2006, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include "TGLPolyMarker.h"
#include "TGLRnrCtx.h"
#include "TGLIncludes.h"

#include "TBuffer3D.h"
#include "TBuffer3DTypes.h"
#include "TMath.h"

#include "TAttMarker.h"

// For debug tracing
#include "TClass.h"
#include "TError.h"

//______________________________________________________________________________
/* Begin_Html

GL Polymarker

To draw a 3D polymarker in a GL window.
End_Html */

ClassImp(TGLPolyMarker)

//______________________________________________________________________________
TGLPolyMarker::TGLPolyMarker(const TBuffer3D & buffer) :
   TGLLogicalShape(buffer),
   fVertices(buffer.fPnts, buffer.fPnts + 3 * buffer.NbPnts()),
   fStyle(7),
   fSize(1.)
{
   //TAttMarker is not TObject descendant, so I need dynamic_cast
   if (TAttMarker *realObj = dynamic_cast<TAttMarker *>(buffer.fID)) {
      fStyle = realObj->GetMarkerStyle();
      fSize  = realObj->GetMarkerSize() / 2.;
   }
}

//______________________________________________________________________________
void TGLPolyMarker::DirectDraw(TGLRnrCtx & rnrCtx) const
{
   // Debug tracing
   if (gDebug > 4) {
      Info("TGLPolyMarker::DirectDraw", "this %d (class %s) LOD %d", this, IsA()->GetName(), rnrCtx.ShapeLOD());
   }

   if (rnrCtx.DrawPass() == TGLRnrCtx::kPassOutlineLine)
      return;

   const Double_t *vertices = &fVertices[0];
   UInt_t size = fVertices.size();
   Int_t stacks = 6, slices = 6;
   Float_t pixelSize  = 1;
   Double_t topRadius = fSize;

   switch (fStyle) {
   case 27:
      stacks = 2, slices = 4;
   case 4:case 8:case 20:case 24:
      for (UInt_t i = 0; i < size; i += 3) {
         glPushMatrix();
         glTranslated(vertices[i], vertices[i + 1], vertices[i + 2]);
         gluSphere(rnrCtx.GetGluQuadric(), fSize, slices, stacks);
         glPopMatrix();
      }
      break;
   case 22:case 26:
      topRadius = 0.;
   case 21:case 25:
      for (UInt_t i = 0; i < size; i += 3) {
         glPushMatrix();
         glTranslated(vertices[i], vertices[i + 1], vertices[i + 2]);
         gluCylinder(rnrCtx.GetGluQuadric(), fSize, topRadius, fSize, 4, 1);
         glPopMatrix();
      }
      break;
   case 23:
      for (UInt_t i = 0; i < size; i += 3) {
         glPushMatrix();
         glTranslated(vertices[i], vertices[i + 1], vertices[i + 2]);
         glRotated(180, 1., 0., 0.);
         gluCylinder(rnrCtx.GetGluQuadric(), fSize, 0., fSize, 4, 1);
         glPopMatrix();
      }
      break;
   case 3: case 2: case 5:
      DrawStars();
      break;
   case 7:
      pixelSize += 1;
   case 6:
      pixelSize += 1;
   case 1: case 9: case 10: case 11: default:
      glPointSize(pixelSize);
      glBegin(GL_POINTS);
      for (UInt_t i = 0; i < size; i += 3)
         glVertex3dv(vertices + i);
      glEnd();
      break;
   }
}

//______________________________________________________________________________
void TGLPolyMarker::DrawStars()const
{
   // Draw stars
   glDisable(GL_LIGHTING);
   const Double_t diag = TMath::Sqrt(2 * fSize * fSize) / 2;

   for (UInt_t i = 0; i < fVertices.size(); i += 3) {
      Double_t x = fVertices[i];
      Double_t y = fVertices[i + 1];
      Double_t z = fVertices[i + 2];
      glBegin(GL_LINES);
      if (fStyle == 2 || fStyle == 3) {
         glVertex3d(x - fSize, y, z);
         glVertex3d(x + fSize, y, z);
         glVertex3d(x, y, z - fSize);
         glVertex3d(x, y, z + fSize);
         glVertex3d(x, y - fSize, z);
         glVertex3d(x, y + fSize, z);
      }
      if(fStyle != 2) {
         glVertex3d(x - diag, y - diag, z - diag);
         glVertex3d(x + diag, y + diag, z + diag);
         glVertex3d(x - diag, y - diag, z + diag);
         glVertex3d(x + diag, y + diag, z - diag);
         glVertex3d(x - diag, y + diag, z - diag);
         glVertex3d(x + diag, y - diag, z + diag);
         glVertex3d(x - diag, y + diag, z + diag);
         glVertex3d(x + diag, y - diag, z - diag);
      }
      glEnd();
   }
   glEnable(GL_LIGHTING);
}
<commit_msg>Also use point-scaling in TGLPolyMarker.<commit_after>// @(#)root/gl:$Id$
// Author:  Timur Pocheptsov  03/08/2004
// NOTE: This code moved from obsoleted TGLSceneObject.h / .cxx - see these
// attic files for previous CVS history

/*************************************************************************
 * Copyright (C) 1995-2006, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include "TGLPolyMarker.h"
#include "TGLRnrCtx.h"
#include "TGLIncludes.h"
#include "TGLUtil.h"

#include "TBuffer3D.h"
#include "TBuffer3DTypes.h"
#include "TMath.h"

#include "TAttMarker.h"

// For debug tracing
#include "TClass.h"
#include "TError.h"

//______________________________________________________________________________
/* Begin_Html

GL Polymarker

To draw a 3D polymarker in a GL window.
End_Html */

ClassImp(TGLPolyMarker)

//______________________________________________________________________________
TGLPolyMarker::TGLPolyMarker(const TBuffer3D & buffer) :
   TGLLogicalShape(buffer),
   fVertices(buffer.fPnts, buffer.fPnts + 3 * buffer.NbPnts()),
   fStyle(7),
   fSize(1.)
{
   //TAttMarker is not TObject descendant, so I need dynamic_cast
   if (TAttMarker *realObj = dynamic_cast<TAttMarker *>(buffer.fID)) {
      fStyle = realObj->GetMarkerStyle();
      fSize  = realObj->GetMarkerSize() / 2.;
   }
}

//______________________________________________________________________________
void TGLPolyMarker::DirectDraw(TGLRnrCtx & rnrCtx) const
{
   // Debug tracing
   if (gDebug > 4) {
      Info("TGLPolyMarker::DirectDraw", "this %d (class %s) LOD %d", this, IsA()->GetName(), rnrCtx.ShapeLOD());
   }

   if (rnrCtx.DrawPass() == TGLRnrCtx::kPassOutlineLine)
      return;

   const Double_t *vertices = &fVertices[0];
   UInt_t size = fVertices.size();
   Int_t stacks = 6, slices = 6;
   Float_t pixelSize  = 1;
   Double_t topRadius = fSize;

   switch (fStyle) {
   case 27:
      stacks = 2, slices = 4;
   case 4:case 8:case 20:case 24:
      for (UInt_t i = 0; i < size; i += 3) {
         glPushMatrix();
         glTranslated(vertices[i], vertices[i + 1], vertices[i + 2]);
         gluSphere(rnrCtx.GetGluQuadric(), fSize, slices, stacks);
         glPopMatrix();
      }
      break;
   case 22:case 26:
      topRadius = 0.;
   case 21:case 25:
      for (UInt_t i = 0; i < size; i += 3) {
         glPushMatrix();
         glTranslated(vertices[i], vertices[i + 1], vertices[i + 2]);
         gluCylinder(rnrCtx.GetGluQuadric(), fSize, topRadius, fSize, 4, 1);
         glPopMatrix();
      }
      break;
   case 23:
      for (UInt_t i = 0; i < size; i += 3) {
         glPushMatrix();
         glTranslated(vertices[i], vertices[i + 1], vertices[i + 2]);
         glRotated(180, 1., 0., 0.);
         gluCylinder(rnrCtx.GetGluQuadric(), fSize, 0., fSize, 4, 1);
         glPopMatrix();
      }
      break;
   case 3: case 2: case 5:
      DrawStars();
      break;
   case 7:
      pixelSize += 1;
   case 6:
      pixelSize += 1;
   case 1: case 9: case 10: case 11: default:
      TGLUtil::PointSize(pixelSize);
      glBegin(GL_POINTS);
      for (UInt_t i = 0; i < size; i += 3)
         glVertex3dv(vertices + i);
      glEnd();
      break;
   }
}

//______________________________________________________________________________
void TGLPolyMarker::DrawStars()const
{
   // Draw stars
   glDisable(GL_LIGHTING);
   const Double_t diag = TMath::Sqrt(2 * fSize * fSize) / 2;

   for (UInt_t i = 0; i < fVertices.size(); i += 3) {
      Double_t x = fVertices[i];
      Double_t y = fVertices[i + 1];
      Double_t z = fVertices[i + 2];
      glBegin(GL_LINES);
      if (fStyle == 2 || fStyle == 3) {
         glVertex3d(x - fSize, y, z);
         glVertex3d(x + fSize, y, z);
         glVertex3d(x, y, z - fSize);
         glVertex3d(x, y, z + fSize);
         glVertex3d(x, y - fSize, z);
         glVertex3d(x, y + fSize, z);
      }
      if(fStyle != 2) {
         glVertex3d(x - diag, y - diag, z - diag);
         glVertex3d(x + diag, y + diag, z + diag);
         glVertex3d(x - diag, y - diag, z + diag);
         glVertex3d(x + diag, y + diag, z - diag);
         glVertex3d(x - diag, y + diag, z - diag);
         glVertex3d(x + diag, y - diag, z + diag);
         glVertex3d(x - diag, y + diag, z + diag);
         glVertex3d(x + diag, y - diag, z - diag);
      }
      glEnd();
   }
   glEnable(GL_LIGHTING);
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: DAVSession.hxx,v $
 *
 *  $Revision: 1.15 $
 *
 *  last change: $Author: vg $ $Date: 2003-07-25 11:39:28 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _DAVSESSION_HXX_
#define _DAVSESSION_HXX_

#include <memory>

#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif

#ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_
#include <com/sun/star/io/XInputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XOUTPUTSTREAM_HPP_
#include <com/sun/star/io/XOutputStream.hpp>
#endif

#ifndef _DAVEXCEPTION_HXX_
#include "DAVException.hxx"
#endif
#ifndef _DAVPROPERTIES_HXX_
#include "DAVProperties.hxx"
#endif
#ifndef _DAVRESOURCE_HXX_
#include "DAVResource.hxx"
#endif
#ifndef _DAVSESSIONFACTORY_HXX_
#include "DAVSessionFactory.hxx"
#endif
#ifndef _DAVTYPES_HXX_
#include "DAVTypes.hxx"
#endif
#ifndef _DAVREQUESTENVIRONMENT_HXX_
#include "DAVRequestEnvironment.hxx"
#endif

namespace webdav_ucp
{

class DAVAuthListener;

class DAVSession
{
public:
    inline void acquire() SAL_THROW(())
    {
        osl_incrementInterlockedCount( &m_nRefCount );
    }

    void release() SAL_THROW(())
    {
        if ( osl_decrementInterlockedCount( &m_nRefCount ) == 0 )
        {
            m_xFactory->releaseElement( this );
            delete this;
        }
    }

    virtual sal_Bool CanUse( const ::rtl::OUString & inPath ) = 0;

    virtual sal_Bool UsesProxy() = 0;

    // DAV methods
    //

    virtual void OPTIONS( const ::rtl::OUString &  inPath,
                          DAVCapabilities & outCapabilities,
                          const DAVRequestEnvironment & rEnv )
        throw( DAVException ) = 0;

    // allprop & named
    virtual void PROPFIND( const ::rtl::OUString &                inPath,
                           const Depth                            inDepth,
                           const std::vector< ::rtl::OUString > & inPropertyNames,
                           std::vector< DAVResource > &           ioResources,
                           const DAVRequestEnvironment & rEnv )
        throw( DAVException ) = 0;

    // propnames
    virtual void PROPFIND( const ::rtl::OUString &          inPath,
                           const Depth                      inDepth,
                           std::vector< DAVResourceInfo > & ioResInfo,
                           const DAVRequestEnvironment & rEnv )
        throw( DAVException ) = 0;

    virtual void PROPPATCH( const ::rtl::OUString &               inPath,
                             const std::vector< ProppatchValue > & inValues,
                            const DAVRequestEnvironment & rEnv )
        throw( DAVException ) = 0;

    virtual void HEAD( const ::rtl::OUString &  inPath,
                       const std::vector< ::rtl::OUString > & inHeaderNames,
                       DAVResource & ioResource,
                       const DAVRequestEnvironment & rEnv )
        throw( DAVException ) = 0;

    virtual com::sun::star::uno::Reference< com::sun::star::io::XInputStream >
                    GET( const ::rtl::OUString & inPath,
                         const DAVRequestEnvironment & rEnv )
        throw( DAVException ) = 0;

    virtual void GET( void* userData,
                      const ::rtl::OUString & inPath,
                      const DAVRequestEnvironment & rEnv )
        throw( DAVException ) = 0;

    virtual void    GET( const ::rtl::OUString & inPath,
        com::sun::star::uno::Reference< com::sun::star::io::XOutputStream >& o,
        const DAVRequestEnvironment & rEnv )
        throw( DAVException ) = 0;

    virtual com::sun::star::uno::Reference< com::sun::star::io::XInputStream >
                    GET( const ::rtl::OUString & inPath,
                         const std::vector< ::rtl::OUString > & inHeaderNames,
                         DAVResource & ioResource,
                         const DAVRequestEnvironment & rEnv )
        throw( DAVException ) = 0;

    virtual void GET( void* userData,
                      const ::rtl::OUString & inPath,
                      const std::vector< ::rtl::OUString > & inHeaderNames,
                      DAVResource & ioResource,
                      const DAVRequestEnvironment & rEnv )
        throw( DAVException ) = 0;

    virtual void    GET( const ::rtl::OUString & inPath,
        com::sun::star::uno::Reference< com::sun::star::io::XOutputStream >& o,
        const std::vector< ::rtl::OUString > & inHeaderNames,
        DAVResource & ioResource,
        const DAVRequestEnvironment & rEnv )
        throw( DAVException ) = 0;

    virtual void    PUT( const ::rtl::OUString & inPath,
        const com::sun::star::uno::Reference<
            com::sun::star::io::XInputStream >& s,
        const DAVRequestEnvironment & rEnv )
        throw( DAVException ) = 0;

    virtual com::sun::star::uno::Reference< com::sun::star::io::XInputStream >
                    POST( const rtl::OUString & inPath,
                          const rtl::OUString & rContentType,
                          const rtl::OUString & rReferer,
                          const com::sun::star::uno::Reference<
                           com::sun::star::io::XInputStream > & inInputStream,
                          const DAVRequestEnvironment & rEnv )
        throw ( DAVException ) = 0;

    virtual void POST( const rtl::OUString & inPath,
                       const rtl::OUString & rContentType,
                       const rtl::OUString & rReferer,
                       const com::sun::star::uno::Reference<
                        com::sun::star::io::XInputStream > & inInputStream,
                       com::sun::star::uno::Reference<
                        com::sun::star::io::XOutputStream > & oOutputStream,
                       const DAVRequestEnvironment & rEnv )
        throw ( DAVException ) = 0;

    virtual void    MKCOL( const ::rtl::OUString & inPath,
                           const DAVRequestEnvironment & rEnv )
        throw( DAVException ) = 0;

    virtual void    COPY( const ::rtl::OUString & inSource,
                          const ::rtl::OUString & inDestination,
                          const DAVRequestEnvironment & rEnv,
                          sal_Bool inOverwrite = false )
        throw( DAVException ) = 0;

    virtual void    MOVE( const ::rtl::OUString & inSource,
                          const ::rtl::OUString & inDestination,
                          const DAVRequestEnvironment & rEnv,
                          sal_Bool inOverwrite = false )
        throw( DAVException ) = 0;

    virtual void    DESTROY( const ::rtl::OUString & inPath,
                             const DAVRequestEnvironment & rEnv )
        throw( DAVException ) = 0;

    // Note: Uncomment the following if locking support is required
    /*
    virtual void LOCK ( const Lock & inLock,
                        const DAVRequestEnvironment & rEnv )
        throw( DAVException ) = 0;

    virtual void UNLOCK ( const Lock & inLock,
                          const DAVRequestEnvironment & rEnv )
        throw( DAVException ) = 0;
    */
protected:
    rtl::Reference< DAVSessionFactory > m_xFactory;

    DAVSession( rtl::Reference< DAVSessionFactory > const & rFactory )
    : m_xFactory( rFactory ), m_nRefCount( 0 ) {}

    virtual ~DAVSession() {}

private:
    DAVSessionFactory::Map::iterator m_aContainerIt;
    oslInterlockedCount m_nRefCount;

    friend class DAVSessionFactory;
#if defined WNT
    friend struct std::auto_ptr< DAVSession >;
    // work around compiler bug...
#else // WNT
    friend class std::auto_ptr< DAVSession >;
#endif // WNT
};

}; // namespace webdav_ucp

#endif // _DAVSESSION_HXX_

<commit_msg>INTEGRATION: CWS net2003 (1.15.14); FILE MERGED 2003/09/24 09:50:38 obo 1.15.14.1: #111136# .net 2003 port<commit_after>/*************************************************************************
 *
 *  $RCSfile: DAVSession.hxx,v $
 *
 *  $Revision: 1.16 $
 *
 *  last change: $Author: vg $ $Date: 2003-10-06 18:52:36 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _DAVSESSION_HXX_
#define _DAVSESSION_HXX_

#include <memory>

#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif

#ifndef _COM_SUN_STAR_IO_XINPUTSTREAM_HPP_
#include <com/sun/star/io/XInputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XOUTPUTSTREAM_HPP_
#include <com/sun/star/io/XOutputStream.hpp>
#endif

#ifndef _DAVEXCEPTION_HXX_
#include "DAVException.hxx"
#endif
#ifndef _DAVPROPERTIES_HXX_
#include "DAVProperties.hxx"
#endif
#ifndef _DAVRESOURCE_HXX_
#include "DAVResource.hxx"
#endif
#ifndef _DAVSESSIONFACTORY_HXX_
#include "DAVSessionFactory.hxx"
#endif
#ifndef _DAVTYPES_HXX_
#include "DAVTypes.hxx"
#endif
#ifndef _DAVREQUESTENVIRONMENT_HXX_
#include "DAVRequestEnvironment.hxx"
#endif

namespace webdav_ucp
{

class DAVAuthListener;

class DAVSession
{
public:
    inline void acquire() SAL_THROW(())
    {
        osl_incrementInterlockedCount( &m_nRefCount );
    }

    void release() SAL_THROW(())
    {
        if ( osl_decrementInterlockedCount( &m_nRefCount ) == 0 )
        {
            m_xFactory->releaseElement( this );
            delete this;
        }
    }

    virtual sal_Bool CanUse( const ::rtl::OUString & inPath ) = 0;

    virtual sal_Bool UsesProxy() = 0;

    // DAV methods
    //

    virtual void OPTIONS( const ::rtl::OUString &  inPath,
                          DAVCapabilities & outCapabilities,
                          const DAVRequestEnvironment & rEnv )
        throw( DAVException ) = 0;

    // allprop & named
    virtual void PROPFIND( const ::rtl::OUString &                inPath,
                           const Depth                            inDepth,
                           const std::vector< ::rtl::OUString > & inPropertyNames,
                           std::vector< DAVResource > &           ioResources,
                           const DAVRequestEnvironment & rEnv )
        throw( DAVException ) = 0;

    // propnames
    virtual void PROPFIND( const ::rtl::OUString &          inPath,
                           const Depth                      inDepth,
                           std::vector< DAVResourceInfo > & ioResInfo,
                           const DAVRequestEnvironment & rEnv )
        throw( DAVException ) = 0;

    virtual void PROPPATCH( const ::rtl::OUString &               inPath,
                             const std::vector< ProppatchValue > & inValues,
                            const DAVRequestEnvironment & rEnv )
        throw( DAVException ) = 0;

    virtual void HEAD( const ::rtl::OUString &  inPath,
                       const std::vector< ::rtl::OUString > & inHeaderNames,
                       DAVResource & ioResource,
                       const DAVRequestEnvironment & rEnv )
        throw( DAVException ) = 0;

    virtual com::sun::star::uno::Reference< com::sun::star::io::XInputStream >
                    GET( const ::rtl::OUString & inPath,
                         const DAVRequestEnvironment & rEnv )
        throw( DAVException ) = 0;

    virtual void GET( void* userData,
                      const ::rtl::OUString & inPath,
                      const DAVRequestEnvironment & rEnv )
        throw( DAVException ) = 0;

    virtual void    GET( const ::rtl::OUString & inPath,
        com::sun::star::uno::Reference< com::sun::star::io::XOutputStream >& o,
        const DAVRequestEnvironment & rEnv )
        throw( DAVException ) = 0;

    virtual com::sun::star::uno::Reference< com::sun::star::io::XInputStream >
                    GET( const ::rtl::OUString & inPath,
                         const std::vector< ::rtl::OUString > & inHeaderNames,
                         DAVResource & ioResource,
                         const DAVRequestEnvironment & rEnv )
        throw( DAVException ) = 0;

    virtual void GET( void* userData,
                      const ::rtl::OUString & inPath,
                      const std::vector< ::rtl::OUString > & inHeaderNames,
                      DAVResource & ioResource,
                      const DAVRequestEnvironment & rEnv )
        throw( DAVException ) = 0;

    virtual void    GET( const ::rtl::OUString & inPath,
        com::sun::star::uno::Reference< com::sun::star::io::XOutputStream >& o,
        const std::vector< ::rtl::OUString > & inHeaderNames,
        DAVResource & ioResource,
        const DAVRequestEnvironment & rEnv )
        throw( DAVException ) = 0;

    virtual void    PUT( const ::rtl::OUString & inPath,
        const com::sun::star::uno::Reference<
            com::sun::star::io::XInputStream >& s,
        const DAVRequestEnvironment & rEnv )
        throw( DAVException ) = 0;

    virtual com::sun::star::uno::Reference< com::sun::star::io::XInputStream >
                    POST( const rtl::OUString & inPath,
                          const rtl::OUString & rContentType,
                          const rtl::OUString & rReferer,
                          const com::sun::star::uno::Reference<
                           com::sun::star::io::XInputStream > & inInputStream,
                          const DAVRequestEnvironment & rEnv )
        throw ( DAVException ) = 0;

    virtual void POST( const rtl::OUString & inPath,
                       const rtl::OUString & rContentType,
                       const rtl::OUString & rReferer,
                       const com::sun::star::uno::Reference<
                        com::sun::star::io::XInputStream > & inInputStream,
                       com::sun::star::uno::Reference<
                        com::sun::star::io::XOutputStream > & oOutputStream,
                       const DAVRequestEnvironment & rEnv )
        throw ( DAVException ) = 0;

    virtual void    MKCOL( const ::rtl::OUString & inPath,
                           const DAVRequestEnvironment & rEnv )
        throw( DAVException ) = 0;

    virtual void    COPY( const ::rtl::OUString & inSource,
                          const ::rtl::OUString & inDestination,
                          const DAVRequestEnvironment & rEnv,
                          sal_Bool inOverwrite = false )
        throw( DAVException ) = 0;

    virtual void    MOVE( const ::rtl::OUString & inSource,
                          const ::rtl::OUString & inDestination,
                          const DAVRequestEnvironment & rEnv,
                          sal_Bool inOverwrite = false )
        throw( DAVException ) = 0;

    virtual void    DESTROY( const ::rtl::OUString & inPath,
                             const DAVRequestEnvironment & rEnv )
        throw( DAVException ) = 0;

    // Note: Uncomment the following if locking support is required
    /*
    virtual void LOCK ( const Lock & inLock,
                        const DAVRequestEnvironment & rEnv )
        throw( DAVException ) = 0;

    virtual void UNLOCK ( const Lock & inLock,
                          const DAVRequestEnvironment & rEnv )
        throw( DAVException ) = 0;
    */
protected:
    rtl::Reference< DAVSessionFactory > m_xFactory;

    DAVSession( rtl::Reference< DAVSessionFactory > const & rFactory )
    : m_xFactory( rFactory ), m_nRefCount( 0 ) {}

    virtual ~DAVSession() {}

private:
    DAVSessionFactory::Map::iterator m_aContainerIt;
    oslInterlockedCount m_nRefCount;

    friend class DAVSessionFactory;
#if defined WNT && _MSC_VER < 1310
    friend struct std::auto_ptr< DAVSession >;
    // work around compiler bug...
#else // WNT
    friend class std::auto_ptr< DAVSession >;
#endif // WNT
};

}; // namespace webdav_ucp

#endif // _DAVSESSION_HXX_

<|endoftext|>


<commit_before>// Copyright (c) 2012 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 "libcef/browser/url_request_context_getter.h"

#if defined(OS_WIN)
#include <winhttp.h>
#endif
#include <string>
#include <vector>

#include "libcef/browser/content_browser_client.h"
#include "libcef/browser/context.h"
#include "libcef/browser/scheme_handler.h"
#include "libcef/browser/thread_util.h"
#include "libcef/browser/url_network_delegate.h"
#include "libcef/browser/url_request_context_proxy.h"
#include "libcef/browser/url_request_interceptor.h"
#include "libcef/common/cef_switches.h"

#include "base/command_line.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/stl_util.h"
#include "base/strings/string_util.h"
#include "base/threading/thread_restrictions.h"
#include "base/threading/worker_pool.h"
#include "chrome/browser/net/proxy_service_factory.h"
#include "content/browser/net/sqlite_persistent_cookie_store.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/url_constants.h"
#include "net/cert/cert_verifier.h"
#include "net/cookies/cookie_monster.h"
#include "net/dns/host_resolver.h"
#include "net/ftp/ftp_network_layer.h"
#include "net/http/http_auth_handler_factory.h"
#include "net/http/http_cache.h"
#include "net/http/http_server_properties_impl.h"
#include "net/http/transport_security_state.h"
#include "net/proxy/proxy_service.h"
#include "net/ssl/default_server_bound_cert_store.h"
#include "net/ssl/server_bound_cert_service.h"
#include "net/ssl/ssl_config_service_defaults.h"
#include "net/url_request/static_http_user_agent_settings.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_storage.h"
#include "net/url_request/url_request_job_factory_impl.h"
#include "net/url_request/url_request_job_manager.h"

using content::BrowserThread;

#if defined(OS_WIN)
#pragma comment(lib, "winhttp.lib")
#endif

CefURLRequestContextGetter::CefURLRequestContextGetter(
    base::MessageLoop* io_loop,
    base::MessageLoop* file_loop,
    content::ProtocolHandlerMap* protocol_handlers)
    : io_loop_(io_loop),
      file_loop_(file_loop) {
  // Must first be created on the UI thread.
  CEF_REQUIRE_UIT();

  std::swap(protocol_handlers_, *protocol_handlers);
}

CefURLRequestContextGetter::~CefURLRequestContextGetter() {
  CEF_REQUIRE_IOT();
  STLDeleteElements(&url_request_context_proxies_);
}

net::URLRequestContext* CefURLRequestContextGetter::GetURLRequestContext() {
  CEF_REQUIRE_IOT();

  if (!url_request_context_.get()) {
    const base::FilePath& cache_path = CefContext::Get()->cache_path();
    const CommandLine& command_line = *CommandLine::ForCurrentProcess();
    const CefSettings& settings = CefContext::Get()->settings();

    url_request_context_.reset(new net::URLRequestContext());
    storage_.reset(
        new net::URLRequestContextStorage(url_request_context_.get()));

    bool persist_session_cookies =
        (settings.persist_session_cookies ||
         command_line.HasSwitch(switches::kPersistSessionCookies));
    SetCookieStoragePath(cache_path, persist_session_cookies);

    storage_->set_network_delegate(new CefNetworkDelegate);

    storage_->set_server_bound_cert_service(new net::ServerBoundCertService(
        new net::DefaultServerBoundCertStore(NULL),
        base::WorkerPool::GetTaskRunner(true)));
    storage_->set_http_user_agent_settings(
        new net::StaticHttpUserAgentSettings("en-us,en", EmptyString()));

    storage_->set_host_resolver(net::HostResolver::CreateDefaultResolver(NULL));
    storage_->set_cert_verifier(net::CertVerifier::CreateDefault());
    storage_->set_transport_security_state(new net::TransportSecurityState);

    scoped_ptr<net::ProxyService> system_proxy_service;
    system_proxy_service.reset(
        ProxyServiceFactory::CreateProxyService(
            NULL,
            url_request_context_.get(),
            url_request_context_->network_delegate(),
            CefContentBrowserClient::Get()->proxy_config_service().release(),
            command_line));
    storage_->set_proxy_service(system_proxy_service.release());

    storage_->set_ssl_config_service(new net::SSLConfigServiceDefaults);

    // Add support for single sign-on.
    url_security_manager_.reset(net::URLSecurityManager::Create(NULL, NULL));

    std::vector<std::string> supported_schemes;
    supported_schemes.push_back("basic");
    supported_schemes.push_back("digest");
    supported_schemes.push_back("ntlm");
    supported_schemes.push_back("negotiate");

    storage_->set_http_auth_handler_factory(
        net::HttpAuthHandlerRegistryFactory::Create(
            supported_schemes,
            url_security_manager_.get(),
            url_request_context_->host_resolver(),
            std::string(),
            false,
            false));
    storage_->set_http_server_properties(
        make_scoped_ptr<net::HttpServerProperties>(
            new net::HttpServerPropertiesImpl));

    net::HttpCache::DefaultBackend* main_backend =
        new net::HttpCache::DefaultBackend(
            cache_path.empty() ? net::MEMORY_CACHE : net::DISK_CACHE,
            net::CACHE_BACKEND_DEFAULT,
            cache_path,
            0,
            BrowserThread::GetMessageLoopProxyForThread(
                BrowserThread::CACHE));

    net::HttpNetworkSession::Params network_session_params;
    network_session_params.host_resolver =
        url_request_context_->host_resolver();
    network_session_params.cert_verifier =
        url_request_context_->cert_verifier();
    network_session_params.transport_security_state =
        url_request_context_->transport_security_state();
    network_session_params.server_bound_cert_service =
        url_request_context_->server_bound_cert_service();
    network_session_params.proxy_service =
        url_request_context_->proxy_service();
    network_session_params.ssl_config_service =
        url_request_context_->ssl_config_service();
    network_session_params.http_auth_handler_factory =
        url_request_context_->http_auth_handler_factory();
    network_session_params.network_delegate =
        url_request_context_->network_delegate();
    network_session_params.http_server_properties =
        url_request_context_->http_server_properties();
    network_session_params.ignore_certificate_errors =
        (settings.ignore_certificate_errors ||
         command_line.HasSwitch(switches::kIgnoreCertificateErrors));

    net::HttpCache* main_cache = new net::HttpCache(network_session_params,
                                                    main_backend);
    storage_->set_http_transaction_factory(main_cache);

#if !defined(DISABLE_FTP_SUPPORT)
    ftp_transaction_factory_.reset(
        new net::FtpNetworkLayer(network_session_params.host_resolver));
#endif

    scoped_ptr<net::URLRequestJobFactoryImpl> job_factory(
        new net::URLRequestJobFactoryImpl());
    job_factory_impl_ = job_factory.get();

    scheme::InstallInternalProtectedHandlers(job_factory.get(),
                                             &protocol_handlers_,
                                             ftp_transaction_factory_.get());
    protocol_handlers_.clear();

    storage_->set_job_factory(job_factory.release());

    request_interceptor_.reset(new CefRequestInterceptor);
  }

  return url_request_context_.get();
}

scoped_refptr<base::SingleThreadTaskRunner>
    CefURLRequestContextGetter::GetNetworkTaskRunner() const {
  return BrowserThread::GetMessageLoopProxyForThread(CEF_IOT);
}

net::HostResolver* CefURLRequestContextGetter::host_resolver() {
  return url_request_context_->host_resolver();
}

void CefURLRequestContextGetter::SetCookieStoragePath(
    const base::FilePath& path,
    bool persist_session_cookies) {
  CEF_REQUIRE_IOT();

  if (url_request_context_->cookie_store() &&
      ((cookie_store_path_.empty() && path.empty()) ||
       cookie_store_path_ == path)) {
    // The path has not changed so don't do anything.
    return;
  }

  scoped_refptr<content::SQLitePersistentCookieStore> persistent_store;
  if (!path.empty()) {
    // TODO(cef): Move directory creation to the blocking pool instead of
    // allowing file IO on this thread.
    base::ThreadRestrictions::ScopedAllowIO allow_io;
    if (base::DirectoryExists(path) ||
        file_util::CreateDirectory(path)) {
      const base::FilePath& cookie_path = path.AppendASCII("Cookies");
      persistent_store =
          new content::SQLitePersistentCookieStore(
              cookie_path,
              BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO),
              BrowserThread::GetMessageLoopProxyForThread(BrowserThread::DB),
              persist_session_cookies,
              NULL);
    } else {
      NOTREACHED() << "The cookie storage directory could not be created";
    }
  }

  // Set the new cookie store that will be used for all new requests. The old
  // cookie store, if any, will be automatically flushed and closed when no
  // longer referenced.
  scoped_refptr<net::CookieMonster> cookie_monster =
      new net::CookieMonster(persistent_store.get(), NULL);
  storage_->set_cookie_store(cookie_monster);
  if (persistent_store.get() && persist_session_cookies)
      cookie_monster->SetPersistSessionCookies(true);
  cookie_store_path_ = path;

  // Restore the previously supported schemes.
  SetCookieSupportedSchemes(cookie_supported_schemes_);
}

void CefURLRequestContextGetter::SetCookieSupportedSchemes(
    const std::vector<std::string>& schemes) {
  CEF_REQUIRE_IOT();

  cookie_supported_schemes_ = schemes;

  if (cookie_supported_schemes_.empty()) {
    cookie_supported_schemes_.push_back("http");
    cookie_supported_schemes_.push_back("https");
  }

  std::set<std::string> scheme_set;
  std::vector<std::string>::const_iterator it =
      cookie_supported_schemes_.begin();
  for (; it != cookie_supported_schemes_.end(); ++it)
    scheme_set.insert(*it);

  const char** arr = new const char*[scheme_set.size()];
  std::set<std::string>::const_iterator it2 = scheme_set.begin();
  for (int i = 0; it2 != scheme_set.end(); ++it2, ++i)
    arr[i] = it2->c_str();

  url_request_context_->cookie_store()->GetCookieMonster()->
      SetCookieableSchemes(arr, scheme_set.size());

  delete [] arr;
}

CefURLRequestContextProxy*
    CefURLRequestContextGetter::CreateURLRequestContextProxy() {
  CEF_REQUIRE_IOT();
  CefURLRequestContextProxy* proxy = new CefURLRequestContextProxy(this);
  url_request_context_proxies_.insert(proxy);
  return proxy;
}

void CefURLRequestContextGetter::ReleaseURLRequestContextProxy(
    CefURLRequestContextProxy* proxy) {
  CEF_REQUIRE_IOT();

  // Don't do anything if we're currently shutting down. The proxy objects will
  // be deleted when this object is destroyed.
  if (CefContext::Get()->shutting_down())
    return;

  if (proxy->url_requests()->size() == 0) {
    // Safe to delete the proxy.
    RequestContextProxySet::iterator it =
        url_request_context_proxies_.find(proxy);
    DCHECK(it != url_request_context_proxies_.end());
    url_request_context_proxies_.erase(it);
    delete proxy;
  } else {
    proxy->increment_delete_try_count();
    if (proxy->delete_try_count() <= 1) {
      // Cancel the pending requests. This may result in additional tasks being
      // posted on the IO thread.
      std::set<const net::URLRequest*>::iterator it =
          proxy->url_requests()->begin();
      for (; it != proxy->url_requests()->end(); ++it)
        const_cast<net::URLRequest*>(*it)->Cancel();

      // Try to delete the proxy again later.
      CEF_POST_TASK(CEF_IOT,
          base::Bind(&CefURLRequestContextGetter::ReleaseURLRequestContextProxy,
                     this, proxy));
    } else {
      NOTREACHED() <<
          "too many retries to delete URLRequestContext proxy object";
    }
  }
}

void CefURLRequestContextGetter::CreateProxyConfigService() {
  if (proxy_config_service_.get())
    return;

  proxy_config_service_.reset(
      net::ProxyService::CreateSystemProxyConfigService(
          io_loop_->message_loop_proxy(), file_loop_));
}
<commit_msg>Fix AssertNoURLRequests due to pending proxy connections during shutdown (issue #1037).<commit_after>// Copyright (c) 2012 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 "libcef/browser/url_request_context_getter.h"

#if defined(OS_WIN)
#include <winhttp.h>
#endif
#include <string>
#include <vector>

#include "libcef/browser/content_browser_client.h"
#include "libcef/browser/context.h"
#include "libcef/browser/scheme_handler.h"
#include "libcef/browser/thread_util.h"
#include "libcef/browser/url_network_delegate.h"
#include "libcef/browser/url_request_context_proxy.h"
#include "libcef/browser/url_request_interceptor.h"
#include "libcef/common/cef_switches.h"

#include "base/command_line.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/stl_util.h"
#include "base/strings/string_util.h"
#include "base/threading/thread_restrictions.h"
#include "base/threading/worker_pool.h"
#include "chrome/browser/net/proxy_service_factory.h"
#include "content/browser/net/sqlite_persistent_cookie_store.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/url_constants.h"
#include "net/cert/cert_verifier.h"
#include "net/cookies/cookie_monster.h"
#include "net/dns/host_resolver.h"
#include "net/ftp/ftp_network_layer.h"
#include "net/http/http_auth_handler_factory.h"
#include "net/http/http_cache.h"
#include "net/http/http_server_properties_impl.h"
#include "net/http/transport_security_state.h"
#include "net/proxy/proxy_service.h"
#include "net/ssl/default_server_bound_cert_store.h"
#include "net/ssl/server_bound_cert_service.h"
#include "net/ssl/ssl_config_service_defaults.h"
#include "net/url_request/static_http_user_agent_settings.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_storage.h"
#include "net/url_request/url_request_job_factory_impl.h"
#include "net/url_request/url_request_job_manager.h"

using content::BrowserThread;

#if defined(OS_WIN)
#pragma comment(lib, "winhttp.lib")
#endif

CefURLRequestContextGetter::CefURLRequestContextGetter(
    base::MessageLoop* io_loop,
    base::MessageLoop* file_loop,
    content::ProtocolHandlerMap* protocol_handlers)
    : io_loop_(io_loop),
      file_loop_(file_loop) {
  // Must first be created on the UI thread.
  CEF_REQUIRE_UIT();

  std::swap(protocol_handlers_, *protocol_handlers);
}

CefURLRequestContextGetter::~CefURLRequestContextGetter() {
  CEF_REQUIRE_IOT();
  STLDeleteElements(&url_request_context_proxies_);

  // Delete the ProxyService object here so that any pending requests will be
  // canceled before the associated URLRequestContext is destroyed in this
  // object's destructor.
  storage_->set_proxy_service(NULL);
}

net::URLRequestContext* CefURLRequestContextGetter::GetURLRequestContext() {
  CEF_REQUIRE_IOT();

  if (!url_request_context_.get()) {
    const base::FilePath& cache_path = CefContext::Get()->cache_path();
    const CommandLine& command_line = *CommandLine::ForCurrentProcess();
    const CefSettings& settings = CefContext::Get()->settings();

    url_request_context_.reset(new net::URLRequestContext());
    storage_.reset(
        new net::URLRequestContextStorage(url_request_context_.get()));

    bool persist_session_cookies =
        (settings.persist_session_cookies ||
         command_line.HasSwitch(switches::kPersistSessionCookies));
    SetCookieStoragePath(cache_path, persist_session_cookies);

    storage_->set_network_delegate(new CefNetworkDelegate);

    storage_->set_server_bound_cert_service(new net::ServerBoundCertService(
        new net::DefaultServerBoundCertStore(NULL),
        base::WorkerPool::GetTaskRunner(true)));
    storage_->set_http_user_agent_settings(
        new net::StaticHttpUserAgentSettings("en-us,en", EmptyString()));

    storage_->set_host_resolver(net::HostResolver::CreateDefaultResolver(NULL));
    storage_->set_cert_verifier(net::CertVerifier::CreateDefault());
    storage_->set_transport_security_state(new net::TransportSecurityState);

    scoped_ptr<net::ProxyService> system_proxy_service;
    system_proxy_service.reset(
        ProxyServiceFactory::CreateProxyService(
            NULL,
            url_request_context_.get(),
            url_request_context_->network_delegate(),
            CefContentBrowserClient::Get()->proxy_config_service().release(),
            command_line));
    storage_->set_proxy_service(system_proxy_service.release());

    storage_->set_ssl_config_service(new net::SSLConfigServiceDefaults);

    // Add support for single sign-on.
    url_security_manager_.reset(net::URLSecurityManager::Create(NULL, NULL));

    std::vector<std::string> supported_schemes;
    supported_schemes.push_back("basic");
    supported_schemes.push_back("digest");
    supported_schemes.push_back("ntlm");
    supported_schemes.push_back("negotiate");

    storage_->set_http_auth_handler_factory(
        net::HttpAuthHandlerRegistryFactory::Create(
            supported_schemes,
            url_security_manager_.get(),
            url_request_context_->host_resolver(),
            std::string(),
            false,
            false));
    storage_->set_http_server_properties(
        make_scoped_ptr<net::HttpServerProperties>(
            new net::HttpServerPropertiesImpl));

    net::HttpCache::DefaultBackend* main_backend =
        new net::HttpCache::DefaultBackend(
            cache_path.empty() ? net::MEMORY_CACHE : net::DISK_CACHE,
            net::CACHE_BACKEND_DEFAULT,
            cache_path,
            0,
            BrowserThread::GetMessageLoopProxyForThread(
                BrowserThread::CACHE));

    net::HttpNetworkSession::Params network_session_params;
    network_session_params.host_resolver =
        url_request_context_->host_resolver();
    network_session_params.cert_verifier =
        url_request_context_->cert_verifier();
    network_session_params.transport_security_state =
        url_request_context_->transport_security_state();
    network_session_params.server_bound_cert_service =
        url_request_context_->server_bound_cert_service();
    network_session_params.proxy_service =
        url_request_context_->proxy_service();
    network_session_params.ssl_config_service =
        url_request_context_->ssl_config_service();
    network_session_params.http_auth_handler_factory =
        url_request_context_->http_auth_handler_factory();
    network_session_params.network_delegate =
        url_request_context_->network_delegate();
    network_session_params.http_server_properties =
        url_request_context_->http_server_properties();
    network_session_params.ignore_certificate_errors =
        (settings.ignore_certificate_errors ||
         command_line.HasSwitch(switches::kIgnoreCertificateErrors));

    net::HttpCache* main_cache = new net::HttpCache(network_session_params,
                                                    main_backend);
    storage_->set_http_transaction_factory(main_cache);

#if !defined(DISABLE_FTP_SUPPORT)
    ftp_transaction_factory_.reset(
        new net::FtpNetworkLayer(network_session_params.host_resolver));
#endif

    scoped_ptr<net::URLRequestJobFactoryImpl> job_factory(
        new net::URLRequestJobFactoryImpl());
    job_factory_impl_ = job_factory.get();

    scheme::InstallInternalProtectedHandlers(job_factory.get(),
                                             &protocol_handlers_,
                                             ftp_transaction_factory_.get());
    protocol_handlers_.clear();

    storage_->set_job_factory(job_factory.release());

    request_interceptor_.reset(new CefRequestInterceptor);
  }

  return url_request_context_.get();
}

scoped_refptr<base::SingleThreadTaskRunner>
    CefURLRequestContextGetter::GetNetworkTaskRunner() const {
  return BrowserThread::GetMessageLoopProxyForThread(CEF_IOT);
}

net::HostResolver* CefURLRequestContextGetter::host_resolver() {
  return url_request_context_->host_resolver();
}

void CefURLRequestContextGetter::SetCookieStoragePath(
    const base::FilePath& path,
    bool persist_session_cookies) {
  CEF_REQUIRE_IOT();

  if (url_request_context_->cookie_store() &&
      ((cookie_store_path_.empty() && path.empty()) ||
       cookie_store_path_ == path)) {
    // The path has not changed so don't do anything.
    return;
  }

  scoped_refptr<content::SQLitePersistentCookieStore> persistent_store;
  if (!path.empty()) {
    // TODO(cef): Move directory creation to the blocking pool instead of
    // allowing file IO on this thread.
    base::ThreadRestrictions::ScopedAllowIO allow_io;
    if (base::DirectoryExists(path) ||
        file_util::CreateDirectory(path)) {
      const base::FilePath& cookie_path = path.AppendASCII("Cookies");
      persistent_store =
          new content::SQLitePersistentCookieStore(
              cookie_path,
              BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO),
              BrowserThread::GetMessageLoopProxyForThread(BrowserThread::DB),
              persist_session_cookies,
              NULL);
    } else {
      NOTREACHED() << "The cookie storage directory could not be created";
    }
  }

  // Set the new cookie store that will be used for all new requests. The old
  // cookie store, if any, will be automatically flushed and closed when no
  // longer referenced.
  scoped_refptr<net::CookieMonster> cookie_monster =
      new net::CookieMonster(persistent_store.get(), NULL);
  storage_->set_cookie_store(cookie_monster);
  if (persistent_store.get() && persist_session_cookies)
      cookie_monster->SetPersistSessionCookies(true);
  cookie_store_path_ = path;

  // Restore the previously supported schemes.
  SetCookieSupportedSchemes(cookie_supported_schemes_);
}

void CefURLRequestContextGetter::SetCookieSupportedSchemes(
    const std::vector<std::string>& schemes) {
  CEF_REQUIRE_IOT();

  cookie_supported_schemes_ = schemes;

  if (cookie_supported_schemes_.empty()) {
    cookie_supported_schemes_.push_back("http");
    cookie_supported_schemes_.push_back("https");
  }

  std::set<std::string> scheme_set;
  std::vector<std::string>::const_iterator it =
      cookie_supported_schemes_.begin();
  for (; it != cookie_supported_schemes_.end(); ++it)
    scheme_set.insert(*it);

  const char** arr = new const char*[scheme_set.size()];
  std::set<std::string>::const_iterator it2 = scheme_set.begin();
  for (int i = 0; it2 != scheme_set.end(); ++it2, ++i)
    arr[i] = it2->c_str();

  url_request_context_->cookie_store()->GetCookieMonster()->
      SetCookieableSchemes(arr, scheme_set.size());

  delete [] arr;
}

CefURLRequestContextProxy*
    CefURLRequestContextGetter::CreateURLRequestContextProxy() {
  CEF_REQUIRE_IOT();
  CefURLRequestContextProxy* proxy = new CefURLRequestContextProxy(this);
  url_request_context_proxies_.insert(proxy);
  return proxy;
}

void CefURLRequestContextGetter::ReleaseURLRequestContextProxy(
    CefURLRequestContextProxy* proxy) {
  CEF_REQUIRE_IOT();

  // Don't do anything if we're currently shutting down. The proxy objects will
  // be deleted when this object is destroyed.
  if (CefContext::Get()->shutting_down())
    return;

  if (proxy->url_requests()->size() == 0) {
    // Safe to delete the proxy.
    RequestContextProxySet::iterator it =
        url_request_context_proxies_.find(proxy);
    DCHECK(it != url_request_context_proxies_.end());
    url_request_context_proxies_.erase(it);
    delete proxy;
  } else {
    proxy->increment_delete_try_count();
    if (proxy->delete_try_count() <= 1) {
      // Cancel the pending requests. This may result in additional tasks being
      // posted on the IO thread.
      std::set<const net::URLRequest*>::iterator it =
          proxy->url_requests()->begin();
      for (; it != proxy->url_requests()->end(); ++it)
        const_cast<net::URLRequest*>(*it)->Cancel();

      // Try to delete the proxy again later.
      CEF_POST_TASK(CEF_IOT,
          base::Bind(&CefURLRequestContextGetter::ReleaseURLRequestContextProxy,
                     this, proxy));
    } else {
      NOTREACHED() <<
          "too many retries to delete URLRequestContext proxy object";
    }
  }
}

void CefURLRequestContextGetter::CreateProxyConfigService() {
  if (proxy_config_service_.get())
    return;

  proxy_config_service_.reset(
      net::ProxyService::CreateSystemProxyConfigService(
          io_loop_->message_loop_proxy(), file_loop_));
}
<|endoftext|>