<commit_before>//RVIZ measurement tool
//Qiaosong Wang
//University of Delaware
//qiaosong@udel.edu

#include <ros/ros.h>
#include <visualization_msgs/Marker.h>
#include <boost/foreach.hpp>
#include <pcl/io/pcd_io.h>
#include <pcl/io/vtk_io.h>
#include <pcl/ros/conversions.h>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/point_types.h>
#include <pcl/filters/voxel_grid.h>
#include <pcl/surface/gp3.h>
#include <pcl/kdtree/kdtree_flann.h>
#include <pcl/features/normal_3d.h>
#include <pcl/filters/voxel_grid.h>
#include <sensor_msgs/PointCloud2.h>
#include <std_msgs/String.h>
#include <geometry_msgs/PointStamped.h>
#include <boost/bind.hpp>
#include <cmath>
#include <vector>
#include <math.h>

using namespace std;

//changing modes
int workmode =0; //1 polyline mode 2 box selection

//Defining ROS parameters
ros::Publisher marker_pub;
ros::NodeHandle *nhp;
ros::Subscriber click_sub;
ros::Subscriber ptcloud_sub;

float cpdist=0; //Current frame
float globalscale =100;
geometry_msgs::Point fp; //future point
geometry_msgs::Point cp; //current point
geometry_msgs::Point pp; //previous point

//Number of points, need to be dynamically assiagned once the panel is done
int num_polypoints=100;
int polycount = 0;

//Declare 3D point storage structure
vector<vector<float> > polypoints(3, vector<float>(100));

//Declare received pointcloud from RVIZ
pcl::PointCloud< pcl::PointXYZRGB> rviz_pt;
pcl::PointCloud< pcl::PointXYZRGB> rviz_pt_filtered;
float calc_cp_dist(int i, vector<vector<float> > polypoints)
{
  float cp_dist= sqrt((polypoints[0][i]-polypoints[0][i-1])*(polypoints[0][i]-polypoints[0][i-1])+(polypoints[1][i]-polypoints[1][i-1])*(polypoints[1][i]-polypoints[1][i-1])+(polypoints[2][i]-polypoints[2][i-1])*(polypoints[2][i]-polypoints[2][i-1]));
  return cp_dist;
}

void ptcloudCallback(const sensor_msgs::PointCloud2ConstPtr& input)
{

/*
 pcl::fromROSMsg(*input, rviz_pt);
 sensor_msgs::PointCloud2 cloud_filtered;

// Perform the actual filtering
   pcl::VoxelGrid<pcl::PointXYZRGB> sor ;
   sor.setInputCloud (rviz_pt);
   sor.setLeafSize (0.01, 0.01, 0.01);
   sor.filter (rviz_pt_filtered);

  //Convert the pcl cloud back to rosmsg
  pcl::toROSMsg(*rviz_pt_filtered, cloud_filtered);
  //Set the header of the cloud
  cloud_filtered.header.frame_id = input->header.frame_id;
  // Publish the data
  //You may have to set the header frame id of the cloud_filtered also
  pub.publish (cloud_filtered);

*/
}

//This function returns downsampled pointcloud and convert it to pcl::PolygonMesh, needs another panel to define
//saving path for the mesh file, and mesh reconstruction parameters.
sensor_msgs::PointCloud2::Ptr pcd2mesh(sensor_msgs::PointCloud2::Ptr rawpt)
{

// Load input file into a PointCloud<T> with an appropriate type
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ>);
  sensor_msgs::PointCloud2 cloud_blob;

  sensor_msgs::PointCloud2::Ptr input (new sensor_msgs::PointCloud2 ());
  sensor_msgs::PointCloud2::Ptr output (new sensor_msgs::PointCloud2 ());

  input= rawpt;

 //For testing

 // pcl::PCDReader reader;

 // reader.read ("./armory_stairs1_hokuyo.pcd", *input);

  pcl::VoxelGrid<sensor_msgs::PointCloud2> sor;
  sor.setInputCloud (input);
  sor.setLeafSize (0.1, 0.1, 0.1);
  sor.filter (*output);

 //For testing
// pcl::PCDWriter writer;
// writer.write ("./downsampled.pcd", *output,
//       Eigen::Vector4f::Zero (), Eigen::Quaternionf::Identity (), false);

printf("Downsampling completed!\n");

cloud_blob=*output;

// pcl::io::loadPCDFile ("./downsampled.pcd", cloud_blob);
pcl::fromROSMsg (cloud_blob, *cloud);
//* the data should be available in cloud

// Normal estimation*
pcl::NormalEstimation<pcl::PointXYZ, pcl::Normal> n;
pcl::PointCloud<pcl::Normal>::Ptr normals (new pcl::PointCloud<pcl::Normal>);
pcl::search::KdTree<pcl::PointXYZ>::Ptr tree (new pcl::search::KdTree<pcl::PointXYZ>);
tree->setInputCloud (cloud);
n.setInputCloud (cloud);
n.setSearchMethod (tree);
n.setKSearch (20);
n.compute (*normals);
//* normals should not contain the point normals + surface curvatures

// Concatenate the XYZ and normal fields*
pcl::PointCloud<pcl::PointNormal>::Ptr cloud_with_normals (new pcl::PointCloud<pcl::PointNormal>);
pcl::concatenateFields (*cloud, *normals, *cloud_with_normals);
//* cloud_with_normals = cloud + normals

// Create search tree*
pcl::search::KdTree<pcl::PointNormal>::Ptr tree2 (new pcl::search::KdTree<pcl::PointNormal>);
tree2->setInputCloud (cloud_with_normals);

// Initialize objects
pcl::GreedyProjectionTriangulation<pcl::PointNormal> gp3;
pcl::PolygonMesh triangles;

// Set the maximum distance between connected points (maximum edge length)
gp3.setSearchRadius (3);

// Set typical values for the parameters
gp3.setMu (3);
gp3.setMaximumNearestNeighbors (300);
gp3.setMaximumSurfaceAngle(M_PI/4); // 45 degrees
gp3.setMinimumAngle(M_PI/18); // 10 degrees
gp3.setMaximumAngle(2*M_PI/3); // 120 degrees
gp3.setNormalConsistency(false);

// Get result
gp3.setInputCloud (cloud_with_normals);
gp3.setSearchMethod (tree2);
gp3.reconstruct (triangles);

// Additional vertex information
std::vector<int> parts = gp3.getPartIDs();
std::vector<int> states = gp3.getPointStates();

//For testing
pcl::io::saveVTKFile("mesh.vtk",triangles);

return output;
}

void clickCallback(const geometry_msgs::PointStamped& msg)
{

     //Getting ROS geometry msgs
    //ROS_INFO("New Point at X: %f, Y: %f, Z: %f\n", msg.point.x, msg.point.y, msg.point.z);
    fp.x =  msg.point.x;
    fp.y =  msg.point.y;
    fp.z =  msg.point.z;

    // Initialize marker parameters
    visualization_msgs::Marker points, line_strip, line_list , psphere, csphere, arrow, showtext,showtextid;
    showtext.header.frame_id = arrow.header.frame_id=psphere.header.frame_id=csphere.header.frame_id = points.header.frame_id = line_strip.header.frame_id = line_list.header.frame_id = "/base_link";
    showtext.header.stamp = arrow.header.stamp=psphere.header.stamp =csphere.header.stamp= points.header.stamp = line_strip.header.stamp = line_list.header.stamp = ros::Time::now();
    showtext.ns = arrow.ns=psphere.ns=csphere.ns=points.ns = line_strip.ns = line_list.ns = "UD_rviz_interaction";
    showtext.action = arrow.action=psphere.action=csphere.action=points.action = line_strip.action = line_list.action = visualization_msgs::Marker::ADD;
    showtext.pose.orientation.w = arrow.pose.orientation.w=psphere.pose.orientation.w =csphere.pose.orientation.w= points.pose.orientation.w = line_strip.pose.orientation.w = line_list.pose.orientation.w = 1.0;

    //ID
    points.id = 0;
    line_strip.id = 1;
    line_list.id = 2;
    psphere.id =3;
    csphere.id =4;
    arrow.id=5;
    showtext.id=6;
    showtextid.id=7;

    //Type
    points.type = visualization_msgs::Marker::POINTS;
    line_strip.type = visualization_msgs::Marker::LINE_STRIP;
    line_list.type = visualization_msgs::Marker::LINE_LIST;
    psphere.type = visualization_msgs::Marker::SPHERE;
    csphere.type = visualization_msgs::Marker::SPHERE;
    arrow.type = visualization_msgs::Marker::ARROW;
    showtext.type = visualization_msgs::Marker::TEXT_VIEW_FACING;
    showtextid.type = visualization_msgs::Marker::TEXT_VIEW_FACING;

    //Scale
    psphere.scale.x = 0.05*globalscale;
    psphere.scale.y = 0.05*globalscale;
    psphere.scale.z = 0.05*globalscale;

    csphere.scale.x = 0.05*globalscale;
    csphere.scale.y = 0.05*globalscale;
    csphere.scale.z = 0.05*globalscale;

    showtext.scale.x = 0.05*globalscale;
    showtext.scale.y = 0.05*globalscale;
    showtext.scale.z = 0.05*globalscale;

    showtextid.scale.x = 0.05*globalscale;
    showtextid.scale.y = 0.05*globalscale;
    showtextid.scale.z = 0.05*globalscale;

    line_list.scale.x = 0.005*globalscale;
    line_list.scale.y = 0.005*globalscale;
    line_list.scale.z = 0.005*globalscale;

    line_strip.scale.x = 0.005*globalscale;

    //Color
    points.color.b = 1.0;
    points.color.a = 1.0;

    // Line strip is blue
    line_list.color.b = 1.0;
    line_list.color.a = 1.0;

     line_strip.color.b = 1.0;
     line_strip.color.a = 1.0;

    // Sphere is green
    psphere.color.r = 1.0;
    psphere.color.a = 0.6;

    csphere.color.g = 1.0;
    csphere.color.a = 1.0;

    //Text is green
    showtext.color.r = 1.0;
    showtext.color.g = 1.0;
    showtext.color.a = 1.0;

    showtextid.color.r = 0.0;
    showtextid.color.g = 1.0;
    showtextid.color.a = 1.0;

    cp.x=fp.x;
    cp.y=fp.y;
    cp.z=fp.z;

      psphere.points.push_back(pp);
      psphere.pose.position.x = pp.x;
      psphere.pose.position.y = pp.y;
      psphere.pose.position.z = pp.z;

      csphere.points.push_back(cp);
      csphere.pose.position.x = cp.x;
      csphere.pose.position.y = cp.y;
      csphere.pose.position.z = cp.z;

     // Create the vertices for the points and lines

    polypoints[0][polycount]=fp.x;
    polypoints[1][polycount]=fp.y;
    polypoints[2][polycount]=fp.z;

       for (int i = 0; i<=polycount;i++)
        {

           geometry_msgs::Point p;
           p.x = polypoints[0][i];
           p.y = polypoints[1][i];
	   p.z = polypoints[2][i];
           /*
           printf("%f\n", polypoints[0][i]);
           printf("%f\n", polypoints[1][i]);
           printf("%f\n", polypoints[2][i]);
           */
           points.points.push_back(p);
           line_strip.points.push_back(p);

            std::stringstream point_id;
            point_id<< i << "\n";

             printf("%d\n", i);

         showtextid.text = point_id.str();
         showtextid.pose.position.x = polypoints[0][i];
         showtextid.pose.position.y = polypoints[1][i];
         showtextid.pose.position.z = polypoints[2][i];

          // line_list.points.push_back(p);
          // p.z += 1.0;
           //line_list.points.push_back(p);
          if(i>0)
          cpdist=cpdist+calc_cp_dist(i,polypoints);
        }

       pp.x = cp.x;
       pp.y = cp.y;
       pp.z = cp.z;

         printf("Distance: %f \n", cpdist);

            std::stringstream show_dist;
            show_dist<< cpdist << "\n";

         showtext.text = show_dist.str();
         showtext.pose.position.x = polypoints[0][polycount];
         showtext.pose.position.y = polypoints[1][polycount];
         showtext.pose.position.z = polypoints[2][polycount];

// Publish markers
    marker_pub.publish(line_list);
    marker_pub.publish(psphere);
    marker_pub.publish(csphere);
    marker_pub.publish(showtext);
    marker_pub.publish(showtextid);
    marker_pub.publish(line_strip);

    if (polycount!=num_polypoints)
     polycount++;
    else
     {
     polycount=0;
     cpdist=0;
     }

}

