<commit_before>#include <ros/ros.h>
#include <pcl_ros/point_cloud.h>
#include <pcl/point_types.h>
#include <boost/foreach.hpp>
#include <math.h>
#include <geometry_msgs/Pose.h>
#include <set>
#include <map>

// consists of redundancy, remove later
// copied from rvizView to work with PointCloud2 object
#include <ros/ros.h>
#include <pcl/io/io.h>
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>
#include <pcl_ros/publisher.h>
#include <pcl_conversions/pcl_conversions.h>
#include <ros/publisher.h>
#include <string>
#include <pcl_ros/point_cloud.h>

typedef pcl::PointCloud<pcl::PointXYZ> PointCloud;

// represnts a point with x,y,z coordinates
struct Point {

    float x;
    float y;
    float z;
};

class PMDCloudPublisher
{
    // protected:
    //     std::string tf_frame;
    //     ros::NodeHandle nh;
    //     ros::NodeHandle private_nh;

    // public:
    //     pcl::PointCloud<pcl::PointXYZ>::Ptr cloud;
    //     std::string file_name, cloud_topic;
    //     pcl_ros::Publisher<sensor_msgs::PointCloud2> pub;

    //     PMDCloudPublisher()
    //         : tf_frame("/map"),
    //         private_nh("~")
    // {
    //     cloud_topic = "cloud";
    //     pub.advertise(nh, cloud_topic.c_str(), 1); // published here
    //     private_nh.param("frame_id", tf_frame, std::string("/map"));
    //     ROS_INFO_STREAM("Publishing data on topic \"" << nh.resolveName(cloud_topic) << "\" with frame_id \"" << tf_frame << "\"");
    // }

    //     bool spin ()
    //     {
    //         int nr_points = cloud->width * cloud->height;
    //         std::string fields_list = pcl::getFieldsList(cloud);
    //         ros::Rate r(40);

    //         while(nh.ok ())
    //         {
    //             ROS_DEBUG_STREAM_ONCE("Publishing data with " << nr_points
    //                     << " points " << fields_list
    //                     << " on topic \"" << nh.resolveName(cloud_topic)
    //                     << "\" in frame \"" << cloud.header.frame_id << "\"");
    //             // cloud.header.stamp = ros::Time::now();
    //             pub.publish(cloud);

    //             r.sleep();
    //         }
    //         return (true);
    //     }
};

void publishData(pcl::PointCloud<pcl::PointXYZ>::Ptr filteredCloud, std::map<float, geometry_msgs::Pose> viewablePoints){

    // //ros::init (1, temp, "cloud_publisher");
    // ros::NodeHandle nh;

    // PMDCloudPublisher c;
    // c.file_name = "spray_bottle.pcd";
    // c.cloud = filteredCloud;
    // nh.getParam(filteredCloud, c.cloud);

    // if (c.start () == -1)
    // {
    //     ROS_ERROR_STREAM("Could not load file \"" << c.file_name  <<"\". Exiting...");
    // }
    // ROS_INFO_STREAM("Loaded a point cloud with " << c.cloud.width * c.cloud.height
    //         << " points (total size is " << c.cloud.data.size() << ") and the following channels: " << pcl::getFieldsList (c.cloud));
    // c.spin();
}

// calculating slope of line formed by two points in 3d space
float calculate_slope(float pt_x, float pt_y, float pt_z, float pt2_x, float pt2_y, float pt2_z)
{
    float rise = pt2_z - pt_z;

    float square = pow((pt2_x - pt_x), 2) + pow((pt2_y - pt_y), 2);
    float run = sqrt(square);
    return rise/run;
}

// bool onLine(float view_x, float view_y, float view_z, float pt_x, float pt_y, float pt_z, float check_pt_x, float check_pt_y, float check_pt_z)
// {
//     // Calculate the slope from the view to the check_pt
//     float slope_pt_to_view = calculate_slope(view_x, view_y, view_z, check_pt_x, check_pt_y, check_pt_z);

//     // printf("Slope from view to check_pt: %f\n", slope_pt_to_view);

//     // Calculate slope from the check_pt to the pt
//     float slope_check_pt_to_pt = calculate_slope(view_x, view_y, view_z, pt_x, pt_y, pt_z);

//     // printf("Slope from view to pt: %f\n", slope_check_pt_to_pt);
//     // printf("Are they equivalent?: %d\n", temp);

//     float delta = 0.0000000045f;

//     float diff = fabs(slope_pt_to_view - slope_check_pt_to_pt);

//     bool temp = (diff < delta);
//     // printf("Difference: %f\n", diff);
//     // printf("Boolean: %d\n", temp);

//     //printf("Difference: %f\n", diff);
//     // If they are equal return true
//     return temp;
// }

// calculating distance between two points in  3d space
float distance(float x1, float y1, float z1, float x2, float y2, float z2){

    return sqrt(pow(x1 - x2, 2) + pow(y1 - y2, 2) + pow(z1 - z2, 2));
}

// method to find viewable points from a given view.
// arg1: Passed in a pose that represents a point in space
// arg2: the point cloud object of the pcd file

// PENDING: consider orientation (various angles for a given point) when viewing the object
float findPoints(const geometry_msgs::Pose createdPoint, const PointCloud::ConstPtr& msg)
{

    // printing the current view point
    printf("Coordinates: %f, %f, %f\n", createdPoint.position.x, createdPoint.position.y, createdPoint.position.z);

    // x,y,z represents the cooridnates of the view
    float x = createdPoint.position.x;
    float y = createdPoint.position.y;
    float z = createdPoint.position.z;

    // total number of points in the point cloud
    int size = 0;

    // idea is that for a given line from the view point, slope is the same
    // we want to count for a single point and exclude all the other points on that line
    // by that way we count for a single point and not count points behind the counted
    // point
    // if slope is already contained, then check which point is closer
    // to the view point
    // map for: slope -> point
    std::map<float, geometry_msgs::Pose> viewablePoints;
    std::map<float, geometry_msgs::Pose>::iterator it;
    BOOST_FOREACH (const pcl::PointXYZ& pt, msg->points) {
        float slope_pt_to_view = (int) floorf(calculate_slope(x, y, z, pt.x, pt.y, pt.z) * 100000000.0 + 0.5)/100000000.0;
        it = viewablePoints.find(slope_pt_to_view);

        // if slope is already present
        if(it != viewablePoints.end()){
            // if the slop is already taken into account
            // then we must see the point it corresponds to is the closest to the view point
            // if this new point is closer then must updates the map accordingly
            geometry_msgs::Pose existingPoint = it->second; // get the point
            float oldDistance = distance(x, y, z, existingPoint.position.x, existingPoint.position.y, existingPoint.position.z);
            float newDistance = distance(x, y, z, pt.x, pt.y, pt.z);
            if(newDistance < oldDistance) {
            	geometry_msgs::Pose newPose;
    			newPose.position.x = pt.x;
    			newPose.position.y = pt.y;
    			newPose.position.z = pt.z;
                viewablePoints.insert(std::pair<float, geometry_msgs::Pose> (slope_pt_to_view, newPose));
                //printf("Old point: %f, %f, %f with distance of %f\n", existingPoint.x, existingPoint.y, existingPoint.z, oldDistance);
                //printf("New point: %f, %f, %f with distance of %f\n", newPoint.x, newPoint.y, newPoint.z, newDistance);
            }

        } else {
            // first time looking at this point
            // just add it
            geometry_msgs::Pose newPose;
            newPose.position.x = pt.x;
            newPose.position.y = pt.y;
            newPose.position.z = pt.z;
            viewablePoints.insert(std::pair<float, geometry_msgs::Pose> (slope_pt_to_view, newPose));
        }
        size++; // totalNum points

    }

    // displaying contents of the map
    // multipying by 10000 because %f truncates values, so it appears as if duplictes exist
    // for(it = viewablePoints.begin(); it != viewablePoints.end(); it++){
    //     printf("key: %f, Value: %f, %f, %f\n", it->first * 10000, it->second.x, it->second.y, it->second.z);
    // }

    // at this point we have filtered points based on slope,distance and angle
    // these points need to be used to create a pointcloud2 object
    // once this is created, we will publish this to rviz and view it accoringly
    // references to publishing to rviz check rvizView and generateViews.cpp

    // in progress
    // refer: http://wiki.ros.org/pcl_ros
    // refer: http://pointclouds.org/documentation/tutorials/passthrough.php

    pcl::PointCloud<pcl::PointXYZ>::Ptr filteredCloud (new pcl::PointCloud<pcl::PointXYZ>);

    filteredCloud->width = viewablePoints.size(); // need to verify
    filteredCloud->height = 1;
    filteredCloud->points.resize(filteredCloud->width * filteredCloud->height);

    int filterIndex = 0;

    // loading a new pointcloud object from the points that we collected
    for(it = viewablePoints.begin(); it != viewablePoints.end(); it++, filterIndex++){

    	// ideally no segfaults because filterdCloud size
    	// is viewable points * 1 == viewablePoints.size();
    	filteredCloud->points[filterIndex].x = it->second.position.x;
    	filteredCloud->points[filterIndex].y = it->second.position.y;
    	filteredCloud->points[filterIndex].z = it->second.position.z;
    }

    publishData(filteredCloud, viewablePoints);

    float viewableAmount = 100 * viewablePoints.size() / (float) (size);
    return viewableAmount; // percentag of points viewed

    // old implementation!

    // traverse through points of the point cloud
    // for a given point we scan all the same points
    // for each pair of points, we check if they have the same slope or comparable slopes
    // if they are similar we discount this because we have seen this point before
    // by this way we count all the points, without duplicates
    // by doing numberInLine <=1 we make sure we count only unique points and not duplicates
    // BOOST_FOREACH (const pcl::PointXYZ& pt, msg->points) {
    //     int numberInLine = 0;
    //     BOOST_FOREACH (const pcl::PointXYZ& pt2, msg->points) {
    //         bool onTheLine = onLine(x, y, z, pt.x, pt.y, pt.z, pt2.x, pt2.y, pt2.z);
    //         if (onTheLine) {
    //             numberInLine++;
    //         }
    //     }
    //     // printf("inView: %d\n", inView);
    //     if (numberInLine <= 1) {
    //         count++;
    //     }
    //     size++;
    // }

    // // printf("Count: %d\n", count);
    // // printf("Size: %d\n", size);

    // //printf("Percent of points viewed from pose: %f\n", 100 * count/(float)size);

    // // finally return a ratio of the points seen to the total number of points
    // // in the pcl
    // return (100 * count / (float) (size));
}

