<commit_before>#include <ros/ros.h>
#include <itomp_cio_planner/optimization/itomp_optimizer.h>
#include <itomp_cio_planner/optimization/phase_manager.h>
#include <itomp_cio_planner/contact/ground_manager.h>
#include <itomp_cio_planner/visualization/new_viz_manager.h>
#include <itomp_cio_planner/util/planning_parameters.h>
#include <itomp_cio_planner/optimization/improvement_manager_nlp.h>
//#include <itomp_cio_planner/optimization/improvement_manager_chomp.h>

using namespace std;

namespace itomp_cio_planner
{

ItompOptimizer::ItompOptimizer(int trajectory_index,
                               const ItompTrajectoryPtr& itomp_trajectory,
							   const ItompRobotModelConstPtr& robot_model,
							   const planning_scene::PlanningSceneConstPtr& planning_scene,
							   const ItompPlanningGroupConstPtr& planning_group,
							   double planning_start_time, double trajectory_start_time,
                               const std::vector<moveit_msgs::Constraints>& trajectory_constraints) :
    trajectory_index_(trajectory_index), planning_start_time_(planning_start_time), iteration_(-1),
    best_parameter_cost_(std::numeric_limits<double>::max()), is_best_parameter_feasible_(false), best_parameter_iteration_(-1)
{
    initialize(itomp_trajectory, robot_model, planning_scene, planning_group,
               trajectory_start_time, trajectory_constraints);
}

void ItompOptimizer::initialize(const ItompTrajectoryPtr& itomp_trajectory,
								const ItompRobotModelConstPtr& robot_model,
								const planning_scene::PlanningSceneConstPtr& planning_scene,
								const ItompPlanningGroupConstPtr& planning_group,
								double trajectory_start_time,
                                const std::vector<moveit_msgs::Constraints>& trajectory_constraints)
{
	improvement_manager_ = boost::make_shared<ImprovementManagerNLP>();
	//improvement_manager_ = boost::make_shared<ImprovementManagerChomp>();

	NewVizManager::getInstance()->setPlanningGroup(planning_group);

    NewEvalManager::ref_evaluation_manager_ = NULL;
	evaluation_manager_ = boost::make_shared<NewEvalManager>();
    evaluation_manager_->initialize(itomp_trajectory, robot_model,
									planning_scene, planning_group, planning_start_time_,
                                    trajectory_start_time, trajectory_constraints);
	improvement_manager_->initialize(evaluation_manager_, planning_group);

    PhaseManager::getInstance()->init(itomp_trajectory->getNumPoints());

    best_parameter_trajectory_.set_size(itomp_trajectory->getNumParameters(), 1);
}

ItompOptimizer::~ItompOptimizer()
{
    improvement_manager_.reset();
    evaluation_manager_.reset();
}

bool ItompOptimizer::optimize()
{
	ros::WallTime start_time = ros::WallTime::now();
	iteration_ = -1;
	best_parameter_cost_ = numeric_limits<double>::max();
	is_best_parameter_feasible_ = false;
	best_parameter_iteration_ = -1;

	improvement_manager_->updatePlanningParameters();

	evaluation_manager_->evaluate();

	evaluation_manager_->render();
	updateBestTrajectory();
	++iteration_;

	int iteration_after_feasible_solution = 0;
    int num_max_iterations = 3;
    //PlanningParameters::getInstance()->getMaxIterations();

    //++iteration_;

	if (!evaluation_manager_->isLastTrajectoryFeasible())
	{
		while (iteration_ < num_max_iterations)
		{
			if (is_best_parameter_feasible_)
				++iteration_after_feasible_solution;

            PhaseManager::getInstance()->setPhase(iteration_);
            if (iteration_ != 0)
            {
                best_parameter_cost_ = numeric_limits<double>::max();
                evaluation_manager_->resetBestTrajectoryCost();
            }

            ROS_INFO("Planning Phase %d...", iteration_);

			improvement_manager_->runSingleIteration(iteration_);
			evaluation_manager_->printTrajectoryCost(iteration_);

			//bool is_cost_reduced = (evaluation_manager_->getTrajectoryCost() < best_parameter_cost_);
			bool is_updated = updateBestTrajectory();
			// is_cost_reduced : allow moving to non-feasible low-cost solutions
			// is_updated : only moves in feasible solutions
			if (!is_updated)
				evaluation_manager_->setParameters(best_parameter_trajectory_);

			++iteration_;

            if (iteration_after_feasible_solution > PlanningParameters::getInstance()->getMaxIterationsAfterCollisionFree())
				break;

            /*
            if (iteration_ == 2)
            {
                for (int i = 1; i < evaluation_manager_->getTrajectory()->getNumPoints(); ++i)
                {
                    robot_state::RobotState robot_state(*evaluation_manager_->getRobotState(i));
                    const std::vector<const robot_model::LinkModel*>& robot_link_models = evaluation_manager_->getItompRobotModel()->getMoveitRobotModel()->getLinkModels();

                    Eigen::Affine3d root_pose;
                    Eigen::Affine3d left_foot_pose;
                    Eigen::Affine3d right_foot_pose;

                    ElementTrajectoryPtr& joint_traj = evaluation_manager_->getTrajectoryNonConst()->getElementTrajectory(ItompTrajectory::COMPONENT_TYPE_POSITION,
                                                       ItompTrajectory::SUB_COMPONENT_TYPE_JOINT);

                    for (unsigned int j = 0; j < robot_state.getVariableCount(); ++j)
                        robot_state.getVariablePositions()[j] = joint_traj->getTrajectoryPoint(i)(j);
                    robot_state.update(true);
                    root_pose = robot_state.getGlobalLinkTransform(robot_link_models[6]);

                    evaluation_manager_->getItompRobotModel()->getGroupEndeffectorPos("left_leg", robot_state, left_foot_pose);
                    evaluation_manager_->getItompRobotModel()->getGroupEndeffectorPos("right_leg", robot_state, right_foot_pose);

                    Eigen::Vector3d normal_out, pos_out, orientation_out;
                    GroundManager::getInstance()->getNearestContactPosition(left_foot_pose.translation(), exponential_map::RotationToExponentialMap(left_foot_pose.linear()),
                                                                      pos_out, orientation_out, normal_out);
                    //GroundManager::getInstance()->getNearestZPosition(left_foot_pose.translation(), exponential_map::RotationToExponentialMap(left_foot_pose.linear()),
                      //                                                pos_out, orientation_out, normal_out);

                    if ((i == 40 || normal_out.dot(left_foot_pose.translation() - pos_out) < 0.0) ||
                        (PhaseManager::getInstance()->support_foot_ == 1 && i <= 20) ||
                        (PhaseManager::getInstance()->support_foot_ != 1 && i >= 20))
                    {
                        left_foot_pose.translation() = pos_out;
                        left_foot_pose.linear() = exponential_map::ExponentialMapToRotation(orientation_out);
                    }
                    GroundManager::getInstance()->getNearestContactPosition(right_foot_pose.translation(), exponential_map::RotationToExponentialMap(right_foot_pose.linear()),
                                                                      pos_out, orientation_out, normal_out);
                    if ((i == 40 || normal_out.dot(right_foot_pose.translation() - pos_out) < 0.0) ||
                        (PhaseManager::getInstance()->support_foot_ == 2 && i <= 20) ||
                        (PhaseManager::getInstance()->support_foot_ != 2 && i >= 20))
                    {
                        right_foot_pose.translation() = pos_out;
                        right_foot_pose.linear() = exponential_map::ExponentialMapToRotation(orientation_out);
                    }

                    evaluation_manager_->getItompRobotModel()->computeStandIKState(robot_state, root_pose, left_foot_pose, right_foot_pose);

                    Eigen::MatrixXd::RowXpr traj_point = joint_traj->getTrajectoryPoint(i);
                    if (i % 5 == 0)
                    {
                        for (int k = 0; k < robot_state.getVariableCount(); ++k)
                        {
                            double value = robot_state.getVariablePosition(k);
                            if (k == 5)
                            {
                                double prev_value = joint_traj->getTrajectoryPoint(i - 5)(k);
                                while (value - prev_value > M_PI)
                                    value -= 2.0 * M_PI;
                                while (value - prev_value < -M_PI)
                                    value += 2.0 * M_PI;
                            }
                            traj_point(k) = value;
                        }
                    }
                }
            }
            */
		}
	}

	evaluation_manager_->setParameters(best_parameter_trajectory_);
	evaluation_manager_->evaluate();
	evaluation_manager_->printTrajectoryCost(iteration_);

	evaluation_manager_->render();

	double elpsed_time = (ros::WallTime::now() - start_time).toSec();

    //ROS_INFO("Terminated after %d iterations, using path from iteration %d", iteration_, best_parameter_iteration_);
    //ROS_INFO("We think trajectory %d is feasible: %s", trajectory_index_, (is_best_parameter_feasible_ ? "True" : "False"));
    //ROS_INFO("Optimization core finished in %f sec", elpsed_time);

	planning_info_.time = elpsed_time;
	planning_info_.iterations = iteration_ + 1;
	planning_info_.cost = best_parameter_cost_;
	planning_info_.success = is_best_parameter_feasible_ ? 1 : 0;

    evaluation_manager_->printLinkTransforms();

	return is_best_parameter_feasible_;
}

bool ItompOptimizer::updateBestTrajectory()
{
	double cost = evaluation_manager_->getTrajectoryCost();
	bool is_feasible = evaluation_manager_->isLastTrajectoryFeasible();

	bool update = false;

	if (!is_best_parameter_feasible_)
	{
		if (is_feasible || cost < best_parameter_cost_)
			update = true;
		is_best_parameter_feasible_ = is_feasible;
	}
	else
	{
		if (is_feasible && cost < best_parameter_cost_)
			update = true;
	}

	if (update)
	{
		evaluation_manager_->getParameters(best_parameter_trajectory_);
		best_parameter_cost_ = cost;
		best_parameter_iteration_ = iteration_;
		return true;
	}
	return false;
}

}
<commit_msg>code cleanup<commit_after>#include <ros/ros.h>
#include <itomp_cio_planner/optimization/itomp_optimizer.h>
#include <itomp_cio_planner/optimization/phase_manager.h>
#include <itomp_cio_planner/contact/ground_manager.h>
#include <itomp_cio_planner/visualization/new_viz_manager.h>
#include <itomp_cio_planner/util/planning_parameters.h>
#include <itomp_cio_planner/optimization/improvement_manager_nlp.h>
//#include <itomp_cio_planner/optimization/improvement_manager_chomp.h>