int main( int argc, char** argv )
{

fp.x=1;
fp.y=1;
fp.z=1;
cp.x=pp.x=0;
cp.y=pp.y=0;
cp.z=pp.z=0;

  ros::init(argc, argv, "UD_rviz_interaction");

   nhp= new ros::NodeHandle();

  //Publishers
  marker_pub = nhp->advertise<visualization_msgs::Marker>("visualization_marker", 10);

  //Subscribers
  click_sub = nhp->subscribe("ud_clicked_point", 10,clickCallback);

  //ptcloud_sub = nhp->subscribe("cloud_pcd",10,ptcloudCallback);

  ros::Rate UD_rviz_interaction_rate(30);

  while (ros::ok())
  {
    UD_rviz_interaction_rate.sleep();
    ros::spinOnce();
  }
}

<commit_msg>Update UD_rviz_interaction.cpp<commit_after>//RVIZ measurement tool
//Qiaosong Wang
//University of Delaware
//qiaosong@udel.edu

#include <ros/ros.h>
#include <visualization_msgs/Marker.h>
#include <sensor_msgs/PointCloud2.h>
#include <std_msgs/String.h>
#include <geometry_msgs/PointStamped.h>

#include <pcl/io/pcd_io.h>
#include <pcl/io/vtk_io.h>
#include <pcl/ros/conversions.h>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/point_types.h>
#include <pcl/filters/voxel_grid.h>
#include <pcl/surface/gp3.h>
#include <pcl/kdtree/kdtree_flann.h>
#include <pcl/features/normal_3d.h>
#include <pcl/filters/voxel_grid.h>
#include <pcl/sample_consensus/method_types.h>
#include <pcl/sample_consensus/model_types.h>
#include <pcl/segmentation/sac_segmentation.h>
#include <pcl/ModelCoefficients.h>
#include <pcl/kdtree/kdtree_flann.h>
#include <pcl/surface/mls.h>

#include <boost/foreach.hpp>
#include <boost/bind.hpp>

#include <cmath>
#include <vector>
#include <math.h>

using namespace std;

//changing modes
int workmode =0; //1 polyline mode 2 box selection

//Defining ROS parameters
ros::Publisher marker_pub;
ros::NodeHandle *nhp;
ros::Subscriber click_sub;
ros::Subscriber ptcloud_sub;

float cpdist=0; //Current frame
float globalscale =100;
geometry_msgs::Point fp; //future point
geometry_msgs::Point cp; //current point
geometry_msgs::Point pp; //previous point

//Number of points, need to be dynamically assiagned once the panel is done
int num_polypoints=100;
int polycount = 0;

//Declare 3D point storage structure
vector<vector<float> > polypoints(3, vector<float>(100));

//Declare received pointcloud from RVIZ
pcl::PointCloud< pcl::PointXYZRGB> rviz_pt;
pcl::PointCloud< pcl::PointXYZRGB> rviz_pt_filtered;
float calc_cp_dist(int i, vector<vector<float> > polypoints)
{
  float cp_dist= sqrt((polypoints[0][i]-polypoints[0][i-1])*(polypoints[0][i]-polypoints[0][i-1])+(polypoints[1][i]-polypoints[1][i-1])*(polypoints[1][i]-polypoints[1][i-1])+(polypoints[2][i]-polypoints[2][i-1])*(polypoints[2][i]-polypoints[2][i-1]));
  return cp_dist;
}

void ptcloudCallback(const sensor_msgs::PointCloud2ConstPtr& input)
{

/*
 pcl::fromROSMsg(*input, rviz_pt);
 sensor_msgs::PointCloud2 cloud_filtered;

// Perform the actual filtering
   pcl::VoxelGrid<pcl::PointXYZRGB> sor ;
   sor.setInputCloud (rviz_pt);
   sor.setLeafSize (0.01, 0.01, 0.01);
   sor.filter (rviz_pt_filtered);

  //Convert the pcl cloud back to rosmsg
  pcl::toROSMsg(*rviz_pt_filtered, cloud_filtered);
  //Set the header of the cloud
  cloud_filtered.header.frame_id = input->header.frame_id;
  // Publish the data
  //You may have to set the header frame id of the cloud_filtered also
  pub.publish (cloud_filtered);

*/
}

//This function returns downsampled pointcloud and convert it to pcl::PolygonMesh, needs another panel to define
//saving path for the mesh file, and mesh reconstruction parameters.
sensor_msgs::PointCloud2::Ptr pt2mesh(sensor_msgs::PointCloud2::Ptr rawpt)
{

// Load input file into a PointCloud<T> with an appropriate type
  pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ>);

  sensor_msgs::PointCloud2 cloud_blob;
  sensor_msgs::PointCloud2::Ptr input (new sensor_msgs::PointCloud2 ());
  sensor_msgs::PointCloud2::Ptr output (new sensor_msgs::PointCloud2 ());

  input= rawpt;

 //For testing

 // pcl::PCDReader reader;

 // reader.read ("./armory_stairs1_hokuyo.pcd", *input);

  pcl::VoxelGrid<sensor_msgs::PointCloud2> sor;
  sor.setInputCloud (input);
  sor.setLeafSize (0.1, 0.1, 0.1);
  sor.filter (*output);

 //For testing
 pcl::PCDWriter writer;
 writer.write ("./downsampled.pcd", *output,
       Eigen::Vector4f::Zero (), Eigen::Quaternionf::Identity (), false);

printf("Downsampling completed!\n");

cloud_blob=*output;

  pcl::io::loadPCDFile ("./downsampled.pcd", *cloud);
  // Create a KD-Tree
  pcl::search::KdTree<pcl::PointXYZ>::Ptr tree (new pcl::search::KdTree<pcl::PointXYZ>);

  // Output has the PointNormal type in order to store the normals calculated by MLS
  pcl::PointCloud<pcl::PointNormal> mls_points;

  // Init object (second point type is for the normals, even if unused)
  pcl::MovingLeastSquares<pcl::PointXYZ, pcl::PointNormal> mls;

  mls.setComputeNormals (true);

  // Set parameters
  mls.setInputCloud (cloud);
  mls.setPolynomialFit (true);
  mls.setSearchMethod (tree);
  mls.setSearchRadius (0.03);

  // Reconstruct
  mls.process (mls_points);

  // Save output
  pcl::io::savePCDFile ("./smoothed.pcd", mls_points);

//Comment this line to disable smooth
pcl::io::loadPCDFile ("./smoothed.pcd", cloud_blob);
pcl::fromROSMsg (cloud_blob, *cloud);

//* the data should be available in cloud
// Normal estimation*
pcl::NormalEstimation<pcl::PointXYZ, pcl::Normal> n;
pcl::PointCloud<pcl::Normal>::Ptr normals (new pcl::PointCloud<pcl::Normal>);
pcl::search::KdTree<pcl::PointXYZ>::Ptr tree2 (new pcl::search::KdTree<pcl::PointXYZ>);
tree->setInputCloud (cloud);
n.setInputCloud (cloud);
n.setSearchMethod (tree2);
n.setKSearch (20);
n.compute (*normals);
//* normals should not contain the point normals + surface curvatures

// Concatenate the XYZ and normal fields*
pcl::PointCloud<pcl::PointNormal>::Ptr cloud_with_normals (new pcl::PointCloud<pcl::PointNormal>);
pcl::concatenateFields (*cloud, *normals, *cloud_with_normals);
//* cloud_with_normals = cloud + normals

// Create search tree*
pcl::search::KdTree<pcl::PointNormal>::Ptr tree3 (new pcl::search::KdTree<pcl::PointNormal>);
tree3->setInputCloud (cloud_with_normals);

// Initialize objects
pcl::GreedyProjectionTriangulation<pcl::PointNormal> gp3;
pcl::PolygonMesh triangles;

// Set the maximum distance between connected points (maximum edge length)
gp3.setSearchRadius (3);

// Set typical values for the parameters
gp3.setMu (3);
gp3.setMaximumNearestNeighbors (300);
gp3.setMaximumSurfaceAngle(M_PI/4); // 45 degrees
gp3.setMinimumAngle(M_PI/18); // 10 degrees
gp3.setMaximumAngle(2*M_PI/3); // 120 degrees
gp3.setNormalConsistency(false);

// Get result
gp3.setInputCloud (cloud_with_normals);
gp3.setSearchMethod (tree3);
gp3.reconstruct (triangles);

// Additional vertex information
std::vector<int> parts = gp3.getPartIDs();
std::vector<int> states = gp3.getPointStates();

//For testing
pcl::io::saveVTKFile("mesh.vtk",triangles);

return output;
}

void clickCallback(const geometry_msgs::PointStamped& msg)
{

     //Getting ROS geometry msgs
    //ROS_INFO("New Point at X: %f, Y: %f, Z: %f\n", msg.point.x, msg.point.y, msg.point.z);
    fp.x =  msg.point.x;
    fp.y =  msg.point.y;
    fp.z =  msg.point.z;

    // Initialize marker parameters
    visualization_msgs::Marker points, line_strip, line_list , psphere, csphere, arrow, showtext,showtextid;
    showtext.header.frame_id = arrow.header.frame_id=psphere.header.frame_id=csphere.header.frame_id = points.header.frame_id = line_strip.header.frame_id = line_list.header.frame_id = "/base_link";
    showtext.header.stamp = arrow.header.stamp=psphere.header.stamp =csphere.header.stamp= points.header.stamp = line_strip.header.stamp = line_list.header.stamp = ros::Time::now();
    showtext.ns = arrow.ns=psphere.ns=csphere.ns=points.ns = line_strip.ns = line_list.ns = "UD_rviz_interaction";
    showtext.action = arrow.action=psphere.action=csphere.action=points.action = line_strip.action = line_list.action = visualization_msgs::Marker::ADD;
    showtext.pose.orientation.w = arrow.pose.orientation.w=psphere.pose.orientation.w =csphere.pose.orientation.w= points.pose.orientation.w = line_strip.pose.orientation.w = line_list.pose.orientation.w = 1.0;

    //ID
    points.id = 0;
    line_strip.id = 1;
    line_list.id = 2;
    psphere.id =3;
    csphere.id =4;
    arrow.id=5;
    showtext.id=6;
    showtextid.id=7;

    //Type
    points.type = visualization_msgs::Marker::POINTS;
    line_strip.type = visualization_msgs::Marker::LINE_STRIP;
    line_list.type = visualization_msgs::Marker::LINE_LIST;
    psphere.type = visualization_msgs::Marker::SPHERE;
    csphere.type = visualization_msgs::Marker::SPHERE;
    arrow.type = visualization_msgs::Marker::ARROW;
    showtext.type = visualization_msgs::Marker::TEXT_VIEW_FACING;
    showtextid.type = visualization_msgs::Marker::TEXT_VIEW_FACING;

    //Scale
    psphere.scale.x = 0.05*globalscale;
    psphere.scale.y = 0.05*globalscale;
    psphere.scale.z = 0.05*globalscale;

    csphere.scale.x = 0.05*globalscale;
    csphere.scale.y = 0.05*globalscale;
    csphere.scale.z = 0.05*globalscale;

    showtext.scale.x = 0.05*globalscale;
    showtext.scale.y = 0.05*globalscale;
    showtext.scale.z = 0.05*globalscale;

    showtextid.scale.x = 0.05*globalscale;
    showtextid.scale.y = 0.05*globalscale;
    showtextid.scale.z = 0.05*globalscale;

    line_list.scale.x = 0.005*globalscale;
    line_list.scale.y = 0.005*globalscale;
    line_list.scale.z = 0.005*globalscale;

    line_strip.scale.x = 0.005*globalscale;

    //Color
    points.color.b = 1.0;
    points.color.a = 1.0;

    // Line strip is blue
    line_list.color.b = 1.0;
    line_list.color.a = 1.0;

     line_strip.color.b = 1.0;
     line_strip.color.a = 1.0;

    // Sphere is green
    psphere.color.r = 1.0;
    psphere.color.a = 0.6;

    csphere.color.g = 1.0;
    csphere.color.a = 1.0;

    //Text is green
    showtext.color.r = 1.0;
    showtext.color.g = 1.0;
    showtext.color.a = 1.0;

    showtextid.color.r = 0.0;
    showtextid.color.g = 1.0;
    showtextid.color.a = 1.0;

    cp.x=fp.x;
    cp.y=fp.y;
    cp.z=fp.z;

      psphere.points.push_back(pp);
      psphere.pose.position.x = pp.x;
      psphere.pose.position.y = pp.y;
      psphere.pose.position.z = pp.z;

      csphere.points.push_back(cp);
      csphere.pose.position.x = cp.x;
      csphere.pose.position.y = cp.y;
      csphere.pose.position.z = cp.z;

     // Create the vertices for the points and lines

    polypoints[0][polycount]=fp.x;
    polypoints[1][polycount]=fp.y;
    polypoints[2][polycount]=fp.z;

       for (int i = 0; i<=polycount;i++)
        {

           geometry_msgs::Point p;
           p.x = polypoints[0][i];
           p.y = polypoints[1][i];
	   p.z = polypoints[2][i];
           /*
           printf("%f\n", polypoints[0][i]);
           printf("%f\n", polypoints[1][i]);
           printf("%f\n", polypoints[2][i]);
           */
           points.points.push_back(p);
           line_strip.points.push_back(p);

            std::stringstream point_id;
            point_id<< i << "\n";

             printf("%d\n", i);

         showtextid.text = point_id.str();
         showtextid.pose.position.x = polypoints[0][i];
         showtextid.pose.position.y = polypoints[1][i];
         showtextid.pose.position.z = polypoints[2][i];

          // line_list.points.push_back(p);
          // p.z += 1.0;
           //line_list.points.push_back(p);
          if(i>0)
          cpdist=cpdist+calc_cp_dist(i,polypoints);
        }

       pp.x = cp.x;
       pp.y = cp.y;
       pp.z = cp.z;

         printf("Distance: %f \n", cpdist);

            std::stringstream show_dist;
            show_dist<< cpdist << "\n";

         showtext.text = show_dist.str();
         showtext.pose.position.x = polypoints[0][polycount];
         showtext.pose.position.y = polypoints[1][polycount];
         showtext.pose.position.z = polypoints[2][polycount];

// Publish markers
    marker_pub.publish(line_list);
    marker_pub.publish(psphere);
    marker_pub.publish(csphere);
    marker_pub.publish(showtext);
    marker_pub.publish(showtextid);
    marker_pub.publish(line_strip);

    if (polycount!=num_polypoints)
     polycount++;
    else
     {
     polycount=0;
     cpdist=0;
     }

}

