<commit_before>/*
 * Copyright (c) 2011, Willow Garage, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the <ORGANIZATION> nor the names of its
 *       contributors may be used to endorse or promote products derived from
 *       this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

// Author: E. Gil Jones

#include <ros/ros.h>
#include <distance_field/propagation_distance_field.h>
#include <moveit_visualization_ros/kinematic_state_joint_state_publisher.h>
#include <planning_scene_monitor/planning_scene_monitor.h>
#include <collision_distance_field/collision_distance_field_types.h>
#include <interactive_markers/interactive_marker_server.h>
#include <visualization_msgs/InteractiveMarkerFeedback.h>
#include <moveit_visualization_ros/interactive_marker_helper_functions.h>
#include <planning_models/transforms.h>

using namespace moveit_visualization_ros;

static const std::string VIS_TOPIC_NAME = "distance_field_visualization";

boost::shared_ptr<KinematicStateJointStatePublisher> joint_state_publisher_;
boost::shared_ptr<planning_scene_monitor::PlanningSceneMonitor> planning_scene_monitor_;
//boost::shared_ptr<InteractiveObjectVisualization> iov_;

void publisher_function() {
  ros::WallRate r(10.0);
  while(ros::ok())
  {
    joint_state_publisher_->broadcastRootTransform(planning_scene_monitor_->getPlanningScene()->getCurrentState());
    joint_state_publisher_->publishKinematicState(planning_scene_monitor_->getPlanningScene()->getCurrentState());
    r.sleep();
  }
}

class MovingMarkers {

public:

  MovingMarkers(boost::shared_ptr<interactive_markers::InteractiveMarkerServer>& interactive_marker_server,
                const std::string& world_frame,
                double x_size, double y_size, double z_size) :
    interactive_marker_server_(interactive_marker_server),
    world_frame_(world_frame),
    x_size_(x_size), y_size_(y_size), z_size_(z_size)
  {
    update_thread_.reset(new boost::thread(boost::bind(&MovingMarkers::updateAllMarkers, this)));
  }

  void addSphere() {
    geometry_msgs::PoseStamped ps;
    ps.header.frame_id = world_frame_;
    ps.pose.position.x = 1.0;
    ps.pose.position.y = 1.0;
    ps.pose.position.z = 1.0;
    ps.pose.orientation.w = 1.0;
    markers_["sphere"] = makeButtonSphere("sphere",
                                          ps,
                                          .1,
                                          false,
                                          false);
    interactive_marker_server_->insert(markers_["sphere"]);
    velocities_["sphere"] = Eigen::Translation3d(1.0,0.0,0.0);
  }

  // TODO- add mutex
  bool getFirstSpherePosition(Eigen::Translation3d& translation)
  {
    std::map<std::string, visualization_msgs::InteractiveMarker>::iterator it = markers_.begin();
    if( it != markers_.end() )
    {
      Eigen::Affine3d pose_e;
      planning_models::poseFromMsg(it->second.pose, pose_e);
      translation.x() = pose_e.translation().x();
      translation.y() = pose_e.translation().y();
      translation.z() = pose_e.translation().z();
      //transform.translation = pose_e.translation;
      return true;
    }
    return false;
  }

  void updateAllMarkers() {
    while(ros::ok()) {
      for(std::map<std::string, visualization_msgs::InteractiveMarker>::iterator it = markers_.begin();
          it != markers_.end();
          it++) {
        Eigen::Affine3d pose_e;
        planning_models::poseFromMsg(it->second.pose, pose_e);
        Eigen::Translation3d m(velocities_[it->first].x()*.05,
                               velocities_[it->first].y()*.05,
                               velocities_[it->first].z()*.05);
        pose_e = pose_e*m;
        if(pose_e.translation().x() > x_size_ || pose_e.translation().x() < -x_size_) {
          velocities_[it->first].x() *= -1;
        }
        if(pose_e.translation().y() > y_size_ || pose_e.translation().y() < -y_size_) {
          velocities_[it->first].y() *= -1;
        }
        if(pose_e.translation().z() > z_size_ || pose_e.translation().z() < -z_size_) {
          velocities_[it->first].z() *= -1;
        }
        planning_models::msgFromPose(pose_e, it->second.pose);
        interactive_marker_server_->insert(it->second);
        interactive_marker_server_->applyChanges();
      }
      boost::this_thread::sleep((ros::WallTime::now()+ros::WallDuration(.05)).toBoost());
    }
  }

protected:

  boost::shared_ptr<interactive_markers::InteractiveMarkerServer> interactive_marker_server_;
  std::string world_frame_;
  double x_size_, y_size_, z_size_;
  boost::shared_ptr<boost::thread> update_thread_;
  std::map<std::string, Eigen::Translation3d> velocities_;
  std::map<std::string, visualization_msgs::InteractiveMarker> markers_;

};

// void updateCallback(planning_scene::PlanningSceneConstPtr planning_scene) {
//   kv_->updatePlanningScene(planning_scene);
// }

// void addCubeCallback(const std::string& name) {
//   iov_->addCube();
// }

int main(int argc, char** argv)
{
  ros::init(argc, argv, "interactive_object_visualization", ros::init_options::NoSigintHandler);

  ros::AsyncSpinner spinner(1);
  spinner.start();

  boost::shared_ptr<interactive_markers::InteractiveMarkerServer> interactive_marker_server_;
  interactive_marker_server_.reset(new interactive_markers::InteractiveMarkerServer("interactive_distance_field_visualization", "", false));
  planning_scene_monitor_.reset(new planning_scene_monitor::PlanningSceneMonitor("robot_description"));
  joint_state_publisher_.reset(new KinematicStateJointStatePublisher());

  boost::thread publisher_thread(boost::bind(&publisher_function));

  ros::NodeHandle nh;

  ros::Publisher vis_marker_array_publisher;
  ros::Publisher vis_marker_publisher;

  vis_marker_publisher = nh.advertise<visualization_msgs::Marker> (VIS_TOPIC_NAME, 128);
  vis_marker_array_publisher = nh.advertise<visualization_msgs::MarkerArray> (VIS_TOPIC_NAME + "_array", 128);

  const double resolution = 0.025;
  const double max_distance = 0.5;
  distance_field::PropagationDistanceField distance_field(3.0, 3.0, 4.0, resolution, -1.0, -1.5, -2.0, max_distance);

  shapes::Box* box = new shapes::Box(2.5, 2.5, 0.4);
  collision_distance_field::BodyDecomposition bd("box", box, resolution, 0.0);
  Eigen::Affine3d trans(Eigen::Translation3d(0.0,0.0,-1.0)*Eigen::Quaterniond::Identity());
  bd.updatePose(trans);
  std::vector<Eigen::Vector3d> all_points = bd.getCollisionPoints();

  //ROS_INFO_STREAM("Adding " << all_points.size() << " to field");

  distance_field.updatePointsInField(all_points);

  visualization_msgs::Marker mark;

  MovingMarkers mm(interactive_marker_server_,
                   planning_scene_monitor_->getPlanningScene()->getPlanningFrame(),
                   1.5,1.5,2.0);
  mm.addSphere();

  int i = 0;
  while(1) {
    Eigen::Translation3d translation;
    if( mm.getFirstSpherePosition(translation) )
    {
/*    // TODO- create body decomposition for sphere
      shapes::Box* box = new shapes::Box(1.0, 1.0,1.0);
      collision_distance_field::BodyDecomposition bd("box", box, 0.025, 0.0);
      Eigen::Affine3d trans(translation*Eigen::Quaterniond::Identity());
      bd.updatePose(trans);
*/
      // Adding center point for sphere
      Eigen::Vector3d point(translation.x(), translation.y(), translation.z());
      //ROS_INFO_STREAM( "transform="<<point.x()<<","<<point.y()<<","<<point.z()<<std::endl );
      all_points.push_back(point);

      distance_field.updatePointsInField(all_points, true);

      distance_field.getProjectionPlanes( planning_scene_monitor_->getPlanningScene()->getPlanningFrame(),
                                          ros::Time::now(), max_distance,
                                          mark);
      //distance_field.getIsoSurfaceMarkers(0.0000,0.5,planning_scene_monitor_->getPlanningScene()->getPlanningFrame(),
      //                                    ros::Time::now(),
      //                                    Eigen::Affine3d::Identity(),
      //                                    mark);

      all_points.pop_back();
      ROS_INFO_STREAM( "num_points="<<all_points.size()<<std::endl );
    }

    vis_marker_publisher.publish(mark);
    i++;
  }
  // std_msgs::ColorRGBA col;
  // col.r = col.g = col.b = .5;
  // col.a = 1.0;

  // std_msgs::ColorRGBA good_color;
  // good_color.a = 1.0;
  // good_color.g = 1.0;

  // std_msgs::ColorRGBA bad_color;
  // bad_color.a = 1.0;
  // bad_color.r = 1.0;

  // iov_.reset(new InteractiveObjectVisualization(planning_scene_monitor_->getPlanningScene(),
  //                                               interactive_marker_server_,
  //                                               col));

  // kv_->addMenuEntry("Add Cube", boost::bind(&addCubeCallback, _1));

  // iov_->setUpdateCallback(boost::bind(&updateCallback, _1));

  ros::waitForShutdown();
}

