<commit_before>#include <ros/ros.h>
#include <nav_msgs/Odometry.h>
#include <geometry_msgs/Twist.h>
#include <tf2_msgs/TFMessage.h>

#include <boost/thread.hpp>

#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>
#include <string.h>
#include <errno.h>

#include "drive_command.h"

static int timespec_eq(const struct timespec *a, const struct timespec *b)
{
	return a->tv_sec == b->tv_sec && a->tv_nsec == b->tv_nsec;
}

class bridge_node {
private:
	ros::NodeHandle node;
	ros::Publisher pubOdom, pubTf;
	ros::Subscriber subVel;

	boost::thread odomThread;

	struct drive_shm *shm;
public:
	bool start() {
		int fd = shm_open(DRIVE_SHM_NAME, O_RDWR, 0);
		if (fd < 0) {
			ROS_ERROR("shm_open: %s", strerror(errno));
			return false;
		}

		shm = (struct drive_shm *)mmap(NULL, sizeof(*shm), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
		if (close(fd) < 0)
			ROS_WARN("close: %s", strerror(errno));

		if (shm == MAP_FAILED) {
			ROS_ERROR("mmap: %s", strerror(errno));
			return false;
		}

		subVel = node.subscribe("cmd_vel", 2, &bridge_node::sub_vel, this);

		pubOdom = node.advertise<nav_msgs::Odometry>("odom", 50);
		pubTf = node.advertise<tf2_msgs::TFMessage>("/tf", 100);

		odomThread = boost::thread(&bridge_node::process_odometry, this);

		return true;
	}

	void process_odometry() {
		bool first_time = true;
		struct timespec stat_time;
		struct drive_status stat;

		double x = 0.0;
		double y = 0.0;
		double theta = 0.0;
		double last_lin_enc, last_ang_enc;
		bool first_enc = true;

		while (ros::ok()) {
			pthread_mutex_lock(&shm->stat_lock);
			if (first_time) {
				first_time = false;
				stat_time = shm->stat_time;
			}
			while (timespec_eq(&stat_time, &shm->stat_time)) {
				pthread_cond_wait(&shm->stat_cond, &shm->stat_lock);
			}
			stat_time = shm->stat_time;
			stat = shm->stat;
			pthread_mutex_unlock(&shm->stat_lock);

			ros::Time time = ros::Time::now();

			double lin_enc = (stat.encoder_1 - stat.encoder_2) * 0.0040578907f;
			double ang_enc = (stat.encoder_2 + stat.encoder_1) * -0.019415744f;
			double lin_vel = stat.actualLinearVelocity / 65536.0;
			double ang_vel = stat.actualAngularVelocity / 65536.0;

			if (first_enc) {
				first_enc = false;
				last_lin_enc = lin_enc;
				last_ang_enc = ang_enc;
				continue;
			}

			double movement = lin_enc - last_lin_enc;
			double rotation = ang_enc - last_ang_enc;
			// add calibration factors
			double lin_calib = 1.0;
			double ang_calib = 1.0;
			movement *= lin_calib;
			rotation *= ang_calib;
			last_lin_enc = lin_enc;
			last_ang_enc = ang_enc;
			x += cos(theta + rotation/2) * movement;
			y += sin(theta + rotation/2) * movement;
			theta += rotation;

			nav_msgs::Odometry odom;
			odom.header.stamp = time;
			odom.header.frame_id = "odom";
			odom.child_frame_id = "base_link";

			odom.pose.pose.position.x = x;
			odom.pose.pose.position.y = y;
			odom.pose.pose.orientation.z = sin(theta/2);
			odom.pose.pose.orientation.w = cos(theta/2);

			odom.twist.twist.linear.x = lin_vel;
			odom.twist.twist.angular.z = ang_vel;

			odom.twist.twist.linear.z = movement;
			odom.twist.twist.angular.x = rotation;

			pubOdom.publish(odom);

			// geometry_msgs::TransformStamped trans;
			// trans.header.stamp = odom.header.stamp;
			// trans.header.frame_id = odom.header.frame_id;
			// trans.child_frame_id = odom.child_frame_id;

			// trans.transform.translation.x = odom.pose.pose.position.x;
			// trans.transform.translation.y = odom.pose.pose.position.y;
			// trans.transform.translation.z = odom.pose.pose.position.z;
			// trans.transform.rotation = odom.pose.pose.orientation;

			// tf2_msgs::TFMessage tf2msg;
			// tf2msg.transforms.push_back(trans);
			// pubTf.publish(tf2msg);
		}
	}

	void join() {
		odomThread.join();
	}

	void sub_vel(const geometry_msgs::Twist::ConstPtr& msg) {
		double lin_vel = msg->linear.x;
		double ang_vel = msg->angular.z;

		if (lin_vel > 0.5 || ang_vel > 0.5) {
			ROS_WARN("velocity too large, lin:%f ang:%f", lin_vel, ang_vel);
			return;
		}

		struct drive_command cmd = {DRIVE_COMMAND_MAGIC, 1,
			lin_vel*65536, ang_vel*65536, 0, -1, -1};
		struct timespec now;
		clock_gettime(CLOCK_MONOTONIC, &now);

		now.tv_nsec += 150000000;
		if (now.tv_nsec >= 1000000000) {
			now.tv_sec++;
			now.tv_nsec -= 1000000000;
		}

		pthread_mutex_lock(&shm->cmd_lock);
		shm->cmd_time = now;
		shm->cmd = cmd;
		pthread_mutex_unlock(&shm->cmd_lock);
	}
};

int main(int argc, char **argv) {
	ros::init(argc, argv, "beam");

	bridge_node bridge;

	if (!bridge.start())
		return 1;

	ROS_INFO("start");
	ros::spin();

	bridge.join();

	return 0;
}
<commit_msg>calibrated odom and added tf back<commit_after>#include <ros/ros.h>
#include <nav_msgs/Odometry.h>
#include <geometry_msgs/Twist.h>
#include <tf2_msgs/TFMessage.h>

#include <boost/thread.hpp>

#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>
#include <string.h>
#include <errno.h>

#include "drive_command.h"

static int timespec_eq(const struct timespec *a, const struct timespec *b)
{
	return a->tv_sec == b->tv_sec && a->tv_nsec == b->tv_nsec;
}

class bridge_node {
private:
	ros::NodeHandle node;
	ros::Publisher pubOdom, pubTf;
	ros::Subscriber subVel;

	boost::thread odomThread;