int main( int argc, char** argv )
{

fp.x=1;
fp.y=1;
fp.z=1;
cp.x=pp.x=0;
cp.y=pp.y=0;
cp.z=pp.z=0;

  ros::init(argc, argv, "UD_rviz_interaction");

   nhp= new ros::NodeHandle();

  //Publishers
  marker_pub = nhp->advertise<visualization_msgs::Marker>("visualization_marker", 10);

  //Subscribers
  click_sub = nhp->subscribe("ud_clicked_point", 10,clickCallback);

  ptcloud_sub = nhp->subscribe("cloud_pcd",10,ptcloudCallback);

  ros::Rate UD_rviz_interaction_rate(30);

  while (ros::ok())
  {
    UD_rviz_interaction_rate.sleep();
    ros::spinOnce();
  }
}

<|endoftext|>


<commit_before>
#include "Internal.h"
#include <Lumino/UI/UIContext.h>		// TODO: Ȃ
#include <Lumino/UI/UILayoutView.h>		// TODO: Ȃ
#include <Lumino/UI/UIPanel.h>
#include <Lumino/UI/UIContentControl.h>

LN_NAMESPACE_BEGIN

//==============================================================================
// UIContentControl
//==============================================================================
LN_UI_TYPEINFO_IMPLEMENT(UIContentControl, UIElement);

//------------------------------------------------------------------------------
UIContentControl::UIContentControl()
	: m_contentHost(nullptr)
	, m_contentElement(nullptr)
	, m_contentElementModified(false)
{
}

//------------------------------------------------------------------------------
UIContentControl::~UIContentControl()
{
	LN_SAFE_RELEASE(m_contentElement);
	LN_SAFE_RELEASE(m_contentHost);
}

//------------------------------------------------------------------------------
void UIContentControl::Initialize(detail::UIManager* manager)
{
	UIControl::Initialize(manager);

	SetVerticalContentAlignment(VerticalAlignment::Stretch);
	SetHorizontalContentAlignment(HorizontalAlignment::Stretch);
}

//------------------------------------------------------------------------------
void UIContentControl::SetContent(UIElement* element)
{
	//  content ĂΎ菜Ă
	if (m_contentElement != nullptr && m_contentHost != nullptr)
	{
		m_contentHost->RemoveChild(m_contentElement);
		LN_SAFE_RELEASE(m_contentElement);
	}

	// V m_contentElement ێ
	LN_REFOBJ_SET(m_contentElement, element);
	if (m_contentElement != nullptr)
	{
		m_contentElementModified = true;
	}
}

//------------------------------------------------------------------------------
void UIContentControl::OnUpdatingLayout()
{
	// VisualTree ΒPȂ Panel  m_contentHost ƂĎgB
	// ̎_ VisualTree ƂƂ́AStyle łȂA
	// Style ̎ Template  Host ƂȂ Panel ܂܂ĂȂƂƁB
	if (GetVisualTreeRoot() == nullptr)
	{
		auto panel = RefPtr<UIPanel>::MakeRef();
		panel->Initialize(GetManager());

		// ContentAlignment ݒ
		panel->SetVerticalAlignment(GetVerticalContentAlignment());
		panel->SetHorizontalAlignment(GetHorizontalContentAlignment());

		m_contentHost = panel.DetachMove();
		SetVisualTreeRoot(m_contentHost);
	}

	// m_contentHost  m_contentElement ǉ
	if (m_contentElementModified)
	{
		m_contentHost->AddChild(m_contentElement);

		// vfc[ɓ̂ŃX^CXV
		m_contentHost->ApplyTemplateHierarchy(GetOwnerLayoutView()->GetOwnerContext()->GetRootStyleTable(), GetLocalStyle());
		m_contentElementModified = false;
	}
}

LN_NAMESPACE_END
<commit_msg>UIButton<commit_after>
#include "Internal.h"
#include <Lumino/UI/UIContext.h>		// TODO: Ȃ
#include <Lumino/UI/UILayoutView.h>		// TODO: Ȃ
#include <Lumino/UI/UIPanel.h>
#include <Lumino/UI/UIContentControl.h>

LN_NAMESPACE_BEGIN

//==============================================================================
// UIContentControl
//==============================================================================
LN_UI_TYPEINFO_IMPLEMENT(UIContentControl, UIElement);

//------------------------------------------------------------------------------
UIContentControl::UIContentControl()
	: m_contentHost(nullptr)
	, m_contentElement(nullptr)
	, m_contentElementModified(false)
{
}

//------------------------------------------------------------------------------
UIContentControl::~UIContentControl()
{
	LN_SAFE_RELEASE(m_contentElement);
	LN_SAFE_RELEASE(m_contentHost);
}

//------------------------------------------------------------------------------
void UIContentControl::Initialize(detail::UIManager* manager)
{
	UIControl::Initialize(manager);

	SetVerticalContentAlignment(VerticalAlignment::Stretch);
	SetHorizontalContentAlignment(HorizontalAlignment::Stretch);
}

//------------------------------------------------------------------------------
void UIContentControl::SetContent(UIElement* element)
{
	//  content ĂΎ菜Ă
	if (m_contentElement != nullptr && m_contentHost != nullptr)
	{
		m_contentHost->RemoveChild(m_contentElement);
		LN_SAFE_RELEASE(m_contentElement);
	}

	// V m_contentElement ێ
	LN_REFOBJ_SET(m_contentElement, element);
	if (m_contentElement != nullptr)
	{
		m_contentElementModified = true;
	}
}

//------------------------------------------------------------------------------
void UIContentControl::OnUpdatingLayout()
{
	// VisualTree ΒPȂ Panel  m_contentHost ƂĎgB
	// ̎_ VisualTree ƂƂ́AStyle łȂA
	// Style ̎ Template  Host ƂȂ Panel ܂܂ĂȂƂƁB
	if (GetVisualTreeRoot() == nullptr)
	{
		auto panel = RefPtr<UIPanel>::MakeRef();
		panel->Initialize(GetManager());

		// ContentAlignment ݒ
		panel->SetVerticalAlignment(GetVerticalContentAlignment());
		panel->SetHorizontalAlignment(GetHorizontalContentAlignment());

		m_contentHost = panel.DetachMove();
		SetVisualTreeRoot(m_contentHost);
	}

	// m_contentHost  m_contentElement ǉ
	if (m_contentElementModified)
	{
		m_contentHost->AddChild(m_contentElement);

		// vfc[ɓ̂ŃX^CXV
		m_contentHost->ApplyTemplateHierarchy(GetOwnerLayoutView()->GetOwnerContext()->GetRootStyleTable(), GetLocalStyle());
		m_contentElementModified = false;
	}

	UIElement::OnUpdatingLayout();
}

LN_NAMESPACE_END
<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
#if !defined(XALAN_STYLESHEETROOT_HEADER_GUARD)
#define XALAN_STYLESHEETROOT_HEADER_GUARD

// Base include file.  Must be first.
#include "XSLTDefinitions.hpp"

#include "Stylesheet.hpp"

#include <XalanDOM/XalanDOMString.hpp>

#include <PlatformSupport/FormatterListener.hpp>

class StylesheetConstructionContext;
class XSLTResultTarget;

/**
 * This acts as the stylesheet root of the stylesheet
 * tree, and holds values that are shared by all
 * stylesheets in the tree.
 */
class XALAN_XSLT_EXPORT StylesheetRoot : public Stylesheet
{
public:

	/**
	 * Construct a Stylesheet from a Document.
	 *
	 * @param baseIdentifier document identifier
	 * @param constructionContext context for construction of object
	 */
	StylesheetRoot(
        const XalanDOMString&			baseIdentifier,
		StylesheetConstructionContext&	constructionContext);

	virtual
	~StylesheetRoot();

	/**
	 * Called after construction is completed.
	 */
	virtual void
	postConstruction(StylesheetConstructionContext&		constructionContext);

	/**
	 * Transform the source tree to the output in the given result tree target.
	 *
	 * @param inputSource  The input source tree
	 * @param outputTarget The output source tree
	 * @param constructionContext context for construction of object
	 */
	void
	process(
			XalanNode*						sourceTree,
			XSLTResultTarget&				outputTarget,
			StylesheetExecutionContext&		executionContext) const;

	/**
	 * Have the stylesheet create the appropriate FormatterListener,
	 * based on the XSLTResultTarget provided.  setupFormatterListener
	 * also calls setFormatterListener() on the execution context
	 * instance.  setupFormatterListener() is done automatically by
	 * process(), but this is provided as an escape, to allow for
	 * changing the FormatterListener on-the-fly.
	 *
	 * @param outputTarget The output source tree
	 * @param constructionContext context for construction of object
	 * @return a pointer to the new FormatterListener instance.
	 */
	FormatterListener*
	setupFormatterListener(
			XSLTResultTarget&				outputTarget,
			StylesheetExecutionContext&		executionContext) const;

	/**
	 * Return the output method that was specified in the stylesheet.
	 * The returned value is one of FormatterLister::eFormat values.
	 *
	 * @return value of output method
	 */
	FormatterListener::eFormat
	getOutputMethod() const
	{
		return m_outputMethod;
	}

	bool
	isOutputMethodSet() const
	{
		return getOutputMethod() == FormatterListener::OUTPUT_METHOD_NONE ? false : true;
	}

	/**
	 * Get the output version string that was specified in the
	 * xsl:output element
	 *
	 * @return output version string
	 */
	XalanDOMString
	getOutputVersion() const
	{
		return m_version;
	}

	/**
	 * Determine if output indenting was specified in the
	 * xsl:output element
	 *
	 * @return true to indent
	 */
	bool
	getOutputIndent() const
	{
		return m_indentResult;
	}

	/**
	 * Get the output encoding string that was specified in the
	 * xsl:output element
	 *
	 * @return encoding string
	 */
	XalanDOMString
	getOutputEncoding() const
	{
		return m_encoding;
	}

	/**
	 * Get the media-type string that was specified in the
	 * xsl:output element
	 *
	 * @return media type string
	 */
	XalanDOMString
	getOutputMediaType() const
	{
		return m_mediatype;
	}

	/**
	 * Get the doctype-system-id string that was specified in the
	 * xsl:output element
	 *
	 * @return document type string
	 */
	XalanDOMString
	getOutputDoctypeSystem() const
	{
		return m_doctypeSystem;
	}

	/**
	 * Get the doctype-public-id string that was specified in the
	 * xsl:output element
	 *
	 * @return document type public id string
	 */
	XalanDOMString
	getOutputDoctypePublic() const
	{
		return m_doctypePublic;
	}

	/**
	 * Determine whether to output XML declarations.
	 *
	 * @return true to output declarations
	 */
	bool
	getOmitOutputXMLDecl() const
	{
		return m_omitxmlDecl;
	}