// void callback(const PointCloud::ConstPtr& msg)
// {
//     // printf("Percent of points viewed: %f\n", findPoints(msg));
// }

// int main(int argc, char** argv)
// {
//     ros::init(argc, argv, "generate_views");
//     ros::NodeHandle nh;
//     ros::Subscriber sub = nh.subscribe<PointCloud>("cloud", 1, callback);
//     ros::spin();
// }<commit_msg>findpoints: visualizing filtered cloud impl<commit_after>#include <ros/ros.h>
#include <pcl_ros/point_cloud.h>
#include <pcl/point_types.h>
#include <boost/foreach.hpp>
#include <math.h>
#include <geometry_msgs/Pose.h>
#include <set>
#include <map>

// consists of redundancy, remove later
// copied from rvizView to work with PointCloud2 object
#include <ros/ros.h>
#include <pcl/io/io.h>
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>
#include <pcl_ros/publisher.h>
#include <pcl_conversions/pcl_conversions.h>
#include <ros/publisher.h>
#include <string>
#include <pcl_ros/point_cloud.h>

typedef pcl::PointCloud<pcl::PointXYZ> PointCloud;

// represnts a point with x,y,z coordinates
struct Point {

    float x;
    float y;
    float z;
};

class PMDCloudPublisher
{
    // protected:
    //     std::string tf_frame;
    //     ros::NodeHandle nh;
    //     ros::NodeHandle private_nh;

    // public:
    //     pcl::PointCloud<pcl::PointXYZ>::Ptr cloud;
    //     std::string file_name, cloud_topic;
    //     pcl_ros::Publisher<sensor_msgs::PointCloud2> pub;

    //     PMDCloudPublisher()
    //         : tf_frame("/map"),
    //         private_nh("~")
    // {
    //     cloud_topic = "cloud";
    //     pub.advertise(nh, cloud_topic.c_str(), 1); // published here
    //     private_nh.param("frame_id", tf_frame, std::string("/map"));
    //     ROS_INFO_STREAM("Publishing data on topic \"" << nh.resolveName(cloud_topic) << "\" with frame_id \"" << tf_frame << "\"");
    // }

    //     bool spin ()
    //     {
    //         int nr_points = cloud->width * cloud->height;
    //         std::string fields_list = pcl::getFieldsList(cloud);
    //         ros::Rate r(40);

    //         while(nh.ok ())
    //         {
    //             ROS_DEBUG_STREAM_ONCE("Publishing data with " << nr_points
    //                     << " points " << fields_list
    //                     << " on topic \"" << nh.resolveName(cloud_topic)
    //                     << "\" in frame \"" << cloud.header.frame_id << "\"");
    //             // cloud.header.stamp = ros::Time::now();
    //             pub.publish(cloud);

    //             r.sleep();
    //         }
    //         return (true);
    //     }
};

void publishData(pcl::PointCloud<pcl::PointXYZ>::Ptr filteredCloud, std::map<float, geometry_msgs::Pose> viewablePoints){

    // //ros::init (1, temp, "cloud_publisher");
    // ros::NodeHandle nh;

    // PMDCloudPublisher c;
    // c.file_name = "spray_bottle.pcd";
    // c.cloud = filteredCloud;
    // nh.getParam(filteredCloud, c.cloud);

    // if (c.start () == -1)
    // {
    //     ROS_ERROR_STREAM("Could not load file \"" << c.file_name  <<"\". Exiting...");
    // }
    // ROS_INFO_STREAM("Loaded a point cloud with " << c.cloud.width * c.cloud.height
    //         << " points (total size is " << c.cloud.data.size() << ") and the following channels: " << pcl::getFieldsList (c.cloud));
    // c.spin();
}

// calculating slope of line formed by two points in 3d space
float calculate_slope(float pt_x, float pt_y, float pt_z, float pt2_x, float pt2_y, float pt2_z)
{
    float rise = pt2_z - pt_z;

    float square = pow((pt2_x - pt_x), 2) + pow((pt2_y - pt_y), 2);
    float run = sqrt(square);
    return rise/run;
}

// bool onLine(float view_x, float view_y, float view_z, float pt_x, float pt_y, float pt_z, float check_pt_x, float check_pt_y, float check_pt_z)
// {
//     // Calculate the slope from the view to the check_pt
//     float slope_pt_to_view = calculate_slope(view_x, view_y, view_z, check_pt_x, check_pt_y, check_pt_z);

//     // printf("Slope from view to check_pt: %f\n", slope_pt_to_view);

//     // Calculate slope from the check_pt to the pt
//     float slope_check_pt_to_pt = calculate_slope(view_x, view_y, view_z, pt_x, pt_y, pt_z);

//     // printf("Slope from view to pt: %f\n", slope_check_pt_to_pt);
//     // printf("Are they equivalent?: %d\n", temp);

//     float delta = 0.0000000045f;

//     float diff = fabs(slope_pt_to_view - slope_check_pt_to_pt);

//     bool temp = (diff < delta);
//     // printf("Difference: %f\n", diff);
//     // printf("Boolean: %d\n", temp);

//     //printf("Difference: %f\n", diff);
//     // If they are equal return true
//     return temp;
// }

// calculating distance between two points in  3d space
float distance(float x1, float y1, float z1, float x2, float y2, float z2){

    return sqrt(pow(x1 - x2, 2) + pow(y1 - y2, 2) + pow(z1 - z2, 2));
}

// method to find viewable points from a given view.
// arg1: Passed in a pose that represents a point in space
// arg2: the point cloud object of the pcd file

// PENDING: consider orientation (various angles for a given point) when viewing the object
void findPoints(const geometry_msgs::Pose createdPoint, const PointCloud::ConstPtr& msg)
{

    // printing the current view point
    printf("Coordinates: %f, %f, %f\n", createdPoint.position.x, createdPoint.position.y, createdPoint.position.z);

    // x,y,z represents the cooridnates of the view
    float x = createdPoint.position.x;
    float y = createdPoint.position.y;
    float z = createdPoint.position.z;

    // total number of points in the point cloud
    int size = 0;

    // idea is that for a given line from the view point, slope is the same
    // we want to count for a single point and exclude all the other points on that line
    // by that way we count for a single point and not count points behind the counted
    // point
    // if slope is already contained, then check which point is closer
    // to the view point
    // map for: slope -> point
    std::map<float, geometry_msgs::Pose> viewablePoints;
    std::map<float, geometry_msgs::Pose>::iterator it;
    BOOST_FOREACH (const pcl::PointXYZ& pt, msg->points) {

        float slope_pt_to_view = round(calculate_slope(x, y, z, pt.x, pt.y, pt.z) * 100000.0) / 100000.0 ;
        it = viewablePoints.find(slope_pt_to_view);

        // if slope is already present
        if(it != viewablePoints.end()){
            // if the slop is already taken into account
            // then we must see the point it corresponds to is the closest to the view point
            // if this new point is closer then must updates the map accordingly
            geometry_msgs::Pose existingPoint = it->second; // get the point
            float oldDistance = distance(x, y, z, existingPoint.position.x, existingPoint.position.y, existingPoint.position.z);
            float newDistance = distance(x, y, z, pt.x, pt.y, pt.z);
            if(newDistance < oldDistance) {
            	geometry_msgs::Pose newPose;
    			newPose.position.x = pt.x;
    			newPose.position.y = pt.y;
    			newPose.position.z = pt.z;
                viewablePoints.insert(std::pair<float, geometry_msgs::Pose> (slope_pt_to_view, newPose));
                //printf("Old point: %f, %f, %f with distance of %f\n", existingPoint.x, existingPoint.y, existingPoint.z, oldDistance);
                //printf("New point: %f, %f, %f with distance of %f\n", newPoint.x, newPoint.y, newPoint.z, newDistance);
            }

        } else {
            // first time looking at this point
            // just add it
            geometry_msgs::Pose newPose;
            newPose.position.x = pt.x;
            newPose.position.y = pt.y;
            newPose.position.z = pt.z;
            viewablePoints.insert(std::pair<float, geometry_msgs::Pose> (slope_pt_to_view, newPose));
        }
        size++; // totalNum points

    }

    // displaying contents of the map
    // multipying by 10000 because %f truncates values, so it appears as if duplictes exist
    // for(it = viewablePoints.begin(); it != viewablePoints.end(); it++){
    //     printf("key: %f, Value: %f, %f, %f\n", it->first * 10000, it->second.x, it->second.y, it->second.z);
    // }

    // at this point we have filtered points based on slope,distance and angle
    // these points need to be used to create a pointcloud2 object
    // once this is created, we will publish this to rviz and view it accoringly
    // references to publishing to rviz check rvizView and generateViews.cpp

    // in progress
    // refer: http://wiki.ros.org/pcl_ros
    // refer: http://pointclouds.org/documentation/tutorials/passthrough.php

    // publishing data set
    ros::NodeHandle nh;
    ros::Publisher pub = nh.advertise<PointCloud> ("fileredCloud", 1);

    pcl::PointCloud<pcl::PointXYZ>::Ptr filteredCloud (new pcl::PointCloud<pcl::PointXYZ>);

    filteredCloud->width = viewablePoints.size(); // need to verify
    filteredCloud->height = 1;
    filteredCloud->points.resize(filteredCloud->width * filteredCloud->height);
    filteredCloud->header.frame_id = "/map";
    int filterIndex = 0;

    // loading a new pointcloud object from the points that we collected
    for(it = viewablePoints.begin(); it != viewablePoints.end(); it++, filterIndex++){

    	// ideally no segfaults because filterdCloud size
    	// is viewable points * 1 == viewablePoints.size();
    	filteredCloud->points[filterIndex].x = it->second.position.x;
    	filteredCloud->points[filterIndex].y = it->second.position.y;
    	filteredCloud->points[filterIndex].z = it->second.position.z;

    }

    // publishing to rviz topic
    // currently infinite
    ros::Rate loop_rate(4);
    while (nh.ok()) {
        filteredCloud->header.stamp = ros::Time::now().toNSec();
        pub.publish (filteredCloud);

        printf("view coordinates: %f, %f, %f - viewable: %f\n", x,y,z, 100 * viewablePoints.size() / (float) (size));
        ros::spinOnce ();
        loop_rate.sleep ();
    }

    // for modularity, break into separate methods
    // publishData(filteredCloud, viewablePoints);

    //float viewableAmount =
    //return viewableAmount; // percentag of points viewed

    // old implementation!

    // traverse through points of the point cloud
    // for a given point we scan all the same points
    // for each pair of points, we check if they have the same slope or comparable slopes
    // if they are similar we discount this because we have seen this point before
    // by this way we count all the points, without duplicates
    // by doing numberInLine <=1 we make sure we count only unique points and not duplicates
    // BOOST_FOREACH (const pcl::PointXYZ& pt, msg->points) {
    //     int numberInLine = 0;
    //     BOOST_FOREACH (const pcl::PointXYZ& pt2, msg->points) {
    //         bool onTheLine = onLine(x, y, z, pt.x, pt.y, pt.z, pt2.x, pt2.y, pt2.z);
    //         if (onTheLine) {
    //             numberInLine++;
    //         }
    //     }
    //     // printf("inView: %d\n", inView);
    //     if (numberInLine <= 1) {
    //         count++;
    //     }
    //     size++;
    // }

    // // printf("Count: %d\n", count);
    // // printf("Size: %d\n", size);

    // //printf("Percent of points viewed from pose: %f\n", 100 * count/(float)size);

    // // finally return a ratio of the points seen to the total number of points
    // // in the pcl
    // return (100 * count / (float) (size));
}