<commit_msg>separated out table and sphere objects.  Much faster updates<commit_after>/*
 * Copyright (c) 2011, Willow Garage, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the <ORGANIZATION> nor the names of its
 *       contributors may be used to endorse or promote products derived from
 *       this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

// Author: E. Gil Jones

#include <ros/ros.h>
#include <distance_field/propagation_distance_field.h>
#include <moveit_visualization_ros/kinematic_state_joint_state_publisher.h>
#include <planning_scene_monitor/planning_scene_monitor.h>
#include <collision_distance_field/collision_distance_field_types.h>
#include <interactive_markers/interactive_marker_server.h>
#include <visualization_msgs/InteractiveMarkerFeedback.h>
#include <moveit_visualization_ros/interactive_marker_helper_functions.h>
#include <planning_models/transforms.h>

using namespace moveit_visualization_ros;

static const std::string VIS_TOPIC_NAME = "distance_field_visualization";

boost::shared_ptr<KinematicStateJointStatePublisher> joint_state_publisher_;
boost::shared_ptr<planning_scene_monitor::PlanningSceneMonitor> planning_scene_monitor_;
//boost::shared_ptr<InteractiveObjectVisualization> iov_;

void publisher_function() {
  ros::WallRate r(10.0);
  while(ros::ok())
  {
    joint_state_publisher_->broadcastRootTransform(planning_scene_monitor_->getPlanningScene()->getCurrentState());
    joint_state_publisher_->publishKinematicState(planning_scene_monitor_->getPlanningScene()->getCurrentState());
    r.sleep();
  }
}

class MovingMarkers {

public:

  MovingMarkers(boost::shared_ptr<interactive_markers::InteractiveMarkerServer>& interactive_marker_server,
                const std::string& world_frame,
                double x_size, double y_size, double z_size) :
    interactive_marker_server_(interactive_marker_server),
    world_frame_(world_frame),
    x_size_(x_size), y_size_(y_size), z_size_(z_size)
  {
    update_thread_.reset(new boost::thread(boost::bind(&MovingMarkers::updateAllMarkers, this)));
  }

  void addSphere() {
    geometry_msgs::PoseStamped ps;
    ps.header.frame_id = world_frame_;
    ps.pose.position.x = 1.0;
    ps.pose.position.y = 1.0;
    ps.pose.position.z = 1.0;
    ps.pose.orientation.w = 1.0;
    markers_["sphere"] = makeButtonSphere("sphere",
                                          ps,
                                          .1,
                                          false,
                                          false);
    interactive_marker_server_->insert(markers_["sphere"]);
    velocities_["sphere"] = Eigen::Translation3d(1.0,0.0,0.0);
  }

  // TODO- add mutex
  bool getFirstSpherePosition(Eigen::Translation3d& translation)
  {
    std::map<std::string, visualization_msgs::InteractiveMarker>::iterator it = markers_.begin();
    if( it != markers_.end() )
    {
      Eigen::Affine3d pose_e;
      planning_models::poseFromMsg(it->second.pose, pose_e);
      translation.x() = pose_e.translation().x();
      translation.y() = pose_e.translation().y();
      translation.z() = pose_e.translation().z();
      //transform.translation = pose_e.translation;
      return true;
    }
    return false;
  }

  void updateAllMarkers() {
    while(ros::ok()) {
      for(std::map<std::string, visualization_msgs::InteractiveMarker>::iterator it = markers_.begin();
          it != markers_.end();
          it++) {
        Eigen::Affine3d pose_e;
        planning_models::poseFromMsg(it->second.pose, pose_e);
        Eigen::Translation3d m(velocities_[it->first].x()*.05,
                               velocities_[it->first].y()*.05,
                               velocities_[it->first].z()*.05);
        pose_e = pose_e*m;
        if(pose_e.translation().x() > x_size_ || pose_e.translation().x() < -x_size_) {
          velocities_[it->first].x() *= -1;
        }
        if(pose_e.translation().y() > y_size_ || pose_e.translation().y() < -y_size_) {
          velocities_[it->first].y() *= -1;
        }
        if(pose_e.translation().z() > z_size_ || pose_e.translation().z() < -z_size_) {
          velocities_[it->first].z() *= -1;
        }
        planning_models::msgFromPose(pose_e, it->second.pose);
        interactive_marker_server_->insert(it->second);
        interactive_marker_server_->applyChanges();
      }
      boost::this_thread::sleep((ros::WallTime::now()+ros::WallDuration(.05)).toBoost());
    }
  }

protected:

  boost::shared_ptr<interactive_markers::InteractiveMarkerServer> interactive_marker_server_;
  std::string world_frame_;
  double x_size_, y_size_, z_size_;
  boost::shared_ptr<boost::thread> update_thread_;
  std::map<std::string, Eigen::Translation3d> velocities_;
  std::map<std::string, visualization_msgs::InteractiveMarker> markers_;

};

// void updateCallback(planning_scene::PlanningSceneConstPtr planning_scene) {
//   kv_->updatePlanningScene(planning_scene);
// }

// void addCubeCallback(const std::string& name) {
//   iov_->addCube();
// }

int main(int argc, char** argv)
{
  ros::init(argc, argv, "interactive_object_visualization", ros::init_options::NoSigintHandler);

  ros::AsyncSpinner spinner(1);
  spinner.start();

  boost::shared_ptr<interactive_markers::InteractiveMarkerServer> interactive_marker_server_;
  interactive_marker_server_.reset(new interactive_markers::InteractiveMarkerServer("interactive_distance_field_visualization", "", false));
  planning_scene_monitor_.reset(new planning_scene_monitor::PlanningSceneMonitor("robot_description"));
  joint_state_publisher_.reset(new KinematicStateJointStatePublisher());

  boost::thread publisher_thread(boost::bind(&publisher_function));

  ros::NodeHandle nh;

  ros::Publisher vis_marker_array_publisher;
  ros::Publisher vis_marker_publisher;

  vis_marker_publisher = nh.advertise<visualization_msgs::Marker> (VIS_TOPIC_NAME, 128);
  vis_marker_array_publisher = nh.advertise<visualization_msgs::MarkerArray> (VIS_TOPIC_NAME + "_array", 128);

  time_t start, diff;
  const double resolution = 0.025;
  const double max_distance = 0.5;//25;
  const bool 	 iterative = true;
  distance_field::PropagationDistanceField distance_field(3.0, 3.0, 4.0, resolution, -1.0, -1.5, -2.0, max_distance);

  shapes::Box* box = new shapes::Box(2.5, 2.5, 0.4);
  collision_distance_field::BodyDecomposition bd("box", box, resolution, 0.0);
  Eigen::Affine3d trans(Eigen::Translation3d(0.0,0.0,-1.0)*Eigen::Quaterniond::Identity());
  bd.updatePose(trans);
  std::vector<Eigen::Vector3d> table_points = bd.getCollisionPoints();
  std::vector<Eigen::Vector3d> sphere_points = bd.getCollisionPoints();	// TODO: this seems the only way to not segfault...
  sphere_points.clear();

  //ROS_INFO_STREAM("Adding " << table_points.size() << " to field");

  distance_field.addPointsToField(table_points);

  visualization_msgs::Marker mark;

  MovingMarkers mm(interactive_marker_server_,
                   planning_scene_monitor_->getPlanningScene()->getPlanningFrame(),
                   1.5,1.5,2.0);
  mm.addSphere();

  //shapes::Sphere* sphere = new shapes::Sphere(0.1);
  //collision_distance_field::BodyDecomposition sbd("sphere", sphere, 0.025, 0.0);

  int i = 0;
  while(1) {
    Eigen::Translation3d translation;
    if( mm.getFirstSpherePosition(translation) )
    {
    // TODO- create body decomposition for sphere
      //Eigen::Affine3d trans(translation*Eigen::Quaterniond::Identity());
      //sbd.updatePose(trans);

      // Adding center point for sphere
      Eigen::Vector3d point(translation.x(), translation.y(), translation.z());
      ROS_INFO_STREAM( "transform="<<point.x()<<","<<point.y()<<","<<point.z()<<std::endl );
      start = clock();

      if( iterative )
      {
        // Just add/remove the sphere points
        if( sphere_points.size() >0 )
        {
          distance_field.removePointsFromField(sphere_points);
          sphere_points.pop_back();
        }
        sphere_points.push_back(point);
        distance_field.addPointsToField(sphere_points);
      }
      else
      {
        // Update the whole voxel map
        table_points.push_back(point);
        distance_field.updatePointsInField(table_points, false);
        table_points.pop_back();
      }

      diff = start-clock();
      std::cout<< "timeToUpdate=" << (double)diff/CLOCKS_PER_SEC << std::endl;
      start = clock();
      distance_field.getProjectionPlanes( planning_scene_monitor_->getPlanningScene()->getPlanningFrame(),
                                          ros::Time::now(), max_distance,
                                          mark);
      //distance_field.getIsoSurfaceMarkers(0.0000,0.5,planning_scene_monitor_->getPlanningScene()->getPlanningFrame(),
      //                                    ros::Time::now(),
      //                                    Eigen::Affine3d::Identity(),
      //                                    mark);

      diff = start-clock();
      std::cout<< "timeToProject=" << (double)diff/CLOCKS_PER_SEC << std::endl;

      ROS_INFO_STREAM( "num_points="<<table_points.size()+sphere_points.size()<<std::endl );
    }

    vis_marker_publisher.publish(mark);
    i++;
  }
  // std_msgs::ColorRGBA col;
  // col.r = col.g = col.b = .5;
  // col.a = 1.0;

  // std_msgs::ColorRGBA good_color;
  // good_color.a = 1.0;
  // good_color.g = 1.0;

  // std_msgs::ColorRGBA bad_color;
  // bad_color.a = 1.0;
  // bad_color.r = 1.0;

  // iov_.reset(new InteractiveObjectVisualization(planning_scene_monitor_->getPlanningScene(),
  //                                               interactive_marker_server_,
  //                                               col));

  // kv_->addMenuEntry("Add Cube", boost::bind(&addCubeCallback, _1));

  // iov_->setUpdateCallback(boost::bind(&updateCallback, _1));

  ros::waitForShutdown();
}

<|endoftext|>


<commit_before>#include "wrappers.hpp"
#include "support/simd.hpp"
#ifdef CPB_USE_MKL
# include <mkl.h>
#endif
using namespace cpb;

PYBIND11_PLUGIN(_pybinding) {
    auto m = py::module("_pybinding");

    wrap_greens(m);
    wrap_lattice(m);
    wrap_leads(m);
    wrap_model(m);
    wrap_modifiers(m);
    wrap_parallel(m);
    wrap_shape(m);
    wrap_solver(m);
    wrap_system(m);

    wrapper_tests(m);

    m.def("simd_info", []() -> std::string {
#if SIMDPP_USE_AVX
        auto const bits = std::to_string(simd::detail::basic_traits::register_size_bytes * 8);
        return "AVX-" + bits;
#elif SIMDPP_USE_SSE3
        return "SSE3";
#elif SIMDPP_USE_SSE2
        return "SSE2";
#else
        return "x87";
#endif
    });

#ifdef CPB_USE_MKL
    m.def("get_max_threads", MKL_Get_Max_Threads,
          "Get the maximum number of MKL threads. (<= logical theads)");
    m.def("set_num_threads", MKL_Set_Num_Threads, "number"_a, "Set the number of MKL threads.");
    m.def("get_max_cpu_frequency", MKL_Get_Max_Cpu_Frequency);
    m.def("get_cpu_frequency", MKL_Get_Cpu_Frequency);
    // The max threads count may change later but at init time it's usually
    // equal to the physical core count which is useful information.
    m.attr("physical_core_count") = py::cast(MKL_Get_Max_Threads());
#endif

#ifdef CPB_VERSION
    m.attr("__version__") = py::str(CPB_VERSION);
#else
    m.attr("__version__") = py::str("dev");
#endif

    return m.ptr();
}
<commit_msg>Distinguish AVX and AVX2 when reporting SIMD support<commit_after>#include "wrappers.hpp"
#include "support/simd.hpp"
#ifdef CPB_USE_MKL
# include <mkl.h>
#endif
using namespace cpb;

PYBIND11_PLUGIN(_pybinding) {
    auto m = py::module("_pybinding");

    wrap_greens(m);
    wrap_lattice(m);
    wrap_leads(m);
    wrap_model(m);
    wrap_modifiers(m);
    wrap_parallel(m);
    wrap_shape(m);
    wrap_solver(m);
    wrap_system(m);

    wrapper_tests(m);

    m.def("simd_info", []() -> std::string {
#if SIMDPP_USE_AVX
        auto const bits = std::to_string(simd::detail::basic_traits::register_size_bytes * 8);
        return (SIMDPP_USE_AVX2 ? "AVX2-" : "AVX-") + bits;
#elif SIMDPP_USE_SSE3
        return "SSE3";
#elif SIMDPP_USE_SSE2
        return "SSE2";
#else
        return "x87";
#endif
    });

#ifdef CPB_USE_MKL
    m.def("get_max_threads", MKL_Get_Max_Threads,
          "Get the maximum number of MKL threads. (<= logical theads)");
    m.def("set_num_threads", MKL_Set_Num_Threads, "number"_a, "Set the number of MKL threads.");
    m.def("get_max_cpu_frequency", MKL_Get_Max_Cpu_Frequency);
    m.def("get_cpu_frequency", MKL_Get_Cpu_Frequency);
    // The max threads count may change later but at init time it's usually
    // equal to the physical core count which is useful information.
    m.attr("physical_core_count") = py::cast(MKL_Get_Max_Threads());
#endif

#ifdef CPB_VERSION
    m.attr("__version__") = py::str(CPB_VERSION);
#else
    m.attr("__version__") = py::str("dev");
#endif

    return m.ptr();
}
<|endoftext|>


<commit_before>
// Copyright (c) 2012, 2013 Lionel MOISAN.
// Copyright (c) 2012, 2013 Pascal MONASSE.
// Copyright (c) 2012, 2013 Pierre MOULON.

// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#ifndef OPENMVG_ROBUST_ESTIMATOR_ACRANSAC_H_
#define OPENMVG_ROBUST_ESTIMATOR_ACRANSAC_H_

//-------------------
// Generic implementation of ACRANSAC
//-------------------
// The A contrario parametrization have been first explained in [1] and
//  later extended to generic model estimation in [2] (with a demonstration for
//  the homography) and extended and use at large scale for Structure from
//  Motion in [3].
//
//--
//  [1] Lionel Moisan, Berenger Stival,
//  A probalistic criterion to detect rigid point matches between
//  two images and estimate the fundamental matrix.
//  IJCV 04.
//--
//  [2] Lionel Moisan, Pierre Moulon, Pascal Monasse.
//  Automatic Homographic Registration of a Pair of Images,
//    with A Contrario Elimination of Outliers
//  Image Processing On Line (IPOL), 2012.
//  http://dx.doi.org/10.5201/ipol.2012.mmm-oh
//--
//  [3] Pierre Moulon, Pascal Monasse and Renaud Marlet.
//  Adaptive Structure from Motion with a contrario mode estimation.
//  In 11th Asian Conference on Computer Vision (ACCV 2012)
//--

#include <algorithm>
#include <cmath>
#include <iostream>
#include <iterator>
#include <limits>
#include <numeric>
#include <vector>

#include "openMVG/robust_estimation/rand_sampling.hpp"

namespace openMVG {
namespace robust{

/// logarithm (base 10) of binomial coefficient
template <typename T>
static T logcombi
(
  size_t k,
  size_t n,
  const std::vector<T> & vec_log10 // lookuptable in [0,n+1]
)
{
  if (k>=n || k<=0) return(0.0f);
  if (n-k<k) k=n-k;
  T r = 0.0f;
  for (size_t i = 1; i <= k; ++i)
    r += vec_log10[n-i+1] - vec_log10[i];
  return r;
}

/// tabulate logcombi(.,n)
template<typename Type>
static void makelogcombi_n
(
  size_t n,
  std::vector<Type> & l,
  std::vector<Type> & vec_log10 // lookuptable [0,n+1]
)
{
  l.resize(n+1);
  for (size_t k = 0; k <= n; ++k)
    l[k] = logcombi<Type>(k, n, vec_log10);
}

/// tabulate logcombi(k,.)
template<typename Type>
static void makelogcombi_k
(
  size_t k,
  size_t nmax,
  std::vector<Type> & l,
  std::vector<Type> & vec_log10 // lookuptable [0,n+1]
)
{
  l.resize(nmax+1);
  for (size_t n = 0; n <= nmax; ++n)
    l[n] = logcombi<Type>(k, n, vec_log10);
}

template <typename Type>
static void makelogcombi
(
  size_t k,
  size_t n,
  std::vector<Type> & vec_logc_k,
  std::vector<Type> & vec_logc_n)
{
  // compute a lookuptable of log10 value for the range [0,n+1]
  std::vector<Type> vec_log10(n + 1);
  for (size_t k = 0; k <= n; ++k)
    vec_log10[k] = log10((Type)k);

  makelogcombi_n(n, vec_logc_n, vec_log10);
  makelogcombi_k(k, n, vec_logc_k, vec_log10);
}

/// NFA and associated index
typedef std::pair<double,size_t> ErrorIndex;

/// Find best NFA and its index wrt square error threshold in e.
static ErrorIndex bestNFA(
  int startIndex, //number of point required for estimation
  double logalpha0,
  const std::vector<ErrorIndex>& e,
  double loge0,
  double maxThreshold,
  const std::vector<float> &logc_n,
  const std::vector<float> &logc_k,
  double multError = 1.0)
{
  ErrorIndex bestIndex(std::numeric_limits<double>::infinity(), startIndex);
  const size_t n = e.size();
  for(size_t k = startIndex + 1; k <= n && e[k - 1].first <= maxThreshold; ++k)
  {
    const double logalpha = logalpha0 +
      multError * log10(e[k - 1].first + std::numeric_limits<float>::epsilon());
    ErrorIndex index(loge0 +
                     logalpha * (double) (k - startIndex) +
                     logc_n[k] +
                     logc_k[k], k);

    if(index.first < bestIndex.first)
      bestIndex = index;
  }
  return bestIndex;
}

/// Pick a random sample
/// \param sizeSample The size of the sample.
/// \param vec_index  The possible data indices.
/// \param sample The random sample of sizeSample indices (output).
static void UniformSample(int sizeSample,
  const std::vector<size_t> &vec_index,
  std::vector<size_t> *sample)
{
  sample->resize(sizeSample);
  random_sample(sizeSample, vec_index.size(), sample);
  for(int i = 0; i < sizeSample; ++i)
    (*sample)[i] = vec_index[ (*sample)[i] ];
}

/**
 * @brief ACRANSAC routine (ErrorThreshold, NFA)
 *
 * @param[in] kernel model and metric object
 * @param[out] vec_inliers points that fit the estimated model
 * @param[in] nIter maximum number of consecutive iterations
 * @param[out] model returned model if found
 * @param[in] precision upper bound of the precision (squared error)
 * @param[in] bVerbose display console log
 *
 * @return (errorMax, minNFA)
 */