using namespace std;

namespace itomp_cio_planner
{

ItompOptimizer::ItompOptimizer(int trajectory_index,
                               const ItompTrajectoryPtr& itomp_trajectory,
							   const ItompRobotModelConstPtr& robot_model,
							   const planning_scene::PlanningSceneConstPtr& planning_scene,
							   const ItompPlanningGroupConstPtr& planning_group,
							   double planning_start_time, double trajectory_start_time,
                               const std::vector<moveit_msgs::Constraints>& trajectory_constraints) :
    trajectory_index_(trajectory_index), planning_start_time_(planning_start_time), iteration_(-1),
    best_parameter_cost_(std::numeric_limits<double>::max()), is_best_parameter_feasible_(false), best_parameter_iteration_(-1)
{
    initialize(itomp_trajectory, robot_model, planning_scene, planning_group,
               trajectory_start_time, trajectory_constraints);
}

void ItompOptimizer::initialize(const ItompTrajectoryPtr& itomp_trajectory,
								const ItompRobotModelConstPtr& robot_model,
								const planning_scene::PlanningSceneConstPtr& planning_scene,
								const ItompPlanningGroupConstPtr& planning_group,
								double trajectory_start_time,
                                const std::vector<moveit_msgs::Constraints>& trajectory_constraints)
{
	improvement_manager_ = boost::make_shared<ImprovementManagerNLP>();
	//improvement_manager_ = boost::make_shared<ImprovementManagerChomp>();

	NewVizManager::getInstance()->setPlanningGroup(planning_group);

    NewEvalManager::ref_evaluation_manager_ = NULL;
	evaluation_manager_ = boost::make_shared<NewEvalManager>();
    evaluation_manager_->initialize(itomp_trajectory, robot_model,
									planning_scene, planning_group, planning_start_time_,
                                    trajectory_start_time, trajectory_constraints);
	improvement_manager_->initialize(evaluation_manager_, planning_group);

    PhaseManager::getInstance()->init(itomp_trajectory->getNumPoints());

    best_parameter_trajectory_.set_size(itomp_trajectory->getNumParameters(), 1);
}

ItompOptimizer::~ItompOptimizer()
{
    improvement_manager_.reset();
    evaluation_manager_.reset();
}

bool ItompOptimizer::optimize()
{
	ros::WallTime start_time = ros::WallTime::now();
	iteration_ = -1;
	best_parameter_cost_ = numeric_limits<double>::max();
	is_best_parameter_feasible_ = false;
	best_parameter_iteration_ = -1;

	improvement_manager_->updatePlanningParameters();

	evaluation_manager_->evaluate();

	evaluation_manager_->render();
	updateBestTrajectory();
	++iteration_;

	int iteration_after_feasible_solution = 0;
    int num_max_iterations = 3;

	if (!evaluation_manager_->isLastTrajectoryFeasible())
	{
		while (iteration_ < num_max_iterations)
		{
            ROS_INFO("Optimization phase %d started", iteration_);

			if (is_best_parameter_feasible_)
				++iteration_after_feasible_solution;

            PhaseManager::getInstance()->setPhase(iteration_);
            if (iteration_ != 0)
            {
                best_parameter_cost_ = numeric_limits<double>::max();
                evaluation_manager_->resetBestTrajectoryCost();
            }

            ROS_INFO("Planning Phase %d...", iteration_);

			improvement_manager_->runSingleIteration(iteration_);
			evaluation_manager_->printTrajectoryCost(iteration_);

			//bool is_cost_reduced = (evaluation_manager_->getTrajectoryCost() < best_parameter_cost_);
			bool is_updated = updateBestTrajectory();
			// is_cost_reduced : allow moving to non-feasible low-cost solutions
			// is_updated : only moves in feasible solutions
			if (!is_updated)
				evaluation_manager_->setParameters(best_parameter_trajectory_);

			++iteration_;

            if (iteration_after_feasible_solution > PlanningParameters::getInstance()->getMaxIterationsAfterCollisionFree())
				break;
		}
	}

	evaluation_manager_->setParameters(best_parameter_trajectory_);
	evaluation_manager_->evaluate();
	evaluation_manager_->printTrajectoryCost(iteration_);

	evaluation_manager_->render();

	double elpsed_time = (ros::WallTime::now() - start_time).toSec();

    //ROS_INFO("Terminated after %d iterations, using path from iteration %d", iteration_, best_parameter_iteration_);
    //ROS_INFO("We think trajectory %d is feasible: %s", trajectory_index_, (is_best_parameter_feasible_ ? "True" : "False"));
    //ROS_INFO("Optimization core finished in %f sec", elpsed_time);

	planning_info_.time = elpsed_time;
	planning_info_.iterations = iteration_ + 1;
	planning_info_.cost = best_parameter_cost_;
	planning_info_.success = is_best_parameter_feasible_ ? 1 : 0;

    evaluation_manager_->printLinkTransforms();

	return is_best_parameter_feasible_;
}

bool ItompOptimizer::updateBestTrajectory()
{
	double cost = evaluation_manager_->getTrajectoryCost();
	bool is_feasible = evaluation_manager_->isLastTrajectoryFeasible();

	bool update = false;

	if (!is_best_parameter_feasible_)
	{
		if (is_feasible || cost < best_parameter_cost_)
			update = true;
		is_best_parameter_feasible_ = is_feasible;
	}
	else
	{
		if (is_feasible && cost < best_parameter_cost_)
			update = true;
	}

	if (update)
	{
		evaluation_manager_->getParameters(best_parameter_trajectory_);
		best_parameter_cost_ = cost;
		best_parameter_iteration_ = iteration_;
		return true;
	}
	return false;
}

}
<|endoftext|>


<commit_before>#ifndef CTHUN_CLIENT_SRC_DATA_CONTAINER_DATA_CONTAINER_H_
#define CTHUN_CLIENT_SRC_DATA_CONTAINER_DATA_CONTAINER_H_

#include <vector>
#include <cstdarg>
#include <iostream>
#include <tuple>
#include <typeinfo>
#include <memory>

// Forward declarations for rapidjson
namespace rapidjson {
    class CrtAllocator;
    template <typename BaseAllocator> class MemoryPoolAllocator;
    template <typename Encoding, typename Allocator> class GenericValue;
    template<typename CharType> struct UTF8;
    using Value = GenericValue<UTF8<char>, MemoryPoolAllocator<CrtAllocator>>;
    using Allocator = MemoryPoolAllocator<CrtAllocator>;
    template <typename Encoding,
              typename Allocator,
              typename StackAllocator> class GenericDocument;
    using Document = GenericDocument<UTF8<char>,
                                     MemoryPoolAllocator<CrtAllocator>,
                                     CrtAllocator>;
 }  // namespace rapidjson

namespace CthunClient {

// Errors

/// Error thrown when trying to parse an invalid JSON string.
class data_parse_error : public std::runtime_error  {
  public:
    explicit data_parse_error(std::string const& msg) : std::runtime_error(msg) {}
};

/// Error due to an operation involving a key.
class data_key_error : public std::runtime_error  {
  public:
    explicit data_key_error(std::string const& msg) : std::runtime_error(msg) {}
};

// Types

enum DataType { Object, Array, String, Int, Bool, Double, Null };

// TODO(ale): support nullptr scalars

//
// DataContainer - data abstraction overlaying the raw JSON objects
//
// Usage:
//
// == supported types
//
//    int, double, bool, std::string, and DataContainer
//
// == set
//
// To set a key to a scalar value in object x
//    x.set<int>("foo", 1);
//    x.set<std::string>(foo", "bar");
//
// To set a nested key to a scalar value in object x
//    x.set<bool>({ "foo", "bar", "baz" }, true);
//
// To set a key to a vector value in object x
//    std::vector<int> tmp { 1, 2, 3 };
//    x.set<std::vector<int>>("foo", tmp);
//
// == get
//
// To get a scalar value from a key in object x
//    x.get<std::string>("foo");
//    x.get<int>("bar");
//
// To get a vector from a key in object x
//    x.get<std::vector<int>>("foo");
//
// To get a result object (json object) from object x
//    x.get<DataContainer>("foo");
//
// To get a null value from a key in object x
//    x.get<std::string>("foo") == "";
//    x.get<int>("foo") == 0;
//    x.get<bool>("foo") == false;
//    x.get<double>("foo") == 0.0;
//
// To get the root value from object x
//    x.get<DataContainer>();
//
// == toString
//
// To get a json string representation of object x
//    x.toString();
//
// == includes
//
// To check if a key is set in object x
//    x.includes("foo");
//    x.includes({ "foo", "bar", "baz" });
//
// == keys
//
// To retrieve the list of keys of object x
//    x.keys();
//
// == type
//
// To retrieve the type of a value, as a DataType value
//    x.type({ "foo", "bar" });
//
// == empty
//
// To check if object x stores an empty array or JSON object
//    x.empty();
//

struct DataContainerKey : public std::string {
    DataContainerKey(const std::string& value) : std::string(value) {}
    DataContainerKey(const char* value) : std::string(value) {}
    DataContainerKey(std::initializer_list<char> il) = delete;
};

class DataContainer {
  public:
    DataContainer();
    /// Throw a data_parse_error in case of invalid JSON text.
    explicit DataContainer(const std::string& json_txt);
    explicit DataContainer(const rapidjson::Value& value);
    DataContainer(const DataContainer& data);
    DataContainer(const DataContainer&& data);
    DataContainer& operator=(DataContainer other);

    ~DataContainer();

    std::vector<std::string> keys() const;

    rapidjson::Document getRaw() const;

    std::string toString() const;

    // Throws a data_key_error in case the specified key is unknown.
    std::string toString (const DataContainerKey& key) const;

    std::string toPrettyString(size_t left_padding) const;
    std::string toPrettyString() const;

    /// Returns true if the root is an empty JSON array or an empty
    /// JSON object, false otherwise.
    bool empty() const;

    bool includes(const DataContainerKey& key) const;
    // NOTE(ale): we don't use const for the arg below for gcc issues
    bool includes(std::vector<DataContainerKey> keys) const;

    DataType type() const;

    /// Throw a data_key_error in case the specified key is unknown.
    DataType type(const DataContainerKey& key) const;

    /// Throw a data_key_error in case of unknown keys.
    DataType type(std::vector<DataContainerKey> keys) const;