// void callback(const PointCloud::ConstPtr& msg)
// {
//     // printf("Percent of points viewed: %f\n", findPoints(msg));
// }

// int main(int argc, char** argv)
// {
//     ros::init(argc, argv, "generate_views");
//     ros::NodeHandle nh;
//     ros::Subscriber sub = nh.subscribe<PointCloud>("cloud", 1, callback);
//     ros::spin();
// }<|endoftext|>


<commit_before>#ifndef _DCM_DCM_SOCKET_SESSION_HPP_
#define _DCM_DCM_SOCKET_SESSION_HPP_

#include <specforge/interprocess/streamsocket/receiver_session.hpp>

namespace dcm {
    namespace streamsocket {
        template <typename socket_type, typename buffer_type = interproc::buffer>
        class receiver_session : public interproc::streamsocket::receiver_session<socket_type, buffer_type> {
            bool is_header_;
            bool is_size_;
            interproc::buffer message_;
        public:
            explicit receiver_session(asio::io_service &io_service):
                    interproc::streamsocket::receiver_session<socket_type>(io_service){
                this->reader_->on_success = [this](interproc::buffer &&_buf){
                    message_.append(_buf);
                    if (is_size_) {
                        interproc::block_size_t block_size;
                        interproc::ibufstream bs(_buf);
                        interproc::read_size(bs, block_size);
                        is_size_ = !is_size_;
                        this->reader_->read(block_size);
                    } else {
                        if (!is_header_) {
                            if (this->on_message) {
                                this->on_message(std::move(message_));
                                message_.clear();
                            }
                        }
                        is_header_ = !is_header_;
                        is_size_ = !is_size_;
                        this->reader_->read(interproc::BLOCK_SIZE_SIZE);
                    }
                };
                this->reader_->on_fail = [this](const asio::error_code &_ec) {
                    if (on_error) on_error(_ec);
                };
            }

            virtual void start() override {
                is_size_ = true;
                is_header_ = true;
                this->reader_->read(interproc::BLOCK_SIZE_SIZE);
            }

            std::function<void(std::shared_ptr<receiver_session<socket_type, buffer_type>> _session)> on_connect;
            std::function<void(std::shared_ptr<receiver_session<socket_type, buffer_type>> _session)> on_error;
        };
    }
}
#endif //_DCM_DCM_SOCKET_SESSION_HPP_
<commit_msg>* comment on_error<commit_after>#ifndef _DCM_DCM_SOCKET_SESSION_HPP_
#define _DCM_DCM_SOCKET_SESSION_HPP_

#include <specforge/interprocess/streamsocket/receiver_session.hpp>

namespace dcm {
    namespace streamsocket {
        template <typename socket_type, typename buffer_type = interproc::buffer>
        class receiver_session : public interproc::streamsocket::receiver_session<socket_type, buffer_type> {
            bool is_header_;
            bool is_size_;
            interproc::buffer message_;
        public:
            explicit receiver_session(asio::io_service &io_service):
                    interproc::streamsocket::receiver_session<socket_type>(io_service){
                this->reader_->on_success = [this](interproc::buffer &&_buf){
                    message_.append(_buf);
                    if (is_size_) {
                        interproc::block_size_t block_size;
                        interproc::ibufstream bs(_buf);
                        interproc::read_size(bs, block_size);
                        is_size_ = !is_size_;
                        this->reader_->read(block_size);
                    } else {
                        if (!is_header_) {
                            if (this->on_message) {
                                this->on_message(std::move(message_));
                                message_.clear();
                            }
                        }
                        is_header_ = !is_header_;
                        is_size_ = !is_size_;
                        this->reader_->read(interproc::BLOCK_SIZE_SIZE);
                    }
                };
//                this->reader_->on_fail = [this](const asio::error_code &_ec) {
//                    if (on_error) on_error(_ec);
//                };
            }

            virtual void start() override {
                is_size_ = true;
                is_header_ = true;
                this->reader_->read(interproc::BLOCK_SIZE_SIZE);
            }

            std::function<void(std::shared_ptr<receiver_session<socket_type, buffer_type>> _session)> on_connect;
            std::function<void(std::shared_ptr<receiver_session<socket_type, buffer_type>> _session)> on_error;
        };
    }
}
#endif //_DCM_DCM_SOCKET_SESSION_HPP_
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) 2001 - 2006, Disney Enterprises, Inc.  All rights reserved
//
// All use of this software is subject to the terms of the Panda 3d
// Software license.  You should have received a copy of this license
// along with this source code; you will also find a current copy of
// the license at http://etc.cmu.edu/panda3d/docs/license/ .
//
// To contact the maintainers of this program write to
// panda3d-general@lists.sourceforge.net .
//
////////////////////////////////////////////////////////////////////
#include <Carbon/Carbon.h>

#include "config_osxdisplay.h"
#include "osxGraphicsBuffer.h"
#include "osxGraphicsPipe.h"
#include "osxGraphicsStateGuardian.h"
#include "osxGraphicsWindow.h"

#include "graphicsPipeSelection.h"
#include "dconfig.h"
#include "pandaSystem.h"

Configure(config_osxdisplay);

NotifyCategoryDef( osxdisplay , "display");

ConfigureFn(config_osxdisplay) {
  init_libosxdisplay();
}

ConfigVariableBool show_resize_box
("show-resize-box", true,
 PRC_DESC("When this variable is true, then resizable OSX Panda windows will "
          "be rendered with a resize control in the lower-right corner.  "
          "This is specially handled by Panda, since otherwise the 3-d "
          "window would completely hide any resize control drawn by the "
          "OS.  Set this variable false to allow this control to be hidden."));

ConfigVariableBool osx_disable_event_loop
("osx-disable-event-loop", false,
 PRC_DESC("Set this true to disable the window event loop for the Panda "
          "windows.  This makes sense only in a publish environment where "
          "the window event loop is already handled by another part of the "
          "app."));

ConfigVariableInt osx_mouse_wheel_scale
("osx-mouse-wheel-scale", 5,
 PRC_DESC("Specify the number of units to spin the Mac mouse wheel to "
          "represent a single wheel_up or wheel_down message."));

////////////////////////////////////////////////////////////////////
//     Function: init_libosxdisplay
//  Description: Initializes the library.  This must be called at
//               least once before any of the functions or classes in
//               this library can be used.  Normally it will be
//               called by the static initializers and need not be
//               called explicitly, but special cases exist.
////////////////////////////////////////////////////////////////////
void
init_libosxdisplay() {
  static bool initialized = false;
  if (initialized) {
    return;
  }
  initialized = true;

  osxGraphicsStateGuardian::init_type();
  osxGraphicsPipe::init_type();
  osxGraphicsWindow::init_type();
  osxGraphicsStateGuardian::init_type();

  GraphicsPipeSelection *selection = GraphicsPipeSelection::get_global_ptr();
  selection->add_pipe_type(osxGraphicsPipe::get_class_type(), osxGraphicsPipe::pipe_constructor);

  PandaSystem *ps = PandaSystem::get_global_ptr();
  ps->set_system_tag("OpenGL", "window_system", "OSX");
}
<commit_msg>make mouse scroll wheel instant<commit_after>////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) 2001 - 2006, Disney Enterprises, Inc.  All rights reserved
//
// All use of this software is subject to the terms of the Panda 3d
// Software license.  You should have received a copy of this license
// along with this source code; you will also find a current copy of
// the license at http://etc.cmu.edu/panda3d/docs/license/ .
//
// To contact the maintainers of this program write to
// panda3d-general@lists.sourceforge.net .
//
////////////////////////////////////////////////////////////////////
#include <Carbon/Carbon.h>

#include "config_osxdisplay.h"
#include "osxGraphicsBuffer.h"
#include "osxGraphicsPipe.h"
#include "osxGraphicsStateGuardian.h"
#include "osxGraphicsWindow.h"

#include "graphicsPipeSelection.h"
#include "dconfig.h"
#include "pandaSystem.h"

Configure(config_osxdisplay);

NotifyCategoryDef( osxdisplay , "display");

ConfigureFn(config_osxdisplay) {
  init_libosxdisplay();
}

ConfigVariableBool show_resize_box
("show-resize-box", true,
 PRC_DESC("When this variable is true, then resizable OSX Panda windows will "
          "be rendered with a resize control in the lower-right corner.  "
          "This is specially handled by Panda, since otherwise the 3-d "
          "window would completely hide any resize control drawn by the "
          "OS.  Set this variable false to allow this control to be hidden."));