template<typename Kernel>
std::pair<double, double> ACRANSAC(const Kernel &kernel,
  std::vector<size_t> & vec_inliers,
  size_t nIter = 1024,
  typename Kernel::Model * model = NULL,
  double precision = std::numeric_limits<double>::infinity(),
  bool bVerbose = false)
{
  vec_inliers.clear();

  const size_t sizeSample = Kernel::MINIMUM_SAMPLES;
  const size_t nData = kernel.NumSamples();
  if (nData <= (size_t)sizeSample)
    return std::make_pair(0.0,0.0);

  const double maxThreshold = (precision==std::numeric_limits<double>::infinity()) ?
    std::numeric_limits<double>::infinity() :
    precision * kernel.normalizer2()(0,0) * kernel.normalizer2()(0,0);

  std::vector<ErrorIndex> vec_residuals(nData); // [residual,index]
  std::vector<double> vec_residuals_(nData);
  std::vector<size_t> vec_sample(sizeSample); // Sample indices

  // Possible sampling indices [0,..,nData] (will change in the optimization phase)
  std::vector<size_t> vec_index(nData);
  std::iota(vec_index.begin(), vec_index.end(), 0);

  // Precompute log combi
  const double loge0 = log10((double)Kernel::MAX_MODELS * (nData-sizeSample));
  std::vector<float> vec_logc_n, vec_logc_k;
  makelogcombi(sizeSample, nData, vec_logc_k, vec_logc_n);

  // Output parameters
  double minNFA = std::numeric_limits<double>::infinity();
  double errorMax = std::numeric_limits<double>::infinity();

  // Reserve 10% of iterations for focused sampling
  size_t nIterReserve = nIter/10;
  nIter -= nIterReserve;

  bool bACRansacMode = (precision == std::numeric_limits<double>::infinity());

  // Main estimation loop.
  for (size_t iter=0; iter < nIter; ++iter)
  {
    if (bACRansacMode)
      UniformSample(sizeSample, vec_index, &vec_sample); // Get random sample
    else
      UniformSample(sizeSample, nData, &vec_sample); // Get random sample

    std::vector<typename Kernel::Model> vec_models; // Up to max_models solutions
    kernel.Fit(vec_sample, &vec_models);

    // Evaluate models
    bool better = false;
    for (size_t k = 0; k < vec_models.size(); ++k)
    {
      // Residuals computation and ordering
      kernel.Errors(vec_models[k], vec_residuals_);

      if (!bACRansacMode)
      {
        unsigned int nInlier = 0;
        for (size_t i = 0; i < nData; ++i)
        {
          if (vec_residuals_[i] <= maxThreshold)
            ++nInlier;
        }
        if (nInlier > 2.5 * sizeSample) // does the model is meaningful
          bACRansacMode = true;
      }
      if (bACRansacMode)
      {
        for (size_t i = 0; i < nData; ++i)  {
          const double error = vec_residuals_[i];
          vec_residuals[i] = ErrorIndex(error, i);
        }
        std::sort(vec_residuals.begin(), vec_residuals.end());

        // Most meaningful discrimination inliers/outliers
        const ErrorIndex best = bestNFA(
          sizeSample,
          kernel.logalpha0(),
          vec_residuals,
          loge0,
          maxThreshold,
          vec_logc_n,
          vec_logc_k,
          kernel.multError());

        if (best.first < minNFA /*&& vec_residuals[best.second-1].first < errorMax*/)  {
          // A better model was found
          better = true;
          minNFA = best.first;
          vec_inliers.resize(best.second);
          for (size_t i=0; i<best.second; ++i)
            vec_inliers[i] = vec_residuals[i].second;
          errorMax = vec_residuals[best.second-1].first; // Error threshold
          if(model) *model = vec_models[k];

          if(bVerbose)  {
            std::cout << "  nfa=" << minNFA
              << " inliers=" << best.second << "/" << nData
              << " precisionNormalized=" << errorMax
              << " precision=" << kernel.unormalizeError(errorMax)
              << " (iter=" << iter;
            std::cout << ",sample=";
            std::copy(vec_sample.begin(), vec_sample.end(),
              std::ostream_iterator<size_t>(std::cout, ","));
            std::cout << ")" <<std::endl;
          }
        }
      } //if(bACRansacMode)
    } //for(size_t k...

    // Early exit test -> no meaningful model found after nIterReserve*2 iterations
    if (!bACRansacMode && iter > nIterReserve*2)
      break;

    // ACRANSAC optimization: draw samples among best set of inliers so far
    if (bACRansacMode && ((better && minNFA<0) || (iter+1==nIter && nIterReserve)))
    {
      if (vec_inliers.empty())
      {
        // No model found at all so far
        ++nIter; // Continue to look for any model, even not meaningful
        --nIterReserve;
      }
      else
      {
        // ACRANSAC optimization: draw samples among best set of inliers so far
        vec_index = vec_inliers;
        if(nIterReserve)
        {
            nIter = iter + 1 + nIterReserve;
            nIterReserve = 0;
        }
      }
    }
  }

  if(minNFA >= 0)
    vec_inliers.clear();

  if (!vec_inliers.empty())
  {
    if (model)
      kernel.Unnormalize(model);
    errorMax = kernel.unormalizeError(errorMax);
  }

  return std::make_pair(errorMax, minNFA);
}

} // namespace robust
} // namespace openMVG
#endif // OPENMVG_ROBUST_ESTIMATOR_ACRANSAC_H_
<commit_msg>[robust] formatting<commit_after>
// Copyright (c) 2012, 2013 Lionel MOISAN.
// Copyright (c) 2012, 2013 Pascal MONASSE.
// Copyright (c) 2012, 2013 Pierre MOULON.

// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#ifndef OPENMVG_ROBUST_ESTIMATOR_ACRANSAC_H_
#define OPENMVG_ROBUST_ESTIMATOR_ACRANSAC_H_

//-------------------
// Generic implementation of ACRANSAC
//-------------------
// The A contrario parametrization have been first explained in [1] and
//  later extended to generic model estimation in [2] (with a demonstration for
//  the homography) and extended and use at large scale for Structure from
//  Motion in [3].
//
//--
//  [1] Lionel Moisan, Berenger Stival,
//  A probalistic criterion to detect rigid point matches between
//  two images and estimate the fundamental matrix.
//  IJCV 04.
//--
//  [2] Lionel Moisan, Pierre Moulon, Pascal Monasse.
//  Automatic Homographic Registration of a Pair of Images,
//    with A Contrario Elimination of Outliers
//  Image Processing On Line (IPOL), 2012.
//  http://dx.doi.org/10.5201/ipol.2012.mmm-oh
//--
//  [3] Pierre Moulon, Pascal Monasse and Renaud Marlet.
//  Adaptive Structure from Motion with a contrario mode estimation.
//  In 11th Asian Conference on Computer Vision (ACCV 2012)
//--

#include <algorithm>
#include <cmath>
#include <iostream>
#include <iterator>
#include <limits>
#include <numeric>
#include <vector>

#include "openMVG/robust_estimation/rand_sampling.hpp"

namespace openMVG {
namespace robust{

/// logarithm (base 10) of binomial coefficient
template <typename T>
static T logcombi
(
  size_t k,
  size_t n,
  const std::vector<T> & vec_log10 // lookuptable in [0,n+1]
)
{
  if (k>=n || k<=0) return(0.0f);
  if (n-k<k) k=n-k;
  T r = 0.0f;
  for (size_t i = 1; i <= k; ++i)
    r += vec_log10[n-i+1] - vec_log10[i];
  return r;
}

/// tabulate logcombi(.,n)
template<typename Type>
static void makelogcombi_n
(
  size_t n,
  std::vector<Type> & l,
  std::vector<Type> & vec_log10 // lookuptable [0,n+1]
)
{
  l.resize(n+1);
  for (size_t k = 0; k <= n; ++k)
    l[k] = logcombi<Type>(k, n, vec_log10);
}

/// tabulate logcombi(k,.)
template<typename Type>
static void makelogcombi_k
(
  size_t k,
  size_t nmax,
  std::vector<Type> & l,
  std::vector<Type> & vec_log10 // lookuptable [0,n+1]
)
{
  l.resize(nmax+1);
  for (size_t n = 0; n <= nmax; ++n)
    l[n] = logcombi<Type>(k, n, vec_log10);
}

template <typename Type>
static void makelogcombi
(
  size_t k,
  size_t n,
  std::vector<Type> & vec_logc_k,
  std::vector<Type> & vec_logc_n)
{
  // compute a lookuptable of log10 value for the range [0,n+1]
  std::vector<Type> vec_log10(n + 1);
  for (size_t k = 0; k <= n; ++k)
    vec_log10[k] = log10((Type)k);

  makelogcombi_n(n, vec_logc_n, vec_log10);
  makelogcombi_k(k, n, vec_logc_k, vec_log10);
}

/// NFA and associated index
typedef std::pair<double,size_t> ErrorIndex;

/// Find best NFA and its index wrt square error threshold in e.
static ErrorIndex bestNFA(
  int startIndex, //number of point required for estimation
  double logalpha0,
  const std::vector<ErrorIndex>& e,
  double loge0,
  double maxThreshold,
  const std::vector<float> &logc_n,
  const std::vector<float> &logc_k,
  double multError = 1.0)
{
  ErrorIndex bestIndex(std::numeric_limits<double>::infinity(), startIndex);
  const size_t n = e.size();
  for(size_t k = startIndex + 1; k <= n && e[k - 1].first <= maxThreshold; ++k)
  {
    const double logalpha = logalpha0 +
      multError * log10(e[k - 1].first + std::numeric_limits<float>::epsilon());
    ErrorIndex index(loge0 +
                     logalpha * (double) (k - startIndex) +
                     logc_n[k] +
                     logc_k[k], k);

    if(index.first < bestIndex.first)
      bestIndex = index;
  }
  return bestIndex;
}

/// Pick a random sample
/// \param sizeSample The size of the sample.
/// \param vec_index  The possible data indices.
/// \param sample The random sample of sizeSample indices (output).
static void UniformSample(int sizeSample,
  const std::vector<size_t> &vec_index,
  std::vector<size_t> *sample)
{
  sample->resize(sizeSample);
  random_sample(sizeSample, vec_index.size(), sample);
  for(int i = 0; i < sizeSample; ++i)
    (*sample)[i] = vec_index[ (*sample)[i] ];
}

/**
 * @brief ACRANSAC routine (ErrorThreshold, NFA)
 *
 * @param[in] kernel model and metric object
 * @param[out] vec_inliers points that fit the estimated model
 * @param[in] nIter maximum number of consecutive iterations
 * @param[out] model returned model if found
 * @param[in] precision upper bound of the precision (squared error)
 * @param[in] bVerbose display console log
 *
 * @return (errorMax, minNFA)
 */
template<typename Kernel>
std::pair<double, double> ACRANSAC(const Kernel &kernel,
  std::vector<size_t> & vec_inliers,
  size_t nIter = 1024,
  typename Kernel::Model * model = NULL,
  double precision = std::numeric_limits<double>::infinity(),
  bool bVerbose = false)
{
  vec_inliers.clear();

  const size_t sizeSample = Kernel::MINIMUM_SAMPLES;
  const size_t nData = kernel.NumSamples();
  if (nData <= (size_t)sizeSample)
    return std::make_pair(0.0,0.0);

  const double maxThreshold = (precision==std::numeric_limits<double>::infinity()) ?
    std::numeric_limits<double>::infinity() :
    precision * kernel.normalizer2()(0,0) * kernel.normalizer2()(0,0);

  std::vector<ErrorIndex> vec_residuals(nData); // [residual,index]
  std::vector<double> vec_residuals_(nData);
  std::vector<size_t> vec_sample(sizeSample); // Sample indices

  // Possible sampling indices [0,..,nData] (will change in the optimization phase)
  std::vector<size_t> vec_index(nData);
  std::iota(vec_index.begin(), vec_index.end(), 0);

  // Precompute log combi
  const double loge0 = log10((double)Kernel::MAX_MODELS * (nData-sizeSample));
  std::vector<float> vec_logc_n, vec_logc_k;
  makelogcombi(sizeSample, nData, vec_logc_k, vec_logc_n);

  // Output parameters
  double minNFA = std::numeric_limits<double>::infinity();
  double errorMax = std::numeric_limits<double>::infinity();

  // Reserve 10% of iterations for focused sampling
  size_t nIterReserve = nIter/10;
  nIter -= nIterReserve;

  bool bACRansacMode = (precision == std::numeric_limits<double>::infinity());

  // Main estimation loop.
  for (size_t iter=0; iter < nIter; ++iter)
  {
    if (bACRansacMode)
      UniformSample(sizeSample, vec_index, &vec_sample); // Get random sample
    else
      UniformSample(sizeSample, nData, &vec_sample); // Get random sample

    std::vector<typename Kernel::Model> vec_models; // Up to max_models solutions
    kernel.Fit(vec_sample, &vec_models);

    // Evaluate models
    bool better = false;
    for (size_t k = 0; k < vec_models.size(); ++k)
    {
      // Residuals computation and ordering
      kernel.Errors(vec_models[k], vec_residuals_);

      if (!bACRansacMode)
      {
        unsigned int nInlier = 0;
        for (size_t i = 0; i < nData; ++i)
        {
          if (vec_residuals_[i] <= maxThreshold)
            ++nInlier;
        }
        if (nInlier > 2.5 * sizeSample) // does the model is meaningful
          bACRansacMode = true;
      }
      if (bACRansacMode)
      {
        for (size_t i = 0; i < nData; ++i)
        {
          const double error = vec_residuals_[i];
          vec_residuals[i] = ErrorIndex(error, i);
        }
        std::sort(vec_residuals.begin(), vec_residuals.end());

        // Most meaningful discrimination inliers/outliers
        const ErrorIndex best = bestNFA(
          sizeSample,
          kernel.logalpha0(),
          vec_residuals,
          loge0,
          maxThreshold,
          vec_logc_n,
          vec_logc_k,
          kernel.multError());

        if (best.first < minNFA /*&& vec_residuals[best.second-1].first < errorMax*/)
        {
          // A better model was found
          better = true;
          minNFA = best.first;
          vec_inliers.resize(best.second);
          for (size_t i=0; i<best.second; ++i)
            vec_inliers[i] = vec_residuals[i].second;
          errorMax = vec_residuals[best.second-1].first; // Error threshold
          if(model) *model = vec_models[k];

          if(bVerbose)
          {
            std::cout << "  nfa=" << minNFA
              << " inliers=" << best.second << "/" << nData
              << " precisionNormalized=" << errorMax
              << " precision=" << kernel.unormalizeError(errorMax)
              << " (iter=" << iter;
            std::cout << ",sample=";
            std::copy(vec_sample.begin(), vec_sample.end(),
              std::ostream_iterator<size_t>(std::cout, ","));
            std::cout << ")" <<std::endl;
          }
        }
      } //if(bACRansacMode)
    } //for(size_t k...

    // Early exit test -> no meaningful model found after nIterReserve*2 iterations
    if (!bACRansacMode && iter > nIterReserve*2)
      break;

    // ACRANSAC optimization: draw samples among best set of inliers so far
    if (bACRansacMode && ((better && minNFA<0) || (iter+1==nIter && nIterReserve)))
    {
      if (vec_inliers.empty())
      {
        // No model found at all so far
        ++nIter; // Continue to look for any model, even not meaningful
        --nIterReserve;
      }
      else
      {
        // ACRANSAC optimization: draw samples among best set of inliers so far
        vec_index = vec_inliers;
        if(nIterReserve)
        {
          nIter = iter + 1 + nIterReserve;
          nIterReserve = 0;
        }
      }
    }
  }

  if(minNFA >= 0)
    vec_inliers.clear();

  if (!vec_inliers.empty())
  {
    if (model)
      kernel.Unnormalize(model);
    errorMax = kernel.unormalizeError(errorMax);
  }

  return std::make_pair(errorMax, minNFA);
}

} // namespace robust
} // namespace openMVG
#endif // OPENMVG_ROBUST_ESTIMATOR_ACRANSAC_H_
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * 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
 *
 * 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.
 *
 ************************************************************************/