    template <typename T>
    T get() const {
        return getValue<T>(*reinterpret_cast<rapidjson::Value*>(document_root_.get()));
    }

    /// Throw an assertion error in case the type T doesn't match the
    /// one of the specified value.
    template <typename T>
    T get(const DataContainerKey& key) const {
        rapidjson::Value* jval = reinterpret_cast<rapidjson::Value*>(document_root_.get());

        if (hasKey(*jval, key.data())) {
            return getValue<T>(*getValueInJson(*jval, key.data()));
        }

        return getValue<T>();
    }

    /// Throw an assertion error in case the type T doesn't match the
    /// one of the specified value.
    template <typename T>
    T get(std::vector<DataContainerKey> keys) const {
        rapidjson::Value* jval = reinterpret_cast<rapidjson::Value*>(document_root_.get());

        for (const auto& key : keys) {
            if (!hasKey(*jval, key.data())) {
                return getValue<T>();
            }

            jval = getValueInJson(*jval, key.data());
        }

        return getValue<T>(*jval);
    }

    /// Throw a data_key_error in case the root is not a valid JSON
    /// object, so that is not possible to set the entry.
    template <typename T>
    void set(const DataContainerKey& key, T value) {
        rapidjson::Value* jval = reinterpret_cast<rapidjson::Value*>(document_root_.get());
        const char* key_data = key.data();

        if (!isObject(*jval)) {
            throw data_key_error { "root is not a valid JSON object" };
        }

        if (!hasKey(*jval, key_data)) {
            createKeyInJson(key_data, *jval);
        }

        setValue<T>(*getValueInJson(*jval, key_data), value);
    }

    /// Throw a data_key_error if a known nested key is not associated
    /// with a valid JSON object, so that it is not  possible to
    /// iterate the remaining keys.
    template <typename T>
    void set(std::vector<DataContainerKey> keys, T value) {
        rapidjson::Value* jval = reinterpret_cast<rapidjson::Value*>(document_root_.get());

        for (const auto& key : keys) {
            const char* key_data = key.data();
            if (!isObject(*jval)) {
                throw data_key_error { "invalid key supplied; cannot "
                                       "navigate the provided path" };
            }
            if (!hasKey(*jval, key_data)) {
                createKeyInJson(key_data, *jval);
            }
            jval = getValueInJson(*jval, key_data);
        }

        setValue<T>(*jval, value);
    }

  private:
    std::unique_ptr<rapidjson::Document> document_root_;

    DataType getValueType(const rapidjson::Value& jval) const;
    bool hasKey(const rapidjson::Value& jval, const char* key) const;
    bool isObject(const rapidjson::Value& jval) const;
    rapidjson::Value* getValueInJson(const rapidjson::Value& jval,
                                     const char* key) const;
    void createKeyInJson(const char* key, rapidjson::Value& jval);

    template <typename T>
    T get_(const rapidjson::Value& jval, const char * first_key) const {
        if (hasKey(jval, first_key)) {
            return getValue<T>(*getValueInJson(jval, first_key));
        }

        return getValue<T>();
    }

    template <typename T, typename ... Args>
    T get_(const rapidjson::Value& jval,
           const char * first_key,
           Args ... nested_keys_and_val) const {
        if (hasKey(jval, first_key)) {
            return get_<T>(*getValueInJson(jval, first_key),
                           nested_keys_and_val...);
        }

        return getValue<T>();
    }

    template<typename T>
    T getValue(const rapidjson::Value& value) const;

    template<typename T>
    T getValue() const;

    template<typename T>
    void setValue(rapidjson::Value& jval, T new_value);
};

template<>
void DataContainer::setValue<>(rapidjson::Value& jval, const std::string& new_value);

template<>
void DataContainer::setValue<>(rapidjson::Value& jval, const char* new_value);

template<>
void DataContainer::setValue<>(rapidjson::Value& jval, bool new_value);

template<>
void DataContainer::setValue<>(rapidjson::Value& jval, int new_value);

template<>
void DataContainer::setValue<>(rapidjson::Value& jval, double new_value);

template<>
void DataContainer::setValue<>(rapidjson::Value& jval, std::vector<std::string> new_value);

template<>
void DataContainer::setValue<>(rapidjson::Value& jval, std::vector<bool> new_value);

template<>
void DataContainer::setValue<>(rapidjson::Value& jval, std::vector<int> new_value);

template<>
void DataContainer::setValue<>(rapidjson::Value& jval, std::vector<double> new_value);

template<>
void DataContainer::setValue<>(rapidjson::Value& jval, std::vector<DataContainer> new_value);

template<>
void DataContainer::setValue<>(rapidjson::Value& jval, DataContainer new_value);

}  // namespace CthunClient

#endif  // CTHUN_CLIENT_SRC_DATA_CONTAINER_DATA_CONTAINER_H_
<commit_msg>(PEG-154) Fix typo in data_container.hpp<commit_after>#ifndef CTHUN_CLIENT_SRC_DATA_CONTAINER_DATA_CONTAINER_H_
#define CTHUN_CLIENT_SRC_DATA_CONTAINER_DATA_CONTAINER_H_

#include <vector>
#include <cstdarg>
#include <iostream>
#include <tuple>
#include <typeinfo>
#include <memory>

// Forward declarations for rapidjson
namespace rapidjson {
    class CrtAllocator;
    template <typename BaseAllocator> class MemoryPoolAllocator;
    template <typename Encoding, typename Allocator> class GenericValue;
    template<typename CharType> struct UTF8;
    using Value = GenericValue<UTF8<char>, MemoryPoolAllocator<CrtAllocator>>;
    using Allocator = MemoryPoolAllocator<CrtAllocator>;
    template <typename Encoding,
              typename Allocator,
              typename StackAllocator> class GenericDocument;
    using Document = GenericDocument<UTF8<char>,
                                     MemoryPoolAllocator<CrtAllocator>,
                                     CrtAllocator>;
 }  // namespace rapidjson

namespace CthunClient {

// Errors

/// Error thrown when trying to parse an invalid JSON string.
class data_parse_error : public std::runtime_error  {
  public:
    explicit data_parse_error(std::string const& msg) : std::runtime_error(msg) {}
};

/// Error due to an operation involving a key.
class data_key_error : public std::runtime_error  {
  public:
    explicit data_key_error(std::string const& msg) : std::runtime_error(msg) {}
};

// Types

enum DataType { Object, Array, String, Int, Bool, Double, Null };

// TODO(ale): support nullptr scalars

//
// DataContainer - data abstraction overlaying the raw JSON objects
//
// Usage:
//
// == supported types
//
//    int, double, bool, std::string, and DataContainer
//
// == set
//
// To set a key to a scalar value in object x
//    x.set<int>("foo", 1);
//    x.set<std::string>(foo", "bar");
//
// To set a nested key to a scalar value in object x
//    x.set<bool>({ "foo", "bar", "baz" }, true);
//
// To set a key to a vector value in object x
//    std::vector<int> tmp { 1, 2, 3 };
//    x.set<std::vector<int>>("foo", tmp);
//
// == get
//
// To get a scalar value from a key in object x
//    x.get<std::string>("foo");
//    x.get<int>("bar");
//
// To get a vector from a key in object x
//    x.get<std::vector<int>>("foo");
//
// To get a result object (json object) from object x
//    x.get<DataContainer>("foo");
//
// To get a null value from a key in object x
//    x.get<std::string>("foo") == "";
//    x.get<int>("foo") == 0;
//    x.get<bool>("foo") == false;
//    x.get<double>("foo") == 0.0;
//
// To get the root value from object x
//    x.get<DataContainer>();
//
// == toString
//
// To get a json string representation of object x
//    x.toString();
//
// == includes
//
// To check if a key is set in object x
//    x.includes("foo");
//    x.includes({ "foo", "bar", "baz" });
//
// == keys
//
// To retrieve the list of keys of object x
//    x.keys();
//
// == type
//
// To retrieve the type of a value, as a DataType value
//    x.type({ "foo", "bar" });
//
// == empty
//
// To check if object x stores an empty array or JSON object
//    x.empty();
//

struct DataContainerKey : public std::string {
    DataContainerKey(const std::string& value) : std::string(value) {}
    DataContainerKey(const char* value) : std::string(value) {}
    DataContainerKey(std::initializer_list<char> il) = delete;
};

class DataContainer {
  public:
    DataContainer();
    /// Throw a data_parse_error in case of invalid JSON text.
    explicit DataContainer(const std::string& json_txt);
    explicit DataContainer(const rapidjson::Value& value);
    DataContainer(const DataContainer& data);
    DataContainer(const DataContainer&& data);
    DataContainer& operator=(DataContainer other);

    ~DataContainer();

    std::vector<std::string> keys() const;

    rapidjson::Document getRaw() const;

    std::string toString() const;

    // Throws a data_key_error in case the specified key is unknown.
    std::string toString(const DataContainerKey& key) const;

    std::string toPrettyString(size_t left_padding) const;
    std::string toPrettyString() const;

    /// Returns true if the root is an empty JSON array or an empty
    /// JSON object, false otherwise.
    bool empty() const;

    bool includes(const DataContainerKey& key) const;
    // NOTE(ale): we don't use const for the arg below for gcc issues
    bool includes(std::vector<DataContainerKey> keys) const;

    DataType type() const;

    /// Throw a data_key_error in case the specified key is unknown.
    DataType type(const DataContainerKey& key) const;

    /// Throw a data_key_error in case of unknown keys.
    DataType type(std::vector<DataContainerKey> keys) const;

    template <typename T>
    T get() const {
        return getValue<T>(*reinterpret_cast<rapidjson::Value*>(document_root_.get()));
    }

    /// Throw an assertion error in case the type T doesn't match the
    /// one of the specified value.
    template <typename T>
    T get(const DataContainerKey& key) const {
        rapidjson::Value* jval = reinterpret_cast<rapidjson::Value*>(document_root_.get());

        if (hasKey(*jval, key.data())) {
            return getValue<T>(*getValueInJson(*jval, key.data()));
        }

        return getValue<T>();
    }

    /// Throw an assertion error in case the type T doesn't match the
    /// one of the specified value.
    template <typename T>
    T get(std::vector<DataContainerKey> keys) const {
        rapidjson::Value* jval = reinterpret_cast<rapidjson::Value*>(document_root_.get());

        for (const auto& key : keys) {
            if (!hasKey(*jval, key.data())) {
                return getValue<T>();
            }

            jval = getValueInJson(*jval, key.data());
        }

        return getValue<T>(*jval);
    }