ConfigVariableBool osx_disable_event_loop
("osx-disable-event-loop", false,
 PRC_DESC("Set this true to disable the window event loop for the Panda "
          "windows.  This makes sense only in a publish environment where "
          "the window event loop is already handled by another part of the "
          "app."));

ConfigVariableInt osx_mouse_wheel_scale
("osx-mouse-wheel-scale", 1,
 PRC_DESC("Specify the number of units to spin the Mac mouse wheel to "
          "represent a single wheel_up or wheel_down message."));

////////////////////////////////////////////////////////////////////
//     Function: init_libosxdisplay
//  Description: Initializes the library.  This must be called at
//               least once before any of the functions or classes in
//               this library can be used.  Normally it will be
//               called by the static initializers and need not be
//               called explicitly, but special cases exist.
////////////////////////////////////////////////////////////////////
void
init_libosxdisplay() {
  static bool initialized = false;
  if (initialized) {
    return;
  }
  initialized = true;

  osxGraphicsStateGuardian::init_type();
  osxGraphicsPipe::init_type();
  osxGraphicsWindow::init_type();
  osxGraphicsStateGuardian::init_type();

  GraphicsPipeSelection *selection = GraphicsPipeSelection::get_global_ptr();
  selection->add_pipe_type(osxGraphicsPipe::get_class_type(), osxGraphicsPipe::pipe_constructor);

  PandaSystem *ps = PandaSystem::get_global_ptr();
  ps->set_system_tag("OpenGL", "window_system", "OSX");
}
<|endoftext|>


<commit_before>#include "retsetmidiportroute.h"

RetSetMidiPortRoute::RetSetMidiPortRoute(Device *device)
		: SysExMessage(SysExMessage::RET_SET_MIDI_PORT_INFO, SysExMessage::QUERY,
									 device) {}

void RetSetMidiPortRoute::parseAnswerData() {
	portId = MIDI::byteJoin(data, 1, 2);
	portRoutings = new BYTE_VECTOR(data->begin() + 2, data->end() - 2);
}
<commit_msg>extract of routng data corrected<commit_after>#include "retsetmidiportroute.h"

RetSetMidiPortRoute::RetSetMidiPortRoute(Device *device)
		: SysExMessage(SysExMessage::RET_SET_MIDI_PORT_INFO, SysExMessage::QUERY,
									 device) {}

void RetSetMidiPortRoute::parseAnswerData() {
	portId = MIDI::byteJoin(data, 1, 2);
	portRoutings = new BYTE_VECTOR(data->begin() + 3, data->end());
}
<|endoftext|>


<commit_before><commit_msg>added comment<commit_after>/*
		Currently, there is not any test code for parametrics.
		Feel free to create some.
*/<|endoftext|>


<commit_before>// Filename: rocketRenderInterface.cxx
// Created by:  rdb (04Nov11)
//
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) Carnegie Mellon University.  All rights reserved.
//
// All use of this software is subject to the terms of the revised BSD
// license.  You should have received a copy of this license along
// with this source code in a file named "LICENSE."
//
////////////////////////////////////////////////////////////////////

#include "rocketRenderInterface.h"
#include "cullableObject.h"
#include "cullHandler.h"
#include "geomVertexData.h"
#include "geomVertexArrayData.h"
#include "internalName.h"
#include "geomVertexWriter.h"
#include "geomTriangles.h"
#include "colorBlendAttrib.h"
#include "cullBinAttrib.h"
#include "depthTestAttrib.h"
#include "depthWriteAttrib.h"
#include "scissorAttrib.h"
#include "texture.h"
#include "textureAttrib.h"
#include "texturePool.h"

////////////////////////////////////////////////////////////////////
//     Function: RocketRenderInterface::render
//       Access: Public
//  Description: Called by RocketNode in cull_callback.  Invokes
//               context->Render() and culls the result.
////////////////////////////////////////////////////////////////////
void RocketRenderInterface::
render(Rocket::Core::Context* context, CullTraverser *trav) {
  nassertv(context != NULL);
  MutexHolder holder(_lock);

  _trav = trav;
  _net_transform = trav->get_world_transform();
  _net_state = RenderState::make(
    CullBinAttrib::make("unsorted", 0),
    DepthTestAttrib::make(RenderAttrib::M_none),
    DepthWriteAttrib::make(DepthWriteAttrib::M_off),
    ColorBlendAttrib::make(ColorBlendAttrib::M_add,
      ColorBlendAttrib::O_incoming_alpha,
      ColorBlendAttrib::O_one_minus_incoming_alpha
    )
  );
  _dimensions = context->GetDimensions();

  context->Render();

  _trav = NULL;
  _net_transform = NULL;
  _net_state = NULL;
}

////////////////////////////////////////////////////////////////////
//     Function: RocketRenderInterface::make_geom
//       Access: Protected
//  Description: Called internally to make a Geom from Rocket data.
////////////////////////////////////////////////////////////////////
PT(Geom) RocketRenderInterface::
make_geom(Rocket::Core::Vertex* vertices, int num_vertices, int* indices, int num_indices, GeomEnums::UsageHint uh) {
  PT(GeomVertexData) vdata = new GeomVertexData("", GeomVertexFormat::get_v3c4t2(), uh);
  vdata->unclean_set_num_rows(num_vertices);
  {
    GeomVertexWriter vwriter(vdata, InternalName::get_vertex());
    GeomVertexWriter cwriter(vdata, InternalName::get_color());
    GeomVertexWriter twriter(vdata, InternalName::get_texcoord());

    // Write the vertex information.
    for (int i = 0; i < num_vertices; ++i) {
      const Rocket::Core::Vertex &vertex = vertices[i];

      vwriter.add_data3f(LVector3f::right() * vertex.position.x + LVector3f::up() * vertex.position.y);
      cwriter.add_data4i(vertex.colour.red, vertex.colour.green,
                         vertex.colour.blue, vertex.colour.alpha);
      twriter.add_data2f(vertex.tex_coord.x, 1.0f - vertex.tex_coord.y);
    }
  }

  // Create a primitive and write the indices.
  PT(GeomTriangles) triangles = new GeomTriangles(uh);
  {
    PT(GeomVertexArrayData) idata = triangles->modify_vertices();
    idata->unclean_set_num_rows(num_indices);
    GeomVertexWriter iwriter(idata, 0);

    for (int i = 0; i < num_indices; ++i) {
      iwriter.add_data1i(indices[i]);
    }
  }

  PT(Geom) geom = new Geom(vdata);
  geom->add_primitive(triangles);
  return geom;
}

////////////////////////////////////////////////////////////////////
//     Function: RocketRenderInterface::render_geom
//       Access: Protected
//  Description: Only call this during render().  Culls a geom.
////////////////////////////////////////////////////////////////////
void RocketRenderInterface::
render_geom(const Geom* geom, const RenderState* state, const Rocket::Core::Vector2f& translation) {
  LVector3 offset = LVector3::right() * translation.x + LVector3::up() * translation.y;

  if (_enable_scissor) {
    state = state->add_attrib(ScissorAttrib::make(_scissor));
    rocket_cat.spam()
      << "Rendering geom " << geom << " with state "
      << *state << ", translation (" << offset << "), "
      << "scissor region (" << _scissor << ")\n";
  } else {
    rocket_cat.spam()
      << "Rendering geom " << geom << " with state "
      << *state << ", translation (" << offset << ")\n";
  }

  CPT(TransformState) net_transform, modelview_transform;
  net_transform = _net_transform->compose(TransformState::make_pos(offset));
  modelview_transform = _trav->get_world_transform()->compose(net_transform);

  CullableObject *object =
    new CullableObject(geom, _net_state->compose(state),
                       net_transform, modelview_transform,
                       _trav->get_gsg());
  _trav->get_cull_handler()->record_object(object, _trav);
}

////////////////////////////////////////////////////////////////////
//     Function: RocketRenderInterface::RenderGeometry
//       Access: Protected
//  Description: Called by Rocket when it wants to render geometry
//               that the application does not wish to optimize.
////////////////////////////////////////////////////////////////////
void RocketRenderInterface::
RenderGeometry(Rocket::Core::Vertex* vertices, int num_vertices, int* indices, int num_indices, Rocket::Core::TextureHandle texture, const Rocket::Core::Vector2f& translation) {
  PT(Geom) geom = make_geom(vertices, num_vertices, indices, num_indices, GeomEnums::UH_stream);

  CPT(RenderState) state;
  if ((Texture*) texture != (Texture*) NULL) {
    state = RenderState::make(TextureAttrib::make((Texture*) texture));
  } else {
    state = RenderState::make_empty();
  }

  render_geom(geom, state, translation);
}

////////////////////////////////////////////////////////////////////
//     Function: RocketRenderInterface::CompileGeometry
//       Access: Protected
//  Description: Called by Rocket when it wants to compile geometry
//               it believes will be static for the forseeable future.
////////////////////////////////////////////////////////////////////
Rocket::Core::CompiledGeometryHandle RocketRenderInterface::
CompileGeometry(Rocket::Core::Vertex* vertices, int num_vertices, int* indices, int num_indices, Rocket::Core::TextureHandle texture) {

  CompiledGeometry *c = new CompiledGeometry;
  c->_geom = make_geom(vertices, num_vertices, indices, num_indices, GeomEnums::UH_static);

  if ((Texture*) texture != (Texture*) NULL) {
    PT(TextureStage) stage = new TextureStage("");
    stage->set_mode(TextureStage::M_replace);

    CPT(TextureAttrib) attr = DCAST(TextureAttrib, TextureAttrib::make());
    attr = DCAST(TextureAttrib, attr->add_on_stage(stage, (Texture*) texture));

    c->_state = RenderState::make(attr);

    rocket_cat.debug()
      << "Compiled geom " << c->_geom << " with texture '"
      << ((Texture*) texture)->get_name() << "'\n";
  } else {
    c->_state = RenderState::make_empty();

    rocket_cat.debug()
      << "Compiled geom " << c->_geom << " without texture\n";
  }

  return (Rocket::Core::CompiledGeometryHandle) c;
}