#include "vbatabstops.hxx"
#include "vbatabstop.hxx"
#include <com/sun/star/style/TabAlign.hpp>
#include <ooo/vba/word/WdTabLeader.hpp>
#include <ooo/vba/word/WdTabAlignment.hpp>

using namespace ::ooo::vba;
using namespace ::com::sun::star;

uno::Sequence< style::TabStop > lcl_getTabStops( const uno::Reference< beans::XPropertySet >& xParaProps ) throw (uno::RuntimeException)
{
    uno::Sequence< style::TabStop > aSeq;
    xParaProps->getPropertyValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("ParaTabStops") ) ) >>= aSeq;
    return aSeq;
}

void lcl_setTabStops( const uno::Reference< beans::XPropertySet >& xParaProps, const uno::Sequence< style::TabStop >& aSeq ) throw (uno::RuntimeException)
{
    xParaProps->setPropertyValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("ParaTabStops") ), uno::makeAny( aSeq ) );
}

typedef ::cppu::WeakImplHelper2< container::XIndexAccess, container::XEnumerationAccess > TabStopCollectionHelper_Base;

class TabStopsEnumWrapper : public EnumerationHelper_BASE
{
    uno::Reference< container::XIndexAccess > mxIndexAccess;
    sal_Int32 nIndex;

public:
    TabStopsEnumWrapper( const uno::Reference< container::XIndexAccess >& xIndexAccess ) : mxIndexAccess( xIndexAccess ), nIndex( 0 )
    {
    }
    virtual ::sal_Bool SAL_CALL hasMoreElements(  ) throw (uno::RuntimeException)
    {
        return ( nIndex < mxIndexAccess->getCount() );
    }

    virtual uno::Any SAL_CALL nextElement(  ) throw (container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException)
    {
        if( nIndex < mxIndexAccess->getCount() )
        {
            return mxIndexAccess->getByIndex( nIndex++ );
        }
        throw container::NoSuchElementException();
    }
};

class TabStopCollectionHelper : public TabStopCollectionHelper_Base
{
private:
    uno::Reference< XHelperInterface > mxParent;
    uno::Reference< uno::XComponentContext > mxContext;
    uno::Reference< beans::XPropertySet > mxParaProps;
    uno::Sequence< style::TabStop > maTabStops;

public:
    TabStopCollectionHelper( const css::uno::Reference< ov::XHelperInterface >& xParent, const css::uno::Reference< css::uno::XComponentContext > & xContext, const css::uno::Reference< css::beans::XPropertySet >& xParaProps ) throw ( css::uno::RuntimeException ): mxParent( xParent ), mxContext( xContext ), mxParaProps( xParaProps )
    {
        maTabStops = lcl_getTabStops( xParaProps );
    }

    virtual ~TabStopCollectionHelper() {}

    virtual sal_Int32 SAL_CALL getCount(  ) throw (uno::RuntimeException)
    {
        return maTabStops.getLength();
    }
    virtual uno::Any SAL_CALL getByIndex( sal_Int32 Index ) throw (lang::IndexOutOfBoundsException, lang::WrappedTargetException, uno::RuntimeException)
    {
        if ( Index < 0 || Index >= getCount() )
            throw css::lang::IndexOutOfBoundsException();

        const style::TabStop* pTabs = maTabStops.getConstArray();
        return uno::makeAny( uno::Reference< word::XTabStop >( new SwVbaTabStop( mxParent, mxContext, mxParaProps, pTabs[ Index ] ) ) );
    }
    virtual uno::Type SAL_CALL getElementType(  ) throw (uno::RuntimeException)
    {
        return word::XTabStop::static_type(0);
    }
    virtual sal_Bool SAL_CALL hasElements(  ) throw (uno::RuntimeException)
    {
        return sal_True;
    }
    // XEnumerationAccess
    virtual uno::Reference< container::XEnumeration > SAL_CALL createEnumeration(  ) throw (uno::RuntimeException)
    {
        return new TabStopsEnumWrapper( this );
    }
};

SwVbaTabStops::SwVbaTabStops( const uno::Reference< XHelperInterface >& xParent, const uno::Reference< uno::XComponentContext > & xContext, const uno::Reference< beans::XPropertySet >& xParaProps ) throw (uno::RuntimeException) : SwVbaTabStops_BASE( xParent, xContext, uno::Reference< container::XIndexAccess >( new TabStopCollectionHelper( xParent, xContext, xParaProps ) ) ), mxParaProps( xParaProps )
{
}

uno::Reference< word::XTabStop > SAL_CALL SwVbaTabStops::Add( float Position, const uno::Any& Alignment, const uno::Any& Leader ) throw (uno::RuntimeException)
{
    sal_Int32 nPosition = Millimeter::getInHundredthsOfOneMillimeter( Position );

    style::TabAlign nAlign = style::TabAlign_LEFT;
    if( Alignment.hasValue() )
    {
        sal_Int32 wdAlign = word::WdTabAlignment::wdAlignTabLeft;
        Alignment >>= wdAlign;
        switch( wdAlign )
        {
            case word::WdTabAlignment::wdAlignTabLeft:
            {
                nAlign = style::TabAlign_LEFT;
                break;
            }
            case word::WdTabAlignment::wdAlignTabRight:
            {
                nAlign = style::TabAlign_RIGHT;
                break;
            }
            case word::WdTabAlignment::wdAlignTabCenter:
            {
                nAlign = style::TabAlign_CENTER;
                break;
            }
            case word::WdTabAlignment::wdAlignTabDecimal:
            {
                nAlign = style::TabAlign_DECIMAL;
                break;
            }
            case word::WdTabAlignment::wdAlignTabBar:
            case word::WdTabAlignment::wdAlignTabList:
            {
                DebugHelper::exception( SbERR_NOT_IMPLEMENTED, rtl::OUString() );
                break;
            }
            default:
            {
                //left
            }
        }
    }

    sal_Char cLeader = ' '; // default is space
    if( Leader.hasValue() )
    {
        sal_Int32 wdLeader = word::WdTabLeader::wdTabLeaderSpaces;
        Leader >>= wdLeader;
        switch( wdLeader )
        {
            case word::WdTabLeader::wdTabLeaderSpaces:
            {
                cLeader = ' ';
                break;
            }
            case word::WdTabLeader::wdTabLeaderMiddleDot:
            {
                cLeader = 183;
                break;
            }
            case word::WdTabLeader::wdTabLeaderDots:
            {
                cLeader = '.';
                break;
            }
            case word::WdTabLeader::wdTabLeaderDashes:
            case word::WdTabLeader::wdTabLeaderHeavy:
            case word::WdTabLeader::wdTabLeaderLines:
            {
                cLeader = '_';
                break;
            }
            default:
            {
                //left
            }
        }
    }

    sal_Char cDecimal = '.'; // default value

    style::TabStop aTab;
    aTab.Position = nPosition;
    aTab.Alignment = nAlign;
    aTab.DecimalChar = cDecimal;
    aTab.FillChar = cLeader;

    uno::Sequence< style::TabStop > aOldTabs = lcl_getTabStops( mxParaProps );
    sal_Bool bOverWriter = sal_False;

    sal_Int32 nTabs = aOldTabs.getLength();
    uno::Sequence< style::TabStop > aNewTabs( nTabs + 1 );

    style::TabStop* pOldTab = aOldTabs.getArray();
    style::TabStop* pNewTab = aNewTabs.getArray();
    pNewTab[0] = aTab;
    for( sal_Int32 nIndex = 0; nIndex < nTabs && !bOverWriter; nIndex++ )
    {
        if( pOldTab[nIndex].Position == nPosition )
        {
            bOverWriter = sal_True;
            pOldTab[nIndex] = aTab;
            break;
        }
        pNewTab[ nIndex+1 ] = pOldTab[ nIndex ];
    }
    if( bOverWriter )
        lcl_setTabStops( mxParaProps, aOldTabs );
    else
        lcl_setTabStops( mxParaProps, aNewTabs );

    return uno::Reference< word::XTabStop >( new SwVbaTabStop( this, mxContext, mxParaProps, aTab ) );
}