    /// Throw a data_key_error in case the root is not a valid JSON
    /// object, so that is not possible to set the entry.
    template <typename T>
    void set(const DataContainerKey& key, T value) {
        rapidjson::Value* jval = reinterpret_cast<rapidjson::Value*>(document_root_.get());
        const char* key_data = key.data();

        if (!isObject(*jval)) {
            throw data_key_error { "root is not a valid JSON object" };
        }

        if (!hasKey(*jval, key_data)) {
            createKeyInJson(key_data, *jval);
        }

        setValue<T>(*getValueInJson(*jval, key_data), value);
    }

    /// Throw a data_key_error if a known nested key is not associated
    /// with a valid JSON object, so that it is not  possible to
    /// iterate the remaining keys.
    template <typename T>
    void set(std::vector<DataContainerKey> keys, T value) {
        rapidjson::Value* jval = reinterpret_cast<rapidjson::Value*>(document_root_.get());

        for (const auto& key : keys) {
            const char* key_data = key.data();
            if (!isObject(*jval)) {
                throw data_key_error { "invalid key supplied; cannot "
                                       "navigate the provided path" };
            }
            if (!hasKey(*jval, key_data)) {
                createKeyInJson(key_data, *jval);
            }
            jval = getValueInJson(*jval, key_data);
        }

        setValue<T>(*jval, value);
    }

  private:
    std::unique_ptr<rapidjson::Document> document_root_;

    DataType getValueType(const rapidjson::Value& jval) const;
    bool hasKey(const rapidjson::Value& jval, const char* key) const;
    bool isObject(const rapidjson::Value& jval) const;
    rapidjson::Value* getValueInJson(const rapidjson::Value& jval,
                                     const char* key) const;
    void createKeyInJson(const char* key, rapidjson::Value& jval);

    template <typename T>
    T get_(const rapidjson::Value& jval, const char * first_key) const {
        if (hasKey(jval, first_key)) {
            return getValue<T>(*getValueInJson(jval, first_key));
        }

        return getValue<T>();
    }

    template <typename T, typename ... Args>
    T get_(const rapidjson::Value& jval,
           const char * first_key,
           Args ... nested_keys_and_val) const {
        if (hasKey(jval, first_key)) {
            return get_<T>(*getValueInJson(jval, first_key),
                           nested_keys_and_val...);
        }

        return getValue<T>();
    }

    template<typename T>
    T getValue(const rapidjson::Value& value) const;

    template<typename T>
    T getValue() const;

    template<typename T>
    void setValue(rapidjson::Value& jval, T new_value);
};

template<>
void DataContainer::setValue<>(rapidjson::Value& jval, const std::string& new_value);

template<>
void DataContainer::setValue<>(rapidjson::Value& jval, const char* new_value);

template<>
void DataContainer::setValue<>(rapidjson::Value& jval, bool new_value);

template<>
void DataContainer::setValue<>(rapidjson::Value& jval, int new_value);

template<>
void DataContainer::setValue<>(rapidjson::Value& jval, double new_value);

template<>
void DataContainer::setValue<>(rapidjson::Value& jval, std::vector<std::string> new_value);

template<>
void DataContainer::setValue<>(rapidjson::Value& jval, std::vector<bool> new_value);

template<>
void DataContainer::setValue<>(rapidjson::Value& jval, std::vector<int> new_value);

template<>
void DataContainer::setValue<>(rapidjson::Value& jval, std::vector<double> new_value);

template<>
void DataContainer::setValue<>(rapidjson::Value& jval, std::vector<DataContainer> new_value);

template<>
void DataContainer::setValue<>(rapidjson::Value& jval, DataContainer new_value);

}  // namespace CthunClient

#endif  // CTHUN_CLIENT_SRC_DATA_CONTAINER_DATA_CONTAINER_H_
<|endoftext|>


<commit_before>#include "rapid_perception/template_matching_heat_mapper.h"

#include <algorithm>
#include <iostream>
#include <math.h>
#include <vector>

#include "Eigen/Core"
#include "pcl/PointIndices.h"
#include "pcl/common/common.h"
#include "pcl/filters/extract_indices.h"
#include "pcl/filters/random_sample.h"
#include "pcl/registration/icp.h"
#include "pcl/point_cloud.h"
#include "pcl/point_types.h"
#include "pcl/recognition/line_rgbd.h"

#include "rapid_msgs/Roi3D.h"
#include "rapid_viz/publish.h"

typedef pcl::PointXYZRGB PointC;
typedef pcl::PointCloud<PointC> PointCloudC;
using std::vector;

namespace rapid {
namespace perception {
TemplateMatchingHeatMapper::TemplateMatchingHeatMapper()
    : scene_(),
      object_(),
      object_roi_(),
      sample_ratio_(0.01),
      max_samples_(1000) {}

void TemplateMatchingHeatMapper::Compute(pcl::PointIndicesPtr indices,
                                         Eigen::VectorXd* importances) {
  pcl::RandomSample<PointC> random;
  random.setInputCloud(scene_);
  int num_samples = static_cast<int>(round(sample_ratio_ * scene_->size()));
  random.setSample(std::min(max_samples_, num_samples));
  random.filter(indices->indices);
  ROS_INFO("Randomly sampled %ld points", indices->indices.size());

  PointCloudC::Ptr working_object(new PointCloudC);
  PointCloudC::Ptr aligned_object(new PointCloudC);
  importances->resize(indices->indices.size());
  pcl::IterativeClosestPoint<PointC, PointC> icp;
  icp.setMaximumIterations(0);
  icp.setInputTarget(scene_);
  for (size_t indices_i = 0; indices_i < indices->indices.size(); ++indices_i) {
    int index = indices->indices[indices_i];
    const PointC& center = scene_->points[index];
    // Transform the object to be centered on the center point
    // So far we just use a translation offset
    // Also assume that the object and scene are in the same frame
    Eigen::Vector3d translation;
    translation.x() = center.x - object_center_.x();
    translation.y() = center.y - object_center_.y();
    translation.z() = center.z - object_center_.z();
    pcl::transformPointCloud(*object_, *working_object, translation,
                             Eigen::Quaterniond::Identity());

    // Run ICP
    icp.setInputSource(working_object);
    icp.align(*aligned_object);
    (*importances)(indices_i) = icp.getFitnessScore();

    // viz::PublishCloud(heatmap_pub_, *aligned_object);
    // if (debug_) {
    //  std::cout << "Score: " << icp.getFitnessScore();
    //  std::string input;
    //  std::getline(std::cin, input);
    //}
  }

  double min = importances->minCoeff();
  importances->array() -= min;
  double max = importances->maxCoeff();
  (*importances) /= max;
  importances->array() = 1 - importances->array();

  // Color point cloud for visualization
  PointCloudC::Ptr working_scene(new PointCloudC);
  *working_scene = *scene_;
  for (size_t indices_i = 0; indices_i < indices->indices.size(); ++indices_i) {
    int color = static_cast<int>(round(255 * (*importances)(indices_i)));
    int index = indices->indices[indices_i];
    working_scene->points[index].r = color;
    working_scene->points[index].g = color;
    working_scene->points[index].b = color;
  }
  PointCloudC::Ptr viz_cloud(new PointCloudC());
  pcl::ExtractIndices<PointC> extract;
  extract.setInputCloud(working_scene);
  extract.setIndices(indices);
  extract.filter(*viz_cloud);
  viz::PublishCloud(heatmap_pub_, *viz_cloud);
}

void TemplateMatchingHeatMapper::set_scene(PointCloudC::Ptr scene) {
  scene_ = scene;
}

void TemplateMatchingHeatMapper::set_object(PointCloudC::Ptr object) {
  object_ = object;
  Eigen::Vector4f min_pt;
  Eigen::Vector4f max_pt;
  pcl::getMinMax3D(*object_, min_pt, max_pt);
  object_center_.x() = (max_pt.x() + min_pt.x()) / 2;
  object_center_.y() = (max_pt.y() + min_pt.y()) / 2;
  object_center_.z() = (max_pt.z() + min_pt.z()) / 2;
}

void TemplateMatchingHeatMapper::set_object_roi(const rapid_msgs::Roi3D& roi) {
  object_roi_ = roi;
}

void TemplateMatchingHeatMapper::set_sample_ratio(double val) {
  sample_ratio_ = val;
}

void TemplateMatchingHeatMapper::set_max_samples(int val) {
  max_samples_ = val;
}
}  // namespace perception
}  // namespace rapid
<commit_msg>Use ICP function incorporating negative space.<commit_after>#include "rapid_perception/template_matching_heat_mapper.h"

#include <algorithm>
#include <iostream>
#include <math.h>
#include <vector>

#include "Eigen/Core"
#include "pcl/PointIndices.h"
#include "pcl/common/common.h"
#include "pcl/filters/extract_indices.h"
#include "pcl/filters/random_sample.h"
#include "pcl/registration/icp.h"
#include "pcl/point_cloud.h"
#include "pcl/point_types.h"
#include "pcl/recognition/line_rgbd.h"

#include "rapid_msgs/Roi3D.h"
#include "rapid_perception/icp_fitness_functions.h"
#include "rapid_viz/publish.h"

typedef pcl::PointXYZRGB PointC;
typedef pcl::PointCloud<PointC> PointCloudC;
using std::vector;