////////////////////////////////////////////////////////////////////
//     Function: RocketRenderInterface::RenderCompiledGeometry
//       Access: Protected
//  Description: Called by Rocket when it wants to render
//               application-compiled geometry.
////////////////////////////////////////////////////////////////////
void RocketRenderInterface::
RenderCompiledGeometry(Rocket::Core::CompiledGeometryHandle geometry, const Rocket::Core::Vector2f& translation) {

  CompiledGeometry *c = (CompiledGeometry*) geometry;
  render_geom(c->_geom, c->_state, translation);
}

////////////////////////////////////////////////////////////////////
//     Function: RocketRenderInterface::ReleaseCompiledGeometry
//       Access: Protected
//  Description: Called by Rocket when it wants to release
//               application-compiled geometry.
////////////////////////////////////////////////////////////////////
void RocketRenderInterface::
ReleaseCompiledGeometry(Rocket::Core::CompiledGeometryHandle geometry) {
  delete (CompiledGeometry*) geometry;
}

////////////////////////////////////////////////////////////////////
//     Function: RocketRenderInterface::LoadTexture
//       Access: Protected
//  Description: Called by Rocket when a texture is required by the
//               library.
////////////////////////////////////////////////////////////////////
bool RocketRenderInterface::
LoadTexture(Rocket::Core::TextureHandle& texture_handle,
            Rocket::Core::Vector2i& texture_dimensions,
            const Rocket::Core::String& source) {

  PT(Texture) tex = TexturePool::load_texture(Filename::from_os_specific(source.CString()));
  if (tex == NULL) {
    texture_handle = 0;
    texture_dimensions.x = 0;
    texture_dimensions.y = 0;
    return false;
  }

  texture_dimensions.x = tex->get_x_size();
  texture_dimensions.y = tex->get_y_size();
  tex->ref();
  texture_handle = (Rocket::Core::TextureHandle) tex.p();

  return true;
}

////////////////////////////////////////////////////////////////////
//     Function: RocketRenderInterface::GenerateTexture
//       Access: Protected
//  Description: Called by Rocket when a texture is required to be
//               built from an internally-generated sequence of pixels.
////////////////////////////////////////////////////////////////////
bool RocketRenderInterface::
GenerateTexture(Rocket::Core::TextureHandle& texture_handle,
                const Rocket::Core::byte* source,
                const Rocket::Core::Vector2i& source_dimensions) {

  PT(Texture) tex = new Texture;
  tex->setup_2d_texture(source_dimensions.x, source_dimensions.y,
                        Texture::T_unsigned_byte, Texture::F_rgba);
  PTA_uchar image = tex->modify_ram_image();

  // Convert RGBA to BGRA
  size_t row_size = source_dimensions.x * 4;
  size_t y2 = image.size();
  for (size_t y = 0; y < image.size(); y += row_size) {
    y2 -= row_size;
    for (size_t i = 0; i < row_size; i += 4) {
      image[y2 + i + 0] = source[y + i + 2];
      image[y2 + i + 1] = source[y + i + 1];
      image[y2 + i + 2] = source[y + i];
      image[y2 + i + 3] = source[y + i + 3];
    }
  }

  tex->set_wrap_u(Texture::WM_clamp);
  tex->set_wrap_v(Texture::WM_clamp);

  tex->ref();
  texture_handle = (Rocket::Core::TextureHandle) tex.p();

  return true;
}

////////////////////////////////////////////////////////////////////
//     Function: RocketRenderInterface::ReleaseTexture
//       Access: Protected
//  Description: Called by Rocket when a loaded texture is no longer
//               required.
////////////////////////////////////////////////////////////////////
void RocketRenderInterface::
ReleaseTexture(Rocket::Core::TextureHandle texture_handle) {
  Texture* tex = (Texture*) texture_handle;
  if (tex != (Texture*) NULL) {
    tex->unref();
  }
}

////////////////////////////////////////////////////////////////////
//     Function: RocketRenderInterface::EnableScissorRegion
//       Access: Protected
//  Description: Called by Rocket when it wants to enable or disable
//               scissoring to clip content.
////////////////////////////////////////////////////////////////////
void RocketRenderInterface::
EnableScissorRegion(bool enable) {
  _enable_scissor = enable;
}

////////////////////////////////////////////////////////////////////
//     Function: RocketRenderInterface::SetScissorRegion
//       Access: Protected
//  Description: Called by Rocket when it wants to change the
//               scissor region.
////////////////////////////////////////////////////////////////////
void RocketRenderInterface::
SetScissorRegion(int x, int y, int width, int height) {
  _scissor[0] = x / (PN_stdfloat) _dimensions.x;
  _scissor[1] = (x + width) / (PN_stdfloat) _dimensions.x;
  _scissor[2] = 1.0f - ((y + height) / (PN_stdfloat) _dimensions.y);
  _scissor[3] = 1.0f - (y / (PN_stdfloat) _dimensions.y);
}
<commit_msg>fix font colour issue (all text was showing up white regardless of font colour)<commit_after>// Filename: rocketRenderInterface.cxx
// Created by:  rdb (04Nov11)
//
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) Carnegie Mellon University.  All rights reserved.
//
// All use of this software is subject to the terms of the revised BSD
// license.  You should have received a copy of this license along
// with this source code in a file named "LICENSE."
//
////////////////////////////////////////////////////////////////////

#include "rocketRenderInterface.h"
#include "cullableObject.h"
#include "cullHandler.h"
#include "geomVertexData.h"
#include "geomVertexArrayData.h"
#include "internalName.h"
#include "geomVertexWriter.h"
#include "geomTriangles.h"
#include "colorBlendAttrib.h"
#include "cullBinAttrib.h"
#include "depthTestAttrib.h"
#include "depthWriteAttrib.h"
#include "scissorAttrib.h"
#include "texture.h"
#include "textureAttrib.h"
#include "texturePool.h"

////////////////////////////////////////////////////////////////////
//     Function: RocketRenderInterface::render
//       Access: Public
//  Description: Called by RocketNode in cull_callback.  Invokes
//               context->Render() and culls the result.
////////////////////////////////////////////////////////////////////
void RocketRenderInterface::
render(Rocket::Core::Context* context, CullTraverser *trav) {
  nassertv(context != NULL);
  MutexHolder holder(_lock);

  _trav = trav;
  _net_transform = trav->get_world_transform();
  _net_state = RenderState::make(
    CullBinAttrib::make("unsorted", 0),
    DepthTestAttrib::make(RenderAttrib::M_none),
    DepthWriteAttrib::make(DepthWriteAttrib::M_off),
    ColorBlendAttrib::make(ColorBlendAttrib::M_add,
      ColorBlendAttrib::O_incoming_alpha,
      ColorBlendAttrib::O_one_minus_incoming_alpha
    )
  );
  _dimensions = context->GetDimensions();

  context->Render();

  _trav = NULL;
  _net_transform = NULL;
  _net_state = NULL;
}

////////////////////////////////////////////////////////////////////
//     Function: RocketRenderInterface::make_geom
//       Access: Protected
//  Description: Called internally to make a Geom from Rocket data.
////////////////////////////////////////////////////////////////////
PT(Geom) RocketRenderInterface::
make_geom(Rocket::Core::Vertex* vertices, int num_vertices, int* indices, int num_indices, GeomEnums::UsageHint uh) {
  PT(GeomVertexData) vdata = new GeomVertexData("", GeomVertexFormat::get_v3c4t2(), uh);
  vdata->unclean_set_num_rows(num_vertices);
  {
    GeomVertexWriter vwriter(vdata, InternalName::get_vertex());
    GeomVertexWriter cwriter(vdata, InternalName::get_color());
    GeomVertexWriter twriter(vdata, InternalName::get_texcoord());

    // Write the vertex information.
    for (int i = 0; i < num_vertices; ++i) {
      const Rocket::Core::Vertex &vertex = vertices[i];

      vwriter.add_data3f(LVector3f::right() * vertex.position.x + LVector3f::up() * vertex.position.y);
      cwriter.add_data4i(vertex.colour.red, vertex.colour.green,
                         vertex.colour.blue, vertex.colour.alpha);
      twriter.add_data2f(vertex.tex_coord.x, 1.0f - vertex.tex_coord.y);
    }
  }

  // Create a primitive and write the indices.
  PT(GeomTriangles) triangles = new GeomTriangles(uh);
  {
    PT(GeomVertexArrayData) idata = triangles->modify_vertices();
    idata->unclean_set_num_rows(num_indices);
    GeomVertexWriter iwriter(idata, 0);

    for (int i = 0; i < num_indices; ++i) {
      iwriter.add_data1i(indices[i]);
    }
  }

  PT(Geom) geom = new Geom(vdata);
  geom->add_primitive(triangles);
  return geom;
}

////////////////////////////////////////////////////////////////////
//     Function: RocketRenderInterface::render_geom
//       Access: Protected
//  Description: Only call this during render().  Culls a geom.
////////////////////////////////////////////////////////////////////
void RocketRenderInterface::
render_geom(const Geom* geom, const RenderState* state, const Rocket::Core::Vector2f& translation) {
  LVector3 offset = LVector3::right() * translation.x + LVector3::up() * translation.y;

  if (_enable_scissor) {
    state = state->add_attrib(ScissorAttrib::make(_scissor));
    rocket_cat.spam()
      << "Rendering geom " << geom << " with state "
      << *state << ", translation (" << offset << "), "
      << "scissor region (" << _scissor << ")\n";
  } else {
    rocket_cat.spam()
      << "Rendering geom " << geom << " with state "
      << *state << ", translation (" << offset << ")\n";
  }

  CPT(TransformState) net_transform, modelview_transform;
  net_transform = _net_transform->compose(TransformState::make_pos(offset));
  modelview_transform = _trav->get_world_transform()->compose(net_transform);

  CullableObject *object =
    new CullableObject(geom, _net_state->compose(state),
                       net_transform, modelview_transform,
                       _trav->get_gsg());
  _trav->get_cull_handler()->record_object(object, _trav);
}