	/**
	 * Get the standalone string that was specified in the
	 * xsl:output element.(either "yes" or "no")
	 *
	 * @return standalone string
	 */
	XalanDOMString
	getOutputStandalone() const
	{
		return m_standalone;
	}

	/**
	 * Get the template representing the default rule for text.
	 *
	 * @return pointer to template rule for text
	 */
	ElemTemplate*
	getDefaultTextRule() const
	{
		return m_defaultTextRule;
	}

	/**
	 * Get the template representing the default rule.
	 *
	 * @return pointer to default template rule
	 */
	ElemTemplate*
	getDefaultRule() const
	{
		return m_defaultRule;
	}

	/**
	 * Get the template representing the default root rule.
	 *
	 * @return pointer to default root template rule
	 */
	ElemTemplate*
	getDefaultRootRule() const
	{
		return m_defaultRootRule;
	}

	/**
	 * Process the "xsl:output" element.
	 *
	 * @param name                name of element
	 * @param atts                attribute list for element
	 * @param constructionContext context for construction of object
	 */
	void
	processOutputSpec(
			const XalanDOMChar*				name,
			const AttributeList&			atts,
			StylesheetConstructionContext&	constructionContext);

	/**
	 * Create the default rule if needed.
	 *
	 * @param constructionContext context for construction of object
	 */
	void
	initDefaultRule(StylesheetConstructionContext&	constructionContext);

	/**
	 * The version tells the version of XML to be used for outputting the result tree,
	 * as specified in xsl:output.
	 */
	XalanDOMString	m_version;

	/**
	 * indent-result is by default no, which means an XSL processor must not
	 * change the whitespace on output.
	 */
	bool			m_indentResult;

	/**
	 * The encoding attribute specifies the preferred encoding to use
	 * for outputting the result tree.
	 */
	XalanDOMString	m_encoding;

	/**
	 * The media-type attribute is applicable for the xml output method.
	 * The default value for the media-type attribute is text/xml.
	 */
	XalanDOMString	m_mediatype;

	/**
	 * If the doctype-system-id attribute is specified, the xml output method should
	 * output a document type declaration immediately before the first element.
	 * The name following <!DOCTYPE should be the name of the first element.
	 */
	XalanDOMString	m_doctypeSystem;

	/**
	 * If doctype-public-id attribute is also specified, then the xml output
	 * method should output PUBLIC followed by the public identifier and then
	 * the system identifier; otherwise, it should output SYSTEM followed by
	 * the system identifier. The internal subset should be empty. The
	 * doctype-public-id attribute should be ignored unless the doctype-system-id
	 * attribute is specified.
	 */
	XalanDOMString	m_doctypePublic;

	/**
	 * Tells whether or not to output an XML declaration.
	 */
	bool			m_omitxmlDecl;

	/**
	 * Tells what the xmldecl should specify for the standalone value.
     */
	XalanDOMString	m_standalone;

	/**
	 * Retrieve the stack of imported stylesheets.
	 *
	 * @return stack of URIs for stylesheets
	 */
	URLStackType&
	getImportStack()
	{
		return m_importStack;
	}

	/**
	 * Retrieve the stack of imported stylesheets.
	 *
	 * @return const stack of URIs for stylesheets
	 */
	const URLStackType&
	getImportStack() const
	{
		return m_importStack;
	}

	/**
	 * Change the value of the flag for indenting results.
	 *
	 * @param bIndent true to indent results
	 */
	void
	setIndentResult(bool bIndent)
	{
		m_indentResult = bIndent;
	}

	/**
	 * Change the value of the output method, one of the
	 * FormatterListener::eFormat values.
	 *
	 * @param meth new method number
	 */
	void
	setOutputMethod(FormatterListener::eFormat	meth)
	{
		m_outputMethod = meth;
	}

	bool
	hasCDATASectionElements() const
	{
		assert(m_hasCdataSectionElems == false && m_cdataSectionElems.size() == 0 ||
			   m_hasCdataSectionElems == true && m_cdataSectionElems.size() != 0);

		return m_hasCdataSectionElems;
	}

	/**
	 * Determine if a QName is in the list of CDATA section
	 * element QNames.
	 *
	 * @param theQName The QName of the element to check.
	 * @return true or false
	 */
	bool
	isCDATASectionElementName(const XalanQName&		theQName) const;

	/**
	 * Given a valid element key, return the corresponding node list.
	 *
	 * @param doc			   source document
	 * @param name			   name of the key, which must match the 'name'
	 *						   attribute on xsl:key
	 * @param ref			   value that must match the value found by the
	 *						   'match' attribute on xsl:key
	 * @param resolver		   resolver for namespace resolution
	 * @param nodelist         A node list to contain the nodes found
	 * @param executionContext current execution context
	 */
	void
	getNodeSetByKey(
			XalanNode*						doc,
			const XalanDOMString&			name,
			const XalanDOMString&			ref,
			const PrefixResolver&			resolver,
			MutableNodeRefList&				nodelist,
			StylesheetExecutionContext&		executionContext,
			KeyTablesTableType&				theKeysTable) const;

private:

	/**
	 * The URL that belongs to the result namespace.
	 * @serial
	 */
	XalanDOMString				m_resultNameSpaceURL;

	/**
	 * The output method as specified in xsl:output.
	 */
	FormatterListener::eFormat	m_outputMethod;

	/**
	 * List of qnames that specifies elements that should be formatted
	 * as CDATA.
	 */
	QNameVectorType				m_cdataSectionElems;

	bool						m_hasCdataSectionElems;

	/**
	 * A stack of who's importing whom is needed in order to detect
	 * a recursive include or import, which is an error.
	 */
	URLStackType				m_importStack;

	/**
	 * The default template to use for text nodes if we don't find
	 * anything else.  This is initialized in initDefaultRule().
	 */
	ElemTemplate*				m_defaultTextRule;

	/**
	 * The default template to use if we don't find anything
	 * else.  This is initialized in initDefaultRule().
	 */
	ElemTemplate*				m_defaultRule;

	/**
	 * The default template to use for the root if we don't find
	 * anything else.  This is initialized in initDefaultRule().
	 */
	ElemTemplate*				m_defaultRootRule;

	/**
	 * This is set to true if an xsl:key directive is found.
	 */
	bool						m_needToBuildKeysTable;
};

#endif	// XALAN_STYLESHEETROOT_HEADER_GUARD
<commit_msg>Added private, unimplemented constructors and operators.<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
#if !defined(XALAN_STYLESHEETROOT_HEADER_GUARD)
#define XALAN_STYLESHEETROOT_HEADER_GUARD

// Base include file.  Must be first.
#include "XSLTDefinitions.hpp"

#include "Stylesheet.hpp"

#include <XalanDOM/XalanDOMString.hpp>

#include <PlatformSupport/FormatterListener.hpp>

class StylesheetConstructionContext;
class XSLTResultTarget;

/**
 * This acts as the stylesheet root of the stylesheet
 * tree, and holds values that are shared by all
 * stylesheets in the tree.
 */
class XALAN_XSLT_EXPORT StylesheetRoot : public Stylesheet
{
public:

	/**
	 * Construct a Stylesheet from a Document.
	 *
	 * @param baseIdentifier document identifier
	 * @param constructionContext context for construction of object
	 */
	StylesheetRoot(
        const XalanDOMString&			baseIdentifier,
		StylesheetConstructionContext&	constructionContext);

	virtual
	~StylesheetRoot();

	/**
	 * Called after construction is completed.
	 */
	virtual void
	postConstruction(StylesheetConstructionContext&		constructionContext);

	/**
	 * Transform the source tree to the output in the given result tree target.
	 *
	 * @param inputSource  The input source tree
	 * @param outputTarget The output source tree
	 * @param constructionContext context for construction of object
	 */
	void
	process(
			XalanNode*						sourceTree,
			XSLTResultTarget&				outputTarget,
			StylesheetExecutionContext&		executionContext) const;

	/**
	 * Have the stylesheet create the appropriate FormatterListener,
	 * based on the XSLTResultTarget provided.  setupFormatterListener
	 * also calls setFormatterListener() on the execution context
	 * instance.  setupFormatterListener() is done automatically by
	 * process(), but this is provided as an escape, to allow for
	 * changing the FormatterListener on-the-fly.
	 *
	 * @param outputTarget The output source tree
	 * @param constructionContext context for construction of object
	 * @return a pointer to the new FormatterListener instance.
	 */
	FormatterListener*
	setupFormatterListener(
			XSLTResultTarget&				outputTarget,
			StylesheetExecutionContext&		executionContext) const;

	/**
	 * Return the output method that was specified in the stylesheet.
	 * The returned value is one of FormatterLister::eFormat values.
	 *
	 * @return value of output method
	 */
	FormatterListener::eFormat
	getOutputMethod() const
	{
		return m_outputMethod;
	}

	bool
	isOutputMethodSet() const
	{
		return getOutputMethod() == FormatterListener::OUTPUT_METHOD_NONE ? false : true;
	}

	/**
	 * Get the output version string that was specified in the
	 * xsl:output element
	 *
	 * @return output version string
	 */
	XalanDOMString
	getOutputVersion() const
	{
		return m_version;
	}

	/**
	 * Determine if output indenting was specified in the
	 * xsl:output element
	 *
	 * @return true to indent
	 */
	bool
	getOutputIndent() const
	{
		return m_indentResult;
	}

	/**
	 * Get the output encoding string that was specified in the
	 * xsl:output element
	 *
	 * @return encoding string
	 */
	XalanDOMString
	getOutputEncoding() const
	{
		return m_encoding;
	}

	/**
	 * Get the media-type string that was specified in the
	 * xsl:output element
	 *
	 * @return media type string
	 */
	XalanDOMString
	getOutputMediaType() const
	{
		return m_mediatype;
	}

	/**
	 * Get the doctype-system-id string that was specified in the
	 * xsl:output element
	 *
	 * @return document type string
	 */
	XalanDOMString
	getOutputDoctypeSystem() const
	{
		return m_doctypeSystem;
	}

	/**
	 * Get the doctype-public-id string that was specified in the
	 * xsl:output element
	 *
	 * @return document type public id string
	 */
	XalanDOMString
	getOutputDoctypePublic() const
	{
		return m_doctypePublic;
	}

	/**
	 * Determine whether to output XML declarations.
	 *
	 * @return true to output declarations
	 */
	bool
	getOmitOutputXMLDecl() const
	{
		return m_omitxmlDecl;
	}

	/**
	 * Get the standalone string that was specified in the
	 * xsl:output element.(either "yes" or "no")
	 *
	 * @return standalone string
	 */
	XalanDOMString
	getOutputStandalone() const
	{
		return m_standalone;
	}

	/**
	 * Get the template representing the default rule for text.
	 *
	 * @return pointer to template rule for text
	 */
	ElemTemplate*
	getDefaultTextRule() const
	{
		return m_defaultTextRule;
	}

	/**
	 * Get the template representing the default rule.
	 *
	 * @return pointer to default template rule
	 */
	ElemTemplate*
	getDefaultRule() const
	{
		return m_defaultRule;
	}

	/**
	 * Get the template representing the default root rule.
	 *
	 * @return pointer to default root template rule
	 */
	ElemTemplate*
	getDefaultRootRule() const
	{
		return m_defaultRootRule;
	}

	/**
	 * Process the "xsl:output" element.
	 *
	 * @param name                name of element
	 * @param atts                attribute list for element
	 * @param constructionContext context for construction of object
	 */
	void
	processOutputSpec(
			const XalanDOMChar*				name,
			const AttributeList&			atts,
			StylesheetConstructionContext&	constructionContext);

	/**
	 * Create the default rule if needed.
	 *
	 * @param constructionContext context for construction of object
	 */
	void
	initDefaultRule(StylesheetConstructionContext&	constructionContext);

	/**
	 * The version tells the version of XML to be used for outputting the result tree,
	 * as specified in xsl:output.
	 */
	XalanDOMString	m_version;

	/**
	 * indent-result is by default no, which means an XSL processor must not
	 * change the whitespace on output.
	 */
	bool			m_indentResult;

	/**
	 * The encoding attribute specifies the preferred encoding to use
	 * for outputting the result tree.
	 */
	XalanDOMString	m_encoding;

	/**
	 * The media-type attribute is applicable for the xml output method.
	 * The default value for the media-type attribute is text/xml.
	 */
	XalanDOMString	m_mediatype;

	/**
	 * If the doctype-system-id attribute is specified, the xml output method should
	 * output a document type declaration immediately before the first element.
	 * The name following <!DOCTYPE should be the name of the first element.
	 */
	XalanDOMString	m_doctypeSystem;