void SAL_CALL SwVbaTabStops::ClearAll() throw (uno::RuntimeException)
{
    uno::Sequence< style::TabStop > aSeq;
    lcl_setTabStops( mxParaProps, aSeq );
}

// XEnumerationAccess
uno::Type
SwVbaTabStops::getElementType() throw (uno::RuntimeException)
{
    return word::XTabStop::static_type(0);
}
uno::Reference< container::XEnumeration >
SwVbaTabStops::createEnumeration() throw (uno::RuntimeException)
{
    return new TabStopsEnumWrapper( m_xIndexAccess );
}

uno::Any
SwVbaTabStops::createCollectionObject( const css::uno::Any& aSource )
{
    return aSource;
}

rtl::OUString&
SwVbaTabStops::getServiceImplName()
{
    static rtl::OUString sImplName( RTL_CONSTASCII_USTRINGPARAM("SwVbaTabStops") );
    return sImplName;
}

css::uno::Sequence<rtl::OUString>
SwVbaTabStops::getServiceNames()
{
    static uno::Sequence< rtl::OUString > sNames;
    if ( sNames.getLength() == 0 )
    {
        sNames.realloc( 1 );
        sNames[0] = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("ooo.vba.word.TabStops") );
    }
    return sNames;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>WaE: truncation of constant value<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * 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
 *
 * 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.
 *
 ************************************************************************/
#include "vbatabstops.hxx"
#include "vbatabstop.hxx"
#include <com/sun/star/style/TabAlign.hpp>
#include <ooo/vba/word/WdTabLeader.hpp>
#include <ooo/vba/word/WdTabAlignment.hpp>

using namespace ::ooo::vba;
using namespace ::com::sun::star;

uno::Sequence< style::TabStop > lcl_getTabStops( const uno::Reference< beans::XPropertySet >& xParaProps ) throw (uno::RuntimeException)
{
    uno::Sequence< style::TabStop > aSeq;
    xParaProps->getPropertyValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("ParaTabStops") ) ) >>= aSeq;
    return aSeq;
}

void lcl_setTabStops( const uno::Reference< beans::XPropertySet >& xParaProps, const uno::Sequence< style::TabStop >& aSeq ) throw (uno::RuntimeException)
{
    xParaProps->setPropertyValue( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("ParaTabStops") ), uno::makeAny( aSeq ) );
}

typedef ::cppu::WeakImplHelper2< container::XIndexAccess, container::XEnumerationAccess > TabStopCollectionHelper_Base;

class TabStopsEnumWrapper : public EnumerationHelper_BASE
{
    uno::Reference< container::XIndexAccess > mxIndexAccess;
    sal_Int32 nIndex;

public:
    TabStopsEnumWrapper( const uno::Reference< container::XIndexAccess >& xIndexAccess ) : mxIndexAccess( xIndexAccess ), nIndex( 0 )
    {
    }
    virtual ::sal_Bool SAL_CALL hasMoreElements(  ) throw (uno::RuntimeException)
    {
        return ( nIndex < mxIndexAccess->getCount() );
    }

    virtual uno::Any SAL_CALL nextElement(  ) throw (container::NoSuchElementException, lang::WrappedTargetException, uno::RuntimeException)
    {
        if( nIndex < mxIndexAccess->getCount() )
        {
            return mxIndexAccess->getByIndex( nIndex++ );
        }
        throw container::NoSuchElementException();
    }
};

class TabStopCollectionHelper : public TabStopCollectionHelper_Base
{
private:
    uno::Reference< XHelperInterface > mxParent;
    uno::Reference< uno::XComponentContext > mxContext;
    uno::Reference< beans::XPropertySet > mxParaProps;
    uno::Sequence< style::TabStop > maTabStops;

public:
    TabStopCollectionHelper( const css::uno::Reference< ov::XHelperInterface >& xParent, const css::uno::Reference< css::uno::XComponentContext > & xContext, const css::uno::Reference< css::beans::XPropertySet >& xParaProps ) throw ( css::uno::RuntimeException ): mxParent( xParent ), mxContext( xContext ), mxParaProps( xParaProps )
    {
        maTabStops = lcl_getTabStops( xParaProps );
    }

    virtual ~TabStopCollectionHelper() {}

    virtual sal_Int32 SAL_CALL getCount(  ) throw (uno::RuntimeException)
    {
        return maTabStops.getLength();
    }
    virtual uno::Any SAL_CALL getByIndex( sal_Int32 Index ) throw (lang::IndexOutOfBoundsException, lang::WrappedTargetException, uno::RuntimeException)
    {
        if ( Index < 0 || Index >= getCount() )
            throw css::lang::IndexOutOfBoundsException();

        const style::TabStop* pTabs = maTabStops.getConstArray();
        return uno::makeAny( uno::Reference< word::XTabStop >( new SwVbaTabStop( mxParent, mxContext, mxParaProps, pTabs[ Index ] ) ) );
    }
    virtual uno::Type SAL_CALL getElementType(  ) throw (uno::RuntimeException)
    {
        return word::XTabStop::static_type(0);
    }
    virtual sal_Bool SAL_CALL hasElements(  ) throw (uno::RuntimeException)
    {
        return sal_True;
    }
    // XEnumerationAccess
    virtual uno::Reference< container::XEnumeration > SAL_CALL createEnumeration(  ) throw (uno::RuntimeException)
    {
        return new TabStopsEnumWrapper( this );
    }
};

SwVbaTabStops::SwVbaTabStops( const uno::Reference< XHelperInterface >& xParent, const uno::Reference< uno::XComponentContext > & xContext, const uno::Reference< beans::XPropertySet >& xParaProps ) throw (uno::RuntimeException) : SwVbaTabStops_BASE( xParent, xContext, uno::Reference< container::XIndexAccess >( new TabStopCollectionHelper( xParent, xContext, xParaProps ) ) ), mxParaProps( xParaProps )
{
}

uno::Reference< word::XTabStop > SAL_CALL SwVbaTabStops::Add( float Position, const uno::Any& Alignment, const uno::Any& Leader ) throw (uno::RuntimeException)
{
    sal_Int32 nPosition = Millimeter::getInHundredthsOfOneMillimeter( Position );

    style::TabAlign nAlign = style::TabAlign_LEFT;
    if( Alignment.hasValue() )
    {
        sal_Int32 wdAlign = word::WdTabAlignment::wdAlignTabLeft;
        Alignment >>= wdAlign;
        switch( wdAlign )
        {
            case word::WdTabAlignment::wdAlignTabLeft:
            {
                nAlign = style::TabAlign_LEFT;
                break;
            }
            case word::WdTabAlignment::wdAlignTabRight:
            {
                nAlign = style::TabAlign_RIGHT;
                break;
            }
            case word::WdTabAlignment::wdAlignTabCenter:
            {
                nAlign = style::TabAlign_CENTER;
                break;
            }
            case word::WdTabAlignment::wdAlignTabDecimal:
            {
                nAlign = style::TabAlign_DECIMAL;
                break;
            }
            case word::WdTabAlignment::wdAlignTabBar:
            case word::WdTabAlignment::wdAlignTabList:
            {
                DebugHelper::exception( SbERR_NOT_IMPLEMENTED, rtl::OUString() );
                break;
            }
            default:
            {
                //left
            }
        }
    }

    sal_Unicode cLeader = ' '; // default is space
    if( Leader.hasValue() )
    {
        sal_Int32 wdLeader = word::WdTabLeader::wdTabLeaderSpaces;
        Leader >>= wdLeader;
        switch( wdLeader )
        {
            case word::WdTabLeader::wdTabLeaderSpaces:
            {
                cLeader = ' ';
                break;
            }
            case word::WdTabLeader::wdTabLeaderMiddleDot:
            {
                cLeader = 183; // U+00B7 MIDDLE DOT
                break;
            }
            case word::WdTabLeader::wdTabLeaderDots:
            {
                cLeader = '.';
                break;
            }
            case word::WdTabLeader::wdTabLeaderDashes:
            case word::WdTabLeader::wdTabLeaderHeavy:
            case word::WdTabLeader::wdTabLeaderLines:
            {
                cLeader = '_';
                break;
            }
            default:
            {
                //left
            }
        }
    }

    sal_Char cDecimal = '.'; // default value

    style::TabStop aTab;
    aTab.Position = nPosition;
    aTab.Alignment = nAlign;
    aTab.DecimalChar = cDecimal;
    aTab.FillChar = cLeader;

    uno::Sequence< style::TabStop > aOldTabs = lcl_getTabStops( mxParaProps );
    sal_Bool bOverWriter = sal_False;

    sal_Int32 nTabs = aOldTabs.getLength();
    uno::Sequence< style::TabStop > aNewTabs( nTabs + 1 );

    style::TabStop* pOldTab = aOldTabs.getArray();
    style::TabStop* pNewTab = aNewTabs.getArray();
    pNewTab[0] = aTab;
    for( sal_Int32 nIndex = 0; nIndex < nTabs && !bOverWriter; nIndex++ )
    {
        if( pOldTab[nIndex].Position == nPosition )
        {
            bOverWriter = sal_True;
            pOldTab[nIndex] = aTab;
            break;
        }
        pNewTab[ nIndex+1 ] = pOldTab[ nIndex ];
    }
    if( bOverWriter )
        lcl_setTabStops( mxParaProps, aOldTabs );
    else
        lcl_setTabStops( mxParaProps, aNewTabs );

    return uno::Reference< word::XTabStop >( new SwVbaTabStop( this, mxContext, mxParaProps, aTab ) );
}

void SAL_CALL SwVbaTabStops::ClearAll() throw (uno::RuntimeException)
{
    uno::Sequence< style::TabStop > aSeq;
    lcl_setTabStops( mxParaProps, aSeq );
}

// XEnumerationAccess
uno::Type
SwVbaTabStops::getElementType() throw (uno::RuntimeException)
{
    return word::XTabStop::static_type(0);
}
uno::Reference< container::XEnumeration >
SwVbaTabStops::createEnumeration() throw (uno::RuntimeException)
{
    return new TabStopsEnumWrapper( m_xIndexAccess );
}

uno::Any
SwVbaTabStops::createCollectionObject( const css::uno::Any& aSource )
{
    return aSource;
}