////////////////////////////////////////////////////////////////////
//     Function: RocketRenderInterface::RenderGeometry
//       Access: Protected
//  Description: Called by Rocket when it wants to render geometry
//               that the application does not wish to optimize.
////////////////////////////////////////////////////////////////////
void RocketRenderInterface::
RenderGeometry(Rocket::Core::Vertex* vertices, int num_vertices, int* indices, int num_indices, Rocket::Core::TextureHandle texture, const Rocket::Core::Vector2f& translation) {
  PT(Geom) geom = make_geom(vertices, num_vertices, indices, num_indices, GeomEnums::UH_stream);

  CPT(RenderState) state;
  if ((Texture*) texture != (Texture*) NULL) {
    state = RenderState::make(TextureAttrib::make((Texture*) texture));
  } else {
    state = RenderState::make_empty();
  }

  render_geom(geom, state, translation);
}

////////////////////////////////////////////////////////////////////
//     Function: RocketRenderInterface::CompileGeometry
//       Access: Protected
//  Description: Called by Rocket when it wants to compile geometry
//               it believes will be static for the forseeable future.
////////////////////////////////////////////////////////////////////
Rocket::Core::CompiledGeometryHandle RocketRenderInterface::
CompileGeometry(Rocket::Core::Vertex* vertices, int num_vertices, int* indices, int num_indices, Rocket::Core::TextureHandle texture) {

  CompiledGeometry *c = new CompiledGeometry;
  c->_geom = make_geom(vertices, num_vertices, indices, num_indices, GeomEnums::UH_static);

  if ((Texture*) texture != (Texture*) NULL) {
    PT(TextureStage) stage = new TextureStage("");
    stage->set_mode(TextureStage::M_modulate);

    CPT(TextureAttrib) attr = DCAST(TextureAttrib, TextureAttrib::make());
    attr = DCAST(TextureAttrib, attr->add_on_stage(stage, (Texture*) texture));

    c->_state = RenderState::make(attr);

    rocket_cat.debug()
      << "Compiled geom " << c->_geom << " with texture '"
      << ((Texture*) texture)->get_name() << "'\n";
  } else {
    c->_state = RenderState::make_empty();

    rocket_cat.debug()
      << "Compiled geom " << c->_geom << " without texture\n";
  }

  return (Rocket::Core::CompiledGeometryHandle) c;
}

////////////////////////////////////////////////////////////////////
//     Function: RocketRenderInterface::RenderCompiledGeometry
//       Access: Protected
//  Description: Called by Rocket when it wants to render
//               application-compiled geometry.
////////////////////////////////////////////////////////////////////
void RocketRenderInterface::
RenderCompiledGeometry(Rocket::Core::CompiledGeometryHandle geometry, const Rocket::Core::Vector2f& translation) {

  CompiledGeometry *c = (CompiledGeometry*) geometry;
  render_geom(c->_geom, c->_state, translation);
}

////////////////////////////////////////////////////////////////////
//     Function: RocketRenderInterface::ReleaseCompiledGeometry
//       Access: Protected
//  Description: Called by Rocket when it wants to release
//               application-compiled geometry.
////////////////////////////////////////////////////////////////////
void RocketRenderInterface::
ReleaseCompiledGeometry(Rocket::Core::CompiledGeometryHandle geometry) {
  delete (CompiledGeometry*) geometry;
}

////////////////////////////////////////////////////////////////////
//     Function: RocketRenderInterface::LoadTexture
//       Access: Protected
//  Description: Called by Rocket when a texture is required by the
//               library.
////////////////////////////////////////////////////////////////////
bool RocketRenderInterface::
LoadTexture(Rocket::Core::TextureHandle& texture_handle,
            Rocket::Core::Vector2i& texture_dimensions,
            const Rocket::Core::String& source) {

  PT(Texture) tex = TexturePool::load_texture(Filename::from_os_specific(source.CString()));
  if (tex == NULL) {
    texture_handle = 0;
    texture_dimensions.x = 0;
    texture_dimensions.y = 0;
    return false;
  }

  texture_dimensions.x = tex->get_x_size();
  texture_dimensions.y = tex->get_y_size();
  tex->ref();
  texture_handle = (Rocket::Core::TextureHandle) tex.p();

  return true;
}

////////////////////////////////////////////////////////////////////
//     Function: RocketRenderInterface::GenerateTexture
//       Access: Protected
//  Description: Called by Rocket when a texture is required to be
//               built from an internally-generated sequence of pixels.
////////////////////////////////////////////////////////////////////
bool RocketRenderInterface::
GenerateTexture(Rocket::Core::TextureHandle& texture_handle,
                const Rocket::Core::byte* source,
                const Rocket::Core::Vector2i& source_dimensions) {

  PT(Texture) tex = new Texture;
  tex->setup_2d_texture(source_dimensions.x, source_dimensions.y,
                        Texture::T_unsigned_byte, Texture::F_rgba);
  PTA_uchar image = tex->modify_ram_image();

  // Convert RGBA to BGRA
  size_t row_size = source_dimensions.x * 4;
  size_t y2 = image.size();
  for (size_t y = 0; y < image.size(); y += row_size) {
    y2 -= row_size;
    for (size_t i = 0; i < row_size; i += 4) {
      image[y2 + i + 0] = source[y + i + 2];
      image[y2 + i + 1] = source[y + i + 1];
      image[y2 + i + 2] = source[y + i];
      image[y2 + i + 3] = source[y + i + 3];
    }
  }

  tex->set_wrap_u(Texture::WM_clamp);
  tex->set_wrap_v(Texture::WM_clamp);

  tex->ref();
  texture_handle = (Rocket::Core::TextureHandle) tex.p();

  return true;
}

////////////////////////////////////////////////////////////////////
//     Function: RocketRenderInterface::ReleaseTexture
//       Access: Protected
//  Description: Called by Rocket when a loaded texture is no longer
//               required.
////////////////////////////////////////////////////////////////////
void RocketRenderInterface::
ReleaseTexture(Rocket::Core::TextureHandle texture_handle) {
  Texture* tex = (Texture*) texture_handle;
  if (tex != (Texture*) NULL) {
    tex->unref();
  }
}

////////////////////////////////////////////////////////////////////
//     Function: RocketRenderInterface::EnableScissorRegion
//       Access: Protected
//  Description: Called by Rocket when it wants to enable or disable
//               scissoring to clip content.
////////////////////////////////////////////////////////////////////
void RocketRenderInterface::
EnableScissorRegion(bool enable) {
  _enable_scissor = enable;
}

////////////////////////////////////////////////////////////////////
//     Function: RocketRenderInterface::SetScissorRegion
//       Access: Protected
//  Description: Called by Rocket when it wants to change the
//               scissor region.
////////////////////////////////////////////////////////////////////
void RocketRenderInterface::
SetScissorRegion(int x, int y, int width, int height) {
  _scissor[0] = x / (PN_stdfloat) _dimensions.x;
  _scissor[1] = (x + width) / (PN_stdfloat) _dimensions.x;
  _scissor[2] = 1.0f - ((y + height) / (PN_stdfloat) _dimensions.y);
  _scissor[3] = 1.0f - (y / (PN_stdfloat) _dimensions.y);
}
<|endoftext|>


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

#include "xwalk/runtime/browser/runtime_url_request_context_getter.h"

#include <algorithm>
#include <string>
#include <utility>
#include <vector>

#include "base/command_line.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "base/threading/sequenced_worker_pool.h"
#include "base/threading/worker_pool.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/cookie_store_factory.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/dns/mapped_host_resolver.h"
#include "net/http/http_auth_handler_factory.h"
#include "net/http/http_cache.h"
#include "net/http/http_network_session.h"
#include "net/http/http_server_properties_impl.h"
#include "net/proxy/proxy_service.h"
#include "net/ssl/channel_id_service.h"
#include "net/ssl/default_channel_id_store.h"
#include "net/ssl/ssl_config_service_defaults.h"
#include "net/url_request/data_protocol_handler.h"
#include "net/url_request/file_protocol_handler.h"
#include "net/url_request/static_http_user_agent_settings.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_storage.h"
#include "net/url_request/url_request_intercepting_job_factory.h"
#include "net/url_request/url_request_interceptor.h"
#include "net/url_request/url_request_job_factory_impl.h"
#include "xwalk/application/common/constants.h"
#include "xwalk/runtime/browser/runtime_network_delegate.h"
#include "xwalk/runtime/common/xwalk_content_client.h"
#include "xwalk/runtime/common/xwalk_switches.h"

#if defined(OS_ANDROID)
#include "net/proxy/proxy_config_service_android.h"
#include "xwalk/runtime/browser/android/cookie_manager.h"
#include "xwalk/runtime/browser/android/net/android_protocol_handler.h"
#include "xwalk/runtime/browser/android/net/url_constants.h"
#include "xwalk/runtime/browser/android/net/xwalk_cookie_store_wrapper.h"
#include "xwalk/runtime/browser/android/net/xwalk_url_request_job_factory.h"
#include "xwalk/runtime/browser/android/xwalk_request_interceptor.h"
#endif

using content::BrowserThread;