namespace rapid {
namespace perception {
TemplateMatchingHeatMapper::TemplateMatchingHeatMapper()
    : scene_(),
      object_(),
      object_roi_(),
      sample_ratio_(0.01),
      max_samples_(1000) {}

void TemplateMatchingHeatMapper::Compute(pcl::PointIndicesPtr indices,
                                         Eigen::VectorXd* importances) {
  pcl::RandomSample<PointC> random;
  random.setInputCloud(scene_);
  int num_samples = static_cast<int>(round(sample_ratio_ * scene_->size()));
  random.setSample(std::min(max_samples_, num_samples));
  random.filter(indices->indices);
  ROS_INFO("Randomly sampled %ld points", indices->indices.size());

  PointCloudC::Ptr working_object(new PointCloudC);
  PointCloudC::Ptr aligned_object(new PointCloudC);
  importances->resize(indices->indices.size());
  pcl::IterativeClosestPoint<PointC, PointC> icp;
  icp.setMaximumIterations(0);
  icp.setInputTarget(scene_);
  for (size_t indices_i = 0; indices_i < indices->indices.size(); ++indices_i) {
    int index = indices->indices[indices_i];
    const PointC& center = scene_->points[index];
    // Transform the object to be centered on the center point
    // So far we just use a translation offset
    // Also assume that the object and scene are in the same frame
    Eigen::Vector3d translation;
    translation.x() = center.x - object_center_.x();
    translation.y() = center.y - object_center_.y();
    translation.z() = center.z - object_center_.z();
    pcl::transformPointCloud(*object_, *working_object, translation,
                             Eigen::Quaterniond::Identity());

    // Run ICP
    icp.setInputSource(working_object);
    icp.align(*aligned_object);

    rapid_msgs::Roi3D roi = object_roi_;
    roi.transform.translation.x += translation.x();
    roi.transform.translation.y += translation.y();
    roi.transform.translation.z += translation.z();
    double fitness = ComputeIcpFitness(scene_, aligned_object, roi);
    (*importances)(indices_i) = fitness;

    // viz::PublishCloud(heatmap_pub_, *aligned_object);
    // if (debug_) {
    //  std::cout << "Score: " << fitness;
    //  std::string input;
    //  std::getline(std::cin, input);
    //}
  }

  double min = importances->minCoeff();
  importances->array() -= min;
  double max = importances->maxCoeff();
  (*importances) /= max;
  importances->array() = 1 - importances->array();

  // Color point cloud for visualization
  PointCloudC::Ptr working_scene(new PointCloudC);
  *working_scene = *scene_;
  for (size_t indices_i = 0; indices_i < indices->indices.size(); ++indices_i) {
    int color = static_cast<int>(round(255 * (*importances)(indices_i)));
    int index = indices->indices[indices_i];
    working_scene->points[index].r = color;
    working_scene->points[index].g = color;
    working_scene->points[index].b = color;
  }
  PointCloudC::Ptr viz_cloud(new PointCloudC());
  pcl::ExtractIndices<PointC> extract;
  extract.setInputCloud(working_scene);
  extract.setIndices(indices);
  extract.filter(*viz_cloud);
  viz::PublishCloud(heatmap_pub_, *viz_cloud);
}

void TemplateMatchingHeatMapper::set_scene(PointCloudC::Ptr scene) {
  scene_ = scene;
}

void TemplateMatchingHeatMapper::set_object(PointCloudC::Ptr object) {
  object_ = object;
  Eigen::Vector4f min_pt;
  Eigen::Vector4f max_pt;
  pcl::getMinMax3D(*object_, min_pt, max_pt);
  object_center_.x() = (max_pt.x() + min_pt.x()) / 2;
  object_center_.y() = (max_pt.y() + min_pt.y()) / 2;
  object_center_.z() = (max_pt.z() + min_pt.z()) / 2;
}

void TemplateMatchingHeatMapper::set_object_roi(const rapid_msgs::Roi3D& roi) {
  object_roi_ = roi;
}

void TemplateMatchingHeatMapper::set_sample_ratio(double val) {
  sample_ratio_ = val;
}

void TemplateMatchingHeatMapper::set_max_samples(int val) {
  max_samples_ = val;
}
}  // namespace perception
}  // namespace rapid
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: moduleuiconfigurationmanager.hxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 11:03:20 $
 *
 *  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
 *
 ************************************************************************/

#ifndef __FRAMEWORK_UICONFIGURATION_MODULEUICONFIGMANAGER_HXX_
#define __FRAMEWORK_UICONFIGURATION_MODULEUICONFIGMANAGER_HXX_

/** Attention: stl headers must(!) be included at first. Otherwhise it can make trouble
               with solaris headers ...
*/
#include <vector>
#include <list>
#include <hash_map>

//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________

#ifndef __FRAMEWORK_ACCELERATORS_PRESETHANDLER_HXX_
#include <accelerators/presethandler.hxx>
#endif

#ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_
#include <threadhelp/threadhelpbase.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_GENERIC_HXX_
#include <macros/generic.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_
#include <macros/xinterface.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_
#include <macros/xtypeprovider.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_XSERVICEINFO_HXX_
#include <macros/xserviceinfo.hxx>
#endif

#ifndef __FRAMEWORK_STDTYPES_H_
#include <stdtypes.h>
#endif

#ifndef __FRAMEWORK_UICONFIGURATION_MODULEIMAGEMANAGER_HXX_
#include <uiconfiguration/moduleimagemanager.hxx>
#endif

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_
#include <com/sun/star/lang/XTypeProvider.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif

#ifndef _COM_SUN_STAR_UI_XUICONFIGURATIONPERSISTENCE_HPP_
#include <com/sun/star/ui/XUIConfigurationPersistence.hpp>
#endif

#ifndef _COM_SUN_STAR_UI_XUICONFIGURATION_HPP_
#include <com/sun/star/ui/XUIConfiguration.hpp>
#endif

#ifndef _COM_SUN_STAR_UI_XUICONFIGURATIONMANAGER_HPP_
#include <com/sun/star/ui/XUIConfigurationManager.hpp>
#endif

#ifndef _COM_SUN_STAR_UI_XMODULEUICONFIGURATIONMANAGER_HPP_
#include <com/sun/star/ui/XModuleUIConfigurationManager.hpp>
#endif

#ifndef _COM_SUN_STAR_UI_UIELEMENTTYPE_HPP_
#include <com/sun/star/ui/UIElementType.hpp>
#endif

#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif

#ifndef _COM_SUN_STAR_UI_CONFIGURATIONEVENT_HPP_
#include <com/sun/star/ui/ConfigurationEvent.hpp>
#endif

#ifndef _COM_SUN_STAR_EMBED_XTRANSACTEDOBJECT_HPP_
#include <com/sun/star/embed/XTransactedObject.hpp>
#endif

#ifndef _COM_SUN_STAR_CONTAINER_XINDEXCONTAINER_HPP_
#include <com/sun/star/container/XIndexContainer.hpp>
#endif

//_________________________________________________________________________________________________________________
//  other includes
//_________________________________________________________________________________________________________________

#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif

#ifndef _CPPUHELPER_INTERFACECONTAINER_HXX_
#include <cppuhelper/interfacecontainer.hxx>
#endif

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

namespace framework
{
    class ModuleUIConfigurationManager :   public com::sun::star::lang::XTypeProvider                       ,
                                           public com::sun::star::lang::XServiceInfo                        ,
                                           public com::sun::star::lang::XComponent                          ,
                                           public com::sun::star::lang::XInitialization                     ,
                                           public ::com::sun::star::ui::XUIConfiguration              ,
                                           public ::com::sun::star::ui::XUIConfigurationManager       ,
                                           public ::com::sun::star::ui::XModuleUIConfigurationManager ,
                                           public ::com::sun::star::ui::XUIConfigurationPersistence   ,
                                           private ThreadHelpBase                       ,   // Struct for right initalization of mutex member! Must be first of baseclasses.
                                           public ::cppu::OWeakObject
    {
        public:
            //  XInterface, XTypeProvider, XServiceInfo
            FWK_DECLARE_XINTERFACE
            FWK_DECLARE_XTYPEPROVIDER
            DECLARE_XSERVICEINFO

            ModuleUIConfigurationManager( com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory > xServiceManager );
            virtual ~ModuleUIConfigurationManager();

            // XComponent
            virtual void SAL_CALL dispose() throw (::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL addEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& xListener ) throw (::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL removeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& aListener ) throw (::com::sun::star::uno::RuntimeException);

            // XInitialization
            virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);