	struct drive_shm *shm;
public:
	bool start() {
		int fd = shm_open(DRIVE_SHM_NAME, O_RDWR, 0);
		if (fd < 0) {
			ROS_ERROR("shm_open: %s", strerror(errno));
			return false;
		}

		shm = (struct drive_shm *)mmap(NULL, sizeof(*shm), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
		if (close(fd) < 0)
			ROS_WARN("close: %s", strerror(errno));

		if (shm == MAP_FAILED) {
			ROS_ERROR("mmap: %s", strerror(errno));
			return false;
		}

		subVel = node.subscribe("cmd_vel", 2, &bridge_node::sub_vel, this);

		pubOdom = node.advertise<nav_msgs::Odometry>("odom", 50);
		pubTf = node.advertise<tf2_msgs::TFMessage>("/tf", 100);

		odomThread = boost::thread(&bridge_node::process_odometry, this);

		return true;
	}

	void process_odometry() {
		bool first_time = true;
		struct timespec stat_time;
		struct drive_status stat;

		double x = 0.0;
		double y = 0.0;
		double theta = 0.0;
		double last_lin_enc, last_ang_enc;
		bool first_enc = true;

		while (ros::ok()) {
			pthread_mutex_lock(&shm->stat_lock);
			if (first_time) {
				first_time = false;
				stat_time = shm->stat_time;
			}
			while (timespec_eq(&stat_time, &shm->stat_time)) {
				pthread_cond_wait(&shm->stat_cond, &shm->stat_lock);
			}
			stat_time = shm->stat_time;
			stat = shm->stat;
			pthread_mutex_unlock(&shm->stat_lock);

			ros::Time time = ros::Time::now();

			double lin_enc = (stat.encoder_1 - stat.encoder_2) * 0.0040578907f;
			double ang_enc = (stat.encoder_2 + stat.encoder_1) * -0.019415744f;
			double lin_vel = stat.actualLinearVelocity / 65536.0;
			double ang_vel = stat.actualAngularVelocity / 65536.0;

			if (first_enc) {
				first_enc = false;
				last_lin_enc = lin_enc;
				last_ang_enc = ang_enc;
				continue;
			}

			double movement = lin_enc - last_lin_enc;
			double rotation = ang_enc - last_ang_enc;
			last_lin_enc = lin_enc;
			last_ang_enc = ang_enc;

			// add calibration factors
			double lin_calib = 0.84;
			double ang_calib = 1.0;
			double movement_calib = movement * lin_calib;
			double rotation_calib = rotation * ang_calib;

			x += cos(theta + rotation_calib/2) * movement_calib;
			y += sin(theta + rotation_calib/2) * movement_calib;
			theta += rotation_calib;

			nav_msgs::Odometry odom;
			odom.header.stamp = time;
			odom.header.frame_id = "odom";
			odom.child_frame_id = "base";

			odom.pose.pose.position.x = x;
			odom.pose.pose.position.y = y;
			odom.pose.pose.orientation.z = sin(theta/2);
			odom.pose.pose.orientation.w = cos(theta/2);

			odom.twist.twist.linear.x = lin_vel;
			odom.twist.twist.angular.z = ang_vel;

			odom.twist.twist.linear.z = movement;
			odom.twist.twist.angular.x = rotation;

			pubOdom.publish(odom);

			geometry_msgs::TransformStamped trans;
			trans.header.stamp = odom.header.stamp;
			trans.header.frame_id = odom.header.frame_id;
			trans.child_frame_id = odom.child_frame_id;

			trans.transform.translation.x = odom.pose.pose.position.x;
			trans.transform.translation.y = odom.pose.pose.position.y;
			trans.transform.translation.z = odom.pose.pose.position.z;
			trans.transform.rotation = odom.pose.pose.orientation;

			tf2_msgs::TFMessage tf2msg;
			tf2msg.transforms.push_back(trans);
			pubTf.publish(tf2msg);
		}
	}

	void join() {
		odomThread.join();
	}

	void sub_vel(const geometry_msgs::Twist::ConstPtr& msg) {
		double lin_vel = msg->linear.x;
		double ang_vel = msg->angular.z;

		if (lin_vel > 0.5 || ang_vel > 0.5) {
			ROS_WARN("velocity too large, lin:%f ang:%f", lin_vel, ang_vel);
			return;
		}

		struct drive_command cmd = {DRIVE_COMMAND_MAGIC, 1,
			lin_vel*65536, ang_vel*65536, 0, -1, -1};
		struct timespec now;
		clock_gettime(CLOCK_MONOTONIC, &now);

		now.tv_nsec += 150000000;
		if (now.tv_nsec >= 1000000000) {
			now.tv_sec++;
			now.tv_nsec -= 1000000000;
		}

		pthread_mutex_lock(&shm->cmd_lock);
		shm->cmd_time = now;
		shm->cmd = cmd;
		pthread_mutex_unlock(&shm->cmd_lock);
	}
};

int main(int argc, char **argv) {
	ros::init(argc, argv, "beam");

	bridge_node bridge;

	if (!bridge.start())
		return 1;

	ROS_INFO("start");
	ros::spin();

	bridge.join();

	return 0;
}
<|endoftext|>


<commit_before>/*

Copyright (c) 2009, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include "libtorrent/utp_stream.hpp"
#include "libtorrent/udp_socket.hpp"
#include "libtorrent/utp_socket_manager.hpp"
#include "libtorrent/instantiate_connection.hpp"
#include "libtorrent/socket_io.hpp"

// #define TORRENT_DEBUG_MTU 1135

namespace libtorrent
{

	utp_socket_manager::utp_socket_manager(session_settings const& sett, udp_socket& s
		, incoming_utp_callback_t cb)
		: m_sock(s)
		, m_cb(cb)
		, m_last_socket(0)
		, m_new_connection(-1)
		, m_sett(sett)
	{}

	utp_socket_manager::~utp_socket_manager()
	{
		for (socket_map_t::iterator i = m_utp_sockets.begin()
			, end(m_utp_sockets.end()); i != end; ++i)
		{
			delete_utp_impl(i->second);
		}
	}

	void utp_socket_manager::get_status(utp_status& s) const
	{
		s.num_idle = 0;
		s.num_syn_sent = 0;
		s.num_connected = 0;
		s.num_fin_sent = 0;
		s.num_close_wait = 0;

		for (socket_map_t::const_iterator i = m_utp_sockets.begin()
			, end(m_utp_sockets.end()); i != end; ++i)
		{
			int state = utp_socket_state(i->second);
			switch (state)
			{
				case 0: ++s.num_idle; break;
				case 1: ++s.num_syn_sent; break;
				case 2: ++s.num_connected; break;
				case 3: ++s.num_fin_sent; break;
				case 4: ++s.num_close_wait; break;
				case 5: ++s.num_close_wait; break;
			}
		}
	}

	void utp_socket_manager::tick(ptime now)
	{
		for (socket_map_t::iterator i = m_utp_sockets.begin()
			, end(m_utp_sockets.end()); i != end;)
		{
			if (should_delete(i->second))
			{
				delete_utp_impl(i->second);
				if (m_last_socket == i->second) m_last_socket = 0;
				m_utp_sockets.erase(i++);
				continue;
			}
			tick_utp_impl(i->second, now);
			++i;
		}
	}

	void utp_socket_manager::send_packet(udp::endpoint const& ep, char const* p
		, int len, error_code& ec, int flags)
	{
		if (!m_sock.is_open())
		{
			ec = asio::error::operation_aborted;
			return;
		}

#ifdef TORRENT_DEBUG_MTU
		// drop packets that exceed the debug MTU
		if ((flags & dont_fragment) && len > TORRENT_DEBUG_MTU) return;
#endif

#ifdef TORRENT_HAS_DONT_FRAGMENT
		error_code tmp;
		if (flags & dont_fragment) m_sock.set_option(dont_fragment(true), tmp);
#endif
		m_sock.send(ep, p, len, ec);
#ifdef TORRENT_HAS_DONT_FRAGMENT
		if (flags & dont_fragment) m_sock.set_option(dont_fragment(false), tmp);
#endif
	}

	tcp::endpoint utp_socket_manager::local_endpoint(error_code& ec) const
	{
		return m_sock.local_endpoint(ec);
	}

	bool utp_socket_manager::incoming_packet(char const* p, int size, udp::endpoint const& ep)
	{
//		UTP_LOGV("incoming packet size:%d\n", size);

		if (size < sizeof(utp_header)) return false;

		utp_header const* ph = (utp_header*)p;

//		UTP_LOGV("incoming packet version:%d\n", int(ph->get_version()));

		if (ph->get_version() != 1) return false;

		const ptime receive_time = time_now_hires();

		// parse out connection ID and look for existing
		// connections. If found, forward to the utp_stream.
		boost::uint16_t id = ph->connection_id;

		// first test to see if it's the same socket as last time
		// in most cases it is
		if (m_last_socket
			&& utp_match(m_last_socket, ep, id))
		{
			return utp_incoming_packet(m_last_socket, p, size, ep, receive_time);
		}

		socket_map_t::iterator i = m_utp_sockets.find(id);

		std::pair<socket_map_t::iterator, socket_map_t::iterator> r =
			m_utp_sockets.equal_range(id);

		for (; r.first != r.second; ++r.first)
		{
			if (!utp_match(r.first->second, ep, id)) continue;
			bool ret = utp_incoming_packet(r.first->second, p, size, ep, receive_time);
			if (ret) m_last_socket = r.first->second;
			return ret;
		}

//		UTP_LOGV("incoming packet id:%d source:%s\n", id, print_endpoint(ep).c_str());

		if (!m_sett.enable_incoming_utp)
			return false;

		// if not found, see if it's a SYN packet, if it is,
		// create a new utp_stream
		if (ph->get_type() == ST_SYN)
		{
			// create the new socket with this ID
			m_new_connection = id;

//			UTP_LOGV("not found, new connection id:%d\n", m_new_connection);

			boost::shared_ptr<socket_type> c(new (std::nothrow) socket_type(m_sock.get_io_service()));
			if (!c) return false;
			instantiate_connection(m_sock.get_io_service(), proxy_settings(), *c, 0, this);
			utp_stream* str = c->get<utp_stream>();
			TORRENT_ASSERT(str);
			bool ret = utp_incoming_packet(str->get_impl(), p, size, ep, receive_time);
			if (!ret) return false;
			m_cb(c);
			// the connection most likely changed its connection ID here
			// we need to move it to the correct ID
			return true;
		}

		// #error send reset

		return false;
	}

	void utp_socket_manager::remove_socket(boost::uint16_t id)
	{
		socket_map_t::iterator i = m_utp_sockets.find(id);
		if (i == m_utp_sockets.end()) return;
		delete_utp_impl(i->second);
		if (m_last_socket == i->second) m_last_socket = 0;
		m_utp_sockets.erase(i);
	}

	utp_socket_impl* utp_socket_manager::new_utp_socket(utp_stream* str)
	{
		boost::uint16_t send_id = 0;
		boost::uint16_t recv_id = 0;
		if (m_new_connection != -1)
		{
			send_id = m_new_connection;
			recv_id = m_new_connection + 1;
			m_new_connection = -1;
		}
		else
		{
			send_id = rand();
			recv_id = send_id - 1;
		}
		utp_socket_impl* impl = construct_utp_impl(recv_id, send_id, str, this);
		m_utp_sockets.insert(std::make_pair(recv_id, impl));
		return impl;
	}
}

<commit_msg>fix msvc build issue<commit_after>/*

Copyright (c) 2009, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include "libtorrent/utp_stream.hpp"
#include "libtorrent/udp_socket.hpp"
#include "libtorrent/utp_socket_manager.hpp"
#include "libtorrent/instantiate_connection.hpp"
#include "libtorrent/socket_io.hpp"

// #define TORRENT_DEBUG_MTU 1135

namespace libtorrent
{

	utp_socket_manager::utp_socket_manager(session_settings const& sett, udp_socket& s
		, incoming_utp_callback_t cb)
		: m_sock(s)
		, m_cb(cb)
		, m_last_socket(0)
		, m_new_connection(-1)
		, m_sett(sett)
	{}

	utp_socket_manager::~utp_socket_manager()
	{
		for (socket_map_t::iterator i = m_utp_sockets.begin()
			, end(m_utp_sockets.end()); i != end; ++i)
		{
			delete_utp_impl(i->second);
		}
	}

	void utp_socket_manager::get_status(utp_status& s) const
	{
		s.num_idle = 0;
		s.num_syn_sent = 0;
		s.num_connected = 0;
		s.num_fin_sent = 0;
		s.num_close_wait = 0;

		for (socket_map_t::const_iterator i = m_utp_sockets.begin()
			, end(m_utp_sockets.end()); i != end; ++i)
		{
			int state = utp_socket_state(i->second);
			switch (state)
			{
				case 0: ++s.num_idle; break;
				case 1: ++s.num_syn_sent; break;
				case 2: ++s.num_connected; break;
				case 3: ++s.num_fin_sent; break;
				case 4: ++s.num_close_wait; break;
				case 5: ++s.num_close_wait; break;
			}
		}
	}

	void utp_socket_manager::tick(ptime now)
	{
		for (socket_map_t::iterator i = m_utp_sockets.begin()
			, end(m_utp_sockets.end()); i != end;)
		{
			if (should_delete(i->second))
			{
				delete_utp_impl(i->second);
				if (m_last_socket == i->second) m_last_socket = 0;
				m_utp_sockets.erase(i++);
				continue;
			}
			tick_utp_impl(i->second, now);
			++i;
		}
	}

	void utp_socket_manager::send_packet(udp::endpoint const& ep, char const* p
		, int len, error_code& ec, int flags)
	{
		if (!m_sock.is_open())
		{
			ec = asio::error::operation_aborted;
			return;
		}

#ifdef TORRENT_DEBUG_MTU
		// drop packets that exceed the debug MTU
		if ((flags & dont_fragment) && len > TORRENT_DEBUG_MTU) return;
#endif

#ifdef TORRENT_HAS_DONT_FRAGMENT
		error_code tmp;
		if (flags & utp_socket_manager::dont_fragment)
			m_sock.set_option(libtorrent::dont_fragment(true), tmp);
#endif
		m_sock.send(ep, p, len, ec);
#ifdef TORRENT_HAS_DONT_FRAGMENT
		if (flags & utp_socket_manager::dont_fragment)
			m_sock.set_option(libtorrent::dont_fragment(false), tmp);
#endif
	}

	tcp::endpoint utp_socket_manager::local_endpoint(error_code& ec) const
	{
		return m_sock.local_endpoint(ec);
	}

	bool utp_socket_manager::incoming_packet(char const* p, int size, udp::endpoint const& ep)
	{
//		UTP_LOGV("incoming packet size:%d\n", size);

		if (size < sizeof(utp_header)) return false;

		utp_header const* ph = (utp_header*)p;

//		UTP_LOGV("incoming packet version:%d\n", int(ph->get_version()));

		if (ph->get_version() != 1) return false;

		const ptime receive_time = time_now_hires();

		// parse out connection ID and look for existing
		// connections. If found, forward to the utp_stream.
		boost::uint16_t id = ph->connection_id;

		// first test to see if it's the same socket as last time
		// in most cases it is
		if (m_last_socket
			&& utp_match(m_last_socket, ep, id))
		{
			return utp_incoming_packet(m_last_socket, p, size, ep, receive_time);
		}

		socket_map_t::iterator i = m_utp_sockets.find(id);

		std::pair<socket_map_t::iterator, socket_map_t::iterator> r =
			m_utp_sockets.equal_range(id);

		for (; r.first != r.second; ++r.first)
		{
			if (!utp_match(r.first->second, ep, id)) continue;
			bool ret = utp_incoming_packet(r.first->second, p, size, ep, receive_time);
			if (ret) m_last_socket = r.first->second;
			return ret;
		}

//		UTP_LOGV("incoming packet id:%d source:%s\n", id, print_endpoint(ep).c_str());

		if (!m_sett.enable_incoming_utp)
			return false;

		// if not found, see if it's a SYN packet, if it is,
		// create a new utp_stream
		if (ph->get_type() == ST_SYN)
		{
			// create the new socket with this ID
			m_new_connection = id;

//			UTP_LOGV("not found, new connection id:%d\n", m_new_connection);

			boost::shared_ptr<socket_type> c(new (std::nothrow) socket_type(m_sock.get_io_service()));
			if (!c) return false;
			instantiate_connection(m_sock.get_io_service(), proxy_settings(), *c, 0, this);
			utp_stream* str = c->get<utp_stream>();
			TORRENT_ASSERT(str);
			bool ret = utp_incoming_packet(str->get_impl(), p, size, ep, receive_time);
			if (!ret) return false;
			m_cb(c);
			// the connection most likely changed its connection ID here
			// we need to move it to the correct ID
			return true;
		}

		// #error send reset

		return false;
	}

	void utp_socket_manager::remove_socket(boost::uint16_t id)
	{
		socket_map_t::iterator i = m_utp_sockets.find(id);
		if (i == m_utp_sockets.end()) return;
		delete_utp_impl(i->second);
		if (m_last_socket == i->second) m_last_socket = 0;
		m_utp_sockets.erase(i);
	}

	utp_socket_impl* utp_socket_manager::new_utp_socket(utp_stream* str)
	{
		boost::uint16_t send_id = 0;
		boost::uint16_t recv_id = 0;
		if (m_new_connection != -1)
		{
			send_id = m_new_connection;
			recv_id = m_new_connection + 1;
			m_new_connection = -1;
		}
		else
		{
			send_id = rand();
			recv_id = send_id - 1;
		}
		utp_socket_impl* impl = construct_utp_impl(recv_id, send_id, str, this);
		m_utp_sockets.insert(std::make_pair(recv_id, impl));
		return impl;
	}
}

<|endoftext|>


<commit_before>
/*
  Test the DDS scanner, parser and DDS class.

  jhrg 8/29/94
*/

#include <iostream.h>
#include <GetOpt.h>

#include "Space.h"

#define YYSTYPE char *

#include "dds.tab.h"
#include "DDS.h"

void test_scanner();
void test_parser();
int ddslex();
int ddsparse(DDS &);

extern YYSTYPE ddslval;
extern int ddsdebug;
const char *prompt = "dds-test: ";

int
main(int argc, char *argv[])
{
    GetOpt getopt (argc, argv, "spdc");
    int option_char;
    int scanner_test = 0, parser_test = 0, class_test = 0;

    // process options

    while ((option_char = getopt ()) != EOF)
	switch (option_char)
	  {
	    case 'd':
	      space_debug = 1;	// defined in Space.h
	      executable_name = "das-test"; // defined in Space.h
	      ddsdebug = 1;
	      break;
	    case 's':
	      scanner_test = 1;
	      break;
	    case 'p':
	      parser_test = 1;
	      break;
	    case 'c':
	      class_test = 1;
	      break;
	    case '?':
	      fprintf (stderr, "usage: %s [d] filename ...\n", argv[0]);
	  }

    if (scanner_test) {
	test_scanner();
    }

    if (parser_test) {
	test_parser();
    }

    if (class_test) {
    }
}

void
test_scanner(void)
{
    int tok;

    cout << prompt;		// first prompt
    while ((tok = ddslex())) {
	switch (tok) {
	  case DATASET:
	    cout << "DATASET" << endl;
	    break;
	  case DEPENDENT:
	    cout << "DEPENDENT" << endl;
	    break;
	  case INDEPENDENT:
	    cout << "INDEPENDENT" << endl;
	    break;
	  case ARRAY:
	    cout << "ARRAY" << endl;
	    break;
	  case MAPS:
	    cout << "MAPS" << endl;
	    break;
	  case LIST:
	    cout << "LIST" << endl;
	    break;
	  case SEQUENCE:
	    cout << "SEQUENCE" << endl;
	    break;
	  case STRUCTURE:
	    cout << "STRUCTURE" << endl;
	    break;
	  case FUNCTION:
	    cout << "FUNCTION" << endl;
	    break;
	  case GRID:
	    cout << "GRID" << endl;
	    break;
	  case BYTE:
	    cout << "BYTE" << endl;
	    break;
	  case INT32:
	    cout << "INT32" << endl;
	    break;
	  case FLOAT64:
	    cout << "FLOAT64" << endl;
	    break;
	  case STRING:
	    cout << "STRING" << endl;
	    break;
	  case URL:
	    cout << "Url" << endl;
	    break;
	  case ID:
	    cout << "ID: " << ddslval << endl;
	    break;
	  case '{':
	    cout << "Left Brace" << endl;
	    break;
	  case '}':
	    cout << "Right Brace" << endl;
	    break;
	  case ';':
	    cout << "Semicolon" << endl;
	    break;
	  default:
	    cout << "Error: Unrecognized input" << endl;
	}
	cout << prompt;		// print prompt after output
    }
}

void
test_parser(void)
{
    DDS table;
    int status = table.parse();
    cout << "Status from parser: " << status << endl;

    if (table.check_semantics())
	cout << "DDS past semantic check" << endl;
    else
	cout << "DDS filed semantic check" << endl;

    if (table.check_semantics(true))
	cout << "DDS past full semantic check" << endl;
    else
	cout << "DDS filed full semantic check" << endl;

    table.print();
}
<commit_msg>Removed the Space.cc stuff - it broke dds-test on the alpha.<commit_after>
/*
  Test the DDS scanner, parser and DDS class.

  jhrg 8/29/94
*/

#include <iostream.h>
#include <GetOpt.h>

#define YYSTYPE char *

#include "dds.tab.h"
#include "DDS.h"

void test_scanner();
void test_parser();
int ddslex();
int ddsparse(DDS &);

extern YYSTYPE ddslval;
extern int ddsdebug;
const char *prompt = "dds-test: ";

int
main(int argc, char *argv[])
{
    GetOpt getopt (argc, argv, "spdc");
    int option_char;
    int scanner_test = 0, parser_test = 0, class_test = 0;

    // process options

    while ((option_char = getopt ()) != EOF)
	switch (option_char)
	  {
	    case 'd':
	      ddsdebug = 1;
	      break;
	    case 's':
	      scanner_test = 1;
	      break;
	    case 'p':
	      parser_test = 1;
	      break;
	    case 'c':
	      class_test = 1;
	      break;
	    case '?':
	      fprintf (stderr, "usage: %s [d] filename ...\n", argv[0]);
	  }

    if (scanner_test) {
	test_scanner();
    }

    if (parser_test) {
	test_parser();
    }

    if (class_test) {
    }
}

void
test_scanner(void)
{
    int tok;

    cout << prompt;		// first prompt
    while ((tok = ddslex())) {
	switch (tok) {
	  case DATASET:
	    cout << "DATASET" << endl;
	    break;
	  case DEPENDENT:
	    cout << "DEPENDENT" << endl;
	    break;
	  case INDEPENDENT:
	    cout << "INDEPENDENT" << endl;
	    break;
	  case ARRAY:
	    cout << "ARRAY" << endl;
	    break;
	  case MAPS:
	    cout << "MAPS" << endl;
	    break;
	  case LIST:
	    cout << "LIST" << endl;
	    break;
	  case SEQUENCE:
	    cout << "SEQUENCE" << endl;
	    break;
	  case STRUCTURE:
	    cout << "STRUCTURE" << endl;
	    break;
	  case FUNCTION:
	    cout << "FUNCTION" << endl;
	    break;
	  case GRID:
	    cout << "GRID" << endl;
	    break;
	  case BYTE:
	    cout << "BYTE" << endl;
	    break;
	  case INT32:
	    cout << "INT32" << endl;
	    break;
	  case FLOAT64:
	    cout << "FLOAT64" << endl;
	    break;
	  case STRING:
	    cout << "STRING" << endl;
	    break;
	  case URL:
	    cout << "Url" << endl;
	    break;
	  case ID:
	    cout << "ID: " << ddslval << endl;
	    break;
	  case '{':
	    cout << "Left Brace" << endl;
	    break;
	  case '}':
	    cout << "Right Brace" << endl;
	    break;
	  case ';':
	    cout << "Semicolon" << endl;
	    break;
	  default:
	    cout << "Error: Unrecognized input" << endl;
	}
	cout << prompt;		// print prompt after output
    }
}

void
test_parser(void)
{
    DDS table;
    int status = table.parse();
    cout << "Status from parser: " << status << endl;

    if (table.check_semantics())
	cout << "DDS past semantic check" << endl;
    else
	cout << "DDS filed semantic check" << endl;

    if (table.check_semantics(true))
	cout << "DDS past full semantic check" << endl;
    else
	cout << "DDS filed full semantic check" << endl;

    table.print();
}
<|endoftext|>


<commit_before>//
//  libavg - Media Playback Engine.
//  Copyright (C) 2003-2011 Ulrich von Zadow
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  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
//
//  Current versions can be found at www.libavg.de
//

#include "AsyncDemuxer.h"

#include "../base/ScopeTimer.h"
#include "../base/Exception.h"
#include "../base/ObjectCounter.h"

#include <boost/bind.hpp>

#include <iostream>

#define PACKET_QUEUE_LENGTH 50

using namespace std;

typedef boost::mutex::scoped_lock scoped_lock;

namespace avg {

AsyncDemuxer::AsyncDemuxer(AVFormatContext * pFormatContext, vector<int> streamIndexes)
    : m_pCmdQ(new VideoDemuxerThread::CQueue),
      m_bSeekPending(false),
      m_pFormatContext(pFormatContext)
{
    ObjectCounter::get()->incRef(&typeid(*this));
    for (unsigned i = 0; i < streamIndexes.size(); ++i) {
        enableStream(streamIndexes[i]);
    }
    m_pDemuxThread = new boost::thread(VideoDemuxerThread(*m_pCmdQ, m_pFormatContext,
            m_PacketQs));
}

AsyncDemuxer::~AsyncDemuxer()
{
    if (m_pDemuxThread) {
        m_pCmdQ->pushCmd(boost::bind(&VideoDemuxerThread::stop, _1));
        map<int, VideoPacketQueuePtr>::iterator it;
        for (it = m_PacketQs.begin(); it != m_PacketQs.end(); ++it) {
            // If the Queue is full, this breaks the lock in the thread.
            PacketVideoMsgPtr pPacketMsg;
            pPacketMsg = it->second->pop(false);
            if (pPacketMsg) {
                pPacketMsg->freePacket();
            }
        }
        m_pDemuxThread->join();
        delete m_pDemuxThread;
        m_pDemuxThread = 0;
        for (it = m_PacketQs.begin(); it != m_PacketQs.end(); it++) {
            VideoPacketQueuePtr pPacketQ = it->second;
            PacketVideoMsgPtr pPacketMsg;
            pPacketMsg = pPacketQ->pop(false);
            while (pPacketMsg) {
                pPacketMsg->freePacket();
                pPacketMsg = pPacketQ->pop(false);
            }
        }
    }
    ObjectCounter::get()->decRef(&typeid(*this));
}

AVPacket * AsyncDemuxer::getPacket(int streamIndex, bool& bSeekDone)
{
//    cerr << "  AsyncDemuxer::getPacket" << endl;
    PacketVideoMsgPtr pPacketMsg = m_PacketQs[streamIndex]->pop(true);
    bSeekDone = pPacketMsg->isSeekDone();
    if (bSeekDone) {
        AVG_ASSERT(!pPacketMsg->getPacket());
    }
    return pPacketMsg->getPacket();
}

void AsyncDemuxer::seek(float destTime)
{
//    cerr << "  AsyncDemuxer::seek" << endl;
    map<int, VideoPacketQueuePtr>::iterator it;
    for (it = m_PacketQs.begin(); it != m_PacketQs.end(); it++) {
        VideoPacketQueuePtr pPacketQ = it->second;
        pPacketQ->clear();
    }
    m_pCmdQ->pushCmd(boost::bind(&VideoDemuxerThread::seek, _1, destTime));
//    cerr << "  AsyncDemuxer::seek end" << endl;
}

void AsyncDemuxer::enableStream(int streamIndex)
{
    VideoPacketQueuePtr pPacketQ(new VideoPacketQueue(PACKET_QUEUE_LENGTH));
    m_PacketQs[streamIndex] = pPacketQ;
    m_bSeekDoneMap[streamIndex] = false;
}

}
<commit_msg>video branch: Fixed memory leak when seeking.<commit_after>//
//  libavg - Media Playback Engine.
//  Copyright (C) 2003-2011 Ulrich von Zadow
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  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
//
//  Current versions can be found at www.libavg.de
//

#include "AsyncDemuxer.h"

#include "../base/ScopeTimer.h"
#include "../base/Exception.h"
#include "../base/ObjectCounter.h"

#include <boost/bind.hpp>

#include <iostream>

#define PACKET_QUEUE_LENGTH 50

using namespace std;

typedef boost::mutex::scoped_lock scoped_lock;

namespace avg {

AsyncDemuxer::AsyncDemuxer(AVFormatContext * pFormatContext, vector<int> streamIndexes)
    : m_pCmdQ(new VideoDemuxerThread::CQueue),
      m_bSeekPending(false),
      m_pFormatContext(pFormatContext)
{
    ObjectCounter::get()->incRef(&typeid(*this));
    for (unsigned i = 0; i < streamIndexes.size(); ++i) {
        enableStream(streamIndexes[i]);
    }
    m_pDemuxThread = new boost::thread(VideoDemuxerThread(*m_pCmdQ, m_pFormatContext,
            m_PacketQs));
}

AsyncDemuxer::~AsyncDemuxer()
{
    if (m_pDemuxThread) {
        m_pCmdQ->pushCmd(boost::bind(&VideoDemuxerThread::stop, _1));
        map<int, VideoPacketQueuePtr>::iterator it;
        for (it = m_PacketQs.begin(); it != m_PacketQs.end(); ++it) {
            // If the Queue is full, this breaks the lock in the thread.
            PacketVideoMsgPtr pPacketMsg;
            pPacketMsg = it->second->pop(false);
            if (pPacketMsg) {
                pPacketMsg->freePacket();
            }
        }
        m_pDemuxThread->join();
        delete m_pDemuxThread;
        m_pDemuxThread = 0;
        for (it = m_PacketQs.begin(); it != m_PacketQs.end(); it++) {
            VideoPacketQueuePtr pPacketQ = it->second;
            PacketVideoMsgPtr pPacketMsg;
            pPacketMsg = pPacketQ->pop(false);
            while (pPacketMsg) {
                pPacketMsg->freePacket();
                pPacketMsg = pPacketQ->pop(false);
            }
        }
    }
    ObjectCounter::get()->decRef(&typeid(*this));
}

AVPacket * AsyncDemuxer::getPacket(int streamIndex, bool& bSeekDone)
{
//    cerr << "  AsyncDemuxer::getPacket" << endl;
    PacketVideoMsgPtr pPacketMsg = m_PacketQs[streamIndex]->pop(true);
    bSeekDone = pPacketMsg->isSeekDone();
    if (bSeekDone) {
        AVG_ASSERT(!pPacketMsg->getPacket());
    }
    return pPacketMsg->getPacket();
}

void AsyncDemuxer::seek(float destTime)
{
//    cerr << "  AsyncDemuxer::seek" << endl;
    map<int, VideoPacketQueuePtr>::iterator it;
    for (it = m_PacketQs.begin(); it != m_PacketQs.end(); it++) {
        VideoPacketQueuePtr pPacketQ = it->second;
        PacketVideoMsgPtr pElem;
        do {
            pElem = pPacketQ->pop(false);
            if (pElem) {
                pElem->freePacket();
            }
        } while (pElem);
    }
    m_pCmdQ->pushCmd(boost::bind(&VideoDemuxerThread::seek, _1, destTime));
//    cerr << "  AsyncDemuxer::seek end" << endl;
}

void AsyncDemuxer::enableStream(int streamIndex)
{
    VideoPacketQueuePtr pPacketQ(new VideoPacketQueue(PACKET_QUEUE_LENGTH));
    m_PacketQs[streamIndex] = pPacketQ;
    m_bSeekDoneMap[streamIndex] = false;
}

}
<|endoftext|>


<commit_before>/* --------------------------------------------------------------------------

   libmusicbrainz4 - Client library to access MusicBrainz

   Copyright (C) 2011 Andrew Hawkins

   This file is part of libmusicbrainz4.

   This library is free software; you can redistribute it and/or
   modify it under the terms of v2 of the GNU Lesser General Public
   License as published by the Free Software Foundation.

   libmusicbrainz4 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 General Public License
   along with this library.  If not, see <http://www.gnu.org/licenses/>.

     $Id$

----------------------------------------------------------------------------*/

#include "config.h"
#include "musicbrainz4/defines.h"

#include "musicbrainz4/Entity.h"

#include "musicbrainz4/RelationList.h"
#include "musicbrainz4/RelationListList.h"

class MusicBrainz4::CEntityPrivate
{
	public:
		CEntityPrivate()
		{
		}