namespace xwalk {

int GetDiskCacheSize() {
  base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();

  if (!command_line->HasSwitch(switches::kDiskCacheSize))
      return 0;

  std::string str_value = command_line->GetSwitchValueASCII(
      switches::kDiskCacheSize);

  int size = 0;
  if (!base::StringToInt(str_value, &size)) {
      LOG(ERROR) << "The value " << str_value
                 << " can not be converted to integer, ignoring!";
  }

  return size;
}

RuntimeURLRequestContextGetter::RuntimeURLRequestContextGetter(
    bool ignore_certificate_errors,
    const base::FilePath& base_path,
    base::MessageLoop* io_loop,
    base::MessageLoop* file_loop,
    content::ProtocolHandlerMap* protocol_handlers,
    content::URLRequestInterceptorScopedVector request_interceptors)
    : ignore_certificate_errors_(ignore_certificate_errors),
      base_path_(base_path),
      io_loop_(io_loop),
      file_loop_(file_loop),
      request_interceptors_(std::move(request_interceptors)) {
  // Must first be created on the UI thread.
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  std::swap(protocol_handlers_, *protocol_handlers);

  // We must create the proxy config service on the UI loop on Linux because it
  // must synchronously run on the glib message loop. This will be passed to
  // the URLRequestContextStorage on the IO thread in GetURLRequestContext().
#if defined(OS_ANDROID)
  proxy_config_service_ = net::ProxyService::CreateSystemProxyConfigService(
      io_loop_->task_runner(), file_loop_->task_runner());
  net::ProxyConfigServiceAndroid* android_config_service =
      static_cast<net::ProxyConfigServiceAndroid*>(proxy_config_service_.get());
  android_config_service->set_exclude_pac_url(true);
#else
  proxy_config_service_ = net::ProxyService::CreateSystemProxyConfigService(
      io_loop_->task_runner(), file_loop_->task_runner());
#endif
}

RuntimeURLRequestContextGetter::~RuntimeURLRequestContextGetter() {
}

net::URLRequestContext* RuntimeURLRequestContextGetter::GetURLRequestContext() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));

  if (!url_request_context_) {
    url_request_context_.reset(new net::URLRequestContext());
    network_delegate_.reset(new RuntimeNetworkDelegate);
    url_request_context_->set_network_delegate(network_delegate_.get());
    storage_.reset(
        new net::URLRequestContextStorage(url_request_context_.get()));
#if defined(OS_ANDROID)
    storage_->set_cookie_store(new XWalkCookieStoreWrapper());
#else
    content::CookieStoreConfig cookie_config(base_path_.Append(
        application::kCookieDatabaseFilename),
        content::CookieStoreConfig::PERSISTANT_SESSION_COOKIES,
        NULL, NULL);

    cookie_config.cookieable_schemes.push_back(application::kApplicationScheme);
    cookie_config.cookieable_schemes.push_back(content::kChromeDevToolsScheme);

    net::CookieStore* cookie_store = content::CreateCookieStore(cookie_config);
    storage_->set_cookie_store(cookie_store);
#endif
    storage_->set_channel_id_service(make_scoped_ptr(new net::ChannelIDService(
        new net::DefaultChannelIDStore(NULL),
        base::WorkerPool::GetTaskRunner(true))));
    storage_->set_http_user_agent_settings(make_scoped_ptr(
        new net::StaticHttpUserAgentSettings("en-us,en",
                                             xwalk::GetUserAgent())));

    scoped_ptr<net::HostResolver> host_resolver(
        net::HostResolver::CreateDefaultResolver(NULL));

    storage_->set_cert_verifier(net::CertVerifier::CreateDefault());
    storage_->set_transport_security_state(
        make_scoped_ptr(new net::TransportSecurityState));
#if defined(OS_ANDROID)
    // Android provides a local HTTP proxy that handles all the proxying.
    // Create the proxy without a resolver since we rely
    // on this local HTTP proxy.
    storage_->set_proxy_service(
        net::ProxyService::CreateWithoutProxyResolver(
        std::move(proxy_config_service_),
        NULL));
#else
    storage_->set_proxy_service(
        net::ProxyService::CreateUsingSystemProxyResolver(
        std::move(proxy_config_service_),
        0,
        NULL));
#endif
    storage_->set_ssl_config_service(new net::SSLConfigServiceDefaults);
    storage_->set_http_auth_handler_factory(
        net::HttpAuthHandlerFactory::CreateDefault(host_resolver.get()));
    storage_->set_http_server_properties(scoped_ptr<net::HttpServerProperties>(
        new net::HttpServerPropertiesImpl));

    base::FilePath cache_path = base_path_.Append(FILE_PATH_LITERAL("Cache"));
    scoped_ptr<net::HttpCache::DefaultBackend> main_backend(
        new net::HttpCache::DefaultBackend(
            net::DISK_CACHE,
            net::CACHE_BACKEND_DEFAULT,
            cache_path,
            GetDiskCacheSize(),
            BrowserThread::GetMessageLoopProxyForThread(
                BrowserThread::CACHE)));

    net::HttpNetworkSession::Params network_session_params;
    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.channel_id_service =
        url_request_context_->channel_id_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 =
        network_delegate_.get();
    network_session_params.http_server_properties =
        url_request_context_->http_server_properties();
    network_session_params.ignore_certificate_errors =
        ignore_certificate_errors_;

    // Give |storage_| ownership at the end in case it's |mapped_host_resolver|.
    storage_->set_host_resolver(std::move(host_resolver));
    network_session_params.host_resolver =
        url_request_context_->host_resolver();

    storage_->set_http_network_session(
        make_scoped_ptr(new net::HttpNetworkSession(network_session_params)));
    storage_->set_http_transaction_factory(
        make_scoped_ptr(new net::HttpCache(storage_->http_network_session(),
                        std::move(main_backend),
                        false /* set_up_quic_server_info */)));
#if defined(OS_ANDROID)
    scoped_ptr<XWalkURLRequestJobFactory> job_factory_impl(
        new XWalkURLRequestJobFactory);
#else
    scoped_ptr<net::URLRequestJobFactoryImpl> job_factory_impl(
        new net::URLRequestJobFactoryImpl);
#endif

    bool set_protocol;

    // Step 1:
    // Install all the default schemes for crosswalk.
    for (content::ProtocolHandlerMap::iterator it =
             protocol_handlers_.begin();
         it != protocol_handlers_.end();
         ++it) {
      set_protocol = job_factory_impl->SetProtocolHandler(
          it->first, make_scoped_ptr(it->second.release()));
      DCHECK(set_protocol);
    }
    protocol_handlers_.clear();

    // Step 2:
    // Add new basic schemes.
    set_protocol = job_factory_impl->SetProtocolHandler(
        url::kDataScheme,
        make_scoped_ptr(new net::DataProtocolHandler));
    DCHECK(set_protocol);
    set_protocol = job_factory_impl->SetProtocolHandler(
        url::kFileScheme,
        make_scoped_ptr(new net::FileProtocolHandler(
            content::BrowserThread::GetBlockingPool()->
            GetTaskRunnerWithShutdownBehavior(
                base::SequencedWorkerPool::SKIP_ON_SHUTDOWN))));
    DCHECK(set_protocol);

    // Step 3:
    // Add the scheme interceptors.
  // in the order in which they appear in the |request_interceptors| vector.
  typedef std::vector<net::URLRequestInterceptor*>
      URLRequestInterceptorVector;
  URLRequestInterceptorVector request_interceptors;

#if defined(OS_ANDROID)
    request_interceptors.push_back(
        CreateContentSchemeRequestInterceptor().release());
    request_interceptors.push_back(
        CreateAssetFileRequestInterceptor().release());
    request_interceptors.push_back(
        CreateAppSchemeRequestInterceptor().release());
    // The XWalkRequestInterceptor must come after the content and asset
    // file job factories. This for WebViewClassic compatibility where it
    // was not possible to intercept resource loads to resolvable content://
    // and file:// URIs.
    // This logical dependency is also the reason why the Content
    // ProtocolHandler has to be added as a ProtocolInterceptJobFactory rather
    // than via SetProtocolHandler.
    request_interceptors.push_back(new XWalkRequestInterceptor());
#endif

    // The chain of responsibility will execute the handlers in reverse to the
    // order in which the elements of the chain are created.
    scoped_ptr<net::URLRequestJobFactory> job_factory(
        std::move(job_factory_impl));
    for (URLRequestInterceptorVector::reverse_iterator
             i = request_interceptors.rbegin();
         i != request_interceptors.rend();
         ++i) {
      job_factory.reset(new net::URLRequestInterceptingJobFactory(
          std::move(job_factory), make_scoped_ptr(*i)));
    }

    // Set up interceptors in the reverse order.
    scoped_ptr<net::URLRequestJobFactory> top_job_factory =
        std::move(job_factory);
    for (content::URLRequestInterceptorScopedVector::reverse_iterator i =
             request_interceptors_.rbegin();
         i != request_interceptors_.rend();
         ++i) {
      top_job_factory.reset(new net::URLRequestInterceptingJobFactory(
          std::move(top_job_factory), make_scoped_ptr(*i)));
    }
    request_interceptors_.weak_clear();

    storage_->set_job_factory(std::move(top_job_factory));
  }

  return url_request_context_.get();
}

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

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

void RuntimeURLRequestContextGetter::UpdateAcceptLanguages(
    const std::string& accept_languages) {
  if (!storage_)
    return;
  storage_->set_http_user_agent_settings(make_scoped_ptr(
      new net::StaticHttpUserAgentSettings(accept_languages,
                                           xwalk::GetUserAgent())));
}

}  // namespace xwalk
<commit_msg>Make sure default schemes (https, http...) are allowed to store cookies.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "xwalk/runtime/browser/runtime_url_request_context_getter.h"

#include <algorithm>
#include <string>
#include <utility>
#include <vector>

#include "base/command_line.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "base/threading/sequenced_worker_pool.h"
#include "base/threading/worker_pool.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/cookie_store_factory.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/dns/mapped_host_resolver.h"
#include "net/http/http_auth_handler_factory.h"
#include "net/http/http_cache.h"
#include "net/http/http_network_session.h"
#include "net/http/http_server_properties_impl.h"
#include "net/proxy/proxy_service.h"
#include "net/ssl/channel_id_service.h"
#include "net/ssl/default_channel_id_store.h"
#include "net/ssl/ssl_config_service_defaults.h"
#include "net/url_request/data_protocol_handler.h"
#include "net/url_request/file_protocol_handler.h"
#include "net/url_request/static_http_user_agent_settings.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_storage.h"
#include "net/url_request/url_request_intercepting_job_factory.h"
#include "net/url_request/url_request_interceptor.h"
#include "net/url_request/url_request_job_factory_impl.h"
#include "xwalk/application/common/constants.h"
#include "xwalk/runtime/browser/runtime_network_delegate.h"
#include "xwalk/runtime/common/xwalk_content_client.h"
#include "xwalk/runtime/common/xwalk_switches.h"

#if defined(OS_ANDROID)
#include "net/proxy/proxy_config_service_android.h"
#include "xwalk/runtime/browser/android/cookie_manager.h"
#include "xwalk/runtime/browser/android/net/android_protocol_handler.h"
#include "xwalk/runtime/browser/android/net/url_constants.h"
#include "xwalk/runtime/browser/android/net/xwalk_cookie_store_wrapper.h"
#include "xwalk/runtime/browser/android/net/xwalk_url_request_job_factory.h"
#include "xwalk/runtime/browser/android/xwalk_request_interceptor.h"
#endif

using content::BrowserThread;