	/**
	 * If doctype-public-id attribute is also specified, then the xml output
	 * method should output PUBLIC followed by the public identifier and then
	 * the system identifier; otherwise, it should output SYSTEM followed by
	 * the system identifier. The internal subset should be empty. The
	 * doctype-public-id attribute should be ignored unless the doctype-system-id
	 * attribute is specified.
	 */
	XalanDOMString	m_doctypePublic;

	/**
	 * Tells whether or not to output an XML declaration.
	 */
	bool			m_omitxmlDecl;

	/**
	 * Tells what the xmldecl should specify for the standalone value.
     */
	XalanDOMString	m_standalone;

	/**
	 * Retrieve the stack of imported stylesheets.
	 *
	 * @return stack of URIs for stylesheets
	 */
	URLStackType&
	getImportStack()
	{
		return m_importStack;
	}

	/**
	 * Retrieve the stack of imported stylesheets.
	 *
	 * @return const stack of URIs for stylesheets
	 */
	const URLStackType&
	getImportStack() const
	{
		return m_importStack;
	}

	/**
	 * Change the value of the flag for indenting results.
	 *
	 * @param bIndent true to indent results
	 */
	void
	setIndentResult(bool bIndent)
	{
		m_indentResult = bIndent;
	}

	/**
	 * Change the value of the output method, one of the
	 * FormatterListener::eFormat values.
	 *
	 * @param meth new method number
	 */
	void
	setOutputMethod(FormatterListener::eFormat	meth)
	{
		m_outputMethod = meth;
	}

	bool
	hasCDATASectionElements() const
	{
		assert(m_hasCdataSectionElems == false && m_cdataSectionElems.size() == 0 ||
			   m_hasCdataSectionElems == true && m_cdataSectionElems.size() != 0);

		return m_hasCdataSectionElems;
	}

	/**
	 * Determine if a QName is in the list of CDATA section
	 * element QNames.
	 *
	 * @param theQName The QName of the element to check.
	 * @return true or false
	 */
	bool
	isCDATASectionElementName(const XalanQName&		theQName) const;

	/**
	 * Given a valid element key, return the corresponding node list.
	 *
	 * @param doc			   source document
	 * @param name			   name of the key, which must match the 'name'
	 *						   attribute on xsl:key
	 * @param ref			   value that must match the value found by the
	 *						   'match' attribute on xsl:key
	 * @param resolver		   resolver for namespace resolution
	 * @param nodelist         A node list to contain the nodes found
	 * @param executionContext current execution context
	 */
	void
	getNodeSetByKey(
			XalanNode*						doc,
			const XalanDOMString&			name,
			const XalanDOMString&			ref,
			const PrefixResolver&			resolver,
			MutableNodeRefList&				nodelist,
			StylesheetExecutionContext&		executionContext,
			KeyTablesTableType&				theKeysTable) const;

private:

	/**
	 * The URL that belongs to the result namespace.
	 * @serial
	 */
	XalanDOMString				m_resultNameSpaceURL;

	/**
	 * The output method as specified in xsl:output.
	 */
	FormatterListener::eFormat	m_outputMethod;

	/**
	 * List of qnames that specifies elements that should be formatted
	 * as CDATA.
	 */
	QNameVectorType				m_cdataSectionElems;

	bool						m_hasCdataSectionElems;

	/**
	 * A stack of who's importing whom is needed in order to detect
	 * a recursive include or import, which is an error.
	 */
	URLStackType				m_importStack;

	/**
	 * The default template to use for text nodes if we don't find
	 * anything else.  This is initialized in initDefaultRule().
	 */
	ElemTemplate*				m_defaultTextRule;

	/**
	 * The default template to use if we don't find anything
	 * else.  This is initialized in initDefaultRule().
	 */
	ElemTemplate*				m_defaultRule;

	/**
	 * The default template to use for the root if we don't find
	 * anything else.  This is initialized in initDefaultRule().
	 */
	ElemTemplate*				m_defaultRootRule;

	/**
	 * This is set to true if an xsl:key directive is found.
	 */
	bool						m_needToBuildKeysTable;

    // Not implemented...
    StylesheetRoot(const StylesheetRoot&);

    StylesheetRoot&
    operator=(const StylesheetRoot&);

    bool
    operator==(const StylesheetRoot&) const;
};

#endif	// XALAN_STYLESHEETROOT_HEADER_GUARD
<|endoftext|>


<commit_before>#ifndef CDM_BOOST_HPP
#define CDM_BOOST_HPP

#include <silicium/file_operations.hpp>
#include <silicium/run_process.hpp>
#include <boost/lexical_cast.hpp>

namespace cdm
{
	struct boost_paths
	{
		Si::absolute_path root;
	};

	inline boost_paths install_boost(
		Si::absolute_path const &source,
		Si::absolute_path const &temporary,
		Si::absolute_path const &install_root,
		Si::absolute_path const &cmake_exe,
		unsigned make_parallelism,
		Si::Sink<char, Si::success>::interface &output)
	{
		boost::ignore_unused_variable_warning(cmake_exe);

		Si::absolute_path const module_in_cache = install_root / Si::relative_path("boost");
		if (!Si::file_exists(module_in_cache, Si::throw_))
		{
			Si::absolute_path const copy_of_boost = temporary / Si::relative_path("boost-copy");
			Si::copy_recursively(source, copy_of_boost, &output, Si::throw_);

			{
				std::vector<Si::os_string> arguments;
				arguments.push_back(SILICIUM_SYSTEM_LITERAL("bash"));
				arguments.push_back(Si::to_os_string(copy_of_boost / "bootstrap.sh"));
				arguments.push_back(SILICIUM_SYSTEM_LITERAL("--prefix=") + Si::to_os_string(module_in_cache));
				int const rc = Si::run_process(*Si::absolute_path::create("/usr/bin/env"), arguments, copy_of_boost, output).get();
				if (rc != 0)
				{
					throw std::runtime_error("bootstrap failed");
				}
			}

			{
				std::vector<Si::os_string> arguments;
				arguments.push_back(SILICIUM_SYSTEM_LITERAL("-j ") + boost::lexical_cast<Si::os_string>(make_parallelism));
				arguments.push_back(SILICIUM_SYSTEM_LITERAL("install"));
				int const rc = Si::run_process(copy_of_boost / "b2", arguments, copy_of_boost, output).get();
				if (rc != 0)
				{
					throw std::runtime_error("b2 failed");
				}
			}
		}
		boost_paths result;
		result.root = module_in_cache;
		return result;
	}
}

#endif
<commit_msg>travis: avoid overly long output when copying Boost<commit_after>#ifndef CDM_BOOST_HPP
#define CDM_BOOST_HPP

#include <silicium/file_operations.hpp>
#include <silicium/run_process.hpp>
#include <boost/lexical_cast.hpp>

namespace cdm
{
	struct boost_paths
	{
		Si::absolute_path root;
	};

	inline boost_paths install_boost(
		Si::absolute_path const &source,
		Si::absolute_path const &temporary,
		Si::absolute_path const &install_root,
		Si::absolute_path const &cmake_exe,
		unsigned make_parallelism,
		Si::Sink<char, Si::success>::interface &output)
	{
		boost::ignore_unused_variable_warning(cmake_exe);

		Si::absolute_path const module_in_cache = install_root / Si::relative_path("boost");
		if (!Si::file_exists(module_in_cache, Si::throw_))
		{
			Si::absolute_path const copy_of_boost = temporary / Si::relative_path("boost-copy");
			Si::copy_recursively(
				source, copy_of_boost,
#ifdef CDM_TESTS_RUNNING_ON_TRAVIS_CI
				//Boost is so large that the output of cp exceeds the 4 MB log limit of travis
				//which aborts the build job then.
				nullptr
#else
				&output
#endif
				, Si::throw_);

			{
				std::vector<Si::os_string> arguments;
				arguments.push_back(SILICIUM_SYSTEM_LITERAL("bash"));
				arguments.push_back(Si::to_os_string(copy_of_boost / "bootstrap.sh"));
				arguments.push_back(SILICIUM_SYSTEM_LITERAL("--prefix=") + Si::to_os_string(module_in_cache));
				int const rc = Si::run_process(*Si::absolute_path::create("/usr/bin/env"), arguments, copy_of_boost, output).get();
				if (rc != 0)
				{
					throw std::runtime_error("bootstrap failed");
				}
			}

			{
				std::vector<Si::os_string> arguments;
				arguments.push_back(SILICIUM_SYSTEM_LITERAL("-j ") + boost::lexical_cast<Si::os_string>(make_parallelism));
				arguments.push_back(SILICIUM_SYSTEM_LITERAL("install"));
				int const rc = Si::run_process(copy_of_boost / "b2", arguments, copy_of_boost, output).get();
				if (rc != 0)
				{
					throw std::runtime_error("b2 failed");
				}
			}
		}
		boost_paths result;
		result.root = module_in_cache;
		return result;
	}
}

#endif
<|endoftext|>


<commit_before>/*
**
** Copyright (C) 2012 Aldebaran Robotics
*/

#include <map>
#include <gtest/gtest.h>
#include <qi/qi.hpp>
#include <qi/application.hpp>
#include <qitype/anyobject.hpp>
#include <qitype/dynamicobjectbuilder.hpp>
#include <qi/atomic.hpp>
#include <qimessaging/session.hpp>

#include <testsession/testsessionpair.hpp>

qiLogCategory("test");

/*
 * Bound object do not have the same event id as "raw" object.
 * BoundObject add an offset of 10.
 *
 * So we take both id, the local and the remote one.
 */

static qi::Promise<int> *payload1;
qi::Atomic<int> i = 0;

void onFire1(const int& pl)
{
  std::cout << "onFire:" << pl << std::endl;
  std::cout.flush();
  payload1->setValue(pl);
}

static qi::Promise<int> *payload2;

void onFire2(const int& pl)
{
  std::cout << "onFire2:" << pl << std::endl;
  std::cout.flush();
  payload2->setValue(pl);
}

void callbackCounter(const int& value)
{
  ++i;
  std::cout << "callback called " << i._value <<" times" << std::endl;
}

void callbackCounterBis(const int& value, std::string secondValue)
{
  ++i;
  std::cout << "callback called " << i._value <<" times" << std::endl;
}

class TestObject: public ::testing::Test
{
public:
  TestObject() : p2(p1)
  {
    qi::DynamicObjectBuilder obs1, obs2;
    se1 = obs1.advertiseSignal<const int&>("fire1");
    se2 = obs2.advertiseSignal<const int&>("fire2");
    sm1 = obs1.advertiseMethod("onFire1", &onFire1);
    callbackId = obs1.advertiseMethod("callbackCounter", &callbackCounter);
    secondCallbackId = obs1.advertiseMethod("callbackCounter", &callbackCounterBis);
    sm2 = obs2.advertiseMethod("onFire2", &onFire2);
    oserver1 = obs1.object();
    oserver2 = obs2.object();
  }

protected:
  void SetUp()
  {
    // Two objects with a fire event and a onFire method.
    unsigned int nbLocalServices = TestMode::getTestMode() == TestMode::Mode_Nightmare ? 2 : 1;
    unsigned int nbConnectedServices = TestMode::getTestMode() == TestMode::Mode_Nightmare ? 5 : 3;

    ASSERT_TRUE(p1.server()->registerService("coin1", oserver1).hasValue(1000));
    ASSERT_TRUE(p2.server()->registerService("coin2", oserver2).hasValue(1000));
    EXPECT_EQ(nbLocalServices, p1.server()->services(qi::Session::ServiceLocality_Local).value().size());
    EXPECT_EQ(nbLocalServices, p2.server()->services(qi::Session::ServiceLocality_Local).value().size());

    std::vector<qi::ServiceInfo> services = p1.client()->services();
    EXPECT_EQ(nbConnectedServices, services.size());
    services = p2.client()->services();
    EXPECT_EQ(nbConnectedServices, services.size());

    qi::Future<qi::AnyObject> fut;
    fut = p2.client()->service("coin1");
    ASSERT_FALSE(fut.hasError());
    oclient1 = fut.value();

    fut = p1.client()->service("coin2");
    ASSERT_FALSE(fut.hasError());

    oclient2 = fut.value();

    oe1 = oclient1.metaObject().signalId("fire1::(i)");
    oe2 = oclient2.metaObject().signalId("fire2::(i)");
    qiLogDebug() << "Object E1:" << oe1 << " - Server E1:" << se1;
    qiLogDebug() << "Object E2:" << oe2 << " - Server E2:" << se2;
    ASSERT_TRUE(oe1 >= 10 && oe1 < 1000);
    ASSERT_TRUE(oe2 >= 10 && oe2 < 1000);

    om1 = oclient1.metaObject().methodId("onFire1::(i)");
    om2 = oclient2.metaObject().methodId("onFire2::(i)");
    qiLogDebug() << "Object M1:" << om1 << " - Server M1:" << sm1;
    qiLogDebug() << "Object M2:" << om2 << " - Server M2:" << sm2;
    ASSERT_TRUE(om1 >= 10 && om1 < 1000);
    ASSERT_TRUE(om2 >= 10 && om2 < 1000);

    payload1 = &prom1;
    payload2 = &prom2;
  }