		std::map<std::string,std::string> m_ExtAttributes;
		std::map<std::string,std::string> m_ExtElements;
};

MusicBrainz4::CEntity::CEntity()
:	m_d(new CEntityPrivate)
{
}

MusicBrainz4::CEntity::CEntity(const CEntity& Other)
:	m_d(new CEntityPrivate)
{
	*this=Other;
}

MusicBrainz4::CEntity& MusicBrainz4::CEntity::operator =(const CEntity& Other)
{
	if (this!=&Other)
	{
		Cleanup();

		m_d->m_ExtAttributes=Other.m_d->m_ExtAttributes;
		m_d->m_ExtElements=Other.m_d->m_ExtElements;
	}

	return *this;
}

MusicBrainz4::CEntity::~CEntity()
{
	Cleanup();

	delete m_d;
}

void MusicBrainz4::CEntity::Cleanup()
{
}

bool MusicBrainz4::CEntity::Parse(const XMLNode& Node)
{
	bool RetVal=true;

	if (!Node.isEmpty())
	{
		for (int count=0;count<Node.nAttribute();count++)
		{
			std::string Name=Node.getAttributeName(count);
			std::string Value=Node.getAttributeValue(count);

			if ("ext:"==Name.substr(0,4))
			{
				m_d->m_ExtAttributes[Name.substr(4)]=Value;
			}
			else
				RetVal=RetVal && ParseAttribute(Name,Value);
		}

		//std::cout << "Node: " << std::endl << Node.createXMLString(true) << std::endl;

		for (int count=0;count<Node.nChildNode();count++)
		{
			XMLNode ChildNode=Node.getChildNode(count);

			std::string Name=ChildNode.getName();
			std::string Value;
			if (ChildNode.getText())
				Value=ChildNode.getText();

			if ("ext:"==Name.substr(0,4))
			{
				m_d->m_ExtElements[Name.substr(4)]=Value;
			}
			else
				RetVal=RetVal && ParseElement(ChildNode);
		}
	}

	return RetVal;
}

std::map<std::string,std::string> MusicBrainz4::CEntity::ExtAttributes() const
{
	return m_d->m_ExtAttributes;
}

std::map<std::string,std::string> MusicBrainz4::CEntity::ExtElements() const
{
	return m_d->m_ExtElements;
}

bool MusicBrainz4::CEntity::ProcessRelationList(const XMLNode& Node, CRelationListList* & RetVal)
{
	if (0==RetVal)
		RetVal=new CRelationListList;

	CRelationList *RelationList=0;
	ProcessItem(Node,RelationList);
	RetVal->Add(RelationList);
	delete RelationList;

	return true;
}
std::ostream& MusicBrainz4::CEntity::Serialise(std::ostream& os) const
{
	if (!ExtAttributes().empty())
	{
		std::cout << "Ext attrs: " << std::endl;
		std::map<std::string,std::string> ExtAttrs=ExtAttributes();
		std::map<std::string,std::string>::const_iterator ThisExtAttr=ExtAttrs.begin();
		while (ThisExtAttr!=ExtAttrs.end())
		{
			os << (*ThisExtAttr).first << " = " << (*ThisExtAttr).second << std::endl;

			++ThisExtAttr;
		}
	}

	if (!ExtElements().empty())
	{
		std::cout << "Ext elements: " << std::endl;
		std::map<std::string,std::string> ExtElems=ExtElements();
		std::map<std::string,std::string>::const_iterator ThisExtElement=ExtElems.begin();
		while (ThisExtElement!=ExtElems.end())
		{
			os << (*ThisExtElement).first << " = " << (*ThisExtElement).second << std::endl;

			++ThisExtElement;
		}
	}

	return os;
}

std::ostream& operator << (std::ostream& os, const MusicBrainz4::CEntity& Entity)
{
	return Entity.Serialise(os);
}

<commit_msg>Serialise to correct stream<commit_after>/* --------------------------------------------------------------------------

   libmusicbrainz4 - Client library to access MusicBrainz

   Copyright (C) 2011 Andrew Hawkins

   This file is part of libmusicbrainz4.

   This library is free software; you can redistribute it and/or
   modify it under the terms of v2 of the GNU Lesser General Public
   License as published by the Free Software Foundation.

   libmusicbrainz4 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 General Public License
   along with this library.  If not, see <http://www.gnu.org/licenses/>.

     $Id$

----------------------------------------------------------------------------*/

#include "config.h"
#include "musicbrainz4/defines.h"

#include "musicbrainz4/Entity.h"

#include "musicbrainz4/RelationList.h"
#include "musicbrainz4/RelationListList.h"

class MusicBrainz4::CEntityPrivate
{
	public:
		CEntityPrivate()
		{
		}