rtl::OUString&
SwVbaTabStops::getServiceImplName()
{
    static rtl::OUString sImplName( RTL_CONSTASCII_USTRINGPARAM("SwVbaTabStops") );
    return sImplName;
}

css::uno::Sequence<rtl::OUString>
SwVbaTabStops::getServiceNames()
{
    static uno::Sequence< rtl::OUString > sNames;
    if ( sNames.getLength() == 0 )
    {
        sNames.realloc( 1 );
        sNames[0] = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("ooo.vba.word.TabStops") );
    }
    return sNames;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


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

#ifndef _CONNECTIVITY_FILE_TABLE_HXX_
#define _CONNECTIVITY_FILE_TABLE_HXX_

#ifndef _CONNECTIVITY_SDBCX_TABLE_HXX_
#include "connectivity/sdbcx/VTable.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XDATABASEMETADATA_HPP_
#include <com/sun/star/sdbc/XDatabaseMetaData.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XUNOTUNNEL_HPP_
#include <com/sun/star/lang/XUnoTunnel.hpp>
#endif
#ifndef _CONNECTIVITY_FILE_BCONNECTION_HXX_
#include "file/FConnection.hxx"
#endif
#ifndef _STREAM_HXX
#include <tools/stream.hxx>
#endif
#ifndef _CONNECTIVITY_FILE_VALUE_HXX_
#include "connectivity/FValue.hxx"
#endif
#ifndef CONNECTIVITY_TRESULTSETHELPER_HXX
#include "TResultSetHelper.hxx"
#endif

namespace connectivity
{
    namespace file
    {
        typedef connectivity::sdbcx::OTable OTable_TYPEDEF;

        class OFileTable :  public OTable_TYPEDEF
        {
        protected:
            ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData >   m_xMetaData;
            OConnection*                                        m_pConnection;
            SvStream*                                           m_pFileStream;
            ::vos::ORef<OSQLColumns>                            m_aColumns;
            sal_Int32                                           m_nFilePos;                 // aktuelle IResultSetHelper::Movement
            sal_uInt8*                                          m_pBuffer;
            sal_uInt16                                          m_nBufferSize;  // Groesse des ReadBuffer, wenn pBuffer != NULL
            sal_Bool                                            m_bWriteable;   // svstream cann't say if we are writeable
                                                                                // so we have to

            virtual void FileClose();
            virtual ~OFileTable( );
        public:
            virtual void refreshColumns();
            virtual void refreshKeys();
            virtual void refreshIndexes();
        public:
            OFileTable( sdbcx::OCollection* _pTables,OConnection* _pConnection);
            OFileTable( sdbcx::OCollection* _pTables,OConnection* _pConnection,
                    const ::rtl::OUString& _Name,
                    const ::rtl::OUString& _Type,
                    const ::rtl::OUString& _Description = ::rtl::OUString(),
                    const ::rtl::OUString& _SchemaName = ::rtl::OUString(),
                    const ::rtl::OUString& _CatalogName = ::rtl::OUString()
                );

            //XInterface
            virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL acquire() throw();
            virtual void SAL_CALL release() throw();
            // ::cppu::OComponentHelper
            virtual void SAL_CALL disposing(void);

            OConnection* getConnection() const { return m_pConnection;}
            virtual sal_Int32 getCurrentLastPos() const {return -1;}

            virtual sal_Bool seekRow(IResultSetHelper::Movement eCursorPosition, sal_Int32 nOffset, sal_Int32& nCurPos) = 0;
            virtual sal_Bool fetchRow(OValueRow _rRow,const OSQLColumns& _rCols, sal_Bool _bUseTableDefs,sal_Bool bRetrieveData) = 0;

            ::vos::ORef<OSQLColumns> getTableColumns() const {return m_aColumns;}
            virtual BOOL InsertRow(OValueVector& rRow, BOOL bFlush,const ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess>& _xCols);
            virtual BOOL DeleteRow(const OSQLColumns& _rCols);
            virtual BOOL UpdateRow(OValueVector& rRow, OValueRow pOrgRow,const ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess>& _xCols);
            virtual void addColumn(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& descriptor);
            virtual void dropColumn(sal_Int32 _nPos);
            // refresh the header of file based tables to see changes done by someone
            virtual void refreshHeader();

            ::rtl::OUString SAL_CALL getName() throw() { return m_Name; }

            ::rtl::OUString getSchema() { return m_SchemaName; }
            sal_Bool isReadOnly() const { return !m_bWriteable; }
                // m_pFileStream && !m_pFileStream->IsWritable(); }
            // com::sun::star::lang::XUnoTunnel
            virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier ) throw(::com::sun::star::uno::RuntimeException);
            static ::com::sun::star::uno::Sequence< sal_Int8 > getUnoTunnelImplementationId();

            sal_Int32 getFilePos() const { return m_nFilePos; }

        public:
            // helper

            // creates a stream using ::utl::UcbStreamHelper::CreateStream, but the error is simplified
            // (NULL or non-NULL is returned)
            static SvStream* createStream_simpleError( const String& _rFileName, StreamMode _eOpenMode);
        };
    }
}
#endif // _CONNECTIVITY_FILE_TABLE_HXX_

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

#ifndef _CONNECTIVITY_FILE_TABLE_HXX_
#define _CONNECTIVITY_FILE_TABLE_HXX_

#ifndef _CONNECTIVITY_SDBCX_TABLE_HXX_
#include "connectivity/sdbcx/VTable.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XDATABASEMETADATA_HPP_
#include <com/sun/star/sdbc/XDatabaseMetaData.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XUNOTUNNEL_HPP_
#include <com/sun/star/lang/XUnoTunnel.hpp>
#endif
#ifndef _CONNECTIVITY_FILE_BCONNECTION_HXX_
#include "file/FConnection.hxx"
#endif
#ifndef _STREAM_HXX
#include <tools/stream.hxx>
#endif
#ifndef _CONNECTIVITY_FILE_VALUE_HXX_
#include "connectivity/FValue.hxx"
#endif
#ifndef CONNECTIVITY_TRESULTSETHELPER_HXX
#include "TResultSetHelper.hxx"
#endif

namespace connectivity
{
    namespace file
    {
        typedef connectivity::sdbcx::OTable OTable_TYPEDEF;

        class OFileTable :  public OTable_TYPEDEF
        {
        protected:
            ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData >   m_xMetaData;
            OConnection*                                        m_pConnection;
            SvStream*                                           m_pFileStream;
            ::vos::ORef<OSQLColumns>                            m_aColumns;
            sal_Int32                                           m_nFilePos;                 // aktuelle IResultSetHelper::Movement
            sal_uInt8*                                          m_pBuffer;
            sal_uInt16                                          m_nBufferSize;  // Groesse des ReadBuffer, wenn pBuffer != NULL
            sal_Bool                                            m_bWriteable;   // svstream cann't say if we are writeable
                                                                                // so we have to

            virtual void FileClose();
            virtual ~OFileTable( );
        public:
            virtual void refreshColumns();
            virtual void refreshKeys();
            virtual void refreshIndexes();
        public:
            OFileTable( sdbcx::OCollection* _pTables,OConnection* _pConnection);
            OFileTable( sdbcx::OCollection* _pTables,OConnection* _pConnection,
                    const ::rtl::OUString& _Name,
                    const ::rtl::OUString& _Type,
                    const ::rtl::OUString& _Description = ::rtl::OUString(),
                    const ::rtl::OUString& _SchemaName = ::rtl::OUString(),
                    const ::rtl::OUString& _CatalogName = ::rtl::OUString()
                );

            //XInterface
            virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL acquire() throw();
            virtual void SAL_CALL release() throw();
            // ::cppu::OComponentHelper
            virtual void SAL_CALL disposing(void);

            OConnection* getConnection() const { return m_pConnection;}
            virtual sal_Int32 getCurrentLastPos() const {return -1;}

            virtual sal_Bool seekRow(IResultSetHelper::Movement eCursorPosition, sal_Int32 nOffset, sal_Int32& nCurPos) = 0;
            virtual sal_Bool fetchRow(OValueRefRow& _rRow,const OSQLColumns& _rCols, sal_Bool _bUseTableDefs,sal_Bool bRetrieveData) = 0;

            ::vos::ORef<OSQLColumns> getTableColumns() const {return m_aColumns;}
            virtual BOOL InsertRow(OValueRefVector& rRow, BOOL bFlush,const ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess>& _xCols);
            virtual BOOL DeleteRow(const OSQLColumns& _rCols);
            virtual BOOL UpdateRow(OValueRefVector& rRow, OValueRefRow& pOrgRow,const ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess>& _xCols);
            virtual void addColumn(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& descriptor);
            virtual void dropColumn(sal_Int32 _nPos);
            // refresh the header of file based tables to see changes done by someone
            virtual void refreshHeader();

            ::rtl::OUString SAL_CALL getName() throw() { return m_Name; }

            ::rtl::OUString getSchema() { return m_SchemaName; }
            sal_Bool isReadOnly() const { return !m_bWriteable; }
                // m_pFileStream && !m_pFileStream->IsWritable(); }
            // com::sun::star::lang::XUnoTunnel
            virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier ) throw(::com::sun::star::uno::RuntimeException);
            static ::com::sun::star::uno::Sequence< sal_Int8 > getUnoTunnelImplementationId();

            sal_Int32 getFilePos() const { return m_nFilePos; }

        public:
            // helper

            // creates a stream using ::utl::UcbStreamHelper::CreateStream, but the error is simplified
            // (NULL or non-NULL is returned)
            static SvStream* createStream_simpleError( const String& _rFileName, StreamMode _eOpenMode);
        };
    }
}
#endif // _CONNECTIVITY_FILE_TABLE_HXX_

<|endoftext|>


<commit_before>#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#if !defined(_WIN32) && !defined(NDEBUG)
#include <execinfo.h>
#include <signal.h>
#endif
#include "gason.h"