  void TearDown()
  {
    payload1 = payload2 = 0;
  }

public:
  unsigned int se1, se2;
  unsigned int sm1, sm2;
  unsigned int callbackId, secondCallbackId;

  unsigned int oe1, oe2;
  unsigned int om1, om2;

  qi::Promise<int>     prom1, prom2;
  TestSessionPair      p1;
  TestSessionPair      p2;
  qi::AnyObject        oserver1, oserver2;
  qi::AnyObject        oclient1, oclient2;
};

// We try to test all possible combinations of where we connect, where we emit.

TEST_F(TestObject, Connect1)
{
  oclient1.connect(oe1, oclient1, om1).wait(2000);
  oclient1.post("fire1", 12);
  ASSERT_TRUE(payload1->future().hasValue(2000));
  EXPECT_EQ(12, payload1->future().value());
}

TEST_F(TestObject, Connect2)
{
  oclient1.connect(oe1, oclient1, om1).wait(2000);
  oserver1.post("fire1", 12);
  ASSERT_TRUE(payload1->future().hasValue(2000));
  EXPECT_EQ(12, payload1->future().value());
}

TEST_F(TestObject, Connect3)
{
  oclient1.connect(oe1, oserver1, sm1).wait(2000);
  oserver1.post("fire1", 12);
  ASSERT_TRUE(payload1->future().hasValue(2000));
  EXPECT_EQ(12, payload1->future().value());
}

TEST_F(TestObject, Connect4)
{
  oclient1.connect(oe1, oserver1, sm1).wait(2000);
  oclient1.post("fire1", 12);
  ASSERT_TRUE(payload1->future().hasValue(2000));
  EXPECT_EQ(12, payload1->future().value());
}

TEST_F(TestObject, Connect5)
{
  oserver1.connect(se1, oclient1, om1).wait(2000);
  oclient1.post("fire1", 12);
  ASSERT_TRUE(payload1->future().hasValue(2000));
  EXPECT_EQ(12, payload1->future().value());
}

TEST_F(TestObject, Connect6)
{
  oserver1.connect(se1, oclient1, om1).wait(2000);
  oserver1.post("fire1", 12);
  ASSERT_TRUE(payload1->future().hasValue(2000));
  EXPECT_EQ(12, payload1->future().value());
}

TEST_F(TestObject, Connect7)
{
  oserver1.connect(se1, oserver1, sm1).wait(2000);
  oserver1.post("fire1", 12);
  ASSERT_TRUE(payload1->future().hasValue(2000));
  EXPECT_EQ(12, payload1->future().value());
}

TEST_F(TestObject, Connect8)
{
  oserver1.connect(se1, oserver1, sm1).wait(2000);
  oclient1.post("fire1", 12);
  ASSERT_TRUE(payload1->future().hasValue(2000));
  EXPECT_EQ(12, payload1->future().value());
}

TEST_F(TestObject, Connect10)
{
  oclient1.connect(oe1, oclient2, om2).wait(2000);
  oclient1.post("fire1", 12);
  ASSERT_TRUE(payload2->future().hasValue(2000));
  EXPECT_EQ(12, payload2->future().value());
}

TEST_F(TestObject, Connect11)
{
  oclient1.connect(oe1, oclient2, om2).wait(2000);
  oserver1.post("fire1", 12);
  ASSERT_TRUE(payload2->future().hasValue(2000));
  EXPECT_EQ(12, payload2->future().value());
}

TEST_F(TestObject, Connect12)
{
  oclient1.connect(oe1, oserver2, sm2).wait(2000);
  oserver1.post("fire1", 12);
  ASSERT_TRUE(payload2->future().hasValue(2000));
  EXPECT_EQ(12, payload2->future().value());
}

TEST_F(TestObject, Connect13)
{
  oclient1.connect(oe1, oserver2, sm2).wait(2000);
  oclient1.post("fire1", 12);
  ASSERT_TRUE(payload2->future().hasValue(2000));
  EXPECT_EQ(12, payload2->future().value());
}

TEST_F(TestObject, Connect14)
{
  oserver1.connect(se1, oclient2, om2).wait(2000);
  oclient1.post("fire1", 12);
  ASSERT_TRUE(payload2->future().hasValue(2000));
  EXPECT_EQ(12, payload2->future().value());
}

TEST_F(TestObject, Connect15)
{
  oserver1.connect(se1, oclient2, om2).wait(2000);
  oserver1.post("fire1", 12);
  ASSERT_TRUE(payload2->future().hasValue(2000));
  EXPECT_EQ(12, payload2->future().value());
}

TEST_F(TestObject, Connect16)
{
  oserver1.connect(se1, oserver2, sm2).wait(2000);
  oserver1.post("fire1", 12);
  ASSERT_TRUE(payload2->future().hasValue(2000));
  EXPECT_EQ(12, payload2->future().value());
}

TEST_F(TestObject, Connect17)
{
  oserver1.connect(se1, oserver2, sm2).wait(2000);
  oclient1.post("fire1", 12);
  ASSERT_TRUE(payload2->future().hasValue(2000));
  EXPECT_EQ(12, payload2->future().value());
}

TEST_F(TestObject, multipleConnect)
{
  int additional_timeout = 5;//time to wait after having received the correct number of callbacks
  qi::SignalLink link1 = oclient2.connect(se2, oserver1, callbackId).value(2000);
  qi::SignalLink link2 = oclient2.connect(se2, oserver1, callbackId).value(2000);
  qi::SignalLink link3 = oclient2.connect(se2, oserver1, callbackId).value(2000);
  qi::SignalLink link4 = oclient2.connect(se2, oserver1, callbackId).value(2000);

  ASSERT_NE(link1, link2);
  ASSERT_NE(link2, link3);
  ASSERT_NE(link3, link4);

  oclient2.post("fire2", 42);
  oclient2.post("fire2", 42);

  int waiting_time = 0;
  while(i._value != 8 && waiting_time < 10000)//waiting 10 seconds max
  {
    qi::os::msleep(additional_timeout); //additional timeout to wait for unwanted callback
    waiting_time += additional_timeout;
  }
  qi::os::msleep(additional_timeout);
  ASSERT_EQ(i._value, 8);

  //disconnect 3/4 callbacks
  oclient2.disconnect(link2);
  oclient2.disconnect(link3);
  oclient2.disconnect(link4);

  oclient2.post("fire2", 42);//post signal twice
  oclient2.post("fire2", 42);

  while(i._value != 10 && waiting_time < 10000)//waiting 10 seconds max
  {
    qi::os::msleep(additional_timeout); //additional timeout to wait for unwanted callback
    waiting_time += additional_timeout;
  }
  qi::os::msleep(additional_timeout); //additional timeout to wait for unwanted callback
  ASSERT_EQ(i._value, 10);
  //i = 0;

  //reconnect callbacks
  link2 = oclient2.connect(se2, oserver1, callbackId).value(2000);
  link3 = oclient2.connect(se2, oserver1, callbackId).value(2000);
  link4 = oclient2.connect(se2, oserver1, callbackId).value(2000);

  oclient2.post("fire2", 42);//post signal twice
  oclient2.post("fire2", 42);

  while((*i) != 10 && waiting_time < 10000)//waiting 10 seconds max
  {
    qi::os::msleep(additional_timeout); //additional timeout to wait for unwanted callback
    waiting_time += additional_timeout;
  }
  qi::os::msleep(additional_timeout); //additional timeout to wait for unwanted callback
  ASSERT_EQ(*i, 18);

  oclient2.disconnect(link1);
  oclient2.disconnect(link2);
  oclient2.disconnect(link3);
  oclient2.disconnect(link4);

  oclient2.post("fire2", 42);

  qi::os::msleep(additional_timeout); //additional timeout to wait for unwanted callback
  ASSERT_EQ(*i, 18);

}

int main(int argc, char *argv[])
{
#if defined(__APPLE__) || defined(__linux__)
  setsid();
#endif
  qi::Application app(argc, argv);
  TestMode::initTestMode(argc, argv);
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}
<commit_msg>test special case of event ServiceAdded<commit_after>/*
**
** Copyright (C) 2012 Aldebaran Robotics
*/

#include <map>
#include <gtest/gtest.h>
#include <qi/qi.hpp>
#include <qi/application.hpp>
#include <qitype/anyobject.hpp>
#include <qitype/dynamicobjectbuilder.hpp>
#include <qi/atomic.hpp>
#include <qimessaging/session.hpp>

#include <testsession/testsessionpair.hpp>

qiLogCategory("test");

/*
 * Bound object do not have the same event id as "raw" object.
 * BoundObject add an offset of 10.
 *
 * So we take both id, the local and the remote one.
 */

static qi::Promise<int> *payload1;
qi::Atomic<int> i = 0;

void onFire1(const int& pl)
{
  std::cout << "onFire:" << pl << std::endl;
  std::cout.flush();
  payload1->setValue(pl);
}

static qi::Promise<int> *payload2;

void onFire2(const int& pl)
{
  std::cout << "onFire2:" << pl << std::endl;
  std::cout.flush();
  payload2->setValue(pl);
}

void callbackCounter(const int& value)
{
  ++i;
  std::cout << "callback called " << i._value <<" times" << std::endl;
}

void callbackCounterBis(const int& value, std::string secondValue)
{
  ++i;
  std::cout << "callback called " << *i <<" times" << std::endl;
}

class TestObject: public ::testing::Test
{
public:
  TestObject() : p2(p1)
  {
    qi::DynamicObjectBuilder obs1, obs2;
    se1 = obs1.advertiseSignal<const int&>("fire1");
    se2 = obs2.advertiseSignal<const int&>("fire2");
    sm1 = obs1.advertiseMethod("onFire1", &onFire1);
    callbackId = obs1.advertiseMethod("callbackCounter", &callbackCounter);
    secondCallbackId = obs1.advertiseMethod("callbackCounter", &callbackCounterBis);
    sm2 = obs2.advertiseMethod("onFire2", &onFire2);
    oserver1 = obs1.object();
    oserver2 = obs2.object();
  }

protected:
  void SetUp()
  {
    // Two objects with a fire event and a onFire method.
    unsigned int nbLocalServices = TestMode::getTestMode() == TestMode::Mode_Nightmare ? 2 : 1;
    unsigned int nbConnectedServices = TestMode::getTestMode() == TestMode::Mode_Nightmare ? 5 : 3;

    ASSERT_TRUE(p1.server()->registerService("coin1", oserver1).hasValue(1000));
    ASSERT_TRUE(p2.server()->registerService("coin2", oserver2).hasValue(1000));
    EXPECT_EQ(nbLocalServices, p1.server()->services(qi::Session::ServiceLocality_Local).value().size());
    EXPECT_EQ(nbLocalServices, p2.server()->services(qi::Session::ServiceLocality_Local).value().size());

    std::vector<qi::ServiceInfo> services = p1.client()->services();
    EXPECT_EQ(nbConnectedServices, services.size());
    services = p2.client()->services();
    EXPECT_EQ(nbConnectedServices, services.size());

    qi::Future<qi::AnyObject> fut;
    fut = p2.client()->service("coin1");
    ASSERT_FALSE(fut.hasError());
    oclient1 = fut.value();

    fut = p1.client()->service("coin2");
    ASSERT_FALSE(fut.hasError());

    oclient2 = fut.value();

    oe1 = oclient1.metaObject().signalId("fire1::(i)");
    oe2 = oclient2.metaObject().signalId("fire2::(i)");
    qiLogDebug() << "Object E1:" << oe1 << " - Server E1:" << se1;
    qiLogDebug() << "Object E2:" << oe2 << " - Server E2:" << se2;
    ASSERT_TRUE(oe1 >= 10 && oe1 < 1000);
    ASSERT_TRUE(oe2 >= 10 && oe2 < 1000);

    om1 = oclient1.metaObject().methodId("onFire1::(i)");
    om2 = oclient2.metaObject().methodId("onFire2::(i)");
    qiLogDebug() << "Object M1:" << om1 << " - Server M1:" << sm1;
    qiLogDebug() << "Object M2:" << om2 << " - Server M2:" << sm2;
    ASSERT_TRUE(om1 >= 10 && om1 < 1000);
    ASSERT_TRUE(om2 >= 10 && om2 < 1000);

    payload1 = &prom1;
    payload2 = &prom2;
  }