namespace xwalk {

int GetDiskCacheSize() {
  base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();

  if (!command_line->HasSwitch(switches::kDiskCacheSize))
      return 0;

  std::string str_value = command_line->GetSwitchValueASCII(
      switches::kDiskCacheSize);

  int size = 0;
  if (!base::StringToInt(str_value, &size)) {
      LOG(ERROR) << "The value " << str_value
                 << " can not be converted to integer, ignoring!";
  }

  return size;
}

RuntimeURLRequestContextGetter::RuntimeURLRequestContextGetter(
    bool ignore_certificate_errors,
    const base::FilePath& base_path,
    base::MessageLoop* io_loop,
    base::MessageLoop* file_loop,
    content::ProtocolHandlerMap* protocol_handlers,
    content::URLRequestInterceptorScopedVector request_interceptors)
    : ignore_certificate_errors_(ignore_certificate_errors),
      base_path_(base_path),
      io_loop_(io_loop),
      file_loop_(file_loop),
      request_interceptors_(std::move(request_interceptors)) {
  // Must first be created on the UI thread.
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  std::swap(protocol_handlers_, *protocol_handlers);

  // We must create the proxy config service on the UI loop on Linux because it
  // must synchronously run on the glib message loop. This will be passed to
  // the URLRequestContextStorage on the IO thread in GetURLRequestContext().
#if defined(OS_ANDROID)
  proxy_config_service_ = net::ProxyService::CreateSystemProxyConfigService(
      io_loop_->task_runner(), file_loop_->task_runner());
  net::ProxyConfigServiceAndroid* android_config_service =
      static_cast<net::ProxyConfigServiceAndroid*>(proxy_config_service_.get());
  android_config_service->set_exclude_pac_url(true);
#else
  proxy_config_service_ = net::ProxyService::CreateSystemProxyConfigService(
      io_loop_->task_runner(), file_loop_->task_runner());
#endif
}

RuntimeURLRequestContextGetter::~RuntimeURLRequestContextGetter() {
}

net::URLRequestContext* RuntimeURLRequestContextGetter::GetURLRequestContext() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));

  if (!url_request_context_) {
    url_request_context_.reset(new net::URLRequestContext());
    network_delegate_.reset(new RuntimeNetworkDelegate);
    url_request_context_->set_network_delegate(network_delegate_.get());
    storage_.reset(
        new net::URLRequestContextStorage(url_request_context_.get()));
#if defined(OS_ANDROID)
    storage_->set_cookie_store(new XWalkCookieStoreWrapper());
#else
    content::CookieStoreConfig cookie_config(base_path_.Append(
        application::kCookieDatabaseFilename),
        content::CookieStoreConfig::PERSISTANT_SESSION_COOKIES,
        NULL, NULL);

    cookie_config.cookieable_schemes.insert(
        cookie_config.cookieable_schemes.begin(),
        net::CookieMonster::kDefaultCookieableSchemes,
        net::CookieMonster::kDefaultCookieableSchemes +
        net::CookieMonster::kDefaultCookieableSchemesCount);
    cookie_config.cookieable_schemes.push_back(application::kApplicationScheme);
    cookie_config.cookieable_schemes.push_back(content::kChromeDevToolsScheme);

    net::CookieStore* cookie_store = content::CreateCookieStore(cookie_config);
    storage_->set_cookie_store(cookie_store);
#endif
    storage_->set_channel_id_service(make_scoped_ptr(new net::ChannelIDService(
        new net::DefaultChannelIDStore(NULL),
        base::WorkerPool::GetTaskRunner(true))));
    storage_->set_http_user_agent_settings(make_scoped_ptr(
        new net::StaticHttpUserAgentSettings("en-us,en",
                                             xwalk::GetUserAgent())));

    scoped_ptr<net::HostResolver> host_resolver(
        net::HostResolver::CreateDefaultResolver(NULL));

    storage_->set_cert_verifier(net::CertVerifier::CreateDefault());
    storage_->set_transport_security_state(
        make_scoped_ptr(new net::TransportSecurityState));
#if defined(OS_ANDROID)
    // Android provides a local HTTP proxy that handles all the proxying.
    // Create the proxy without a resolver since we rely
    // on this local HTTP proxy.
    storage_->set_proxy_service(
        net::ProxyService::CreateWithoutProxyResolver(
        std::move(proxy_config_service_),
        NULL));
#else
    storage_->set_proxy_service(
        net::ProxyService::CreateUsingSystemProxyResolver(
        std::move(proxy_config_service_),
        0,
        NULL));
#endif
    storage_->set_ssl_config_service(new net::SSLConfigServiceDefaults);
    storage_->set_http_auth_handler_factory(
        net::HttpAuthHandlerFactory::CreateDefault(host_resolver.get()));
    storage_->set_http_server_properties(scoped_ptr<net::HttpServerProperties>(
        new net::HttpServerPropertiesImpl));

    base::FilePath cache_path = base_path_.Append(FILE_PATH_LITERAL("Cache"));
    scoped_ptr<net::HttpCache::DefaultBackend> main_backend(
        new net::HttpCache::DefaultBackend(
            net::DISK_CACHE,
            net::CACHE_BACKEND_DEFAULT,
            cache_path,
            GetDiskCacheSize(),
            BrowserThread::GetMessageLoopProxyForThread(
                BrowserThread::CACHE)));

    net::HttpNetworkSession::Params network_session_params;
    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.channel_id_service =
        url_request_context_->channel_id_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 =
        network_delegate_.get();
    network_session_params.http_server_properties =
        url_request_context_->http_server_properties();
    network_session_params.ignore_certificate_errors =
        ignore_certificate_errors_;

    // Give |storage_| ownership at the end in case it's |mapped_host_resolver|.
    storage_->set_host_resolver(std::move(host_resolver));
    network_session_params.host_resolver =
        url_request_context_->host_resolver();

    storage_->set_http_network_session(
        make_scoped_ptr(new net::HttpNetworkSession(network_session_params)));
    storage_->set_http_transaction_factory(
        make_scoped_ptr(new net::HttpCache(storage_->http_network_session(),
                        std::move(main_backend),
                        false /* set_up_quic_server_info */)));
#if defined(OS_ANDROID)
    scoped_ptr<XWalkURLRequestJobFactory> job_factory_impl(
        new XWalkURLRequestJobFactory);
#else
    scoped_ptr<net::URLRequestJobFactoryImpl> job_factory_impl(
        new net::URLRequestJobFactoryImpl);
#endif

    bool set_protocol;

    // Step 1:
    // Install all the default schemes for crosswalk.
    for (content::ProtocolHandlerMap::iterator it =
             protocol_handlers_.begin();
         it != protocol_handlers_.end();
         ++it) {
      set_protocol = job_factory_impl->SetProtocolHandler(
          it->first, make_scoped_ptr(it->second.release()));
      DCHECK(set_protocol);
    }
    protocol_handlers_.clear();

    // Step 2:
    // Add new basic schemes.
    set_protocol = job_factory_impl->SetProtocolHandler(
        url::kDataScheme,
        make_scoped_ptr(new net::DataProtocolHandler));
    DCHECK(set_protocol);
    set_protocol = job_factory_impl->SetProtocolHandler(
        url::kFileScheme,
        make_scoped_ptr(new net::FileProtocolHandler(
            content::BrowserThread::GetBlockingPool()->
            GetTaskRunnerWithShutdownBehavior(
                base::SequencedWorkerPool::SKIP_ON_SHUTDOWN))));
    DCHECK(set_protocol);

    // Step 3:
    // Add the scheme interceptors.
  // in the order in which they appear in the |request_interceptors| vector.
  typedef std::vector<net::URLRequestInterceptor*>
      URLRequestInterceptorVector;
  URLRequestInterceptorVector request_interceptors;

#if defined(OS_ANDROID)
    request_interceptors.push_back(
        CreateContentSchemeRequestInterceptor().release());
    request_interceptors.push_back(
        CreateAssetFileRequestInterceptor().release());
    request_interceptors.push_back(
        CreateAppSchemeRequestInterceptor().release());
    // The XWalkRequestInterceptor must come after the content and asset
    // file job factories. This for WebViewClassic compatibility where it
    // was not possible to intercept resource loads to resolvable content://
    // and file:// URIs.
    // This logical dependency is also the reason why the Content
    // ProtocolHandler has to be added as a ProtocolInterceptJobFactory rather
    // than via SetProtocolHandler.
    request_interceptors.push_back(new XWalkRequestInterceptor());
#endif

    // The chain of responsibility will execute the handlers in reverse to the
    // order in which the elements of the chain are created.
    scoped_ptr<net::URLRequestJobFactory> job_factory(
        std::move(job_factory_impl));
    for (URLRequestInterceptorVector::reverse_iterator
             i = request_interceptors.rbegin();
         i != request_interceptors.rend();
         ++i) {
      job_factory.reset(new net::URLRequestInterceptingJobFactory(
          std::move(job_factory), make_scoped_ptr(*i)));
    }

    // Set up interceptors in the reverse order.
    scoped_ptr<net::URLRequestJobFactory> top_job_factory =
        std::move(job_factory);
    for (content::URLRequestInterceptorScopedVector::reverse_iterator i =
             request_interceptors_.rbegin();
         i != request_interceptors_.rend();
         ++i) {
      top_job_factory.reset(new net::URLRequestInterceptingJobFactory(
          std::move(top_job_factory), make_scoped_ptr(*i)));
    }
    request_interceptors_.weak_clear();

    storage_->set_job_factory(std::move(top_job_factory));
  }

  return url_request_context_.get();
}

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

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

void RuntimeURLRequestContextGetter::UpdateAcceptLanguages(
    const std::string& accept_languages) {
  if (!storage_)
    return;
  storage_->set_http_user_agent_settings(make_scoped_ptr(
      new net::StaticHttpUserAgentSettings(accept_languages,
                                           xwalk::GetUserAgent())));
}

}  // namespace xwalk
<|endoftext|>


<commit_before><commit_msg>INTEGRATION: CWS os8 (1.41.2.1.58); FILE MERGED 2003/04/03 07:10:58 os 1.41.2.1.58.1: #108583# precompiled headers removed<commit_after><|endoftext|>