		std::map<std::string,std::string> m_ExtAttributes;
		std::map<std::string,std::string> m_ExtElements;
};

MusicBrainz4::CEntity::CEntity()
:	m_d(new CEntityPrivate)
{
}

MusicBrainz4::CEntity::CEntity(const CEntity& Other)
:	m_d(new CEntityPrivate)
{
	*this=Other;
}

MusicBrainz4::CEntity& MusicBrainz4::CEntity::operator =(const CEntity& Other)
{
	if (this!=&Other)
	{
		Cleanup();

		m_d->m_ExtAttributes=Other.m_d->m_ExtAttributes;
		m_d->m_ExtElements=Other.m_d->m_ExtElements;
	}

	return *this;
}

MusicBrainz4::CEntity::~CEntity()
{
	Cleanup();

	delete m_d;
}

void MusicBrainz4::CEntity::Cleanup()
{
}

bool MusicBrainz4::CEntity::Parse(const XMLNode& Node)
{
	bool RetVal=true;

	if (!Node.isEmpty())
	{
		for (int count=0;count<Node.nAttribute();count++)
		{
			std::string Name=Node.getAttributeName(count);
			std::string Value=Node.getAttributeValue(count);

			if ("ext:"==Name.substr(0,4))
			{
				m_d->m_ExtAttributes[Name.substr(4)]=Value;
			}
			else
				RetVal=RetVal && ParseAttribute(Name,Value);
		}

		//std::cout << "Node: " << std::endl << Node.createXMLString(true) << std::endl;

		for (int count=0;count<Node.nChildNode();count++)
		{
			XMLNode ChildNode=Node.getChildNode(count);

			std::string Name=ChildNode.getName();
			std::string Value;
			if (ChildNode.getText())
				Value=ChildNode.getText();

			if ("ext:"==Name.substr(0,4))
			{
				m_d->m_ExtElements[Name.substr(4)]=Value;
			}
			else
				RetVal=RetVal && ParseElement(ChildNode);
		}
	}

	return RetVal;
}

std::map<std::string,std::string> MusicBrainz4::CEntity::ExtAttributes() const
{
	return m_d->m_ExtAttributes;
}

std::map<std::string,std::string> MusicBrainz4::CEntity::ExtElements() const
{
	return m_d->m_ExtElements;
}

bool MusicBrainz4::CEntity::ProcessRelationList(const XMLNode& Node, CRelationListList* & RetVal)
{
	if (0==RetVal)
		RetVal=new CRelationListList;

	CRelationList *RelationList=0;
	ProcessItem(Node,RelationList);
	RetVal->Add(RelationList);
	delete RelationList;

	return true;
}
std::ostream& MusicBrainz4::CEntity::Serialise(std::ostream& os) const
{
	if (!ExtAttributes().empty())
	{
		os << "Ext attrs: " << std::endl;
		std::map<std::string,std::string> ExtAttrs=ExtAttributes();
		std::map<std::string,std::string>::const_iterator ThisExtAttr=ExtAttrs.begin();
		while (ThisExtAttr!=ExtAttrs.end())
		{
			os << (*ThisExtAttr).first << " = " << (*ThisExtAttr).second << std::endl;

			++ThisExtAttr;
		}
	}

	if (!ExtElements().empty())
	{
		os << "Ext elements: " << std::endl;
		std::map<std::string,std::string> ExtElems=ExtElements();
		std::map<std::string,std::string>::const_iterator ThisExtElement=ExtElems.begin();
		while (ThisExtElement!=ExtElems.end())
		{
			os << (*ThisExtElement).first << " = " << (*ThisExtElement).second << std::endl;

			++ThisExtElement;
		}
	}

	return os;
}

std::ostream& operator << (std::ostream& os, const MusicBrainz4::CEntity& Entity)
{
	return Entity.Serialise(os);
}

<|endoftext|>


<commit_before>/////////////////////////////////////////////////////////////////////////
// $Id: slowdown_timer.cc,v 1.16 2003/08/26 20:24:36 cbothamy Exp $
/////////////////////////////////////////////////////////////////////////
//
//  Copyright (C) 2002  MandrakeSoft S.A.
//
//    MandrakeSoft S.A.
//    43, rue d'Aboukir
//    75002 Paris - France
//    http://www.linux-mandrake.com/
//    http://www.mandrakesoft.com/
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  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
//

#include "bochs.h"
#include <errno.h>

//These need to stay printfs because they are useless in the log file.
#define BX_SLOWDOWN_PRINTF_FEEDBACK 0

#define SECINUSEC 1000000
#define usectosec(a) ((a)/SECINUSEC)
#define sectousec(a) ((a)*SECINUSEC)
#define nsectousec(a) ((a)/1000)

#define MSECINUSEC 1000
#define usectomsec(a) ((a)/MSECINUSEC)

#if BX_HAVE_USLEEP
#  define Qval 1000
#else
#  define Qval SECINUSEC
#endif

#define MAXMULT 1.5
#define REALTIME_Q SECINUSEC

#define LOG_THIS bx_slowdown_timer.

bx_slowdown_timer_c bx_slowdown_timer;

bx_slowdown_timer_c::bx_slowdown_timer_c() {
  put("STIMER");
  settype(STIMERLOG);

  s.start_time=0;
  s.start_emulated_time=0;
  s.timer_handle=BX_NULL_TIMER_HANDLE;
}

void
bx_slowdown_timer_c::init(void) {

  // Return early if slowdown timer not selected
  if ( (bx_options.clock.Osync->get () != BX_CLOCK_SYNC_SLOWDOWN)
    && (bx_options.clock.Osync->get () != BX_CLOCK_SYNC_BOTH) )
    return;

  BX_INFO(("using 'slowdown' timer synchronization method"));
  s.MAXmultiplier=MAXMULT;
  s.Q=Qval;

  if(s.MAXmultiplier<1)
    s.MAXmultiplier=1;

  s.start_time=sectousec(time(NULL));
  s.start_emulated_time = bx_pc_system.time_usec();
  s.lasttime=0;
  if (s.timer_handle == BX_NULL_TIMER_HANDLE) {
    s.timer_handle=bx_pc_system.register_timer(this, timer_handler, 100 , 1, 1,
	"slowdown_timer");
  }
  bx_pc_system.deactivate_timer(s.timer_handle);
  bx_pc_system.activate_timer(s.timer_handle,(Bit32u)s.Q,0);
}

void
bx_slowdown_timer_c::reset(unsigned type)
{
}

void
bx_slowdown_timer_c::timer_handler(void * this_ptr) {
  bx_slowdown_timer_c * class_ptr = (bx_slowdown_timer_c *) this_ptr;

  class_ptr->handle_timer();
}

void
bx_slowdown_timer_c::handle_timer() {
  Bit64u total_emu_time = (bx_pc_system.time_usec()) - s.start_emulated_time;
  Bit64u wanttime = s.lasttime+s.Q;
  Bit64u totaltime = sectousec(time(NULL)) - s.start_time;
  Bit64u thistime=(wanttime>totaltime)?wanttime:totaltime;

#if BX_SLOWDOWN_PRINTF_FEEDBACK
  printf("Entering slowdown timer handler.\n");
#endif

  /* Decide if we're behind.
   * Set interrupt interval accordingly. */
  if(totaltime > total_emu_time) {
    bx_pc_system.deactivate_timer(s.timer_handle);
    bx_pc_system.activate_timer(s.timer_handle,
				(Bit32u)((Bit64u)
					 (s.MAXmultiplier * (float)s.Q)),
				0);
#if BX_SLOWDOWN_PRINTF_FEEDBACK
    printf("running at MAX speed\n");
#endif
  } else {
    bx_pc_system.deactivate_timer(s.timer_handle);
    bx_pc_system.activate_timer(s.timer_handle,s.Q,0);
#if BX_SLOWDOWN_PRINTF_FEEDBACK
    printf("running at NORMAL speed\n");
#endif
  }

  /* Make sure we took at least one time quantum. */
  /* This is a little strange.  I'll try to explain.
   * We're running bochs one second ahead of real time.
   *  this gives us a very precise division on whether
   *  we're ahead or behind the second line.
   * Basically, here's how it works:
   * *****|******************|***********...
   *      Time               Time+1sec
   *                        <^Bochs doesn't delay.
   *                          ^>Bochs delays.
   *    <^Bochs runs at MAX speed.
   *      ^>Bochs runs at normal
   */
  if(wanttime > (totaltime+REALTIME_Q)) {
#if BX_HAVE_USLEEP
    usleep(s.Q);
#elif BX_HAVE_MSLEEP
    msleep(usectomsec(s.Q));
#elif BX_HAVE_SLEEP
    sleep(usectosec(s.Q));
#else
#error do not know have to sleep
#endif    //delay(wanttime-totaltime);
    /*alternatively: delay(Q);
     * This works okay because we share the delay between
     * two time quantums.
     */
#if BX_SLOWDOWN_PRINTF_FEEDBACK
    printf("DELAYING for a quantum\n");
#endif
  }
  s.lasttime=thistime;

  //Diagnostic info:
#if 0
  if(wanttime > (totaltime+REALTIME_Q)) {
    if(totaltime > total_emu_time) {
      printf("Solving OpenBSD problem.\n");
    } else {
      printf("too fast.\n");
    }
  } else {
    if(totaltime > total_emu_time) {
      printf("too slow.\n");
    } else {
      printf("sometimes invalid state, normally okay.\n");
    }
  }
#endif // Diagnostic info
}

<commit_msg>- add typecast to Bit64s to get around VC++ fatal error<commit_after>/////////////////////////////////////////////////////////////////////////
// $Id: slowdown_timer.cc,v 1.17 2003/10/01 02:06:14 bdenney Exp $
/////////////////////////////////////////////////////////////////////////
//
//  Copyright (C) 2002  MandrakeSoft S.A.
//
//    MandrakeSoft S.A.
//    43, rue d'Aboukir
//    75002 Paris - France
//    http://www.linux-mandrake.com/
//    http://www.mandrakesoft.com/
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2 of the License, or (at your option) any later version.
//
//  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
//

#include "bochs.h"
#include <errno.h>

//These need to stay printfs because they are useless in the log file.
#define BX_SLOWDOWN_PRINTF_FEEDBACK 0

#define SECINUSEC 1000000
#define usectosec(a) ((a)/SECINUSEC)
#define sectousec(a) ((a)*SECINUSEC)
#define nsectousec(a) ((a)/1000)

#define MSECINUSEC 1000
#define usectomsec(a) ((a)/MSECINUSEC)

#if BX_HAVE_USLEEP
#  define Qval 1000
#else
#  define Qval SECINUSEC
#endif

#define MAXMULT 1.5
#define REALTIME_Q SECINUSEC

#define LOG_THIS bx_slowdown_timer.

bx_slowdown_timer_c bx_slowdown_timer;

bx_slowdown_timer_c::bx_slowdown_timer_c() {
  put("STIMER");
  settype(STIMERLOG);

  s.start_time=0;
  s.start_emulated_time=0;
  s.timer_handle=BX_NULL_TIMER_HANDLE;
}

void
bx_slowdown_timer_c::init(void) {

  // Return early if slowdown timer not selected
  if ( (bx_options.clock.Osync->get () != BX_CLOCK_SYNC_SLOWDOWN)
    && (bx_options.clock.Osync->get () != BX_CLOCK_SYNC_BOTH) )
    return;

  BX_INFO(("using 'slowdown' timer synchronization method"));
  s.MAXmultiplier=MAXMULT;
  s.Q=Qval;

  if(s.MAXmultiplier<1)
    s.MAXmultiplier=1;

  s.start_time=sectousec(time(NULL));
  s.start_emulated_time = bx_pc_system.time_usec();
  s.lasttime=0;
  if (s.timer_handle == BX_NULL_TIMER_HANDLE) {
    s.timer_handle=bx_pc_system.register_timer(this, timer_handler, 100 , 1, 1,
	"slowdown_timer");
  }
  bx_pc_system.deactivate_timer(s.timer_handle);
  bx_pc_system.activate_timer(s.timer_handle,(Bit32u)s.Q,0);
}

void
bx_slowdown_timer_c::reset(unsigned type)
{
}

void
bx_slowdown_timer_c::timer_handler(void * this_ptr) {
  bx_slowdown_timer_c * class_ptr = (bx_slowdown_timer_c *) this_ptr;

  class_ptr->handle_timer();
}

void
bx_slowdown_timer_c::handle_timer() {
  Bit64u total_emu_time = (bx_pc_system.time_usec()) - s.start_emulated_time;
  Bit64u wanttime = s.lasttime+s.Q;
  Bit64u totaltime = sectousec(time(NULL)) - s.start_time;
  Bit64u thistime=(wanttime>totaltime)?wanttime:totaltime;

#if BX_SLOWDOWN_PRINTF_FEEDBACK
  printf("Entering slowdown timer handler.\n");
#endif

  /* Decide if we're behind.
   * Set interrupt interval accordingly. */
  if(totaltime > total_emu_time) {
    bx_pc_system.deactivate_timer(s.timer_handle);
    bx_pc_system.activate_timer(s.timer_handle,
				(Bit32u)(s.MAXmultiplier * (float)((Bit64s)s.Q)),
				0);
#if BX_SLOWDOWN_PRINTF_FEEDBACK
    printf("running at MAX speed\n");
#endif
  } else {
    bx_pc_system.deactivate_timer(s.timer_handle);
    bx_pc_system.activate_timer(s.timer_handle,s.Q,0);
#if BX_SLOWDOWN_PRINTF_FEEDBACK
    printf("running at NORMAL speed\n");
#endif
  }

  /* Make sure we took at least one time quantum. */
  /* This is a little strange.  I'll try to explain.
   * We're running bochs one second ahead of real time.
   *  this gives us a very precise division on whether
   *  we're ahead or behind the second line.
   * Basically, here's how it works:
   * *****|******************|***********...
   *      Time               Time+1sec
   *                        <^Bochs doesn't delay.
   *                          ^>Bochs delays.
   *    <^Bochs runs at MAX speed.
   *      ^>Bochs runs at normal
   */
  if(wanttime > (totaltime+REALTIME_Q)) {
#if BX_HAVE_USLEEP
    usleep(s.Q);
#elif BX_HAVE_MSLEEP
    msleep(usectomsec(s.Q));
#elif BX_HAVE_SLEEP
    sleep(usectosec(s.Q));
#else
#error do not know have to sleep
#endif    //delay(wanttime-totaltime);
    /*alternatively: delay(Q);
     * This works okay because we share the delay between
     * two time quantums.
     */
#if BX_SLOWDOWN_PRINTF_FEEDBACK
    printf("DELAYING for a quantum\n");
#endif
  }
  s.lasttime=thistime;

  //Diagnostic info:
#if 0
  if(wanttime > (totaltime+REALTIME_Q)) {
    if(totaltime > total_emu_time) {
      printf("Solving OpenBSD problem.\n");
    } else {
      printf("too fast.\n");
    }
  } else {
    if(totaltime > total_emu_time) {
      printf("too slow.\n");
    } else {
      printf("sometimes invalid state, normally okay.\n");
    }
  }
#endif // Diagnostic info
}

<|endoftext|>


<commit_before>/*
 * Header-only variant of pugixml.
 * This file is provided to the public domain.
 * Written by Arseny Kapoulkine (arseny.kapoulkine@gmail.com)
 */

#ifndef HEADER_PUGIXML_HEADER_ONLY_HPP
#define HEADER_PUGIXML_HEADER_ONLY_HPP

/*
 * This file provides a header-only variant of pugixml.
 * This is generally not recommended because of resulting code bloat/increased link time/conflicts with local symbols,
 * so use it with caution.
 */

#include "pugixml.cpp"
#include "pugixpath.cpp"

#endif
<commit_msg>contrib: Removed header_only.hpp (can't link without FORCE:MULTIPLE, users can include cpp files themselves)<commit_after><|endoftext|>


<commit_before>/*
    Copyright (c) 2006 Volker Krause <vkrause@kde.org>

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

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

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to the
    Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
    02110-1301, USA.
*/

#include "resourcemanager.h"
#include "tracer.h"
#include "storage/datastore.h"
#include "resourcemanageradaptor.h"
#include "libs/capabilities_p.h"

#include <QtDBus/QDBusConnection>

using namespace Akonadi;

ResourceManager* ResourceManager::mSelf = 0;

Akonadi::ResourceManager::ResourceManager(QObject * parent) :
  QObject( parent )
{
  new ResourceManagerAdaptor( this );
  QDBusConnection::sessionBus().registerObject( QLatin1String("/ResourceManager"), this );
}

void Akonadi::ResourceManager::addResourceInstance(const QString & name, const QStringList &capabilities)
{
  Resource resource = Resource::retrieveByName( name );
  if ( resource.isValid() ) {
    Tracer::self()->error( "ResourceManager", QString::fromLatin1("Resource '%1' already exists.").arg(name) );
    return; // resource already exists
  }

  // create the resource
  resource.setName( name );
  resource.setIsVirtual( capabilities.contains( QLatin1String( AKONADI_AGENT_CAPABILITY_VIRTUAL ) ) );
  if ( !resource.insert() )
    Tracer::self()->error( "ResourceManager", QString::fromLatin1("Could not create resource '%1'.").arg(name) );
}

void Akonadi::ResourceManager::removeResourceInstance(const QString & name)
{
  DataStore *db = DataStore::self();

  // remove items and collections
  Resource resource = Resource::retrieveByName( name );
  if ( resource.isValid() ) {
    const QVector<Collection> collections = resource.collections();
    Q_FOREACH( /*sic!*/ Collection collection, collections )
      db->cleanupCollection( collection );

    // remove resource
    resource.remove();
  }
}

ResourceManager * Akonadi::ResourceManager::self()
{
  if ( !mSelf )
    mSelf = new ResourceManager();
  return mSelf;
}

#include "resourcemanager.moc"
<commit_msg>Fix possible deadlock when creating a bunch of resources at the same time when using the Sqlite backend.<commit_after>/*
    Copyright (c) 2006 Volker Krause <vkrause@kde.org>

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

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

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to the
    Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
    02110-1301, USA.
*/

#include "resourcemanager.h"
#include "tracer.h"
#include "storage/datastore.h"
#include "resourcemanageradaptor.h"
#include "libs/capabilities_p.h"

#include <QtDBus/QDBusConnection>
#include "storage/transaction.h"

using namespace Akonadi;

ResourceManager* ResourceManager::mSelf = 0;

Akonadi::ResourceManager::ResourceManager(QObject * parent) :
  QObject( parent )
{
  new ResourceManagerAdaptor( this );
  QDBusConnection::sessionBus().registerObject( QLatin1String("/ResourceManager"), this );
}

void Akonadi::ResourceManager::addResourceInstance(const QString & name, const QStringList &capabilities)
{
  Transaction transaction( DataStore::self() );
  Resource resource = Resource::retrieveByName( name );
  if ( resource.isValid() ) {
    Tracer::self()->error( "ResourceManager", QString::fromLatin1("Resource '%1' already exists.").arg(name) );
    return; // resource already exists
  }

  // create the resource
  resource.setName( name );
  resource.setIsVirtual( capabilities.contains( QLatin1String( AKONADI_AGENT_CAPABILITY_VIRTUAL ) ) );
  if ( !resource.insert() )
    Tracer::self()->error( "ResourceManager", QString::fromLatin1("Could not create resource '%1'.").arg(name) );
  transaction.commit();
}

void Akonadi::ResourceManager::removeResourceInstance(const QString & name)
{
  DataStore *db = DataStore::self();

  // remove items and collections
  Resource resource = Resource::retrieveByName( name );
  if ( resource.isValid() ) {
    const QVector<Collection> collections = resource.collections();
    Q_FOREACH( /*sic!*/ Collection collection, collections )
      db->cleanupCollection( collection );

    // remove resource
    resource.remove();
  }
}

ResourceManager * Akonadi::ResourceManager::self()
{
  if ( !mSelf )
    mSelf = new ResourceManager();
  return mSelf;
}

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


<commit_before><commit_msg>CLEAN: using prefix operators<commit_after><|endoftext|>


<commit_before>/*************** <auto-copyright.pl BEGIN do not edit this line> **************
 *
 * VR Juggler is (C) Copyright 1998, 1999, 2000 by Iowa State University
 *
 * Original Authors:
 *   Allen Bierbaum, Christopher Just,
 *   Patrick Hartling, Kevin Meinert,
 *   Carolina Cruz-Neira, Albert Baker
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library 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.
 *
 * -----------------------------------------------------------------
 * File:          $RCSfile$
 * Date modified: $Date$
 * Version:       $Revision$
 * -----------------------------------------------------------------
 *
 *************** <auto-copyright.pl END do not edit this line> ***************/

#include <vrj/vrjConfig.h>

#include <vrj/Display/Display.h>
#include <vrj/Display/Viewport.h>
#include <vrj/Display/SimViewport.h>
#include <vrj/Display/SurfaceViewport.h>

namespace vrj
{

void Display::updateProjections()
{
   for(unsigned i=0;i<mViewports.size();i++)
   {
      mViewports[i]->updateProjections();
   }
}

void Display::config(jccl::ConfigChunkPtr chunk)
{
   vprASSERT(chunk.get() != NULL);

   configDisplayWindow(chunk);
   configViewports(chunk);
}

void Display::configDisplayWindow(jccl::ConfigChunkPtr chunk)
{
   vprASSERT(chunk.get() != NULL);

   // -- Get config info from chunk -- //
    int originX = chunk->getProperty("origin", 0);
    int originY = chunk->getProperty("origin", 1);
    int sizeX   = chunk->getProperty("size", 0);
    int sizeY   = chunk->getProperty("size", 1);
    std::string name  = chunk->getProperty("name");
    mBorder     = chunk->getProperty("border");
    int pipe    = chunk->getProperty("pipe");
    mActive  = chunk->getProperty("active");

   // -- Check for error in configuration -- //
   // NOTE: If there are errors, set them to some default value
   if(sizeX <= 0)
   {
      vprDEBUG(vrjDBG_DISP_MGR,2) << "WARNING: window sizeX set to: " << sizeX
                                << ".  Setting to 10." << std::endl
                                << vprDEBUG_FLUSH;
      sizeX = 10;
   }

   if(sizeY <= 0)
   {
      vprDEBUG(vrjDBG_DISP_MGR,2) << "WARNING: window sizeY set to: " << sizeY
                                << ".  Setting to 10." << std::endl
                                << vprDEBUG_FLUSH;
      sizeY = 10;
   }

   if(pipe < 0)
   {
      vprDEBUG(vrjDBG_DISP_MGR,2) << "WARNING: pipe was negative, pipe set to: " << pipe << ".  Setting to 0.\n" << vprDEBUG_FLUSH;
      pipe = 0;
   }

      // -- Set local window attributes --- //
    setOriginAndSize(originX, originY, sizeX, sizeY);

    setName(name);
    setPipe(pipe);

    mDisplayChunk = chunk;        // Save the chunk for later use
}

void Display::configViewports(jccl::ConfigChunkPtr chunk)
{
   vprASSERT(chunk.get() != NULL);

   unsigned num_sim_vps = chunk->getNum("sim_viewports");
   unsigned num_surface_vps = chunk->getNum("surface_viewports");

   jccl::ConfigChunkPtr vp_chunk(0);
   SimViewport* sim_vp = NULL;
   SurfaceViewport* surf_vp = NULL;

   unsigned i(0);

   // Create sim viewports
   for(i=0;i<num_sim_vps;i++)
   {
      vp_chunk = chunk->getProperty("sim_viewports",i);
      sim_vp = new SimViewport;
      sim_vp->config(vp_chunk);
      mViewports.push_back(sim_vp);
   }

   // Create sim viewports
   for(i=0;i<num_surface_vps;i++)
   {
      vp_chunk = chunk->getProperty("surface_viewports",i);
      surf_vp = new SurfaceViewport;
      surf_vp->config(vp_chunk);
      mViewports.push_back(surf_vp);
   }
}

VJ_IMPLEMENT(std::ostream&) operator<<(std::ostream& out, Display& disp)
{
   out << std::setw(15) << disp.mName.c_str() << std::endl
        << "  org:" << disp._xo << ", " << disp._yo
        << "  sz:" << disp._xs << ", " << disp._ys
        << "  p:" << disp.mPipe
        << "  act:" << (disp.mActive ? "Y" : "N") << std::endl;
   for(unsigned i=0;i<disp.mViewports.size();i++)
   {
      out << "vp: " << i << " " << *(disp.mViewports[i]) << std::endl;
   }

   return out;
}
};
<commit_msg>Bug:	Stereo was not working correctly<commit_after>/*************** <auto-copyright.pl BEGIN do not edit this line> **************
 *
 * VR Juggler is (C) Copyright 1998, 1999, 2000 by Iowa State University
 *
 * Original Authors:
 *   Allen Bierbaum, Christopher Just,
 *   Patrick Hartling, Kevin Meinert,
 *   Carolina Cruz-Neira, Albert Baker
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library 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.
 *
 * -----------------------------------------------------------------
 * File:          $RCSfile$
 * Date modified: $Date$
 * Version:       $Revision$
 * -----------------------------------------------------------------
 *
 *************** <auto-copyright.pl END do not edit this line> ***************/

#include <vrj/vrjConfig.h>

#include <vrj/Display/Display.h>
#include <vrj/Display/Viewport.h>
#include <vrj/Display/SimViewport.h>
#include <vrj/Display/SurfaceViewport.h>

namespace vrj
{

void Display::updateProjections()
{
   for(unsigned i=0;i<mViewports.size();i++)
   {
      mViewports[i]->updateProjections();
   }
}

void Display::config(jccl::ConfigChunkPtr chunk)
{
   vprASSERT(chunk.get() != NULL);

   configDisplayWindow(chunk);
   configViewports(chunk);
}

void Display::configDisplayWindow(jccl::ConfigChunkPtr chunk)
{
   vprASSERT(chunk.get() != NULL);

   // -- Get config info from chunk -- //
    int originX = chunk->getProperty("origin", 0);
    int originY = chunk->getProperty("origin", 1);
    int sizeX   = chunk->getProperty("size", 0);
    int sizeY   = chunk->getProperty("size", 1);
    std::string name  = chunk->getProperty("name");
    mBorder     = chunk->getProperty("border");
    int pipe    = chunk->getProperty("pipe");
    mActive  = chunk->getProperty("active");
    mStereo  = chunk->getProperty("stereo");

   // -- Check for error in configuration -- //
   // NOTE: If there are errors, set them to some default value
   if(sizeX <= 0)
   {
      vprDEBUG(vrjDBG_DISP_MGR,2) << "WARNING: window sizeX set to: " << sizeX
                                << ".  Setting to 10." << std::endl
                                << vprDEBUG_FLUSH;
      sizeX = 10;
   }

   if(sizeY <= 0)
   {
      vprDEBUG(vrjDBG_DISP_MGR,2) << "WARNING: window sizeY set to: " << sizeY
                                << ".  Setting to 10." << std::endl
                                << vprDEBUG_FLUSH;
      sizeY = 10;
   }

   if(pipe < 0)
   {
      vprDEBUG(vrjDBG_DISP_MGR,2) << "WARNING: pipe was negative, pipe set to: " << pipe << ".  Setting to 0.\n" << vprDEBUG_FLUSH;
      pipe = 0;
   }

      // -- Set local window attributes --- //
    setOriginAndSize(originX, originY, sizeX, sizeY);

    setName(name);
    setPipe(pipe);

    mDisplayChunk = chunk;        // Save the chunk for later use
}

void Display::configViewports(jccl::ConfigChunkPtr chunk)
{
   vprASSERT(chunk.get() != NULL);

   unsigned num_sim_vps = chunk->getNum("sim_viewports");
   unsigned num_surface_vps = chunk->getNum("surface_viewports");

   jccl::ConfigChunkPtr vp_chunk(0);
   SimViewport* sim_vp = NULL;
   SurfaceViewport* surf_vp = NULL;

   unsigned i(0);

   // Create sim viewports
   for(i=0;i<num_sim_vps;i++)
   {
      vp_chunk = chunk->getProperty("sim_viewports",i);
      sim_vp = new SimViewport;
      sim_vp->config(vp_chunk);
      mViewports.push_back(sim_vp);
   }

   // Create sim viewports
   for(i=0;i<num_surface_vps;i++)
   {
      vp_chunk = chunk->getProperty("surface_viewports",i);
      surf_vp = new SurfaceViewport;
      surf_vp->config(vp_chunk);
      mViewports.push_back(surf_vp);
   }
}

VJ_IMPLEMENT(std::ostream&) operator<<(std::ostream& out, Display& disp)
{
   out << std::setw(15) << disp.mName.c_str() << std::endl
        << "  org:" << disp._xo << ", " << disp._yo
        << "  sz:" << disp._xs << ", " << disp._ys
        << "  p:" << disp.mPipe
        << "  act:" << (disp.mActive ? "Y" : "N") << std::endl;
   for(unsigned i=0;i<disp.mViewports.size();i++)
   {
      out << "vp: " << i << " " << *(disp.mViewports[i]) << std::endl;
   }

   return out;
}
};
<|endoftext|>


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

#include "chrome/browser/chromeos/extensions/device_local_account_management_policy_provider.h"

#include <string>

#include "base/logging.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/grit/generated_resources.h"
#include "extensions/common/extension.h"
#include "extensions/common/manifest.h"
#include "ui/base/l10n/l10n_util.h"

namespace chromeos {

namespace {

// Apps/extensions explicitly whitelisted for use in public sessions.
const char* const kPublicSessionWhitelist[] = {
    // Public sessions in general:
    "cbkkbcmdlboombapidmoeolnmdacpkch",  // Chrome RDP
    "djflhoibgkdhkhhcedjiklpkjnoahfmg",  // User Agent Switcher
    "iabmpiboiopbgfabjmgeedhcmjenhbla",  // VNC Viewer
    "haiffjcadagjlijoggckpgfnoeiflnem",  // Citrix Receiver
    "mfaihdlpglflfgpfjcifdjdjcckigekc",  // ARC Runtime

    // Libraries:
    "aclofikceldphonlfmghmimkodjdmhck",  // Ancoris login component
    "eilbnahdgoddoedakcmfkcgfoegeloil",  // Ancoris proxy component
    "ceehlgckkmkaoggdnjhibffkphfnphmg",  // Libdata login

    // Retail mode:
    "ehcabepphndocfmgbdkbjibfodelmpbb",  // Angry Birds demo
    "kgimkbnclbekdkabkpjhpakhhalfanda",  // Bejeweled demo
    "joodangkbfjnajiiifokapkpmhfnpleo",  // Calculator
    "fpgfohogebplgnamlafljlcidjedbdeb",  // Calendar demo
    "hfhhnacclhffhdffklopdkcgdhifgngh",  // Camera
    "cdjikkcakjcdjemakobkmijmikhkegcj",  // Chrome Remote Desktop demo
    "jkoildpomkimndcphjpffmephmcmkfhn",  // Chromebook Demo App
    "ielkookhdphmgbipcfmafkaiagademfp",  // Custom bookmarks
    "kogjlbfgggambihdjcpijgcbmenblimd",  // Custom bookmarks
    "ogbkmlkceflgpilgbmbcfbifckpkfacf",  // Custom bookmarks
    "pbbbjjecobhljkkcenlakfnkmkfkfamd",  // Custom bookmarks
    "jkbfjmnjcdmhlfpephomoiipbhcoiffb",  // Custom bookmarks
    "dgmblbpgafgcgpkoiilhjifindhinmai",  // Custom bookmarks
    "iggnealjakkgfofealilhkkclnbnfnmo",  // Custom bookmarks
    "lplkobnahgbopmpkdapaihnnojkphahc",  // Custom bookmarks
    "lejnflfhjpcannpaghnahbedlabpmhoh",  // Custom bookmarks
    "ebkhfdfghngbimnpgelagnfacdafhaba",  // Deezer demo
    "npnjdccdffhdndcbeappiamcehbhjibf",  // Docs.app demo
    "iddohohhpmajlkbejjjcfednjnhlnenk",  // Evernote demo
    "bjdhhokmhgelphffoafoejjmlfblpdha",  // Gmail demo
    "mdhnphfgagkpdhndljccoackjjhghlif",  // Google Drive demo
    "dondgdlndnpianbklfnehgdhkickdjck",  // Google Keep demo
    "fgjnkhlabjcaajddbaenilcmpcidahll",  // Google+ demo
    "ifpkhncdnjfipfjlhfidljjffdgklanh",  // Google+ Photos demo
    "cgmlfbhkckbedohgdepgbkflommbfkep",  // Hangouts.app demo
    "edhhaiphkklkcfcbnlbpbiepchnkgkpn",  // Helper.extension demo
    "diehajhcjifpahdplfdkhiboknagmfii",  // Kindle demo
    "nhpmmldpbfjofkipjaieeomhnmcgihfm",  // Menu.app demo
    "onbhgdmifjebcabplolilidlpgeknifi",  // Music.app demo
    "kkkbcoabfhgekpnddfkaphobhinociem",  // Netflix demo
    "adlphlfdhhjenpgimjochcpelbijkich",  // New York Times demo
    "cgefhjmlaifaamhhoojmpcnihlbddeki",  // Pandora demo
    "kpjjigggmcjinapdeipapdcnmnjealll",  // Pixlr demo
    "aleodiobpjillgfjdkblghiiaegggmcm",  // Quickoffice demo
    "nifkmgcdokhkjghdlgflonppnefddien",  // Sheets demo
    "hdmobeajeoanbanmdlabnbnlopepchip",  // Slides demo
    "dgohlccohkojjgkkfholmobjjoledflp",  // Spotify demo
    "dhmdaeekeihmajjnmichlhiffffdbpde",  // Store.app demo
    "jeabmjjifhfcejonjjhccaeigpnnjaak",  // TweetDeck demo
    "pbdihpaifchmclcmkfdgffnnpfbobefh",  // YouTube demo

    // Testing extensions:
    "ongnjlefhnoajpbodoldndkbkdgfomlp",  // Show Managed Storage
};

}  // namespace

DeviceLocalAccountManagementPolicyProvider::
    DeviceLocalAccountManagementPolicyProvider(
        policy::DeviceLocalAccount::Type account_type)
    : account_type_(account_type) {
}

DeviceLocalAccountManagementPolicyProvider::
    ~DeviceLocalAccountManagementPolicyProvider() {
}

std::string DeviceLocalAccountManagementPolicyProvider::
    GetDebugPolicyProviderName() const {
#if defined(NDEBUG)
  NOTREACHED();
  return std::string();
#else
  return "whitelist for device-local accounts";
#endif
}

bool DeviceLocalAccountManagementPolicyProvider::UserMayLoad(
    const extensions::Extension* extension,
    base::string16* error) const {
  if (account_type_ == policy::DeviceLocalAccount::TYPE_PUBLIC_SESSION) {
    // Allow extension if it is an externally hosted component of Chrome.
    if (extension->location() ==
        extensions::Manifest::EXTERNAL_COMPONENT) {
      return true;
    }

    // Allow extension if its type is whitelisted for use in public sessions.
    if (extension->GetType() == extensions::Manifest::TYPE_HOSTED_APP)
      return true;

    // Allow extension if its specific ID is whitelisted for use in public
    // sessions.
    for (size_t i = 0; i < arraysize(kPublicSessionWhitelist); ++i) {
      if (extension->id() == kPublicSessionWhitelist[i])
        return true;
    }
  } else if (account_type_ == policy::DeviceLocalAccount::TYPE_KIOSK_APP) {
    // For single-app kiosk sessions, allow only platform apps.
    if (extension->GetType() == extensions::Manifest::TYPE_PLATFORM_APP)
      return true;
  }

  // Disallow all other extensions.
  if (error) {
    *error = l10n_util::GetStringFUTF16(
          IDS_EXTENSION_CANT_INSTALL_IN_DEVICE_LOCAL_ACCOUNT,
          base::UTF8ToUTF16(extension->name()),
          base::UTF8ToUTF16(extension->id()));
  }
  return false;
}

}  // namespace chromeos
<commit_msg>Add new demo applications to the public session white list.<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/extensions/device_local_account_management_policy_provider.h"

#include <string>

#include "base/logging.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/grit/generated_resources.h"
#include "extensions/common/extension.h"
#include "extensions/common/manifest.h"
#include "ui/base/l10n/l10n_util.h"

namespace chromeos {

namespace {

// Apps/extensions explicitly whitelisted for use in public sessions.
const char* const kPublicSessionWhitelist[] = {
    // Public sessions in general:
    "cbkkbcmdlboombapidmoeolnmdacpkch",  // Chrome RDP
    "djflhoibgkdhkhhcedjiklpkjnoahfmg",  // User Agent Switcher
    "iabmpiboiopbgfabjmgeedhcmjenhbla",  // VNC Viewer
    "haiffjcadagjlijoggckpgfnoeiflnem",  // Citrix Receiver
    "mfaihdlpglflfgpfjcifdjdjcckigekc",  // ARC Runtime

    // Libraries:
    "aclofikceldphonlfmghmimkodjdmhck",  // Ancoris login component
    "eilbnahdgoddoedakcmfkcgfoegeloil",  // Ancoris proxy component
    "ceehlgckkmkaoggdnjhibffkphfnphmg",  // Libdata login

    // Retail mode:
    "bjfeaefhaooblkndnoabbkkkenknkemb",  // 500 px demo
    "ehcabepphndocfmgbdkbjibfodelmpbb",  // Angry Birds demo
    "kgimkbnclbekdkabkpjhpakhhalfanda",  // Bejeweled demo
    "joodangkbfjnajiiifokapkpmhfnpleo",  // Calculator
    "fpgfohogebplgnamlafljlcidjedbdeb",  // Calendar demo
    "hfhhnacclhffhdffklopdkcgdhifgngh",  // Camera
    "cdjikkcakjcdjemakobkmijmikhkegcj",  // Chrome Remote Desktop demo
    "jkoildpomkimndcphjpffmephmcmkfhn",  // Chromebook Demo App
    "lbhdhapagjhalobandnbdnmblnmocojh",  // Crackle demo
    "ielkookhdphmgbipcfmafkaiagademfp",  // Custom bookmarks
    "kogjlbfgggambihdjcpijgcbmenblimd",  // Custom bookmarks
    "ogbkmlkceflgpilgbmbcfbifckpkfacf",  // Custom bookmarks
    "pbbbjjecobhljkkcenlakfnkmkfkfamd",  // Custom bookmarks
    "jkbfjmnjcdmhlfpephomoiipbhcoiffb",  // Custom bookmarks
    "dgmblbpgafgcgpkoiilhjifindhinmai",  // Custom bookmarks
    "iggnealjakkgfofealilhkkclnbnfnmo",  // Custom bookmarks
    "lplkobnahgbopmpkdapaihnnojkphahc",  // Custom bookmarks
    "lejnflfhjpcannpaghnahbedlabpmhoh",  // Custom bookmarks
    "dhjmfhojkfjmfbnbnpichdmcdghdpccg",  // Cut the Rope demo
    "ebkhfdfghngbimnpgelagnfacdafhaba",  // Deezer demo
    "npnjdccdffhdndcbeappiamcehbhjibf",  // Docs.app demo
    "ekgadegabdkcbkodfbgidncffijbghhl",  // Duolingo demo
    "iddohohhpmajlkbejjjcfednjnhlnenk",  // Evernote demo
    "bjdhhokmhgelphffoafoejjmlfblpdha",  // Gmail demo
    "mdhnphfgagkpdhndljccoackjjhghlif",  // Google Drive demo
    "dondgdlndnpianbklfnehgdhkickdjck",  // Google Keep demo
    "amfoiggnkefambnaaphodjdmdooiinna",  // Google Play Movie and TV demo
    "fgjnkhlabjcaajddbaenilcmpcidahll",  // Google+ demo
    "ifpkhncdnjfipfjlhfidljjffdgklanh",  // Google+ Photos demo
    "cgmlfbhkckbedohgdepgbkflommbfkep",  // Hangouts.app demo
    "edhhaiphkklkcfcbnlbpbiepchnkgkpn",  // Helper.extension demo
    "jckncghadoodfbbbmbpldacojkooophh",  // Journal demo
    "diehajhcjifpahdplfdkhiboknagmfii",  // Kindle demo
    "idneggepppginmaklfbaniklagjghpio",  // Kingsroad demo
    "nhpmmldpbfjofkipjaieeomhnmcgihfm",  // Menu.app demo
    "kcjbmmhccecjokfmckhddpmghepcnidb",  // Mint demo
    "onbhgdmifjebcabplolilidlpgeknifi",  // Music.app demo
    "kkkbcoabfhgekpnddfkaphobhinociem",  // Netflix demo
    "adlphlfdhhjenpgimjochcpelbijkich",  // New York Times demo
    "cgefhjmlaifaamhhoojmpcnihlbddeki",  // Pandora demo
    "kpjjigggmcjinapdeipapdcnmnjealll",  // Pixlr demo
    "ifnadhpngkodeccijnalokiabanejfgm",  // Pixsta demo
    "klcojgagjmpgmffcildkgbfmfffncpcd",  // Plex demo
    "nnikmgjhdlphciaonjmoppfckbpoinnb",  // Pocket demo
    "khldngaiohpnnoikfmnmfnebecgeobep",  // Polarr Photo demo
    "aleodiobpjillgfjdkblghiiaegggmcm",  // Quickoffice demo
    "nifkmgcdokhkjghdlgflonppnefddien",  // Sheets demo
    "hdmobeajeoanbanmdlabnbnlopepchip",  // Slides demo
    "dgohlccohkojjgkkfholmobjjoledflp",  // Spotify demo
    "dhmdaeekeihmajjnmichlhiffffdbpde",  // Store.app demo
    "onklhlmbpfnmgmelakhgehkfdmkpmekd",  // Todoist demo
    "jeabmjjifhfcejonjjhccaeigpnnjaak",  // TweetDeck demo
    "pdckcbpciaaicoomipamcabpdadhofgh",  // Weatherbug demo
    "biliocemfcghhioihldfdmkkhnofcgmb",  // Webcam Toy demo
    "bhfoghflalnnjfcfkaelngenjgjjhapk",  // Wevideo demo
    "pjckdjlmdcofkkkocnmhcbehkiapalho",  // Wunderlist demo
    "pbdihpaifchmclcmkfdgffnnpfbobefh",  // YouTube demo

    // Testing extensions:
    "ongnjlefhnoajpbodoldndkbkdgfomlp",  // Show Managed Storage
};

}  // namespace

DeviceLocalAccountManagementPolicyProvider::
    DeviceLocalAccountManagementPolicyProvider(
        policy::DeviceLocalAccount::Type account_type)
    : account_type_(account_type) {
}

DeviceLocalAccountManagementPolicyProvider::
    ~DeviceLocalAccountManagementPolicyProvider() {
}

std::string DeviceLocalAccountManagementPolicyProvider::
    GetDebugPolicyProviderName() const {
#if defined(NDEBUG)
  NOTREACHED();
  return std::string();
#else
  return "whitelist for device-local accounts";
#endif
}

bool DeviceLocalAccountManagementPolicyProvider::UserMayLoad(
    const extensions::Extension* extension,
    base::string16* error) const {
  if (account_type_ == policy::DeviceLocalAccount::TYPE_PUBLIC_SESSION) {
    // Allow extension if it is an externally hosted component of Chrome.
    if (extension->location() ==
        extensions::Manifest::EXTERNAL_COMPONENT) {
      return true;
    }

    // Allow extension if its type is whitelisted for use in public sessions.
    if (extension->GetType() == extensions::Manifest::TYPE_HOSTED_APP)
      return true;

    // Allow extension if its specific ID is whitelisted for use in public
    // sessions.
    for (size_t i = 0; i < arraysize(kPublicSessionWhitelist); ++i) {
      if (extension->id() == kPublicSessionWhitelist[i])
        return true;
    }
  } else if (account_type_ == policy::DeviceLocalAccount::TYPE_KIOSK_APP) {
    // For single-app kiosk sessions, allow only platform apps.
    if (extension->GetType() == extensions::Manifest::TYPE_PLATFORM_APP)
      return true;
  }

  // Disallow all other extensions.
  if (error) {
    *error = l10n_util::GetStringFUTF16(
          IDS_EXTENSION_CANT_INSTALL_IN_DEVICE_LOCAL_ACCOUNT,
          base::UTF8ToUTF16(extension->name()),
          base::UTF8ToUTF16(extension->id()));
  }
  return false;
}

}  // namespace chromeos
<|endoftext|>


<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include "Nodes.h"
#include "StringPool.h"

#include <cassert>

using std::string;

void Declaration::checkVariables(Variables& variables) throw (CompilerException){
	if(variables.exists(m_variable)){
		throw CompilerException("Variable has already been declared");
	}

	Variable* var = variables.create(m_variable, m_type);

	m_index = var->index();

	Value* value = dynamic_cast<Value*>(*begin());

	value->checkVariables(variables);

	if(value->type() != m_type){
		throw CompilerException("Incompatible type");
	}
}

void Assignment::checkVariables(Variables& variables) throw (CompilerException){
	if(!variables.exists(m_variable)){
		throw CompilerException("Variable has not  been declared");
	}

	Variable* var = variables.find(m_variable);

	m_index = var->index();

	Value* value = dynamic_cast<Value*>(*begin());

	value->checkVariables(variables);

	if(value->type() != var->type()){
		throw CompilerException("Incompatible type");
	}
}

void VariableValue::checkVariables(Variables& variables) throw (CompilerException){
	if(!variables.exists(m_variable)){
		throw CompilerException("Variable has not been declared");
	}

	Variable* variable = variables.find(m_variable);

	m_type = variable->type();
	m_index = variable->index();
}

void Litteral::checkStrings(StringPool& pool){
	m_index = pool.index(m_litteral);
}

void Declaration::write(ByteCodeFileWriter& writer){
	(*begin())->write(writer);

	switch(m_type){
		case INT:
			writer.writeOneOperandCall(ISTORE, m_index);

			break;
		case STRING:
			writer.writeOneOperandCall(SSTORE, m_index);

			break;
	}
}

void Assignment::write(ByteCodeFileWriter& writer){
	(*begin())->write(writer);

	Value* value = dynamic_cast<Value*>(*begin());

	switch(value->type()){
		case INT:
			writer.writeOneOperandCall(ISTORE, m_index);

			break;
		case STRING:
			writer.writeOneOperandCall(SSTORE, m_index);

			break;
	}
}

void Print::write(ByteCodeFileWriter& writer){
	(*begin())->write(writer);

	Value* value = dynamic_cast<Value*>(*begin());

	switch(value->type()){
		case INT:
			writer.writeSimpleCall(PRINTI);

			break;
		case STRING:
			writer.writeSimpleCall(PRINTS);

			break;
	}
}

void Integer::write(ByteCodeFileWriter& writer){
	writer.writeOneOperandCall(LDCI, m_value);
}

void VariableValue::write(ByteCodeFileWriter& writer){
	switch(m_type){
		case INT:
			writer.writeOneOperandCall(ILOAD, m_index);

			break;
		case STRING:
			writer.writeOneOperandCall(SLOAD, m_index);

			break;
	}
}

void Litteral::write(ByteCodeFileWriter& writer){
	writer.writeOneOperandCall(LDCS, m_index);
}

void Addition::checkVariables(Variables& variables) throw (CompilerException){
	NodeIterator it = begin();

	Value* lhs = dynamic_cast<Value*>(*it++);
	Value* rhs = dynamic_cast<Value*>(*it);

	lhs->checkVariables(variables);
	rhs->checkVariables(variables);

	if(lhs->type() != rhs->type()){
		throw new CompilerException("Can only add two values of the same type");
	}

	m_type = lhs->type();
}

void Addition::write(ByteCodeFileWriter& writer){
	lhs()->write(writer);
	rhs()->write(writer);

	if(m_type == INT){
		writer.writeSimpleCall(IADD);
	} else {
		writer.writeSimpleCall(SADD);
	}
}

//Constantness

bool Value::isConstant(){
	return false;
}

bool Litteral::isConstant(){
	return true;
}

bool Integer::isConstant(){
	return true;
}

bool VariableValue::isConstant(){
	return false;
}

bool Addition::isConstant(){
	return lhs()->isConstant() && rhs()->isConstant();
}

//Values

string Value::getStringValue(){
	throw "Not constant";
}

int Value::getIntValue(){
	throw "Not constant";
}

int Integer::getIntValue(){
	return m_value;
}

string Litteral::getStringValue(){
	return m_litteral;
}

int Addition::getIntValue(){
	if(type() != INT){
		throw "Invalid type";
	}

	if(!isConstant()){
		throw "Not a constant";
	}

	return lhs()->getIntValue() + rhs()->getIntValue();
}

string Addition::getStringValue(){
	if(type() != STRING){
		throw "Invalid type";
	}

	if(!isConstant()){
		throw "Not a constant";
	}

	return lhs()->getStringValue() + rhs()->getStringValue();
}

//Optimizations

void Addition::optimize(){
	//If both of the values are constant, we'll replace the addition with the value of the addition
	if(isConstant()){
		NodeIterator it = begin();

		if(type() == INT){
			Value* value = new Integer(getIntValue());

			parent->replace(this, value);
		} else if(type() == STRING){
			//No optimization at this time
		}
	}

	lhs()->optimize();
	rhs()->optimize();
}

//Utilities

Value* Addition::lhs(){
	return dynamic_cast<Value*>(*begin());
}

Value* Addition::rhs(){
	return dynamic_cast<Value*>(*++begin());
}
<commit_msg>Do not make any optimization if the option is not enabled<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include "Nodes.h"
#include "StringPool.h"
#include "Options.h"

#include <cassert>

using std::string;

void Declaration::checkVariables(Variables& variables) throw (CompilerException){
	if(variables.exists(m_variable)){
		throw CompilerException("Variable has already been declared");
	}

	Variable* var = variables.create(m_variable, m_type);

	m_index = var->index();

	Value* value = dynamic_cast<Value*>(*begin());

	value->checkVariables(variables);

	if(value->type() != m_type){
		throw CompilerException("Incompatible type");
	}
}

void Assignment::checkVariables(Variables& variables) throw (CompilerException){
	if(!variables.exists(m_variable)){
		throw CompilerException("Variable has not  been declared");
	}

	Variable* var = variables.find(m_variable);

	m_index = var->index();

	Value* value = dynamic_cast<Value*>(*begin());

	value->checkVariables(variables);

	if(value->type() != var->type()){
		throw CompilerException("Incompatible type");
	}
}

void VariableValue::checkVariables(Variables& variables) throw (CompilerException){
	if(!variables.exists(m_variable)){
		throw CompilerException("Variable has not been declared");
	}

	Variable* variable = variables.find(m_variable);

	m_type = variable->type();
	m_index = variable->index();
}

void Litteral::checkStrings(StringPool& pool){
	m_index = pool.index(m_litteral);
}

void Declaration::write(ByteCodeFileWriter& writer){
	(*begin())->write(writer);

	switch(m_type){
		case INT:
			writer.writeOneOperandCall(ISTORE, m_index);

			break;
		case STRING:
			writer.writeOneOperandCall(SSTORE, m_index);

			break;
	}
}

void Assignment::write(ByteCodeFileWriter& writer){
	(*begin())->write(writer);

	Value* value = dynamic_cast<Value*>(*begin());

	switch(value->type()){
		case INT:
			writer.writeOneOperandCall(ISTORE, m_index);

			break;
		case STRING:
			writer.writeOneOperandCall(SSTORE, m_index);

			break;
	}
}

void Print::write(ByteCodeFileWriter& writer){
	(*begin())->write(writer);

	Value* value = dynamic_cast<Value*>(*begin());

	switch(value->type()){
		case INT:
			writer.writeSimpleCall(PRINTI);

			break;
		case STRING:
			writer.writeSimpleCall(PRINTS);

			break;
	}
}

void Integer::write(ByteCodeFileWriter& writer){
	writer.writeOneOperandCall(LDCI, m_value);
}

void VariableValue::write(ByteCodeFileWriter& writer){
	switch(m_type){
		case INT:
			writer.writeOneOperandCall(ILOAD, m_index);

			break;
		case STRING:
			writer.writeOneOperandCall(SLOAD, m_index);

			break;
	}
}

void Litteral::write(ByteCodeFileWriter& writer){
	writer.writeOneOperandCall(LDCS, m_index);
}

void Addition::checkVariables(Variables& variables) throw (CompilerException){
	NodeIterator it = begin();

	Value* lhs = dynamic_cast<Value*>(*it++);
	Value* rhs = dynamic_cast<Value*>(*it);

	lhs->checkVariables(variables);
	rhs->checkVariables(variables);

	if(lhs->type() != rhs->type()){
		throw new CompilerException("Can only add two values of the same type");
	}

	m_type = lhs->type();
}

void Addition::write(ByteCodeFileWriter& writer){
	lhs()->write(writer);
	rhs()->write(writer);

	if(m_type == INT){
		writer.writeSimpleCall(IADD);
	} else {
		writer.writeSimpleCall(SADD);
	}
}

//Constantness

bool Value::isConstant(){
	return false;
}

bool Litteral::isConstant(){
	return true;
}

bool Integer::isConstant(){
	return true;
}

bool VariableValue::isConstant(){
	return false;
}

bool Addition::isConstant(){
	return lhs()->isConstant() && rhs()->isConstant();
}

//Values

string Value::getStringValue(){
	throw "Not constant";
}

int Value::getIntValue(){
	throw "Not constant";
}

int Integer::getIntValue(){
	return m_value;
}

string Litteral::getStringValue(){
	return m_litteral;
}

int Addition::getIntValue(){
	if(type() != INT){
		throw "Invalid type";
	}

	if(!isConstant()){
		throw "Not a constant";
	}

	return lhs()->getIntValue() + rhs()->getIntValue();
}

string Addition::getStringValue(){
	if(type() != STRING){
		throw "Invalid type";
	}

	if(!isConstant()){
		throw "Not a constant";
	}

	return lhs()->getStringValue() + rhs()->getStringValue();
}

//Optimizations

void Addition::optimize(){
	//If both of the values are constant, we'll replace the addition with the value of the addition
	if(isConstant()){
		NodeIterator it = begin();

		if(type() == INT){
			if(Options::isSet(OPTIMIZE_INTEGERS) || Options::isSet(OPTIMIZE_ALL)){
				Value* value = new Integer(getIntValue());

				parent->replace(this, value);
			}
		} else if(type() == STRING){
			if(Options::isSet(OPTIMIZE_STRINGS) || Options::isSet(OPTIMIZE_ALL)){
				//No optimization at this time
			}
		}
	}

	lhs()->optimize();
	rhs()->optimize();
}

//Utilities

Value* Addition::lhs(){
	return dynamic_cast<Value*>(*begin());
}

Value* Addition::rhs(){
	return dynamic_cast<Value*>(*++begin());
}
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    Object.cc
  Language:  C++
  Date:      30 Jun 1995
  Version:   1.19

This file is part of the Visualization Toolkit. No part of this file or its
contents may be copied, reproduced or altered in any way without the express
written consent of the authors.

Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994

=========================================================================*/

#include "Object.hh"

// Description:
// Operator allows all subclasses of vtkObject to be printed via <<.
ostream& operator<<(ostream& os, vtkObject& o)
{
  o.Print(os);
  return os;
}

vtkObject::vtkObject()
{
  this->Debug = 0;
  this->Modified(); // Insures modified time > than any other time
}

vtkObject::~vtkObject()
{
  vtkDebugMacro(<< "Destructing!");
}

// Description:
// Return the modification for this object.
unsigned long int vtkObject::GetMTime()
{
  return this->MTime.GetMTime();
}

void vtkObject::Print(ostream& os)
{
  vtkIndent indent;

  this->PrintHeader(os,0);
  this->PrintSelf(os, indent.GetNextIndent());
  this->PrintTrailer(os,0);
}

void vtkObject::PrintHeader(ostream& os, vtkIndent indent)
{
  os << indent << this->GetClassName() << " (" << this << ")\n";
}

// Description:
// Chaining method to print object instance variables as well as
// superclasses.
void vtkObject::PrintSelf(ostream& os, vtkIndent indent)
{
  os << indent << "Debug: " << (this->Debug ? "On\n" : "Off\n");
  os << indent << "Modified Time: " << this->GetMTime() << "\n";
}

void vtkObject::PrintTrailer(ostream& os, vtkIndent indent)
{
  os << indent << "\n";
}

// Description:
// Turn debug printout on.
void vtkObject::DebugOn()
{
  this->Debug = 1;
}

// Description:
// Turn debug printout off.
void vtkObject::DebugOff()
{
  this->Debug = 0;
}

// Description:
// Get the value of the debug flag.
int vtkObject::GetDebug()
{
  return this->Debug;
}
<commit_msg>ERR: Delete method.<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    Object.cc
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

This file is part of the Visualization Toolkit. No part of this file or its
contents may be copied, reproduced or altered in any way without the express
written consent of the authors.

Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994

=========================================================================*/
#include "Object.hh"

// Description:
// Operator allows all subclasses of vtkObject to be printed via <<.
ostream& operator<<(ostream& os, vtkObject& o)
{
  o.Print(os);
  return os;
}

// Description:
// Create an object with Debug turned off and modified time initialized
// to zero.
vtkObject::vtkObject()
{
  this->Debug = 0;
  this->Modified(); // Insures modified time > than any other time
}

// Description:
// Delete a vtk object. Delete() should always be used to delete an object
// when the new operator is used.
void vtkObject::Delete()
{
  delete this;
}

vtkObject::~vtkObject()
{
  vtkDebugMacro(<< "Destructing!");
}

// Description:
// Return the modification for this object.
unsigned long int vtkObject::GetMTime()
{
  return this->MTime.GetMTime();
}

void vtkObject::Print(ostream& os)
{
  vtkIndent indent;

  this->PrintHeader(os,0);
  this->PrintSelf(os, indent.GetNextIndent());
  this->PrintTrailer(os,0);
}

void vtkObject::PrintHeader(ostream& os, vtkIndent indent)
{
  os << indent << this->GetClassName() << " (" << this << ")\n";
}

// Description:
// Chaining method to print object instance variables as well as
// superclasses.
void vtkObject::PrintSelf(ostream& os, vtkIndent indent)
{
  os << indent << "Debug: " << (this->Debug ? "On\n" : "Off\n");
  os << indent << "Modified Time: " << this->GetMTime() << "\n";
}

void vtkObject::PrintTrailer(ostream& os, vtkIndent indent)
{
  os << indent << "\n";
}

// Description:
// Turn debug printout on.
void vtkObject::DebugOn()
{
  this->Debug = 1;
}

// Description:
// Turn debug printout off.
void vtkObject::DebugOff()
{
  this->Debug = 0;
}

// Description:
// Get the value of the debug flag.
int vtkObject::GetDebug()
{
  return this->Debug;
}
<|endoftext|>