  void TearDown()
  {
    payload1 = payload2 = 0;
  }

public:
  unsigned int se1, se2;
  unsigned int sm1, sm2;
  unsigned int callbackId, secondCallbackId;

  unsigned int oe1, oe2;
  unsigned int om1, om2;

  qi::Promise<int>     prom1, prom2;
  TestSessionPair      p1;
  TestSessionPair      p2;
  qi::AnyObject        oserver1, oserver2;
  qi::AnyObject        oclient1, oclient2;
};

// We try to test all possible combinations of where we connect, where we emit.

TEST_F(TestObject, Connect1)
{
  oclient1.connect(oe1, oclient1, om1).wait(2000);
  oclient1.post("fire1", 12);
  ASSERT_TRUE(payload1->future().hasValue(2000));
  EXPECT_EQ(12, payload1->future().value());
}

TEST_F(TestObject, Connect2)
{
  oclient1.connect(oe1, oclient1, om1).wait(2000);
  oserver1.post("fire1", 12);
  ASSERT_TRUE(payload1->future().hasValue(2000));
  EXPECT_EQ(12, payload1->future().value());
}

TEST_F(TestObject, Connect3)
{
  oclient1.connect(oe1, oserver1, sm1).wait(2000);
  oserver1.post("fire1", 12);
  ASSERT_TRUE(payload1->future().hasValue(2000));
  EXPECT_EQ(12, payload1->future().value());
}

TEST_F(TestObject, Connect4)
{
  oclient1.connect(oe1, oserver1, sm1).wait(2000);
  oclient1.post("fire1", 12);
  ASSERT_TRUE(payload1->future().hasValue(2000));
  EXPECT_EQ(12, payload1->future().value());
}

TEST_F(TestObject, Connect5)
{
  oserver1.connect(se1, oclient1, om1).wait(2000);
  oclient1.post("fire1", 12);
  ASSERT_TRUE(payload1->future().hasValue(2000));
  EXPECT_EQ(12, payload1->future().value());
}

TEST_F(TestObject, Connect6)
{
  oserver1.connect(se1, oclient1, om1).wait(2000);
  oserver1.post("fire1", 12);
  ASSERT_TRUE(payload1->future().hasValue(2000));
  EXPECT_EQ(12, payload1->future().value());
}

TEST_F(TestObject, Connect7)
{
  oserver1.connect(se1, oserver1, sm1).wait(2000);
  oserver1.post("fire1", 12);
  ASSERT_TRUE(payload1->future().hasValue(2000));
  EXPECT_EQ(12, payload1->future().value());
}

TEST_F(TestObject, Connect8)
{
  oserver1.connect(se1, oserver1, sm1).wait(2000);
  oclient1.post("fire1", 12);
  ASSERT_TRUE(payload1->future().hasValue(2000));
  EXPECT_EQ(12, payload1->future().value());
}

TEST_F(TestObject, Connect10)
{
  oclient1.connect(oe1, oclient2, om2).wait(2000);
  oclient1.post("fire1", 12);
  ASSERT_TRUE(payload2->future().hasValue(2000));
  EXPECT_EQ(12, payload2->future().value());
}

TEST_F(TestObject, Connect11)
{
  oclient1.connect(oe1, oclient2, om2).wait(2000);
  oserver1.post("fire1", 12);
  ASSERT_TRUE(payload2->future().hasValue(2000));
  EXPECT_EQ(12, payload2->future().value());
}

TEST_F(TestObject, Connect12)
{
  oclient1.connect(oe1, oserver2, sm2).wait(2000);
  oserver1.post("fire1", 12);
  ASSERT_TRUE(payload2->future().hasValue(2000));
  EXPECT_EQ(12, payload2->future().value());
}

TEST_F(TestObject, Connect13)
{
  oclient1.connect(oe1, oserver2, sm2).wait(2000);
  oclient1.post("fire1", 12);
  ASSERT_TRUE(payload2->future().hasValue(2000));
  EXPECT_EQ(12, payload2->future().value());
}

TEST_F(TestObject, Connect14)
{
  oserver1.connect(se1, oclient2, om2).wait(2000);
  oclient1.post("fire1", 12);
  ASSERT_TRUE(payload2->future().hasValue(2000));
  EXPECT_EQ(12, payload2->future().value());
}

TEST_F(TestObject, Connect15)
{
  oserver1.connect(se1, oclient2, om2).wait(2000);
  oserver1.post("fire1", 12);
  ASSERT_TRUE(payload2->future().hasValue(2000));
  EXPECT_EQ(12, payload2->future().value());
}

TEST_F(TestObject, Connect16)
{
  oserver1.connect(se1, oserver2, sm2).wait(2000);
  oserver1.post("fire1", 12);
  ASSERT_TRUE(payload2->future().hasValue(2000));
  EXPECT_EQ(12, payload2->future().value());
}

TEST_F(TestObject, Connect17)
{
  oserver1.connect(se1, oserver2, sm2).wait(2000);
  oclient1.post("fire1", 12);
  ASSERT_TRUE(payload2->future().hasValue(2000));
  EXPECT_EQ(12, payload2->future().value());
}

TEST_F(TestObject, multipleConnect)
{
  int additional_timeout = 5;//time to wait after having received the correct number of callbacks
  qi::SignalLink link1 = oclient2.connect(se2, oserver1, callbackId).value(2000);
  qi::SignalLink link2 = oclient2.connect(se2, oserver1, callbackId).value(2000);
  qi::SignalLink link3 = oclient2.connect(se2, oserver1, callbackId).value(2000);
  qi::SignalLink link4 = oclient2.connect(se2, oserver1, callbackId).value(2000);

  ASSERT_NE(link1, link2);
  ASSERT_NE(link2, link3);
  ASSERT_NE(link3, link4);

  oclient2.post("fire2", 42);
  oclient2.post("fire2", 42);

  int waiting_time = 0;
  while(i._value != 8 && waiting_time < 10000)//waiting 10 seconds max
  {
    qi::os::msleep(additional_timeout); //additional timeout to wait for unwanted callback
    waiting_time += additional_timeout;
  }
  qi::os::msleep(additional_timeout);
  ASSERT_EQ(i._value, 8);

  //disconnect 3/4 callbacks
  oclient2.disconnect(link2);
  oclient2.disconnect(link3);
  oclient2.disconnect(link4);

  oclient2.post("fire2", 42);//post signal twice
  oclient2.post("fire2", 42);

  while(i._value != 10 && waiting_time < 10000)//waiting 10 seconds max
  {
    qi::os::msleep(additional_timeout); //additional timeout to wait for unwanted callback
    waiting_time += additional_timeout;
  }
  qi::os::msleep(additional_timeout); //additional timeout to wait for unwanted callback
  ASSERT_EQ(i._value, 10);
  //i = 0;

  //reconnect callbacks
  link2 = oclient2.connect(se2, oserver1, callbackId).value(2000);
  link3 = oclient2.connect(se2, oserver1, callbackId).value(2000);
  link4 = oclient2.connect(se2, oserver1, callbackId).value(2000);

  oclient2.post("fire2", 42);//post signal twice
  oclient2.post("fire2", 42);

  while((*i) != 10 && waiting_time < 10000)//waiting 10 seconds max
  {
    qi::os::msleep(additional_timeout); //additional timeout to wait for unwanted callback
    waiting_time += additional_timeout;
  }
  qi::os::msleep(additional_timeout); //additional timeout to wait for unwanted callback
  ASSERT_EQ(*i, 18);

  oclient2.disconnect(link1);
  oclient2.disconnect(link2);
  oclient2.disconnect(link3);
  oclient2.disconnect(link4);

  oclient2.post("fire2", 42);

  qi::os::msleep(additional_timeout); //additional timeout to wait for unwanted callback
  ASSERT_EQ(*i, 18);

}

TEST_F(TestObject, serviceDirectoryEvent)
{
  i = 0;
  qi::AnyObject sd = p1.client()->service("ServiceDirectory");

  typedef std::map<unsigned int, qi::MetaSignal> SignalMap;
  SignalMap s_map;
  s_map = sd.metaObject().signalMap();

  unsigned int signal_id;
  for (SignalMap::iterator it = s_map.begin(); it!= s_map.end(); ++it)
  {
    if (it->second.name() == "serviceAdded")
    {
      signal_id = it->second.uid();
    }
  }
  sd.connect(signal_id, oserver1, secondCallbackId);
  sd.connect(signal_id, oserver1, secondCallbackId);
  sd.connect(signal_id, oserver1, secondCallbackId);
  sd.connect(signal_id, oserver1, secondCallbackId);

  ASSERT_TRUE(p1.server()->registerService("test", oserver1).hasValue(1000));

  int waiting_time = 0;
  while(*i != 4 && waiting_time < 10000)
  {
    qi::os::msleep(10);
    waiting_time += 10;
  }
  qi::os::msleep(10);
  ASSERT_EQ(*i, 4);
}

int main(int argc, char *argv[])
{
#if defined(__APPLE__) || defined(__linux__)
  setsid();
#endif
  qi::Application app(argc, argv);
  TestMode::initTestMode(argc, argv);
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}
<|endoftext|>


<commit_before>#include "catch.hpp"

#include "stack.hpp"

TEST_CASE("Stack can be instantiated by various types", "[instantiation]") {
	REQUIRE_NOTHROW(stack<int> st1);
	REQUIRE_NOTHROW(stack<double> st1);
	REQUIRE_NOTHROW(stack<char> st1);
	REQUIRE_NOTHROW(stack<int*> st1);
	REQUIRE_NOTHROW(stack<stack<int>> st1);
}
TEST_CASE("Push, pop, top", "[push_pop_top]") {
	stack<int> st;
	st.push(1);
	st.push(2);
	REQUIRE(st.top() == 2);
	st.pop();
	REQUIRE(st.top() == 1);
	st.pop();
}
TEST_CASE("count", "[count]") {
	stack<int> st;
	REQUIRE(st.count() == 0);
	st.push(1);
	REQUIRE(st.count() == 1);
	st.push(2);
	REQUIRE(st.count() == 2);
	st.pop();
	REQUIRE(st.count() == 1);
	st.pop();
	REQUIRE(st.count() == 0);
}
TEST_CASE("Copy constructor", "[copy_ctr]") {
	stack<int> st1;
	st1.push(1);
	st1.push(2);
	REQUIRE_NOTHROW(stack<int> st2 = st1);

	stack<int> st3 = st1;
	stack<int> st4 = st1;
	REQUIRE(st1.top() == 2);
	REQUIRE(st3.top() == 2);
	st3.pop();
	REQUIRE(st3.top() == 1);
	REQUIRE(st4.top() == 2);
	st4.pop();
	REQUIRE(st4.top() == 1);
}
TEST_CASE("Equal", "[equal]") {
	stack<int> st1;
	REQUIRE_NOTHROW(stack<int> st2;
	st2 = st1);
	stack<int> st2;
	st1.push(1);
	st1.push(4);
	st2 = st1;
	REQUIRE(st2.top() == 4);
	st2.pop();
	REQUIRE(st2.top() == 1);
}
TEST_CASE("Empty", "[empty]") {
	stack<int> st1;
	REQUIRE(st1.empty());
	st1.push(38);
	REQUIRE(!st1.empty());
}
TEST_CASE("Allocator doesn't (use or need) default ctors", "[allocator]") {
	class A {
	public:
		A() {
			throw "ctor is called";
		}
		A(int a) {
			;
		}
	};
	REQUIRE_NOTHROW(
		stack<A> st;
		st.push(4);
		st.push(20);
	);
	class B {
	public:
		B(int a) {
			;
		}
	};
	stack<B> st;
	st.push(40);
}
bool dtor_is_called1 = false;
TEST_CASE("Allocator calls dtors", "[allocator]") {
	class A {
	public:
		A(int a) {
			;
		}
		~A() {
			dtor_is_called1 = true;
		}
	};
	stack<A> st;
	st.push(32);
	st.pop();
	REQUIRE(dtor_is_called1);
}
<commit_msg>Update init.cpp<commit_after>#include "catch.hpp"

#include "shared_pointer.hpp"

SCENARIO("Default constructor, get", "[c]") {
	shared_pointer<int> shared_pointer;
	REQUIRE(shared_pointer.get() == nullptr);
}