const char *SUITE[] =
{
u8R"raw("A JSON payload should be an object or array, not a string.")raw",
u8R"raw(["Unclosed array")raw",
u8R"raw({unquoted_key: "keys must be quoted"})raw",
u8R"raw(["extra comma",])raw",
u8R"raw(["double extra comma",,])raw",
u8R"raw([   , "<-- missing value"])raw",
u8R"raw(["Comma after the close"],)raw",
u8R"raw(["Extra close"]])raw",
u8R"raw({"Extra comma": true,})raw",
u8R"raw({"Extra value after close": true} "misplaced quoted value")raw",
u8R"raw({"Illegal expression": 1 + 2})raw",
u8R"raw({"Illegal invocation": alert()})raw",
u8R"raw({"Numbers cannot have leading zeroes": 013})raw",
u8R"raw({"Numbers cannot be hex": 0x14})raw",
u8R"raw(["Illegal backslash escape: \x15"])raw",
u8R"raw([\naked])raw",
u8R"raw(["Illegal backslash escape: \017"])raw",
u8R"raw([[[[[[[[[[[[[[[[[[[["Too deep"]]]]]]]]]]]]]]]]]]]])raw",
u8R"raw({"Missing colon" null})raw",
u8R"raw({"Double colon":: null})raw",
u8R"raw({"Comma instead of colon", null})raw",
u8R"raw(["Colon instead of comma": false])raw",
u8R"raw(["Bad value", truth])raw",
u8R"raw(['single quote'])raw",
u8R"raw(["	tab	character	in	string	"])raw",
u8R"raw(["tab\   character\   in\  string\  "])raw",
u8R"raw(["line
break"])raw",
u8R"raw(["line\
break"])raw",
u8R"raw([0e])raw",
u8R"raw([0e+])raw",
u8R"raw([0e+-1])raw",
u8R"raw({"Comma instead if closing brace": true,)raw",
u8R"raw(["mismatch"})raw",
u8R"raw(
[
    "JSON Test Pattern pass1",
    {"object with 1 member":["array with 1 element"]},
    {},
    [],
    -42,
    true,
    false,
    null,
    {
        "integer": 1234567890,
        "real": -9876.543210,
        "e": 0.123456789e-12,
        "E": 1.234567890E+34,
        "":  23456789012E66,
        "zero": 0,
        "one": 1,
        "space": " ",
        "quote": "\"",
        "backslash": "\\",
        "controls": "\b\f\n\r\t",
        "slash": "/ & \/",
        "alpha": "abcdefghijklmnopqrstuvwyz",
        "ALPHA": "ABCDEFGHIJKLMNOPQRSTUVWYZ",
        "digit": "0123456789",
        "0123456789": "digit",
        "special": "`1~!@#$%^&*()_+-={':[,]}|;.</>?",
        "hex": "\u0123\u4567\u89AB\uCDEF\uabcd\uef4A",
        "true": true,
        "false": false,
        "null": null,
        "array":[  ],
        "object":{  },
        "address": "50 St. James Street",
        "url": "http://www.JSON.org/",
        "comment": "// /* <!-- --",
        "# -- --> */": " ",
        " s p a c e d " :[1,2 , 3

,

4 , 5        ,          6           ,7        ],"compact":[1,2,3,4,5,6,7],
        "jsontext": "{\"object with 1 member\":[\"array with 1 element\"]}",
        "quotes": "" \u0022 %22 0x22 034 "",
        "\/\\\"\uCAFE\uBABE\uAB98\uFCDE\ubcda\uef4A\b\f\n\r\t`1~!@#$%^&*()_+-=[]{}|;:',./<>?"
: "A key can be any string"
    },
    0.5 ,98.6
,
99.44
,

1066,
1e1,
0.1e1,
1e-1,
1e00,2e+00,2e-00
,"rosebud"])raw",
u8R"raw([[[[[[[[[[[[[[[[[[["Not too deep"]]]]]]]]]]]]]]]]]]])raw",
u8R"raw({
    "JSON Test Pattern pass3": {
        "The outermost value": "must be an object or array.",
        "In this test": "It is an object."
    }
}
)raw",
u8R"raw([1, 2, "хУй", [[0.5], 7.11, 13.19e+1], "ba\u0020r", [ [ ] ], -0, -.666, [true, null], {"WAT?!": false}])raw"
};

int main()
{
#if !defined(_WIN32) && !defined(NDEBUG)
	auto abort_handler = [](int)
	{
		void *callstack[16];
		int size = backtrace(callstack, sizeof(callstack) / sizeof(callstack[0]));
		char **names = backtrace_symbols(callstack, size);
		for (int i = 0; i < size; ++i)
		{
			fprintf(stderr, "%s\n", names[i]);
		}
		free(names);
		exit(EXIT_FAILURE);
	};
	signal(SIGABRT, abort_handler);
#endif

	char *endptr;
	JsonValue value;
	JsonAllocator allocator;
	size_t passed = 0;
	size_t count = 0;
	for (auto *s : SUITE)
	{
		char *source = strdup(s);
		JsonParseStatus status = json_parse(source, &endptr, &value, allocator);
		if (status != JSON_PARSE_OK)
		{
			size_t pos = endptr - source;
			fprintf(stderr, "test-suite%zd:%zd: error: %d, %.*s<--- there\n", count, pos, (int)status, (int)pos, s);
		}
		else
		{
			++passed;
		}
		free(source);
		++count;
	}
	fprintf(stderr, "%zd/%zd\n", passed, count);

	return 0;
}
<commit_msg>even simpler error print<commit_after>#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#if !defined(_WIN32) && !defined(NDEBUG)
#include <execinfo.h>
#include <signal.h>
#endif
#include "gason.h"

const char *SUITE[] =
{
u8R"raw("A JSON payload should be an object or array, not a string.")raw",
u8R"raw(["Unclosed array")raw",
u8R"raw({unquoted_key: "keys must be quoted"})raw",
u8R"raw(["extra comma",])raw",
u8R"raw(["double extra comma",,])raw",
u8R"raw([   , "<-- missing value"])raw",
u8R"raw(["Comma after the close"],)raw",
u8R"raw(["Extra close"]])raw",
u8R"raw({"Extra comma": true,})raw",
u8R"raw({"Extra value after close": true} "misplaced quoted value")raw",
u8R"raw({"Illegal expression": 1 + 2})raw",
u8R"raw({"Illegal invocation": alert()})raw",
u8R"raw({"Numbers cannot have leading zeroes": 013})raw",
u8R"raw({"Numbers cannot be hex": 0x14})raw",
u8R"raw(["Illegal backslash escape: \x15"])raw",
u8R"raw([\naked])raw",
u8R"raw(["Illegal backslash escape: \017"])raw",
u8R"raw([[[[[[[[[[[[[[[[[[[["Too deep"]]]]]]]]]]]]]]]]]]]])raw",
u8R"raw({"Missing colon" null})raw",
u8R"raw({"Double colon":: null})raw",
u8R"raw({"Comma instead of colon", null})raw",
u8R"raw(["Colon instead of comma": false])raw",
u8R"raw(["Bad value", truth])raw",
u8R"raw(['single quote'])raw",
u8R"raw(["	tab	character	in	string	"])raw",
u8R"raw(["tab\   character\   in\  string\  "])raw",
u8R"raw(["line
break"])raw",
u8R"raw(["line\
break"])raw",
u8R"raw([0e])raw",
u8R"raw([0e+])raw",
u8R"raw([0e+-1])raw",
u8R"raw({"Comma instead if closing brace": true,)raw",
u8R"raw(["mismatch"})raw",
u8R"raw(
[
    "JSON Test Pattern pass1",
    {"object with 1 member":["array with 1 element"]},
    {},
    [],
    -42,
    true,
    false,
    null,
    {
        "integer": 1234567890,
        "real": -9876.543210,
        "e": 0.123456789e-12,
        "E": 1.234567890E+34,
        "":  23456789012E66,
        "zero": 0,
        "one": 1,
        "space": " ",
        "quote": "\"",
        "backslash": "\\",
        "controls": "\b\f\n\r\t",
        "slash": "/ & \/",
        "alpha": "abcdefghijklmnopqrstuvwyz",
        "ALPHA": "ABCDEFGHIJKLMNOPQRSTUVWYZ",
        "digit": "0123456789",
        "0123456789": "digit",
        "special": "`1~!@#$%^&*()_+-={':[,]}|;.</>?",
        "hex": "\u0123\u4567\u89AB\uCDEF\uabcd\uef4A",
        "true": true,
        "false": false,
        "null": null,
        "array":[  ],
        "object":{  },
        "address": "50 St. James Street",
        "url": "http://www.JSON.org/",
        "comment": "// /* <!-- --",
        "# -- --> */": " ",
        " s p a c e d " :[1,2 , 3

,

4 , 5        ,          6           ,7        ],"compact":[1,2,3,4,5,6,7],
        "jsontext": "{\"object with 1 member\":[\"array with 1 element\"]}",
        "quotes": "" \u0022 %22 0x22 034 "",
        "\/\\\"\uCAFE\uBABE\uAB98\uFCDE\ubcda\uef4A\b\f\n\r\t`1~!@#$%^&*()_+-=[]{}|;:',./<>?"
: "A key can be any string"
    },
    0.5 ,98.6
,
99.44
,

1066,
1e1,
0.1e1,
1e-1,
1e00,2e+00,2e-00
,"rosebud"])raw",
u8R"raw([[[[[[[[[[[[[[[[[[["Not too deep"]]]]]]]]]]]]]]]]]]])raw",
u8R"raw({
    "JSON Test Pattern pass3": {
        "The outermost value": "must be an object or array.",
        "In this test": "It is an object."
    }
}
)raw",
u8R"raw([1, 2, "хУй", [[0.5], 7.11, 13.19e+1], "ba\u0020r", [ [ ] ], -0, -.666, [true, null], {"WAT?!": false}])raw"
};

int main()
{
#if !defined(_WIN32) && !defined(NDEBUG)
	auto abort_handler = [](int)
	{
		void *callstack[16];
		int size = backtrace(callstack, sizeof(callstack) / sizeof(callstack[0]));
		char **names = backtrace_symbols(callstack, size);
		for (int i = 0; i < size; ++i)
		{
			fprintf(stderr, "%s\n", names[i]);
		}
		free(names);
		exit(EXIT_FAILURE);
	};
	signal(SIGABRT, abort_handler);
#endif

	char *endptr;
	JsonValue value;
	JsonAllocator allocator;
	int passed = 0;
	int count = 0;
	for (auto *s : SUITE)
	{
		char *source = strdup(s);
		JsonParseStatus status = json_parse(source, &endptr, &value, allocator);
		if (status != JSON_PARSE_OK)
		{
			int error_pos = endptr - source + 1;
			fprintf(stderr, "test-suite%d:%d: error: %d, %.*s<--- there\n", count, error_pos, (int)status, error_pos, s);
		}
		else
		{
			++passed;
		}
		free(source);
		++count;
	}
	fprintf(stderr, "%d/%d\n", passed, count);

	return 0;
}
<|endoftext|>