            // XUIConfiguration
            virtual void SAL_CALL addConfigurationListener( const ::com::sun::star::uno::Reference< ::com::sun::star::ui::XUIConfigurationListener >& Listener ) throw (::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL removeConfigurationListener( const ::com::sun::star::uno::Reference< ::com::sun::star::ui::XUIConfigurationListener >& Listener ) throw (::com::sun::star::uno::RuntimeException);

            // XUIConfigurationManager
            virtual void SAL_CALL reset() throw (::com::sun::star::uno::RuntimeException);
            virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > > SAL_CALL getUIElementsInfo( sal_Int16 ElementType ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexContainer > SAL_CALL createSettings(  ) throw (::com::sun::star::uno::RuntimeException);
            virtual sal_Bool SAL_CALL hasSettings( const ::rtl::OUString& ResourceURL ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess > SAL_CALL getSettings( const ::rtl::OUString& ResourceURL, sal_Bool bWriteable ) throw (::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL replaceSettings( const ::rtl::OUString& ResourceURL, const ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess >& aNewData ) throw (::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::IllegalAccessException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL removeSettings( const ::rtl::OUString& ResourceURL ) throw (::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::IllegalAccessException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL insertSettings( const ::rtl::OUString& NewResourceURL, const ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess >& aNewData ) throw (::com::sun::star::container::ElementExistException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::IllegalAccessException, ::com::sun::star::uno::RuntimeException);
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL getImageManager() throw (::com::sun::star::uno::RuntimeException);
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL getShortCutManager() throw (::com::sun::star::uno::RuntimeException);
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL getEventsManager() throw (::com::sun::star::uno::RuntimeException);

            // XModuleUIConfigurationManager
            virtual sal_Bool SAL_CALL isDefaultSettings( const ::rtl::OUString& ResourceURL ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess > SAL_CALL getDefaultSettings( const ::rtl::OUString& ResourceURL ) throw (::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);

            // XUIConfigurationPersistence
            virtual void SAL_CALL reload() throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL store() throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL storeToStorage( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& Storage ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
            virtual sal_Bool SAL_CALL isModified() throw (::com::sun::star::uno::RuntimeException);
            virtual sal_Bool SAL_CALL isReadOnly() throw (::com::sun::star::uno::RuntimeException);

        private:
            // private data types
            enum Layer
            {
                LAYER_DEFAULT,
                LAYER_USERDEFINED,
                LAYER_COUNT
            };

            enum NotifyOp
            {
                NotifyOp_Remove,
                NotifyOp_Insert,
                NotifyOp_Replace
            };

            struct UIElementInfo
            {
                UIElementInfo( const rtl::OUString& rResourceURL, const rtl::OUString& rUIName ) :
                    aResourceURL( rResourceURL), aUIName( rUIName ) {}
                rtl::OUString   aResourceURL;
                rtl::OUString   aUIName;
            };

            struct UIElementData
            {
                UIElementData() : bModified( false ), bDefault( true ), bDefaultNode( true ) {};

                rtl::OUString aResourceURL;
                rtl::OUString aName;
                bool          bModified;        // has been changed since last storing
                bool          bDefault;         // default settings
                bool          bDefaultNode;     // this is a default layer element data
                com::sun::star::uno::Reference< com::sun::star::container::XIndexAccess > xSettings;
            };

            struct UIElementType;
            friend struct UIElementType;
            typedef ::std::hash_map< rtl::OUString, UIElementData, OUStringHashCode, ::std::equal_to< rtl::OUString > > UIElementDataHashMap;

            struct UIElementType
            {
                UIElementType() : bModified( false ),
                                  bLoaded( false ),
                                  bDefaultLayer( false ),
                                  nElementType( ::com::sun::star::ui::UIElementType::UNKNOWN ) {}

                bool                                                              bModified;
                bool                                                              bLoaded;
                bool                                                              bDefaultLayer;
                sal_Int16                                                         nElementType;
                UIElementDataHashMap                                              aElementsHashMap;
                com::sun::star::uno::Reference< com::sun::star::embed::XStorage > xStorage;
            };

            typedef ::std::vector< UIElementType > UIElementTypesVector;
            typedef ::std::vector< ::com::sun::star::ui::ConfigurationEvent > ConfigEventNotifyContainer;
            typedef ::std::hash_map< rtl::OUString, UIElementInfo, OUStringHashCode, ::std::equal_to< rtl::OUString > > UIElementInfoHashMap;

            // private methods
            void            impl_Initialize();
            void            implts_notifyContainerListener( const ::com::sun::star::ui::ConfigurationEvent& aEvent, NotifyOp eOp );
            void            impl_fillSequenceWithElementTypeInfo( UIElementInfoHashMap& aUIElementInfoCollection, sal_Int16 nElementType );
            void            impl_preloadUIElementTypeList( Layer eLayer, sal_Int16 nElementType );
            UIElementData*  impl_findUIElementData( const rtl::OUString& aResourceURL, sal_Int16 nElementType, bool bLoad = true );
            void            impl_requestUIElementData( sal_Int16 nElementType, Layer eLayer, UIElementData& aUIElementData );
            void            impl_storeElementTypeData( com::sun::star::uno::Reference< com::sun::star::embed::XStorage > xStorage, UIElementType& rElementType, bool bResetModifyState = true );
            void            impl_resetElementTypeData( UIElementType& rUserElementType, UIElementType& rDefaultElementType, ConfigEventNotifyContainer& rRemoveNotifyContainer, ConfigEventNotifyContainer& rReplaceNotifyContainer );
            void            impl_reloadElementTypeData( UIElementType& rUserElementType, UIElementType& rDefaultElementType, ConfigEventNotifyContainer& rRemoveNotifyContainer, ConfigEventNotifyContainer& rReplaceNotifyContainer );

            UIElementTypesVector                                                            m_aUIElements[LAYER_COUNT];
            PresetHandler*                                                                  m_pStorageHandler[::com::sun::star::ui::UIElementType::COUNT];
            com::sun::star::uno::Reference< com::sun::star::embed::XStorage >               m_xDefaultConfigStorage;
            com::sun::star::uno::Reference< com::sun::star::embed::XStorage >               m_xUserConfigStorage;
            bool                                                                            m_bReadOnly;
            bool                                                                            m_bInitialized;
            bool                                                                            m_bModified;
            bool                                                                            m_bConfigRead;
            bool                                                                            m_bDisposed;
            rtl::OUString                                                                   m_aXMLPostfix;
            rtl::OUString                                                                   m_aPropUIName;
            rtl::OUString                                                                   m_aPropResourceURL;
            rtl::OUString                                                                   m_aModuleIdentifier;
            rtl::OUString                                                                   m_aModuleShortName;
            com::sun::star::uno::Reference< com::sun::star::embed::XTransactedObject >      m_xUserRootCommit;
            com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >    m_xServiceManager;
            ::cppu::OMultiTypeInterfaceContainerHelper                                      m_aListenerContainer;   /// container for ALL Listener
            com::sun::star::uno::Reference< com::sun::star::lang::XComponent >              m_xModuleImageManager;
   };
}

#endif // __FRAMEWORK_UICONFIGURATION_MODULEUICONFIGMANAGER_HXX_
<commit_msg>INTEGRATION: CWS changefileheader (1.9.318); FILE MERGED 2008/04/01 15:18:26 thb 1.9.318.3: #i85898# Stripping all external header guards 2008/04/01 10:57:55 thb 1.9.318.2: #i85898# Stripping all external header guards 2008/03/28 15:34:54 rt 1.9.318.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: moduleuiconfigurationmanager.hxx,v $
 * $Revision: 1.10 $
 *
 * 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.
 *
 ************************************************************************/

#ifndef __FRAMEWORK_UICONFIGURATION_MODULEUICONFIGMANAGER_HXX_
#define __FRAMEWORK_UICONFIGURATION_MODULEUICONFIGMANAGER_HXX_

/** Attention: stl headers must(!) be included at first. Otherwhise it can make trouble
               with solaris headers ...
*/
#include <vector>
#include <list>
#include <hash_map>

//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________
#include <accelerators/presethandler.hxx>
#include <threadhelp/threadhelpbase.hxx>
#include <macros/generic.hxx>
#include <macros/xinterface.hxx>
#include <macros/xtypeprovider.hxx>
#include <macros/xserviceinfo.hxx>
#include <stdtypes.h>
#include <uiconfiguration/moduleimagemanager.hxx>

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/lang/XTypeProvider.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/ui/XUIConfigurationPersistence.hpp>
#include <com/sun/star/ui/XUIConfiguration.hpp>
#include <com/sun/star/ui/XUIConfigurationManager.hpp>
#include <com/sun/star/ui/XModuleUIConfigurationManager.hpp>
#include <com/sun/star/ui/UIElementType.hpp>
#include <com/sun/star/lang/XInitialization.hpp>
#include <com/sun/star/ui/ConfigurationEvent.hpp>
#include <com/sun/star/embed/XTransactedObject.hpp>
#include <com/sun/star/container/XIndexContainer.hpp>

//_________________________________________________________________________________________________________________
//  other includes
//_________________________________________________________________________________________________________________
#include <cppuhelper/weak.hxx>
#include <cppuhelper/interfacecontainer.hxx>
#include <rtl/ustring.hxx>

namespace framework
{
    class ModuleUIConfigurationManager :   public com::sun::star::lang::XTypeProvider                       ,
                                           public com::sun::star::lang::XServiceInfo                        ,
                                           public com::sun::star::lang::XComponent                          ,
                                           public com::sun::star::lang::XInitialization                     ,
                                           public ::com::sun::star::ui::XUIConfiguration              ,
                                           public ::com::sun::star::ui::XUIConfigurationManager       ,
                                           public ::com::sun::star::ui::XModuleUIConfigurationManager ,
                                           public ::com::sun::star::ui::XUIConfigurationPersistence   ,
                                           private ThreadHelpBase                       ,   // Struct for right initalization of mutex member! Must be first of baseclasses.
                                           public ::cppu::OWeakObject
    {
        public:
            //  XInterface, XTypeProvider, XServiceInfo
            FWK_DECLARE_XINTERFACE
            FWK_DECLARE_XTYPEPROVIDER
            DECLARE_XSERVICEINFO

            ModuleUIConfigurationManager( com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory > xServiceManager );
            virtual ~ModuleUIConfigurationManager();

            // XComponent
            virtual void SAL_CALL dispose() throw (::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL addEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& xListener ) throw (::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL removeEventListener( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XEventListener >& aListener ) throw (::com::sun::star::uno::RuntimeException);

            // XInitialization
            virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);

            // XUIConfiguration
            virtual void SAL_CALL addConfigurationListener( const ::com::sun::star::uno::Reference< ::com::sun::star::ui::XUIConfigurationListener >& Listener ) throw (::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL removeConfigurationListener( const ::com::sun::star::uno::Reference< ::com::sun::star::ui::XUIConfigurationListener >& Listener ) throw (::com::sun::star::uno::RuntimeException);

            // XUIConfigurationManager
            virtual void SAL_CALL reset() throw (::com::sun::star::uno::RuntimeException);
            virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > > SAL_CALL getUIElementsInfo( sal_Int16 ElementType ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexContainer > SAL_CALL createSettings(  ) throw (::com::sun::star::uno::RuntimeException);
            virtual sal_Bool SAL_CALL hasSettings( const ::rtl::OUString& ResourceURL ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess > SAL_CALL getSettings( const ::rtl::OUString& ResourceURL, sal_Bool bWriteable ) throw (::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL replaceSettings( const ::rtl::OUString& ResourceURL, const ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess >& aNewData ) throw (::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::IllegalAccessException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL removeSettings( const ::rtl::OUString& ResourceURL ) throw (::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::IllegalAccessException, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL insertSettings( const ::rtl::OUString& NewResourceURL, const ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess >& aNewData ) throw (::com::sun::star::container::ElementExistException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::IllegalAccessException, ::com::sun::star::uno::RuntimeException);
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL getImageManager() throw (::com::sun::star::uno::RuntimeException);
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL getShortCutManager() throw (::com::sun::star::uno::RuntimeException);
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL getEventsManager() throw (::com::sun::star::uno::RuntimeException);

            // XModuleUIConfigurationManager
            virtual sal_Bool SAL_CALL isDefaultSettings( const ::rtl::OUString& ResourceURL ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XIndexAccess > SAL_CALL getDefaultSettings( const ::rtl::OUString& ResourceURL ) throw (::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);

            // XUIConfigurationPersistence
            virtual void SAL_CALL reload() throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL store() throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL storeToStorage( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& Storage ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
            virtual sal_Bool SAL_CALL isModified() throw (::com::sun::star::uno::RuntimeException);
            virtual sal_Bool SAL_CALL isReadOnly() throw (::com::sun::star::uno::RuntimeException);

        private:
            // private data types
            enum Layer
            {
                LAYER_DEFAULT,
                LAYER_USERDEFINED,
                LAYER_COUNT
            };

            enum NotifyOp
            {
                NotifyOp_Remove,
                NotifyOp_Insert,
                NotifyOp_Replace
            };

            struct UIElementInfo
            {
                UIElementInfo( const rtl::OUString& rResourceURL, const rtl::OUString& rUIName ) :
                    aResourceURL( rResourceURL), aUIName( rUIName ) {}
                rtl::OUString   aResourceURL;
                rtl::OUString   aUIName;
            };

            struct UIElementData
            {
                UIElementData() : bModified( false ), bDefault( true ), bDefaultNode( true ) {};

                rtl::OUString aResourceURL;
                rtl::OUString aName;
                bool          bModified;        // has been changed since last storing
                bool          bDefault;         // default settings
                bool          bDefaultNode;     // this is a default layer element data
                com::sun::star::uno::Reference< com::sun::star::container::XIndexAccess > xSettings;
            };

            struct UIElementType;
            friend struct UIElementType;
            typedef ::std::hash_map< rtl::OUString, UIElementData, OUStringHashCode, ::std::equal_to< rtl::OUString > > UIElementDataHashMap;

            struct UIElementType
            {
                UIElementType() : bModified( false ),
                                  bLoaded( false ),
                                  bDefaultLayer( false ),
                                  nElementType( ::com::sun::star::ui::UIElementType::UNKNOWN ) {}

                bool                                                              bModified;
                bool                                                              bLoaded;
                bool                                                              bDefaultLayer;
                sal_Int16                                                         nElementType;
                UIElementDataHashMap                                              aElementsHashMap;
                com::sun::star::uno::Reference< com::sun::star::embed::XStorage > xStorage;
            };

            typedef ::std::vector< UIElementType > UIElementTypesVector;
            typedef ::std::vector< ::com::sun::star::ui::ConfigurationEvent > ConfigEventNotifyContainer;
            typedef ::std::hash_map< rtl::OUString, UIElementInfo, OUStringHashCode, ::std::equal_to< rtl::OUString > > UIElementInfoHashMap;

            // private methods
            void            impl_Initialize();
            void            implts_notifyContainerListener( const ::com::sun::star::ui::ConfigurationEvent& aEvent, NotifyOp eOp );
            void            impl_fillSequenceWithElementTypeInfo( UIElementInfoHashMap& aUIElementInfoCollection, sal_Int16 nElementType );
            void            impl_preloadUIElementTypeList( Layer eLayer, sal_Int16 nElementType );
            UIElementData*  impl_findUIElementData( const rtl::OUString& aResourceURL, sal_Int16 nElementType, bool bLoad = true );
            void            impl_requestUIElementData( sal_Int16 nElementType, Layer eLayer, UIElementData& aUIElementData );
            void            impl_storeElementTypeData( com::sun::star::uno::Reference< com::sun::star::embed::XStorage > xStorage, UIElementType& rElementType, bool bResetModifyState = true );
            void            impl_resetElementTypeData( UIElementType& rUserElementType, UIElementType& rDefaultElementType, ConfigEventNotifyContainer& rRemoveNotifyContainer, ConfigEventNotifyContainer& rReplaceNotifyContainer );
            void            impl_reloadElementTypeData( UIElementType& rUserElementType, UIElementType& rDefaultElementType, ConfigEventNotifyContainer& rRemoveNotifyContainer, ConfigEventNotifyContainer& rReplaceNotifyContainer );

            UIElementTypesVector                                                            m_aUIElements[LAYER_COUNT];
            PresetHandler*                                                                  m_pStorageHandler[::com::sun::star::ui::UIElementType::COUNT];
            com::sun::star::uno::Reference< com::sun::star::embed::XStorage >               m_xDefaultConfigStorage;
            com::sun::star::uno::Reference< com::sun::star::embed::XStorage >               m_xUserConfigStorage;
            bool                                                                            m_bReadOnly;
            bool                                                                            m_bInitialized;
            bool                                                                            m_bModified;
            bool                                                                            m_bConfigRead;
            bool                                                                            m_bDisposed;
            rtl::OUString                                                                   m_aXMLPostfix;
            rtl::OUString                                                                   m_aPropUIName;
            rtl::OUString                                                                   m_aPropResourceURL;
            rtl::OUString                                                                   m_aModuleIdentifier;
            rtl::OUString                                                                   m_aModuleShortName;
            com::sun::star::uno::Reference< com::sun::star::embed::XTransactedObject >      m_xUserRootCommit;
            com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >    m_xServiceManager;
            ::cppu::OMultiTypeInterfaceContainerHelper                                      m_aListenerContainer;   /// container for ALL Listener
            com::sun::star::uno::Reference< com::sun::star::lang::XComponent >              m_xModuleImageManager;
   };
}

#endif // __FRAMEWORK_UICONFIGURATION_MODULEUICONFIGMANAGER_HXX_
<|endoftext|>


<commit_before>/*
    This file is part of KAddressBook.
    Copyright (c) 2002 Cornelius Schumacher <schumacher@kde.org>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program 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 General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

    As a special exception, permission is given to link this program
    with any edition of Qt, and distribute the resulting executable,
    without including the source code for Qt in the source distribution.
*/

#include <klocale.h>
#include <kdebug.h>

#include "typecombo.h"

TypeCombo::TypeCombo( KABC::PhoneNumber::List &list, QWidget *parent,
                      const char *name )
  : KComboBox( parent, name ),
    mTypeList( list )
{
}

void TypeCombo::updateTypes()
{
  clear();

  QMap<QString,int> labelCount;

  uint i;
  for( i = 0; i < mTypeList.count(); ++i ) {
    QString label = mTypeList[ i ].label();
    int count = 1;
    if ( labelCount.contains( label ) ) {
      count = labelCount[ label ] + 1;
    }
    labelCount[ label ] = count;
    if ( count > 1 ) {
      label = i18n("label (number)", "%1 (%2)").arg( label )
                                           .arg( QString::number( count ) );
    }
    insertItem( label );
  }
}

void TypeCombo::selectType( int type )
{
  uint i;
  for( i = 0; i < mTypeList.count(); ++i ) {
    if ( mTypeList[ i ].type() == type ) {
      setCurrentItem( i );
      break;
    }
  }
}

KABC::PhoneNumber::List::Iterator TypeCombo::selectedElement()
{
  return mTypeList.at( currentItem() );
}

#include "typecombo.moc"
<commit_msg>Remeber current item.<commit_after>/*
    This file is part of KAddressBook.
    Copyright (c) 2002 Cornelius Schumacher <schumacher@kde.org>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program 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 General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

    As a special exception, permission is given to link this program
    with any edition of Qt, and distribute the resulting executable,
    without including the source code for Qt in the source distribution.
*/

#include <klocale.h>
#include <kdebug.h>

#include "typecombo.h"

TypeCombo::TypeCombo( KABC::PhoneNumber::List &list, QWidget *parent,
                      const char *name )
  : KComboBox( parent, name ),
    mTypeList( list )
{
}

void TypeCombo::updateTypes()
{
  // Remeber current item
  QString currentId;
  int current = currentItem();
  if ( current >= 0 ) currentId = mTypeList[ current ].id();

  clear();

  QMap<QString,int> labelCount;

  uint i;
  for( i = 0; i < mTypeList.count(); ++i ) {
    QString label = mTypeList[ i ].label();
    int count = 1;
    if ( labelCount.contains( label ) ) {
      count = labelCount[ label ] + 1;
    }
    labelCount[ label ] = count;
    if ( count > 1 ) {
      label = i18n("label (number)", "%1 (%2)").arg( label )
                                           .arg( QString::number( count ) );
    }
    insertItem( label );
  }

  // Restore previous current item
  if ( !currentId.isEmpty() ) {
    for( i = 0; i < mTypeList.count(); ++i ) {
      if ( mTypeList[ i ].id() == currentId ) {
        setCurrentItem( i );
        break;
      }
    }
  }
}

void TypeCombo::selectType( int type )
{
  uint i;
  for( i = 0; i < mTypeList.count(); ++i ) {
    if ( mTypeList[ i ].type() == type ) {
      setCurrentItem( i );
      break;
    }
  }
}

KABC::PhoneNumber::List::Iterator TypeCombo::selectedElement()
{
  return mTypeList.at( currentItem() );
}

#include "typecombo.moc"
<|endoftext|>


<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2013-2016.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://www.opensource.org/licenses/MIT)
//=======================================================================

#include "drivers/pci.hpp"

#include "kernel_utils.hpp"
#include "logging.hpp"

#include "fs/sysfs.hpp"

namespace {

std::vector<pci::device_descriptor> devices;

#define PCI_CONFIG_ADDRESS 0xCF8
#define PCI_CONFIG_DATA 0xCFC

uint16_t get_vendor_id(uint8_t bus, uint8_t device, uint8_t function){
    // read "device id | vendor id"
    auto large = pci::read_config_dword(bus, device, function, 0);
    // extract vendor id
    return large;
}

uint16_t get_device_id(uint8_t bus, uint8_t device, uint8_t function){
    // read "device id | vendor id"
    auto large = pci::read_config_dword(bus, device, function, 0);
    // extract device id
    return large >> 16;
}

uint8_t get_class_code(uint8_t bus, uint8_t device, uint8_t function){
    // read "class code | subclass | prog if | revision id"
    auto large = pci::read_config_dword(bus, device, function, 8);
    // extract class code only
    return large >> 24 & 0xFF;
}

uint8_t get_subclass(uint8_t bus, uint8_t device, uint8_t function){
    // read "class code | subclass | prog if | revision id"
    auto large = pci::read_config_dword(bus, device, function, 8);
    // extract subclass only
    return large >> 16 & 0xFF;
}

uint8_t get_header_type(uint8_t bus, uint8_t device, uint8_t function){
    // read "BIST | header type | latency timer | cache line size"
    auto large = pci::read_config_dword(bus, device, function, 12);
    // extract header type only
    return large >> 16 & 0xFF;
}

void check_function(uint8_t bus, uint8_t device, uint8_t function){
    auto vendor_id = get_vendor_id(bus, device, function);
    if(vendor_id == 0xFFFF) {
        return;
    }

    auto device_id = get_device_id(bus, device, function);
    auto class_code = get_class_code(bus, device, function);
    auto sub_class = get_subclass(bus, device, function);

    logging::logf(logging::log_level::DEBUG, "Found device pci:%u:%u:%u (vendor:%u class:%u subclass:%u) \n",
        uint64_t(bus), uint64_t(device), uint64_t(function), uint64_t(vendor_id), uint64_t(class_code), uint64_t(sub_class));

    auto& device_desc = devices.emplace_back();

    device_desc.bus = bus;
    device_desc.device = device;
    device_desc.function = function;
    device_desc.vendor_id = vendor_id;
    device_desc.device_id = device_id;
    device_desc.class_code = class_code;
    device_desc.sub_class = sub_class;

    if(class_code < static_cast<uint8_t>(pci::device_class_type::RESERVED)){
        device_desc.class_type = static_cast<pci::device_class_type>(class_code);
    } else if(class_code < static_cast<uint8_t>(pci::device_class_type::UNKNOWN)){
        device_desc.class_type = pci::device_class_type::RESERVED;
    } else {
        device_desc.class_type = pci::device_class_type::UNKNOWN;
    }

    std::string pci_name = "pci:" + std::to_string(bus) + ':' + std::to_string(device) + ':' + std::to_string(function);

    auto p = path("/pci") / pci_name;

    sysfs::set_constant_value(path("/sys"), p / "vendor", std::to_string(vendor_id));
    sysfs::set_constant_value(path("/sys"), p / "device", std::to_string(device_id));
    sysfs::set_constant_value(path("/sys"), p / "class", std::to_string(class_code));
    sysfs::set_constant_value(path("/sys"), p / "subclass", std::to_string(sub_class));
}

void check_device(uint8_t bus, uint8_t device) {
    check_function(bus, device, 0);

    auto header_type = get_header_type(bus, device, 0);
    if((header_type & 0x80) != 0){
        for(uint8_t function = 1; function < 8; ++function){
            check_function(bus, device, function);
        }
    }
}

void brute_force_check_all_buses(){
    for(uint16_t bus = 0; bus < 256; ++bus) {
        for(uint8_t device = 0; device < 32; ++device) {
            check_device(bus, device);
        }
    }
}

} //end of anonymous namespace

void pci::detect_devices(){
    brute_force_check_all_buses();
}

size_t pci::number_of_devices(){
    return devices.size();
}

pci::device_descriptor& pci::device(size_t index){
    return devices[index];
}

uint8_t pci::read_config_byte(uint8_t bus, uint8_t device, uint8_t function, uint8_t offset){
    auto value = read_config_dword(bus, device, function, offset);
    return (value >> ((offset & 3) * 8)) & 0xff;
}

uint16_t pci::read_config_word(uint8_t bus, uint8_t device, uint8_t function, uint8_t offset){
    auto value = read_config_dword(bus, device, function, offset);
    return (value >> ((offset & 3) * 8)) & 0xffff;
}

uint32_t pci::read_config_dword(uint8_t bus, uint8_t device, uint8_t function, uint8_t offset){
    uint32_t address =
        static_cast<uint32_t>(1 << 31)  //enabled
        | (uint32_t(bus) << 16)  //bus number
        | (uint32_t(device) << 11)  //device number
        | (uint32_t(function) << 8) //function number
        | ((uint32_t(offset) ) & 0xfc); //Register number

    out_dword(PCI_CONFIG_ADDRESS, address);

    return in_dword(PCI_CONFIG_DATA);
}

void pci::write_config_byte(uint8_t bus, uint8_t device, uint8_t function, uint8_t offset, uint8_t value){
    auto tmp = read_config_dword(bus, device, function, offset);

    tmp &= ~(0xff << ((offset & 3) * 8));
    tmp |= (value << ((offset & 3) * 8));

    write_config_dword(bus, device, function, offset, tmp);
}

void pci::write_config_word(uint8_t bus, uint8_t device, uint8_t function, uint8_t offset, uint16_t value){
    auto tmp = read_config_dword(bus, device, function, offset);

    tmp &= ~(0xffff << ((offset & 3) * 8));
    tmp |= (value << ((offset & 3) * 8));

    write_config_dword(bus, device, function, offset, tmp);
}

void pci::write_config_dword (uint8_t bus, uint8_t device, uint8_t function, uint8_t offset, uint32_t value){
    uint32_t address =
        static_cast<uint32_t>(1 << 31)  //enabled
        | (uint32_t(bus) << 16)  //bus number
        | (uint32_t(device) << 11)  //device number
        | (uint32_t(function) << 8) //function number
        | ((uint32_t(offset) ) & 0xfc); //Register number

    out_dword(PCI_CONFIG_ADDRESS, address);

    out_dword(PCI_CONFIG_DATA, value);
}
<commit_msg>Reformat code<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2013-2016.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://www.opensource.org/licenses/MIT)
//=======================================================================

#include "drivers/pci.hpp"

#include "kernel_utils.hpp"
#include "logging.hpp"

#include "fs/sysfs.hpp"

namespace {

std::vector<pci::device_descriptor> devices;

#define PCI_CONFIG_ADDRESS 0xCF8
#define PCI_CONFIG_DATA 0xCFC

uint16_t get_vendor_id(uint8_t bus, uint8_t device, uint8_t function){
    // read "device id | vendor id"
    auto large = pci::read_config_dword(bus, device, function, 0);
    // extract vendor id
    return large;
}

uint16_t get_device_id(uint8_t bus, uint8_t device, uint8_t function){
    // read "device id | vendor id"
    auto large = pci::read_config_dword(bus, device, function, 0);
    // extract device id
    return large >> 16;
}

uint8_t get_class_code(uint8_t bus, uint8_t device, uint8_t function){
    // read "class code | subclass | prog if | revision id"
    auto large = pci::read_config_dword(bus, device, function, 8);
    // extract class code only
    return large >> 24 & 0xFF;
}

uint8_t get_subclass(uint8_t bus, uint8_t device, uint8_t function){
    // read "class code | subclass | prog if | revision id"
    auto large = pci::read_config_dword(bus, device, function, 8);
    // extract subclass only
    return large >> 16 & 0xFF;
}

uint8_t get_header_type(uint8_t bus, uint8_t device, uint8_t function){
    // read "BIST | header type | latency timer | cache line size"
    auto large = pci::read_config_dword(bus, device, function, 12);
    // extract header type only
    return large >> 16 & 0xFF;
}

void check_function(uint8_t bus, uint8_t device, uint8_t function){
    auto vendor_id = get_vendor_id(bus, device, function);
    if(vendor_id == 0xFFFF) {
        return;
    }

    auto device_id  = get_device_id(bus, device, function);
    auto class_code = get_class_code(bus, device, function);
    auto sub_class  = get_subclass(bus, device, function);

    logging::logf(logging::log_level::DEBUG, "Found device pci:%u:%u:%u (vendor:%u class:%u subclass:%u) \n",
        uint64_t(bus), uint64_t(device), uint64_t(function), uint64_t(vendor_id), uint64_t(class_code), uint64_t(sub_class));

    auto& device_desc = devices.emplace_back();

    device_desc.bus        = bus;
    device_desc.device     = device;
    device_desc.function   = function;
    device_desc.vendor_id  = vendor_id;
    device_desc.device_id  = device_id;
    device_desc.class_code = class_code;
    device_desc.sub_class  = sub_class;

    if (class_code < static_cast<uint8_t>(pci::device_class_type::RESERVED)) {
        device_desc.class_type = static_cast<pci::device_class_type>(class_code);
    } else if (class_code < static_cast<uint8_t>(pci::device_class_type::UNKNOWN)) {
        device_desc.class_type = pci::device_class_type::RESERVED;
    } else {
        device_desc.class_type = pci::device_class_type::UNKNOWN;
    }

    std::string pci_name = "pci:" + std::to_string(bus) + ':' + std::to_string(device) + ':' + std::to_string(function);

    auto p = path("/pci") / pci_name;

    sysfs::set_constant_value(path("/sys"), p / "vendor", std::to_string(vendor_id));
    sysfs::set_constant_value(path("/sys"), p / "device", std::to_string(device_id));
    sysfs::set_constant_value(path("/sys"), p / "class", std::to_string(class_code));
    sysfs::set_constant_value(path("/sys"), p / "subclass", std::to_string(sub_class));
}

void check_device(uint8_t bus, uint8_t device) {
    check_function(bus, device, 0);

    auto header_type = get_header_type(bus, device, 0);
    if((header_type & 0x80) != 0){
        for(uint8_t function = 1; function < 8; ++function){
            check_function(bus, device, function);
        }
    }
}

void brute_force_check_all_buses(){
    for(uint16_t bus = 0; bus < 256; ++bus) {
        for(uint8_t device = 0; device < 32; ++device) {
            check_device(bus, device);
        }
    }
}

} //end of anonymous namespace

void pci::detect_devices(){
    brute_force_check_all_buses();
}

size_t pci::number_of_devices(){
    return devices.size();
}

pci::device_descriptor& pci::device(size_t index){
    return devices[index];
}

uint8_t pci::read_config_byte(uint8_t bus, uint8_t device, uint8_t function, uint8_t offset){
    auto value = read_config_dword(bus, device, function, offset);
    return (value >> ((offset & 3) * 8)) & 0xff;
}

uint16_t pci::read_config_word(uint8_t bus, uint8_t device, uint8_t function, uint8_t offset){
    auto value = read_config_dword(bus, device, function, offset);
    return (value >> ((offset & 3) * 8)) & 0xffff;
}

uint32_t pci::read_config_dword(uint8_t bus, uint8_t device, uint8_t function, uint8_t offset){
    uint32_t address =
        static_cast<uint32_t>(1 << 31)  //enabled
        | (uint32_t(bus) << 16)  //bus number
        | (uint32_t(device) << 11)  //device number
        | (uint32_t(function) << 8) //function number
        | ((uint32_t(offset) ) & 0xfc); //Register number

    out_dword(PCI_CONFIG_ADDRESS, address);

    return in_dword(PCI_CONFIG_DATA);
}

void pci::write_config_byte(uint8_t bus, uint8_t device, uint8_t function, uint8_t offset, uint8_t value){
    auto tmp = read_config_dword(bus, device, function, offset);

    tmp &= ~(0xff << ((offset & 3) * 8));
    tmp |= (value << ((offset & 3) * 8));

    write_config_dword(bus, device, function, offset, tmp);
}

void pci::write_config_word(uint8_t bus, uint8_t device, uint8_t function, uint8_t offset, uint16_t value){
    auto tmp = read_config_dword(bus, device, function, offset);

    tmp &= ~(0xffff << ((offset & 3) * 8));
    tmp |= (value << ((offset & 3) * 8));

    write_config_dword(bus, device, function, offset, tmp);
}

void pci::write_config_dword (uint8_t bus, uint8_t device, uint8_t function, uint8_t offset, uint32_t value){
    uint32_t address =
        static_cast<uint32_t>(1 << 31)  //enabled
        | (uint32_t(bus) << 16)  //bus number
        | (uint32_t(device) << 11)  //device number
        | (uint32_t(function) << 8) //function number
        | ((uint32_t(offset) ) & 0xfc); //Register number

    out_dword(PCI_CONFIG_ADDRESS, address);

    out_dword(PCI_CONFIG_DATA, value);
}
<|endoftext|>