SCENARIO("T * constructor, getNReferences ", "[a]") {
	shared_pointer<std::string> shared_pointer(new std::string("Hello!"));
	REQUIRE(shared_pointer.getNReferences() == 1);
}
<|endoftext|>


<commit_before>//------------------------------------------------------------------------------
//  Dbg
//------------------------------------------------------------------------------
#include "Pre.h"
#include "Dbg.h"
#include "Core/Trace.h"
#include <cstdarg>

namespace Oryol {

struct Dbg::_state* Dbg::state = nullptr;

//------------------------------------------------------------------------------
void
Dbg::Setup() {
    o_assert(!IsValid());
    state = Memory::New<_state>();
}

//------------------------------------------------------------------------------
void
Dbg::Discard() {
    o_assert(IsValid());
    state->debugTextRenderer.discard();
    Memory::Delete(state);
    state = nullptr;
}

//------------------------------------------------------------------------------
bool
Dbg::IsValid() {
    return nullptr != state;
}

//------------------------------------------------------------------------------
void
Dbg::SetTextScale(const glm::vec2& s) {
    o_assert_dbg(IsValid());
    state->debugTextRenderer.setTextScale(s);
}

//------------------------------------------------------------------------------
const glm::vec2&
Dbg::GetTextScale() {
    o_assert_dbg(IsValid());
    return state->debugTextRenderer.getTextScale();
}

//------------------------------------------------------------------------------
void
Dbg::Print(const char* text) {
    o_assert_dbg(IsValid());
    state->debugTextRenderer.print(text);
}

//------------------------------------------------------------------------------
void
Dbg::PrintF(const char* text, ...) {
    o_assert_dbg(IsValid());
    std::va_list args;
    va_start(args, text);
    state->debugTextRenderer.printf(text, args);
    va_end(args);
}

//------------------------------------------------------------------------------
void
Dbg::CursorPos(uint8 x, uint8 y) {
    o_assert_dbg(IsValid());
    state->debugTextRenderer.cursorPos(x, y);
}

//------------------------------------------------------------------------------
void
Dbg::TextColor(const glm::vec4& c) {
    o_assert_dbg(IsValid());
    state->debugTextRenderer.textColor(c);
}

//------------------------------------------------------------------------------
void
Dbg::DrawTextBuffer() {
    o_trace_scoped(Dbg_DrawTextBuffer);
    o_assert_dbg(IsValid());
    state->debugTextRenderer.drawTextBuffer();
}

} // namespace Oryol
<commit_msg>Dbg::Discard(): don't crash if no text was rendered<commit_after>//------------------------------------------------------------------------------
//  Dbg
//------------------------------------------------------------------------------
#include "Pre.h"
#include "Dbg.h"
#include "Core/Trace.h"
#include <cstdarg>

namespace Oryol {

struct Dbg::_state* Dbg::state = nullptr;

//------------------------------------------------------------------------------
void
Dbg::Setup() {
    o_assert(!IsValid());
    state = Memory::New<_state>();
}

//------------------------------------------------------------------------------
void
Dbg::Discard() {
    o_assert(IsValid());
    if (state->debugTextRenderer.isValid()) {
        state->debugTextRenderer.discard();
    }
    Memory::Delete(state);
    state = nullptr;
}

//------------------------------------------------------------------------------
bool
Dbg::IsValid() {
    return nullptr != state;
}

//------------------------------------------------------------------------------
void
Dbg::SetTextScale(const glm::vec2& s) {
    o_assert_dbg(IsValid());
    state->debugTextRenderer.setTextScale(s);
}

//------------------------------------------------------------------------------
const glm::vec2&
Dbg::GetTextScale() {
    o_assert_dbg(IsValid());
    return state->debugTextRenderer.getTextScale();
}

//------------------------------------------------------------------------------
void
Dbg::Print(const char* text) {
    o_assert_dbg(IsValid());
    state->debugTextRenderer.print(text);
}

//------------------------------------------------------------------------------
void
Dbg::PrintF(const char* text, ...) {
    o_assert_dbg(IsValid());
    std::va_list args;
    va_start(args, text);
    state->debugTextRenderer.printf(text, args);
    va_end(args);
}

//------------------------------------------------------------------------------
void
Dbg::CursorPos(uint8 x, uint8 y) {
    o_assert_dbg(IsValid());
    state->debugTextRenderer.cursorPos(x, y);
}

//------------------------------------------------------------------------------
void
Dbg::TextColor(const glm::vec4& c) {
    o_assert_dbg(IsValid());
    state->debugTextRenderer.textColor(c);
}

//------------------------------------------------------------------------------
void
Dbg::DrawTextBuffer() {
    o_trace_scoped(Dbg_DrawTextBuffer);
    o_assert_dbg(IsValid());
    state->debugTextRenderer.drawTextBuffer();
}

} // namespace Oryol
<|endoftext|>


<commit_before>
<commit_msg>Delete 1.cpp<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: hierarchyservices.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 13:56:48 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_ucb.hxx"

#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_
#include <com/sun/star/registry/XRegistryKey.hpp>
#endif

#ifndef _HIERARCHYPROVIDER_HXX
#include "hierarchyprovider.hxx"
#endif
#ifndef _HIERARCHYDATASOURCE_HXX
#include "hierarchydatasource.hxx"
#endif

using namespace com::sun::star;
using namespace hierarchy_ucp;

//=========================================================================
static sal_Bool writeInfo( void * pRegistryKey,
                           const rtl::OUString & rImplementationName,
                           uno::Sequence< rtl::OUString > const & rServiceNames )
{
    rtl::OUString aKeyName( rtl::OUString::createFromAscii( "/" ) );
    aKeyName += rImplementationName;
    aKeyName += rtl::OUString::createFromAscii( "/UNO/SERVICES" );

    uno::Reference< registry::XRegistryKey > xKey;
    try
    {
        xKey = static_cast< registry::XRegistryKey * >(
                                    pRegistryKey )->createKey( aKeyName );
    }
    catch ( registry::InvalidRegistryException const & )
    {
    }

    if ( !xKey.is() )
        return sal_False;

    sal_Bool bSuccess = sal_True;

    for ( sal_Int32 n = 0; n < rServiceNames.getLength(); ++n )
    {
        try
        {
            xKey->createKey( rServiceNames[ n ] );
        }
        catch ( registry::InvalidRegistryException const & )
        {
            bSuccess = sal_False;
            break;
        }
    }
    return bSuccess;
}

//=========================================================================
extern "C" void SAL_CALL component_getImplementationEnvironment(
    const sal_Char ** ppEnvTypeName, uno_Environment ** /*ppEnv*/ )
{
    *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
}

//=========================================================================
extern "C" sal_Bool SAL_CALL component_writeInfo(
    void * /*pServiceManager*/, void * pRegistryKey )
{
    return pRegistryKey &&

    //////////////////////////////////////////////////////////////////////
    // Hierarchy Content Provider.
    //////////////////////////////////////////////////////////////////////

    writeInfo( pRegistryKey,
               HierarchyContentProvider::getImplementationName_Static(),
               HierarchyContentProvider::getSupportedServiceNames_Static() ) &&

    //////////////////////////////////////////////////////////////////////
    // Hierarchy Data Source.
    //////////////////////////////////////////////////////////////////////

    writeInfo( pRegistryKey,
               HierarchyDataSource::getImplementationName_Static(),
               HierarchyDataSource::getSupportedServiceNames_Static() );
}

//=========================================================================
extern "C" void * SAL_CALL component_getFactory(
    const sal_Char * pImplName, void * pServiceManager, void * /*pRegistryKey*/ )
{
    void * pRet = 0;

    uno::Reference< lang::XMultiServiceFactory > xSMgr(
            reinterpret_cast< lang::XMultiServiceFactory * >(
                pServiceManager ) );
    uno::Reference< lang::XSingleServiceFactory > xFactory;

    //////////////////////////////////////////////////////////////////////
    // Hierarchy Content Provider.
    //////////////////////////////////////////////////////////////////////

    if ( HierarchyContentProvider::getImplementationName_Static().
                compareToAscii( pImplName ) == 0 )
    {
        xFactory = HierarchyContentProvider::createServiceFactory( xSMgr );
    }

    //////////////////////////////////////////////////////////////////////
    // Hierarchy Data Source.
    //////////////////////////////////////////////////////////////////////

    else if ( HierarchyDataSource::getImplementationName_Static().
                compareToAscii( pImplName ) == 0 )
    {
        xFactory = HierarchyDataSource::createServiceFactory( xSMgr );
    }

    //////////////////////////////////////////////////////////////////////

    if ( xFactory.is() )
    {
        xFactory->acquire();
        pRet = xFactory.get();
    }

    return pRet;
}

<commit_msg>INTEGRATION: CWS changefileheader (1.7.118); FILE MERGED 2008/04/01 12:58:19 thb 1.7.118.2: #i85898# Stripping all external header guards 2008/03/31 15:30:24 rt 1.7.118.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: hierarchyservices.cxx,v $
 * $Revision: 1.8 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_ucb.hxx"
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#include <com/sun/star/registry/XRegistryKey.hpp>
#include "hierarchyprovider.hxx"
#include "hierarchydatasource.hxx"

using namespace com::sun::star;
using namespace hierarchy_ucp;

//=========================================================================
static sal_Bool writeInfo( void * pRegistryKey,
                           const rtl::OUString & rImplementationName,
                           uno::Sequence< rtl::OUString > const & rServiceNames )
{
    rtl::OUString aKeyName( rtl::OUString::createFromAscii( "/" ) );
    aKeyName += rImplementationName;
    aKeyName += rtl::OUString::createFromAscii( "/UNO/SERVICES" );

    uno::Reference< registry::XRegistryKey > xKey;
    try
    {
        xKey = static_cast< registry::XRegistryKey * >(
                                    pRegistryKey )->createKey( aKeyName );
    }
    catch ( registry::InvalidRegistryException const & )
    {
    }

    if ( !xKey.is() )
        return sal_False;

    sal_Bool bSuccess = sal_True;

    for ( sal_Int32 n = 0; n < rServiceNames.getLength(); ++n )
    {
        try
        {
            xKey->createKey( rServiceNames[ n ] );
        }
        catch ( registry::InvalidRegistryException const & )
        {
            bSuccess = sal_False;
            break;
        }
    }
    return bSuccess;
}

//=========================================================================
extern "C" void SAL_CALL component_getImplementationEnvironment(
    const sal_Char ** ppEnvTypeName, uno_Environment ** /*ppEnv*/ )
{
    *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
}

//=========================================================================
extern "C" sal_Bool SAL_CALL component_writeInfo(
    void * /*pServiceManager*/, void * pRegistryKey )
{
    return pRegistryKey &&

    //////////////////////////////////////////////////////////////////////
    // Hierarchy Content Provider.
    //////////////////////////////////////////////////////////////////////

    writeInfo( pRegistryKey,
               HierarchyContentProvider::getImplementationName_Static(),
               HierarchyContentProvider::getSupportedServiceNames_Static() ) &&

    //////////////////////////////////////////////////////////////////////
    // Hierarchy Data Source.
    //////////////////////////////////////////////////////////////////////

    writeInfo( pRegistryKey,
               HierarchyDataSource::getImplementationName_Static(),
               HierarchyDataSource::getSupportedServiceNames_Static() );
}

//=========================================================================
extern "C" void * SAL_CALL component_getFactory(
    const sal_Char * pImplName, void * pServiceManager, void * /*pRegistryKey*/ )
{
    void * pRet = 0;

    uno::Reference< lang::XMultiServiceFactory > xSMgr(
            reinterpret_cast< lang::XMultiServiceFactory * >(
                pServiceManager ) );
    uno::Reference< lang::XSingleServiceFactory > xFactory;

    //////////////////////////////////////////////////////////////////////
    // Hierarchy Content Provider.
    //////////////////////////////////////////////////////////////////////

    if ( HierarchyContentProvider::getImplementationName_Static().
                compareToAscii( pImplName ) == 0 )
    {
        xFactory = HierarchyContentProvider::createServiceFactory( xSMgr );
    }

    //////////////////////////////////////////////////////////////////////
    // Hierarchy Data Source.
    //////////////////////////////////////////////////////////////////////

    else if ( HierarchyDataSource::getImplementationName_Static().
                compareToAscii( pImplName ) == 0 )
    {
        xFactory = HierarchyDataSource::createServiceFactory( xSMgr );
    }

    //////////////////////////////////////////////////////////////////////

    if ( xFactory.is() )
    {
        xFactory->acquire();
        pRet = xFactory.get();
    }

    return pRet;
}

<|endoftext|>