<commit_before>#include "Build.hpp"

#include "BuildGraph.hpp"
#include "Command.hpp"
#include "DependencyLink.hpp"
#include "Environ.hpp"
#include "error.hpp"
#include "Filesystem.hpp"
#include "log.hpp"
#include "lua/State.hpp"
#include "Platform.hpp"
#include "Rule.hpp"
#include "quote.hpp"

#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>
#include <boost/functional/hash.hpp>
#include <boost/graph/graphviz.hpp>
#include <boost/scope_exit.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/optional.hpp>

#include <unordered_map>
#include <unordered_set>
#include <vector>

namespace fs = boost::filesystem;

namespace std {

	template<> struct hash<boost::filesystem::path>
	{
		size_t operator ()(boost::filesystem::path const& p) const
		{ return hash_value(p); }
	};

}

namespace configure {

	static bool starts_with(fs::path const& path, fs::path const& prefix)
	{
		auto it = path.begin(), end = path.end();
		for (auto&& p: prefix)
		{
			if (it == end) return false;
			if (p == ".") continue;
			if (*it != p) return false;
			++it;
		}
		return true;
	}

	struct Build::Impl
	{
		path_t                                   root_directory;
		lua::State&                              lua;
		std::vector<path_t>                      project_stack;
		std::vector<path_t>                      build_stack;
		BuildGraph                               build_graph;
		std::unordered_map<std::string, NodePtr> virtual_nodes;
		std::unordered_map<path_t, NodePtr>      file_nodes;
		std::unordered_map<path_t, NodePtr>      directory_nodes;
		NodePtr                                  root_node;
		Filesystem                               fs;
		Environ                                  env;
		fs::path                                 env_path;
		std::map<std::string, std::string>       options;
		std::map<std::string, std::string>       build_args;
		Platform                                 host_platform;
		Platform                                 target_platform;

		Impl(Build& build, lua::State& lua, path_t directory)
			: root_directory(std::move(directory))
			, lua(lua)
			, project_stack()
			, build_stack()
			, build_graph()
			, virtual_nodes()
			, file_nodes()
			, directory_nodes()
			, root_node(this->build_graph.add_node<VirtualNode>(""))
			, fs(build)
			, env()
			, env_path(root_directory / ".configure.env")
			, options()
			, build_args()
			, host_platform(Platform::current())
			, target_platform(Platform::current())
		{}
	};

	Build::Build(lua::State& lua, path_t directory)
		: _this(new Impl(*this, lua, std::move(directory)))
	{
		_this->build_stack.push_back(_this->root_directory);
		if (fs::is_regular_file(_this->env_path))
		{
			try { _this->env.load(_this->env_path); }
			catch (...) {
				CONFIGURE_THROW(
					error::InvalidEnviron("Couldn't load the configuration file")
						<< error::path(_this->env_path)
						<< error::nested(std::current_exception())
				);
			}
		}
	}

	Build::Build(lua::State& lua, path_t root_directory,
	      std::map<std::string, std::string> build_args)
		: Build(lua, std::move(root_directory))
	{
		for (auto& pair: build_args)
			_this->build_args[Environ::normalize(pair.first)] = pair.second;
	}

	Build::~Build()
	{
		try { _this->env.save(_this->env_path); }
		catch (...) {
			log::fatal("Couldn't save environ in", _this->env_path, ":",
			           error_string());
			std::abort();
		}
	}

	void Build::configure(path_t const& project_directory,
	                      path_t const& sub_directory)
	{
		try {
			if (!project_directory.is_absolute())
				CONFIGURE_THROW(error::InvalidProject("Not an absolute path"));
			if (!fs::is_directory(project_directory))
				CONFIGURE_THROW(error::InvalidProject("Not a directory"));
			if (fs::equivalent(project_directory, this->directory()))
				CONFIGURE_THROW(error::InvalidProject("Same as build directory"));
		} catch (error::InvalidProject& err) {
			throw err << error::path(project_directory);
		}
		_this->project_stack.push_back(project_directory);
		_this->build_stack.push_back(_prepare_build_directory(sub_directory));
		log::status("Configuring project", this->project_directory(), "in", this->directory());

		BOOST_SCOPE_EXIT((&_this)){
			_this->project_stack.pop_back();
			_this->build_stack.pop_back();
		} BOOST_SCOPE_EXIT_END

		try {
			_this->lua.load(find_project_file(project_directory));
			_this->lua.getglobal("configure");
			// XXX check if not nil
			_this->lua.construct<std::reference_wrapper<Build>>(*this);
			_this->lua.call(1);
			if (_this->project_stack.size() == 1) // Last project on the stack
				_finalize_build_directory();
		} catch (error::Base& e) {
			//e << error::message(
			//	"While configuring project " + project_directory.string()
			//);
			throw;
		}
	}

	Build::path_t const& Build::project_directory() const
	{
		if (_this->project_stack.empty())
			throw std::logic_error("No project on the stack");
		return _this->project_stack.back();
	}
	Build::path_t const& Build::root_directory() const
	{ return _this->root_directory; }

	Build::path_t const& Build::directory() const
	{ return _this->build_stack.back(); }

	NodePtr const& Build::root_node() const
	{ return _this->root_node; }

	BuildGraph const& Build::build_graph() const
	{ return _this->build_graph; }

	Filesystem& Build::fs()
	{ return _this->fs; }

	Environ& Build::env()
	{ return _this->env; }

	template<typename T>
	boost::optional<T> Build::option(std::string name,
	                                 std::string const& description)
	{
		name = Environ::normalize(std::move(name));
		_this->options[name] = description;
		auto it = _this->build_args.find(name);
		if (it != _this->build_args.end())
		{
			log::debug("Found option", name, "in command line arguments:", it->second);
			if (std::is_same<T, bool>::value)
			{
				std::string str = boost::to_lower_copy(it->second);
				static std::map<std::string, bool> conversions = {
					{"true", true}, {"false", false},
					{"yes", true}, {"no", false},
					{"y", true}, {"n", false},
					{"1", true}, {"0", false},
				};
				bool value;
				try { value = conversions.at(str); }
				catch (...) {
					CONFIGURE_THROW(
						error::InvalidOption("Cannot convert '" + it->second +
						                     "' to a boolean")
					);
				}
				_this->env.set(name, value);
			}
			else
				_this->env.set(name, boost::lexical_cast<T>(it->second));
			_this->build_args.erase(it);
			return boost::optional<T>(_this->env.get<T>(name));
		}
		return boost::none;
	}

	template<typename T>
	typename Environ::const_ref<T>::type
	Build::option(std::string name,
	              std::string const& description,
	              typename Environ::const_ref<T>::type default_value)
	{
		this->option<T>(name, description);
		if (!_this->env.has(name))
			_this->env.set(name, default_value);
		return _this->env.get<T>(name);
	}

#define INSTANCIATE(T) \
	template \
	boost::optional<T> Build::option<T>(std::string name, \
	                                    std::string const& description); \
	template \
	Environ::const_ref<T>::type \
	Build::option<T>(std::string name, \
	                 std::string const& description, \
	                 Environ::const_ref<T>::type default_value); \
/**/

	INSTANCIATE(std::string);
	INSTANCIATE(int);
	INSTANCIATE(bool);
	INSTANCIATE(fs::path);

	Build::path_t Build::_prepare_build_directory(path_t const& sub_directory)
	{
		fs::create_directories(this->directory() / sub_directory);
		return fs::canonical(this->directory() / sub_directory);
	}

	void Build::_finalize_build_directory()
	{
		std::unordered_set<fs::path> directories;
		for (auto const& pair: _this->file_nodes)
		{
			if (starts_with(pair.first, this->root_directory()))
				directories.insert(pair.first.parent_path());
		}

		for (auto&& d: directories)
			fs::create_directories(d);
	}

	std::vector<Build::path_t> const& Build::possible_configure_files()
	{
		static std::vector<path_t> ret {
			"configure.lua",
			".configure.lua",
			".config/project.lua",
		};
		return ret;
	}

	Build::path_t Build::find_project_file(path_t project_directory)
	{
		for (auto&& p: possible_configure_files())
			if (fs::is_regular_file(project_directory / p))
				return project_directory / p;
		throw std::runtime_error("No configuration file found in " + project_directory.string());
	}

	NodePtr& Build::virtual_node(std::string const& name)
	{
		if (name.empty())
			CONFIGURE_THROW(error::InvalidVirtualNode("Name cannot be empty"));
		auto it = _this->virtual_nodes.find(name);
		if (it != _this->virtual_nodes.end())
			return it->second;
		auto node = _this->build_graph.add_node<VirtualNode>(name);
		return (_this->virtual_nodes[name] = std::move(node));
	}

	NodePtr& Build::file_node(path_t const& path)
	{
		if (!path.is_absolute())
			throw std::runtime_error("Not an absolute path: " + path.string());
		auto it = _this->file_nodes.find(path);
		if (it != _this->file_nodes.end())
			return it->second;
		auto node = _this->build_graph.add_node<FileNode>(path);
		return (_this->file_nodes[path] = std::move(node));
	}

	NodePtr& Build::directory_node(path_t const& path)
	{
		if (!path.is_absolute())
			throw std::runtime_error("Not an absolute path: " + path.string());
		auto it = _this->directory_nodes.find(path);
		if (it != _this->directory_nodes.end())
			return it->second;
		auto node = _this->build_graph.add_node<DirectoryNode>(path);
		return (_this->directory_nodes[path] = std::move(node));
	}

	NodePtr& Build::source_node(path_t const& path)
	{
		fs::path src;
		if (!path.is_absolute())
			src = this->project_directory() / path;
		else
		{
			src = path;
			if (starts_with(src, this->root_directory()))
				CONFIGURE_THROW(
					error::InvalidSourceNode("Generated file cannot be a source node")
						<< error::path(src)
				);
		}
		if (!fs::is_regular_file(src))
			CONFIGURE_THROW(error::InvalidSourceNode("File not found")
				<< error::path(src)
			);
		return this->file_node(src);
	}

	NodePtr& Build::target_node(path_t const& path)
	{
		if (path.is_absolute())
			return this->file_node(path);
		return this->file_node(this->directory() / path);
	}

	void Build::add_rule(Rule const& rule)
	{
		CommandPtr cmd = rule.command();
		if (rule.targets().empty())
			CONFIGURE_THROW(error::InvalidRule("No target specified"));

		if (rule.sources().empty())
			for (auto& target: rule.targets())
			{
				try {
					_this->build_graph.link(*_this->root_node, *target).command(cmd);
				} catch (error::CommandAlreadySet&) {
					CONFIGURE_THROW(
						error::InvalidRule(
							"Trying to generate " + target->string() + " twice"
						) << error::nested(std::current_exception())
					);
				}
			}
		else
			for (auto& target: rule.targets())
				for (auto& source: rule.sources())
				{
					try {
						_this->build_graph.link(*source, *target)
							.command(cmd);
					} catch (error::CommandAlreadySet&) {
						CONFIGURE_THROW(
							error::InvalidRule(
								"Trying to generate " + target->string() + " twice"
							) << error::nested(std::current_exception())
						);
					}
				}
	}

	Platform& Build::host()
	{ return _this->host_platform; }

	Platform& Build::target()
	{ return _this->target_platform; }

	void Build::dump_graphviz(std::ostream& out)
	{
		struct Writer {
			Build& _b;
			BuildGraph& _g;

			Writer(Build& b, BuildGraph& g) : _b(b), _g(g) {}

			void operator ()(std::ostream& out, Node::index_type idx) const
			{
				auto& node = _g.node(idx);
				switch (node->kind())
				{
				case Node::file_node:
				case Node::directory_node:
					out << "[label=\"" << node->relative_path(_b.directory()).string() << "\"]";
					break;
				case Node::virtual_node:
					out << "[label=\"" << node->name() << "\"]";
					break;
				default:
					out << "[label=\"" << "UNKNOWN" << "\"]";
				}
			}

			void operator ()(std::ostream& out, DependencyLink::index_type idx) const
			{
				auto const& cmd = _g.link(idx).command();
				out << "[label=\"";
				bool first = true;
				for (auto&& shell_command: cmd.shell_commands())
				{
					if (first) first = false;
					else out << "\\n";
					out << quote<CommandParser::unix_shell>(shell_command.dump());
				}
				out << "\"]";

			}
		} writer(*this, _this->build_graph);
		boost::write_graphviz(
			out,
			_this->build_graph.graph(),
			writer,
			writer
		);
	}

}
<commit_msg>Use correct log level.<commit_after>#include "Build.hpp"

#include "BuildGraph.hpp"
#include "Command.hpp"
#include "DependencyLink.hpp"
#include "Environ.hpp"
#include "error.hpp"
#include "Filesystem.hpp"
#include "log.hpp"
#include "lua/State.hpp"
#include "Platform.hpp"
#include "Rule.hpp"
#include "quote.hpp"

#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>
#include <boost/functional/hash.hpp>
#include <boost/graph/graphviz.hpp>
#include <boost/scope_exit.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/optional.hpp>

#include <unordered_map>
#include <unordered_set>
#include <vector>

namespace fs = boost::filesystem;

namespace std {

	template<> struct hash<boost::filesystem::path>
	{
		size_t operator ()(boost::filesystem::path const& p) const
		{ return hash_value(p); }
	};

}

namespace configure {

	static bool starts_with(fs::path const& path, fs::path const& prefix)
	{
		auto it = path.begin(), end = path.end();
		for (auto&& p: prefix)
		{
			if (it == end) return false;
			if (p == ".") continue;
			if (*it != p) return false;
			++it;
		}
		return true;
	}

	struct Build::Impl
	{
		path_t                                   root_directory;
		lua::State&                              lua;
		std::vector<path_t>                      project_stack;
		std::vector<path_t>                      build_stack;
		BuildGraph                               build_graph;
		std::unordered_map<std::string, NodePtr> virtual_nodes;
		std::unordered_map<path_t, NodePtr>      file_nodes;
		std::unordered_map<path_t, NodePtr>      directory_nodes;
		NodePtr                                  root_node;
		Filesystem                               fs;
		Environ                                  env;
		fs::path                                 env_path;
		std::map<std::string, std::string>       options;
		std::map<std::string, std::string>       build_args;
		Platform                                 host_platform;
		Platform                                 target_platform;

		Impl(Build& build, lua::State& lua, path_t directory)
			: root_directory(std::move(directory))
			, lua(lua)
			, project_stack()
			, build_stack()
			, build_graph()
			, virtual_nodes()
			, file_nodes()
			, directory_nodes()
			, root_node(this->build_graph.add_node<VirtualNode>(""))
			, fs(build)
			, env()
			, env_path(root_directory / ".configure.env")
			, options()
			, build_args()
			, host_platform(Platform::current())
			, target_platform(Platform::current())
		{}
	};

	Build::Build(lua::State& lua, path_t directory)
		: _this(new Impl(*this, lua, std::move(directory)))
	{
		_this->build_stack.push_back(_this->root_directory);
		if (fs::is_regular_file(_this->env_path))
		{
			try { _this->env.load(_this->env_path); }
			catch (...) {
				CONFIGURE_THROW(
					error::InvalidEnviron("Couldn't load the configuration file")
						<< error::path(_this->env_path)
						<< error::nested(std::current_exception())
				);
			}
		}
	}

	Build::Build(lua::State& lua, path_t root_directory,
	      std::map<std::string, std::string> build_args)
		: Build(lua, std::move(root_directory))
	{
		for (auto& pair: build_args)
			_this->build_args[Environ::normalize(pair.first)] = pair.second;
	}

	Build::~Build()
	{
		try { _this->env.save(_this->env_path); }
		catch (...) {
			log::error("Couldn't save environ in", _this->env_path, ":",
			           error_string());
			std::abort();
		}
	}

	void Build::configure(path_t const& project_directory,
	                      path_t const& sub_directory)
	{
		try {
			if (!project_directory.is_absolute())
				CONFIGURE_THROW(error::InvalidProject("Not an absolute path"));
			if (!fs::is_directory(project_directory))
				CONFIGURE_THROW(error::InvalidProject("Not a directory"));
			if (fs::equivalent(project_directory, this->directory()))
				CONFIGURE_THROW(error::InvalidProject("Same as build directory"));
		} catch (error::InvalidProject& err) {
			throw err << error::path(project_directory);
		}
		_this->project_stack.push_back(project_directory);
		_this->build_stack.push_back(_prepare_build_directory(sub_directory));
		log::status("Configuring project", this->project_directory(), "in", this->directory());

		BOOST_SCOPE_EXIT((&_this)){
			_this->project_stack.pop_back();
			_this->build_stack.pop_back();
		} BOOST_SCOPE_EXIT_END

		try {
			_this->lua.load(find_project_file(project_directory));
			_this->lua.getglobal("configure");
			// XXX check if not nil
			_this->lua.construct<std::reference_wrapper<Build>>(*this);
			_this->lua.call(1);
			if (_this->project_stack.size() == 1) // Last project on the stack
				_finalize_build_directory();
		} catch (error::Base& e) {
			//e << error::message(
			//	"While configuring project " + project_directory.string()
			//);
			throw;
		}
	}

	Build::path_t const& Build::project_directory() const
	{
		if (_this->project_stack.empty())
			throw std::logic_error("No project on the stack");
		return _this->project_stack.back();
	}
	Build::path_t const& Build::root_directory() const
	{ return _this->root_directory; }

	Build::path_t const& Build::directory() const
	{ return _this->build_stack.back(); }

	NodePtr const& Build::root_node() const
	{ return _this->root_node; }

	BuildGraph const& Build::build_graph() const
	{ return _this->build_graph; }

	Filesystem& Build::fs()
	{ return _this->fs; }

	Environ& Build::env()
	{ return _this->env; }

	template<typename T>
	boost::optional<T> Build::option(std::string name,
	                                 std::string const& description)
	{
		name = Environ::normalize(std::move(name));
		_this->options[name] = description;
		auto it = _this->build_args.find(name);
		if (it != _this->build_args.end())
		{
			log::debug("Found option", name, "in command line arguments:", it->second);
			if (std::is_same<T, bool>::value)
			{
				std::string str = boost::to_lower_copy(it->second);
				static std::map<std::string, bool> conversions = {
					{"true", true}, {"false", false},
					{"yes", true}, {"no", false},
					{"y", true}, {"n", false},
					{"1", true}, {"0", false},
				};
				bool value;
				try { value = conversions.at(str); }
				catch (...) {
					CONFIGURE_THROW(
						error::InvalidOption("Cannot convert '" + it->second +
						                     "' to a boolean")
					);
				}
				_this->env.set(name, value);
			}
			else
				_this->env.set(name, boost::lexical_cast<T>(it->second));
			_this->build_args.erase(it);
			return boost::optional<T>(_this->env.get<T>(name));
		}
		return boost::none;
	}

	template<typename T>
	typename Environ::const_ref<T>::type
	Build::option(std::string name,
	              std::string const& description,
	              typename Environ::const_ref<T>::type default_value)
	{
		this->option<T>(name, description);
		if (!_this->env.has(name))
			_this->env.set(name, default_value);
		return _this->env.get<T>(name);
	}

#define INSTANCIATE(T) \
	template \
	boost::optional<T> Build::option<T>(std::string name, \
	                                    std::string const& description); \
	template \
	Environ::const_ref<T>::type \
	Build::option<T>(std::string name, \
	                 std::string const& description, \
	                 Environ::const_ref<T>::type default_value); \
/**/

	INSTANCIATE(std::string);
	INSTANCIATE(int);
	INSTANCIATE(bool);
	INSTANCIATE(fs::path);

	Build::path_t Build::_prepare_build_directory(path_t const& sub_directory)
	{
		fs::create_directories(this->directory() / sub_directory);
		return fs::canonical(this->directory() / sub_directory);
	}

	void Build::_finalize_build_directory()
	{
		std::unordered_set<fs::path> directories;
		for (auto const& pair: _this->file_nodes)
		{
			if (starts_with(pair.first, this->root_directory()))
				directories.insert(pair.first.parent_path());
		}

		for (auto&& d: directories)
			fs::create_directories(d);
	}

	std::vector<Build::path_t> const& Build::possible_configure_files()
	{
		static std::vector<path_t> ret {
			"configure.lua",
			".configure.lua",
			".config/project.lua",
		};
		return ret;
	}

	Build::path_t Build::find_project_file(path_t project_directory)
	{
		for (auto&& p: possible_configure_files())
			if (fs::is_regular_file(project_directory / p))
				return project_directory / p;
		throw std::runtime_error("No configuration file found in " + project_directory.string());
	}

	NodePtr& Build::virtual_node(std::string const& name)
	{
		if (name.empty())
			CONFIGURE_THROW(error::InvalidVirtualNode("Name cannot be empty"));
		auto it = _this->virtual_nodes.find(name);
		if (it != _this->virtual_nodes.end())
			return it->second;
		auto node = _this->build_graph.add_node<VirtualNode>(name);
		return (_this->virtual_nodes[name] = std::move(node));
	}

	NodePtr& Build::file_node(path_t const& path)
	{
		if (!path.is_absolute())
			throw std::runtime_error("Not an absolute path: " + path.string());
		auto it = _this->file_nodes.find(path);
		if (it != _this->file_nodes.end())
			return it->second;
		auto node = _this->build_graph.add_node<FileNode>(path);
		return (_this->file_nodes[path] = std::move(node));
	}

	NodePtr& Build::directory_node(path_t const& path)
	{
		if (!path.is_absolute())
			throw std::runtime_error("Not an absolute path: " + path.string());
		auto it = _this->directory_nodes.find(path);
		if (it != _this->directory_nodes.end())
			return it->second;
		auto node = _this->build_graph.add_node<DirectoryNode>(path);
		return (_this->directory_nodes[path] = std::move(node));
	}

	NodePtr& Build::source_node(path_t const& path)
	{
		fs::path src;
		if (!path.is_absolute())
			src = this->project_directory() / path;
		else
		{
			src = path;
			if (starts_with(src, this->root_directory()))
				CONFIGURE_THROW(
					error::InvalidSourceNode("Generated file cannot be a source node")
						<< error::path(src)
				);
		}
		if (!fs::is_regular_file(src))
			CONFIGURE_THROW(error::InvalidSourceNode("File not found")
				<< error::path(src)
			);
		return this->file_node(src);
	}

	NodePtr& Build::target_node(path_t const& path)
	{
		if (path.is_absolute())
			return this->file_node(path);
		return this->file_node(this->directory() / path);
	}

	void Build::add_rule(Rule const& rule)
	{
		CommandPtr cmd = rule.command();
		if (rule.targets().empty())
			CONFIGURE_THROW(error::InvalidRule("No target specified"));

		if (rule.sources().empty())
			for (auto& target: rule.targets())
			{
				try {
					_this->build_graph.link(*_this->root_node, *target).command(cmd);
				} catch (error::CommandAlreadySet&) {
					CONFIGURE_THROW(
						error::InvalidRule(
							"Trying to generate " + target->string() + " twice"
						) << error::nested(std::current_exception())
					);
				}
			}
		else
			for (auto& target: rule.targets())
				for (auto& source: rule.sources())
				{
					try {
						_this->build_graph.link(*source, *target)
							.command(cmd);
					} catch (error::CommandAlreadySet&) {
						CONFIGURE_THROW(
							error::InvalidRule(
								"Trying to generate " + target->string() + " twice"
							) << error::nested(std::current_exception())
						);
					}
				}
	}

	Platform& Build::host()
	{ return _this->host_platform; }

	Platform& Build::target()
	{ return _this->target_platform; }

	void Build::dump_graphviz(std::ostream& out)
	{
		struct Writer {
			Build& _b;
			BuildGraph& _g;

			Writer(Build& b, BuildGraph& g) : _b(b), _g(g) {}

			void operator ()(std::ostream& out, Node::index_type idx) const
			{
				auto& node = _g.node(idx);
				switch (node->kind())
				{
				case Node::file_node:
				case Node::directory_node:
					out << "[label=\"" << node->relative_path(_b.directory()).string() << "\"]";
					break;
				case Node::virtual_node:
					out << "[label=\"" << node->name() << "\"]";
					break;
				default:
					out << "[label=\"" << "UNKNOWN" << "\"]";
				}
			}

			void operator ()(std::ostream& out, DependencyLink::index_type idx) const
			{
				auto const& cmd = _g.link(idx).command();
				out << "[label=\"";
				bool first = true;
				for (auto&& shell_command: cmd.shell_commands())
				{
					if (first) first = false;
					else out << "\\n";
					out << quote<CommandParser::unix_shell>(shell_command.dump());
				}
				out << "\"]";

			}
		} writer(*this, _this->build_graph);
		boost::write_graphviz(
			out,
			_this->build_graph.graph(),
			writer,
			writer
		);
	}

}
<|endoftext|>


<commit_before>/*
 * Copyright (c) <2011>, Tim Simon <tim.simon@radiumblue.net>
 * 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.
 *
 * 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 HOLDER 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 <cstdlib>
#include <string>
#include <iostream>
#include <stdio.h>
#include "wcl/network/TCPServer.h"

using namespace wcl;

void usage() {
    printf("NAME\n\tpcontrol - Network command controller for NEC projectors\n\n"
            "SYNOPSIS\n\t pcontrol [options] -a <address> -p <port> [COMMAND]\n\n"
            "Options:\n"
            "\t-h\n\t--help\n"
            "\t\tDisplay usage options.\n"
            "\t-a\n\t--address\n"
            "\t\tThe address of the projector to communicate with.\n"
            "\t-p\n\t--port\n"
            "\t\tThe port to communicate on.\n"
            "COMMANDS\n[COMMAND] can be any single value of the following:\n"
            "\t--ON\n\t\tPower ON\n"
            "\t--OFF\n\t\tPower OFF\n"
          );
}

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

    std::string address = "127.0.0.1";
    unsigned int port = 7142;

    // Determine whethe the arguments given are valid.
    if ( argc >= 2 ) {

        for ( int counter = 0; counter < argc ; ++counter ) {

            if ( strcmp ( argv[counter], "--help" ) == 0 || strcmp ( argv[counter], "-h" ) == 0 ) {
                usage();
                return 1;
            }

            if ( strcmp ( argv[counter], "--address" ) == 0 || strcmp (argv[counter], "-a" ) == 0 ) {
                if ( counter+1 <= argc ) {
                    //TODO double check that argc[counter+1] is a valid IP address.
                    address=argv[counter+1];
                    counter++;
                } else {
                    usage();
                    return 1;
                }
            }

            if ( strcmp ( argv[counter], "--port" ) == 0 || strcmp (argv[counter], "-p" ) == 0 ) {
                if ( counter+1 <= argc ) {
                    char *pEnd;
                    port = strtol ( argv[counter+1], &pEnd, 10 );
                    counter++;
                } else {
                    usage();
                    return 1;
                }
            }
        }

        // Now determine whether we actually got given a command to send to the projector or not.
        if (( strcmp (argv[argc-1], "--ON" ) == 0 ) ||  ( strcmp (argv[argc-1], "--OFF" ) == 0 ) ) {
        } else {
            usage();
            return -1;
        }

        try {

            TCPSocket projector(address,port);
            // Get the last value, which should be our command, and use it for our command to run.
            if ( strcmp (argv[argc-1], "--ON" ) == 0 ) {
                // 02H 00H 00H 00H 00H 00H 02H
                unsigned char toSend[] = { (unsigned char)2, 0, 0, 0, 0, (unsigned char)2 };
                projector.write((char*) toSend, 6);
            }
            if ( strcmp (argv[argc-1], "--OFF" ) == 0 ) {

                // 02H 01H 00H 00H 00H 03H
                unsigned char toSend[] = { (unsigned char)2, (unsigned char)1, 0, 0, 0, (unsigned char)3 };
                projector.write((char*) toSend, 6);
            }
            // Read the response from the projector.
            unsigned char buffer[4096];
            projector.read((char *)buffer, 4096);
            if ( (int) buffer[0] == 34  ) {
                std::cout << "Projecter sends ACK: Doing task." << std::endl;
            } else {
                std::cout << "Projector did not send ACK. Recieved: " << (int)buffer[0] << std::endl;
            }

            projector.close();
        } catch (SocketException* e) {
            fprintf( stderr, "%s", e->what() );
        }

    } else {
        usage();
        return -1;
    }

    return 0;
}
<commit_msg>pcontrol now uses wcl::RemoteProjector rather then establishing a connection on it's own.<commit_after>/*
 * Copyright (c) <2011>, Tim Simon <tim.simon@radiumblue.net>
 * 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.
 *
 * 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 HOLDER 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 <cstdlib>
#include <string>
#include <iostream>
#include <stdio.h>
#include <wcl/projector/RemoteProjector.h>

using namespace wcl;

void usage() {
    printf("NAME\n\tpcontrol - Network command controller for NEC projectors\n\n"
            "SYNOPSIS\n\t pcontrol [options] -a <address> -p <port> [COMMAND]\n\n"
            "Options:\n"
            "\t-h\n\t--help\n"
            "\t\tDisplay usage options.\n"
            "\t-a\n\t--address\n"
            "\t\tThe address of the projector to communicate with.\n"
            "\t-p\n\t--port\n"
            "\t\tThe port to communicate on.\n"
            "COMMANDS\n[COMMAND] can be any single value of the following:\n"
            "\t--ON\n\t\tPower ON\n"
            "\t--OFF\n\t\tPower OFF\n"
          );
}

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

    std::string address = "127.0.0.1";
    unsigned int port = 7142;

    // Determine whethe the arguments given are valid.
    if ( argc >= 2 ) {

        for ( int counter = 0; counter < argc ; ++counter ) {

            if ( strcmp ( argv[counter], "--help" ) == 0 || strcmp ( argv[counter], "-h" ) == 0 ) {
                usage();
                return 1;
            }

            if ( strcmp ( argv[counter], "--address" ) == 0 || strcmp (argv[counter], "-a" ) == 0 ) {
                if ( counter+1 <= argc ) {
                    //TODO double check that argc[counter+1] is a valid IP address.
                    address=argv[counter+1];
                    counter++;
                } else {
                    usage();
                    return 1;
                }
            }

            if ( strcmp ( argv[counter], "--port" ) == 0 || strcmp (argv[counter], "-p" ) == 0 ) {
                if ( counter+1 <= argc ) {
                    char *pEnd;
                    port = strtol ( argv[counter+1], &pEnd, 10 );
                    counter++;
                } else {
                    usage();
                    return 1;
                }
            }
        }

        // Now determine whether we actually got given a command to send to the projector or not.
        if (( strcmp (argv[argc-1], "--ON" ) == 0 ) ||  ( strcmp (argv[argc-1], "--OFF" ) == 0 ) ) {
        } else {
            usage();
            return -1;
        }

        RemoteProjector *rp = new RemoteProjector(address,port,true);
        // Get the last value, which should be our command, and use it for our command to run.
        if ( strcmp (argv[argc-1], "--ON" ) == 0 ) {
            rp->turnOn();
        }
        if ( strcmp (argv[argc-1], "--OFF" ) == 0 ) {
            rp->turnOff();
        }

        rp->getResponse();

    } else {
        usage();
        return -1;
    }

    return 0;
}
<|endoftext|>


<commit_before>#include <QPainter>
#include <QAbstractEventDispatcher>
#include <QApplication>
#include <QPaintEvent>
#include <QFontMetrics>
#include <QTextStream>
#include <qterm.h>
#include <stdio.h>
#include <QKeyEvent>
#include <QTimer>
#include <sys/select.h>
#include <errno.h>
#ifdef __QNX__
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <bps/bps.h>
#ifdef BPS_VERSION
#include <bps/virtualkeyboard.h>
#else
#include <bbsupport/Keyboard>
#include <bbsupport/Notification>
#endif
#endif

#define WIDTH    80
#define HEIGHT    17
#define BLINK_SPEED 1000

QTerm::QTerm(QWidget *parent) : QWidget(parent)
{
    term_create( &terminal );
    term_begin( terminal, WIDTH, HEIGHT, 0 );
    init();
}

QTerm::QTerm(QWidget *parent, term_t terminal) : QWidget(parent)
{
    this->terminal = terminal;
    init();
}

void QTerm::init()
{
    char_width = 0;
    char_height = 0;
    cursor_x = -1;
    cursor_y = -1;
    cursor_on = 1;

    resize(1024, 600);
    term_set_user_data( terminal, this );
    term_register_update( terminal, term_update );
    term_register_cursor( terminal, term_update_cursor );
    term_register_bell( terminal, term_bell );
    notifier = new QSocketNotifier( term_get_file_descriptor(terminal), QSocketNotifier::Read );
    exit_notifier = new QSocketNotifier( term_get_file_descriptor(terminal), QSocketNotifier::Exception );
    cursor_timer = new QTimer( this );
    QObject::connect(notifier, SIGNAL(activated(int)), this, SLOT(terminal_data()));
    QObject::connect(exit_notifier, SIGNAL(activated(int)), this, SLOT(terminate()));
    QObject::connect(cursor_timer, SIGNAL(timeout()), this, SLOT(blink_cursor()));

    // Setup the initial font
    font = new QFont();
    font->setStyleHint(QFont::Courier);//QFont::TypeWriter);
    font->setPointSize(12);
    font->setStyleStrategy(QFont::NoAntialias);
    font->setFamily("Monospace");
    font->setFixedPitch(true);
    font->setKerning(false);

    // Workaround for a bug in OSX - Dave reports that maxWidth returns 0,
    // when width of different characters returns the correct value
    QFontMetrics metrics(*font);
    char_width = metrics.maxWidth();
    if(char_width==0) {
        fontWorkAround = true;
        char_width = metrics.width(QChar('X'));
    }

    char_height = metrics.lineSpacing();

#ifdef __QNX__
#ifdef BPS_VERSION
    virtualkeyboard_show();
#else
    BlackBerry::Keyboard::instance().show();
#endif
#endif
    cursor_timer->start(BLINK_SPEED);
}

QTerm::~QTerm()
{
    delete notifier;
    delete exit_notifier;
    term_free( terminal );
}

void QTerm::term_bell(term_t handle)
{
#ifdef __QNX__
    char command[] = "msg::play_sound\ndat:json:{\"sound\":\"notification_general\"}";
    int f = open("/pps/services/multimedia/sound/control", O_RDWR);
    write(f, command, sizeof(command));
    ::close(f);
#else
    QApplication::beep();
#endif
}

void QTerm::term_update(term_t handle, int x, int y, int width, int height)
{
    QTerm *term = (QTerm *)term_get_user_data( handle );

    term->update( x * term->char_width, y * term->char_height,
                  width * term->char_width, height * term->char_height + term->char_descent );
}

void QTerm::term_update_cursor(term_t handle, int x, int y)
{
    QTerm *term = (QTerm *)term_get_user_data( handle );

    // Update old cursor location
    term->update( term->cursor_x * term->char_width,
                  term->cursor_y * term->char_height,
                  term->char_width, term->char_height );

    term->cursor_x = x;
    term->cursor_y = y;

    // Update new cursor location
    term->update( term->cursor_x * term->char_width,
                  term->cursor_y * term->char_height,
                  term->char_width, term->char_height );
}

void QTerm::terminal_data()
{
    if( !term_process_child( terminal ) ) {
        exit(0);
    }
}

void QTerm::terminate()
{
    exit(0);
}

void QTerm::blink_cursor()
{
    int coord_x;
    cursor_on ^= 1;
    if (fontWorkAround) {
        // The update region may not be quite monospaced.
        int i;
        char str[WIDTH];
        const uint32_t **grid;
        QFontMetrics metrics(*font);

        grid = term_get_grid( terminal );
        for (i=0;i < WIDTH; i++) {
            str[i] = grid[cursor_y][i];
        }
        coord_x = metrics.width( QString(str),cursor_x );
    } else {
        coord_x = cursor_x * char_width;
    }
    update( coord_x,
                  cursor_y * char_height,
                  char_width, char_height );
}

void QTerm::paintEvent(QPaintEvent *event)
{
    int i, j, color;
    int new_width;
    int new_height;
    const uint32_t **grid;
    const uint32_t **attribs;
    const uint32_t **colors;
    QPainter painter(this);
    char str[WIDTH+1];
    int cursor_x_coord;
    QColor fgColor(255,255,255);
    QColor bgColor(0,0,0);

    int maxX=0;

    painter.setBackgroundMode(Qt::TransparentMode);
    painter.setBrush(QColor(8, 0, 0));
    painter.setFont( *font );

    // First erase the grid with its current dimensions
    painter.drawRect(event->rect());
    int x,y,w,h;
    event->rect().getRect(&x, &y, &w, &h);

    //fprintf(stderr,"Rect: (%d, %d) %d x %d\n", x,y,w,h);
    grid = term_get_grid( terminal );
    attribs = term_get_attribs( terminal );
    colors = term_get_colours( terminal );

    if (cursor_x < 0 || cursor_y < 0) {
        return;
    }
#if 1
    // Brute force convesion
    for(j=0;j<WIDTH;j++) {
        str[j]=grid[cursor_y][j];
    }
    // Workaround to get the cursor in the right spot.  For some
    // reason, on OSX (again), the monospace font does is not really
    // monospace for skinny characters!
    if (fontWorkAround) {
        cursor_x_coord = painter.fontMetrics().width(QString(str),cursor_x);
    } else {
        cursor_x_coord = cursor_x * char_width;
    }

    if ( cursor_on ) {
       painter.setPen(fgColor);
       painter.setBrush(fgColor);
       painter.drawRect( cursor_x_coord +1,
                         cursor_y * char_height + 1,
                         char_width-2, char_height-2);
    } else {
       painter.setPen(bgColor);
       painter.setBrush(bgColor);
       painter.drawRect( cursor_x_coord +1,
                         cursor_y * char_height + 1,
                         char_width-2, char_height-2);
    }
    painter.setPen(fgColor);
    painter.setBrush(fgColor);

    for (i=0; i<term_get_height( terminal );i++) {
        // Brute force convesion to 8-bit UTF
        for( j=0; j< term_get_width( terminal ); j++) {
            str[j]=grid[i][j];
        }
        str[term_get_width( terminal )]=0;
        painter.drawText(0, (i) * char_height,
                        w, char_height,
                        Qt::TextExpandTabs,
                        str,
                        NULL
                        );
    }

#else
    painter.setBrush(fgColor);
    for( i = 0; i < term_get_height( terminal ); i ++ ) {
        for( j = 0; j < term_get_width( terminal ); j ++ ) {
            if( cursor_on && j == cursor_x && i == cursor_y ) {
                painter.drawRect(j * char_width + 1, i * char_height + 1, char_width - 2, char_height - 2);
                painter.setPen(QColor(0, 0, 0));
                painter.drawText(j * char_width, (i + 1) * char_height - char_descent, QString( QChar( grid[ i ][ j ] ) ) );
                painter.setPen(QColor(255, 255, 255));
            } else {

                color = term_get_fg_color( attribs[ i ][ j ], colors[ i ][ j ] );
                painter.setPen(QColor((color >> 16) & 0xFF, (color >> 8) & 0xFF, color & 0xFF));
                painter.drawText(j * char_width, (i + 1) * char_height - char_descent, QString( QChar( grid[ i ][ j ] ) ) );
            }
        }
    }
#endif
}

void QTerm::keyPressEvent(QKeyEvent *event)
{
    switch(event->key()) {
        // FIXME These first two are a workaround for a bug in QT. Remove once it is fixed
        case Qt::Key_CapsLock:
        case Qt::Key_Shift:
            break;
        case Qt::Key_Up:
            term_send_special( terminal, TERM_KEY_UP );
            break;
        case Qt::Key_Down:
            term_send_special( terminal, TERM_KEY_DOWN );
            break;
        case Qt::Key_Right:
            term_send_special( terminal, TERM_KEY_RIGHT );
            break;
        case Qt::Key_Left:
            term_send_special( terminal, TERM_KEY_LEFT );
            break;
        default:
            term_send_data( terminal, event->text().toUtf8().constData(), event->text().count() );
            break;
    }
}

void QTerm::resizeEvent(QResizeEvent *event)
{
    if( char_width != 0 && char_height != 0 ) {
#ifdef __QNX__
        {
            int kbd_height;
#ifdef BPS_VERSION
            virtualkeyboard_get_height( &kbd_height );
#else
            kbd_height = BlackBerry::Keyboard::instance().keyboardHeight();
#endif
            term_resize( terminal, event->size().width() / char_width, (event->size().height() - kbd_height) / char_height, 0 );
        }
#else
        term_resize( terminal, event->size().width() / char_width, event->size().height() / char_height, 0 );
#endif
    }
}

int main(int argc, char *argv[])
{
    term_t terminal;

#ifdef __QNX__
#ifdef BPS_VERSION
    if( bps_initialize() != BPS_SUCCESS ) {
        fprintf(stderr, "Failed to initialize bps (%s)\n", strerror( errno ) );
        exit(1);
    }
#endif
#endif

    if( !term_create( &terminal ) ) {
        fprintf(stderr, "Failed to create terminal (%s)\n", strerror( errno ) );
        exit(1);
    }
    if( !term_begin( terminal, WIDTH, HEIGHT, 0 ) ) {
        fprintf(stderr, "Failed to begin terminal (%s)\n", strerror( errno ) );
        exit(1);
    }
    {
        QCoreApplication::addLibraryPath("app/native/lib");
        QApplication app(argc, argv);

        QTerm term(NULL, terminal);
        term.show();

        return app.exec();
    }
}
<commit_msg>Fix a couple uses of uninitialized variables. This fixes the crash I was seeing, and the descent problem<commit_after>#include <QPainter>
#include <QAbstractEventDispatcher>
#include <QApplication>
#include <QPaintEvent>
#include <QFontMetrics>
#include <QTextStream>
#include <qterm.h>
#include <stdio.h>
#include <QKeyEvent>
#include <QTimer>
#include <sys/select.h>
#include <errno.h>
#ifdef __QNX__
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <bps/bps.h>
#ifdef BPS_VERSION
#include <bps/virtualkeyboard.h>
#else
#include <bbsupport/Keyboard>
#include <bbsupport/Notification>
#endif
#endif

#define WIDTH    80
#define HEIGHT    17
#define BLINK_SPEED 1000

QTerm::QTerm(QWidget *parent) : QWidget(parent)
{
    term_create( &terminal );
    term_begin( terminal, WIDTH, HEIGHT, 0 );
    init();
}

QTerm::QTerm(QWidget *parent, term_t terminal) : QWidget(parent)
{
    this->terminal = terminal;
    init();
}

void QTerm::init()
{
    char_width = 0;
    char_height = 0;
    cursor_x = -1;
    cursor_y = -1;
    cursor_on = 1;

    resize(1024, 600);
    term_set_user_data( terminal, this );
    term_register_update( terminal, term_update );
    term_register_cursor( terminal, term_update_cursor );
    term_register_bell( terminal, term_bell );
    notifier = new QSocketNotifier( term_get_file_descriptor(terminal), QSocketNotifier::Read );
    exit_notifier = new QSocketNotifier( term_get_file_descriptor(terminal), QSocketNotifier::Exception );
    cursor_timer = new QTimer( this );
    QObject::connect(notifier, SIGNAL(activated(int)), this, SLOT(terminal_data()));
    QObject::connect(exit_notifier, SIGNAL(activated(int)), this, SLOT(terminate()));
    QObject::connect(cursor_timer, SIGNAL(timeout()), this, SLOT(blink_cursor()));

    // Setup the initial font
    font = new QFont();
    font->setStyleHint(QFont::Courier);//QFont::TypeWriter);
    font->setPointSize(12);
    font->setStyleStrategy(QFont::NoAntialias);
    font->setFamily("Monospace");
    font->setFixedPitch(true);
    font->setKerning(false);

    // Workaround for a bug in OSX - Dave reports that maxWidth returns 0,
    // when width of different characters returns the correct value
    QFontMetrics metrics(*font);
    char_width = metrics.maxWidth();
    if(char_width==0) {
        fontWorkAround = true;
        char_width = metrics.width(QChar('X'));
    } else {
        fontWorkAround = false;
    }

    char_height = metrics.lineSpacing();
    char_descent = metrics.descent();

#ifdef __QNX__
#ifdef BPS_VERSION
    virtualkeyboard_show();
#else
    BlackBerry::Keyboard::instance().show();
#endif
#endif
    cursor_timer->start(BLINK_SPEED);
}

QTerm::~QTerm()
{
    delete notifier;
    delete exit_notifier;
    term_free( terminal );
}

void QTerm::term_bell(term_t handle)
{
#ifdef __QNX__
    char command[] = "msg::play_sound\ndat:json:{\"sound\":\"notification_general\"}";
    int f = open("/pps/services/multimedia/sound/control", O_RDWR);
    write(f, command, sizeof(command));
    ::close(f);
#else
    QApplication::beep();
#endif
}

void QTerm::term_update(term_t handle, int x, int y, int width, int height)
{
    QTerm *term = (QTerm *)term_get_user_data( handle );

    term->update( x * term->char_width, y * term->char_height,
                  width * term->char_width, height * term->char_height + term->char_descent );
}

void QTerm::term_update_cursor(term_t handle, int x, int y)
{
    QTerm *term = (QTerm *)term_get_user_data( handle );

    // Update old cursor location
    term->update( term->cursor_x * term->char_width,
                  term->cursor_y * term->char_height,
                  term->char_width, term->char_height );

    term->cursor_x = x;
    term->cursor_y = y;

    // Update new cursor location
    term->update( term->cursor_x * term->char_width,
                  term->cursor_y * term->char_height,
                  term->char_width, term->char_height );
}

void QTerm::terminal_data()
{
    if( !term_process_child( terminal ) ) {
        exit(0);
    }
}

void QTerm::terminate()
{
    exit(0);
}

void QTerm::blink_cursor()
{
    int coord_x;
    cursor_on ^= 1;
    if (fontWorkAround) {
        // The update region may not be quite monospaced.
        int i;
        char str[WIDTH];
        const uint32_t **grid;
        QFontMetrics metrics(*font);

        grid = term_get_grid( terminal );
        for (i=0;i < WIDTH; i++) {
            str[i] = grid[cursor_y][i];
        }
        coord_x = metrics.width( QString(str),cursor_x );
    } else {
        coord_x = cursor_x * char_width;
    }
    update( coord_x,
                  cursor_y * char_height,
                  char_width, char_height );
}

void QTerm::paintEvent(QPaintEvent *event)
{
    int i, j, color;
    int new_width;
    int new_height;
    const uint32_t **grid;
    const uint32_t **attribs;
    const uint32_t **colors;
    QPainter painter(this);
    char str[WIDTH+1];
    int cursor_x_coord;
    QColor fgColor(255,255,255);
    QColor bgColor(0,0,0);

    int maxX=0;

    painter.setBackgroundMode(Qt::TransparentMode);
    painter.setBrush(QColor(8, 0, 0));
    painter.setFont( *font );

    // First erase the grid with its current dimensions
    painter.drawRect(event->rect());
    int x,y,w,h;
    event->rect().getRect(&x, &y, &w, &h);

    //fprintf(stderr,"Rect: (%d, %d) %d x %d\n", x,y,w,h);
    grid = term_get_grid( terminal );
    attribs = term_get_attribs( terminal );
    colors = term_get_colours( terminal );

    if (cursor_x < 0 || cursor_y < 0) {
        return;
    }
#if 1
    // Brute force convesion
    for(j=0;j<WIDTH;j++) {
        str[j]=grid[cursor_y][j];
    }
    // Workaround to get the cursor in the right spot.  For some
    // reason, on OSX (again), the monospace font does is not really
    // monospace for skinny characters!
    if (fontWorkAround) {
        cursor_x_coord = painter.fontMetrics().width(QString(str),cursor_x);
    } else {
        cursor_x_coord = cursor_x * char_width;
    }

    if ( cursor_on ) {
       painter.setPen(fgColor);
       painter.setBrush(fgColor);
       painter.drawRect( cursor_x_coord +1,
                         cursor_y * char_height + 1,
                         char_width-2, char_height-2);
    } else {
       painter.setPen(bgColor);
       painter.setBrush(bgColor);
       painter.drawRect( cursor_x_coord +1,
                         cursor_y * char_height + 1,
                         char_width-2, char_height-2);
    }
    painter.setPen(fgColor);
    painter.setBrush(fgColor);

    for (i=0; i<term_get_height( terminal );i++) {
        // Brute force convesion to 8-bit UTF
        for( j=0; j< term_get_width( terminal ); j++) {
            str[j]=grid[i][j];
        }
        str[term_get_width( terminal )]=0;
        painter.drawText(0, (i) * char_height,
                        w, char_height,
                        Qt::TextExpandTabs,
                        str,
                        NULL
                        );
    }

#else
    painter.setBrush(fgColor);
    for( i = 0; i < term_get_height( terminal ); i ++ ) {
        for( j = 0; j < term_get_width( terminal ); j ++ ) {
            if( cursor_on && j == cursor_x && i == cursor_y ) {
                painter.drawRect(j * char_width + 1, i * char_height + 1, char_width - 2, char_height - 2);
                painter.setPen(QColor(0, 0, 0));
                painter.drawText(j * char_width, (i + 1) * char_height - char_descent, QString( QChar( grid[ i ][ j ] ) ) );
                painter.setPen(QColor(255, 255, 255));
            } else {

                color = term_get_fg_color( attribs[ i ][ j ], colors[ i ][ j ] );
                painter.setPen(QColor((color >> 16) & 0xFF, (color >> 8) & 0xFF, color & 0xFF));
                painter.drawText(j * char_width, (i + 1) * char_height - char_descent, QString( QChar( grid[ i ][ j ] ) ) );
            }
        }
    }
#endif
}

void QTerm::keyPressEvent(QKeyEvent *event)
{
    switch(event->key()) {
        // FIXME These first two are a workaround for a bug in QT. Remove once it is fixed
        case Qt::Key_CapsLock:
        case Qt::Key_Shift:
            break;
        case Qt::Key_Up:
            term_send_special( terminal, TERM_KEY_UP );
            break;
        case Qt::Key_Down:
            term_send_special( terminal, TERM_KEY_DOWN );
            break;
        case Qt::Key_Right:
            term_send_special( terminal, TERM_KEY_RIGHT );
            break;
        case Qt::Key_Left:
            term_send_special( terminal, TERM_KEY_LEFT );
            break;
        default:
            term_send_data( terminal, event->text().toUtf8().constData(), event->text().count() );
            break;
    }
}

void QTerm::resizeEvent(QResizeEvent *event)
{
    if( char_width != 0 && char_height != 0 ) {
#ifdef __QNX__
        {
            int kbd_height;
#ifdef BPS_VERSION
            virtualkeyboard_get_height( &kbd_height );
#else
            kbd_height = BlackBerry::Keyboard::instance().keyboardHeight();
#endif
            term_resize( terminal, event->size().width() / char_width, (event->size().height() - kbd_height) / char_height, 0 );
        }
#else
        term_resize( terminal, event->size().width() / char_width, event->size().height() / char_height, 0 );
#endif
    }
}

int main(int argc, char *argv[])
{
    term_t terminal;

#ifdef __QNX__
#ifdef BPS_VERSION
    if( bps_initialize() != BPS_SUCCESS ) {
        fprintf(stderr, "Failed to initialize bps (%s)\n", strerror( errno ) );
        exit(1);
    }
#endif
#endif

    if( !term_create( &terminal ) ) {
        fprintf(stderr, "Failed to create terminal (%s)\n", strerror( errno ) );
        exit(1);
    }
    if( !term_begin( terminal, WIDTH, HEIGHT, 0 ) ) {
        fprintf(stderr, "Failed to begin terminal (%s)\n", strerror( errno ) );
        exit(1);
    }
    {
        QCoreApplication::addLibraryPath("app/native/lib");
        QApplication app(argc, argv);

        QTerm term(NULL, terminal);
        term.show();

        return app.exec();
    }
}
<|endoftext|>


<commit_before>
#include "ImwPlatformWindow.h"

#include "ImwWindowManager.h"
#include <imgui/imgui.h>
#include <imgui/imgui_internal.h>

using namespace ImWindow;

ImwPlatformWindow::ImwPlatformWindow(bool bMain, bool bIsDragWindow)
{
	m_bMain = bMain;
	m_bIsDragWindow = bIsDragWindow;
	m_pContainer = new ImwContainer(this);
	m_pState = NULL;
	m_pPreviousState = NULL;

	void* pTemp = ImGui::GetInternalState();
	m_pState = ImwMalloc(ImGui::GetInternalStateSize());
	ImGui::SetInternalState(m_pState, true);
	ImGui::SetInternalState(pTemp);
}

ImwPlatformWindow::~ImwPlatformWindow()
{
	ImwSafeDelete(m_pContainer);

	SetState();
	if (!IsMain())
	{
		ImGui::GetIO().Fonts = NULL;
	}
	ImGui::Shutdown();
	RestoreState();
	ImwSafeDelete(m_pState);
}

void ImwPlatformWindow::OnClose()
{
	ImwWindowManager::GetInstance()->OnClosePlatformWindow(this);
}

static bool s_bStatePush = false;

bool ImwPlatformWindow::IsStateSet()
{
	return s_bStatePush;
}

void ImwPlatformWindow::SetState()
{
	ImwAssert(s_bStatePush == false);
	s_bStatePush = true;
	m_pPreviousState = ImGui::GetInternalState();
	ImGui::SetInternalState(m_pState);
	memcpy(&((ImGuiState*)m_pState)->Style, &((ImGuiState*)m_pPreviousState)->Style, sizeof(ImGuiStyle));
}

void ImwPlatformWindow::RestoreState()
{
	ImwAssert(s_bStatePush == true);
	s_bStatePush = false;
	memcpy(&((ImGuiState*)m_pPreviousState)->Style, &((ImGuiState*)m_pState)->Style, sizeof(ImGuiStyle));
	ImGui::SetInternalState(m_pPreviousState);
}

void ImwPlatformWindow::OnLoseFocus()
{
	ImGuiState& g = *((ImGuiState*)m_pState);
	g.SetNextWindowPosCond = g.SetNextWindowSizeCond = g.SetNextWindowContentSizeCond = g.SetNextWindowCollapsedCond = g.SetNextWindowFocus = 0;
}

void ImwPlatformWindow::Paint()
{
	ImwWindowManager::GetInstance()->Paint(this);
}

bool ImwPlatformWindow::IsMain()
{
	return m_bMain;
}

void ImwPlatformWindow::Dock(ImwWindow* pWindow)
{
	m_pContainer->Dock(pWindow);
}

bool ImwPlatformWindow::UnDock(ImwWindow* pWindow)
{
	return m_pContainer->UnDock(pWindow);
}

ImwContainer* ImwPlatformWindow::GetContainer()
{
	return m_pContainer;
}

ImwContainer* ImwPlatformWindow::HasWindow(ImwWindow* pWindow)
{
	return m_pContainer->HasWindow(pWindow);
}

void ImwPlatformWindow::PaintContainer()
{
	m_pContainer->Paint();
}
<commit_msg>Never create imgui.ini<commit_after>
#include "ImwPlatformWindow.h"

#include "ImwWindowManager.h"
#include <imgui/imgui.h>
#include <imgui/imgui_internal.h>

using namespace ImWindow;

ImwPlatformWindow::ImwPlatformWindow(bool bMain, bool bIsDragWindow)
{
	m_bMain = bMain;
	m_bIsDragWindow = bIsDragWindow;
	m_pContainer = new ImwContainer(this);
	m_pState = NULL;
	m_pPreviousState = NULL;

	void* pTemp = ImGui::GetInternalState();
	m_pState = ImwMalloc(ImGui::GetInternalStateSize());
	ImGui::SetInternalState(m_pState, true);
	ImGui::GetIO().IniFilename = NULL;
	ImGui::SetInternalState(pTemp);
}

ImwPlatformWindow::~ImwPlatformWindow()
{
	ImwSafeDelete(m_pContainer);

	SetState();
	if (!IsMain())
	{
		ImGui::GetIO().Fonts = NULL;
	}
	ImGui::Shutdown();
	RestoreState();
	ImwSafeDelete(m_pState);
}

void ImwPlatformWindow::OnClose()
{
	ImwWindowManager::GetInstance()->OnClosePlatformWindow(this);
}

static bool s_bStatePush = false;

bool ImwPlatformWindow::IsStateSet()
{
	return s_bStatePush;
}

void ImwPlatformWindow::SetState()
{
	ImwAssert(s_bStatePush == false);
	s_bStatePush = true;
	m_pPreviousState = ImGui::GetInternalState();
	ImGui::SetInternalState(m_pState);
	memcpy(&((ImGuiState*)m_pState)->Style, &((ImGuiState*)m_pPreviousState)->Style, sizeof(ImGuiStyle));
}

void ImwPlatformWindow::RestoreState()
{
	ImwAssert(s_bStatePush == true);
	s_bStatePush = false;
	memcpy(&((ImGuiState*)m_pPreviousState)->Style, &((ImGuiState*)m_pState)->Style, sizeof(ImGuiStyle));
	ImGui::SetInternalState(m_pPreviousState);
}

void ImwPlatformWindow::OnLoseFocus()
{
	ImGuiState& g = *((ImGuiState*)m_pState);
	g.SetNextWindowPosCond = g.SetNextWindowSizeCond = g.SetNextWindowContentSizeCond = g.SetNextWindowCollapsedCond = g.SetNextWindowFocus = 0;
}

void ImwPlatformWindow::Paint()
{
	ImwWindowManager::GetInstance()->Paint(this);
}

bool ImwPlatformWindow::IsMain()
{
	return m_bMain;
}

void ImwPlatformWindow::Dock(ImwWindow* pWindow)
{
	m_pContainer->Dock(pWindow);
}

bool ImwPlatformWindow::UnDock(ImwWindow* pWindow)
{
	return m_pContainer->UnDock(pWindow);
}

ImwContainer* ImwPlatformWindow::GetContainer()
{
	return m_pContainer;
}

ImwContainer* ImwPlatformWindow::HasWindow(ImwWindow* pWindow)
{
	return m_pContainer->HasWindow(pWindow);
}

void ImwPlatformWindow::PaintContainer()
{
	m_pContainer->Paint();
}
<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    vtkImageAccumulate.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$
  Thanks:    Thanks to C. Charles Law who developed this class.

Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen
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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
   of any contributors may be used to endorse or promote products derived
   from this software without specific prior written permission.

 * Modified source versions must be plainly marked as such, and must not be
   misrepresented as being the original software.

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 AUTHORS 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 "vtkImageAccumulate.h"
#include <math.h>
#include <stdlib.h>
#include "vtkObjectFactory.h"

//----------------------------------------------------------------------------
vtkImageAccumulate* vtkImageAccumulate::New()
{
  // First try to create the object from the vtkObjectFactory
  vtkObject* ret = vtkObjectFactory::CreateInstance("vtkImageAccumulate");
  if(ret)
    {
    return (vtkImageAccumulate*)ret;
    }
  // If the factory was unable to create the object, then create it here.
  return new vtkImageAccumulate;
}

//----------------------------------------------------------------------------
// Constructor sets default values
vtkImageAccumulate::vtkImageAccumulate()
{
  int idx;

  for (idx = 0; idx < 3; ++idx)
    {
    this->ComponentSpacing[idx] = 1.0;
    this->ComponentOrigin[idx] = 0.0;
    this->ComponentExtent[idx*2] = 0;
    this->ComponentExtent[idx*2+1] = 0;
    }
  this->ComponentExtent[1] = 255;

  this->ReverseStencil = 0;

  this->Min[0] = this->Min[1] = this->Min[2] = 0.0;
  this->Max[0] = this->Max[1] = this->Max[2] = 0.0;
  this->Mean[0] = this->Mean[1] = this->Mean[2] = 0.0;
  this->StandardDeviation[0] = this->StandardDeviation[1] = this->StandardDeviation[2] = 0.0;
  this->VoxelCount = 0;
}

//----------------------------------------------------------------------------
vtkImageAccumulate::~vtkImageAccumulate()
{
}

//----------------------------------------------------------------------------
void vtkImageAccumulate::SetComponentExtent(int extent[6])
{
  int idx, modified = 0;

  for (idx = 0; idx < 6; ++idx)
    {
    if (this->ComponentExtent[idx] != extent[idx])
      {
      this->ComponentExtent[idx] = extent[idx];
      this->Modified();
      }
    }
  if (modified)
    {
    this->Modified();
    }
}

//----------------------------------------------------------------------------
void vtkImageAccumulate::SetComponentExtent(int minX, int maxX,
                                            int minY, int maxY,
                                            int minZ, int maxZ)
{
  int extent[6];

  extent[0] = minX;  extent[1] = maxX;
  extent[2] = minY;  extent[3] = maxY;
  extent[4] = minZ;  extent[5] = maxZ;
  this->SetComponentExtent(extent);
}

//----------------------------------------------------------------------------
void vtkImageAccumulate::GetComponentExtent(int extent[6])
{
  int idx;

  for (idx = 0; idx < 6; ++idx)
    {
    extent[idx] = this->ComponentExtent[idx];
    }
}

//----------------------------------------------------------------------------
void vtkImageAccumulate::SetStencil(vtkImageStencilData *stencil)
{
  this->vtkProcessObject::SetNthInput(1, stencil);
}

//----------------------------------------------------------------------------
vtkImageStencilData *vtkImageAccumulate::GetStencil()
{
  if (this->NumberOfInputs < 2)
    {
    return NULL;
    }
  else
    {
    return (vtkImageStencilData *)(this->Inputs[1]);
    }
}

//----------------------------------------------------------------------------
// This templated function executes the filter for any type of data.
template <class T>
static void vtkImageAccumulateExecute(vtkImageAccumulate *self,
                                      vtkImageData *inData, T *inPtr,
                                      vtkImageData *outData, int *outPtr,
                                      double Min[3],
                                      double Max[3],
                                      double Mean[3],
                                      long int *VoxelCount)
{
  int idX, idY, idZ, idxC;
  int iter, pmin0, pmax0, min0, max0, min1, max1, min2, max2;
  int inInc0, inInc1, inInc2;
  T *tempPtr;
  int *outPtrC;
  int numC, outIdx, *outExtent, *outIncs;
  float *origin, *spacing;
  unsigned long count = 0;
  unsigned long target;
  double sumSqr[3], variance;

  // variables used to compute statistics (filter handles max 3 components)
  double sum[3];
  sum[0] = sum[1] = sum[2] = 0.0;
  Min[0] = Min[1] = Min[2] = VTK_DOUBLE_MAX;
  Max[0] = Max[1] = Max[2] = VTK_DOUBLE_MIN;
  sumSqr[0] = sumSqr[1] = sumSqr[2] = 0.0;
  StandardDeviation[0] = StandardDeviation[1] = StandardDeviation[2] = 0.0;
  *VoxelCount = 0;

  vtkImageStencilData *stencil = self->GetStencil();

  // Zero count in every bin
  outData->GetExtent(min0, max0, min1, max1, min2, max2);
  memset((void *)outPtr, 0,
         (max0-min0+1)*(max1-min1+1)*(max2-min2+1)*sizeof(int));

  // Get information to march through data
  numC = inData->GetNumberOfScalarComponents();
  inData->GetUpdateExtent(min0, max0, min1, max1, min2, max2);
  inData->GetIncrements(inInc0, inInc1, inInc2);
  outExtent = outData->GetExtent();
  outIncs = outData->GetIncrements();
  origin = outData->GetOrigin();
  spacing = outData->GetSpacing();

  target = (unsigned long)((max2 - min2 + 1)*(max1 - min1 +1)/50.0);
  target++;

  // Loop through input pixels
  for (idZ = min2; idZ <= max2; idZ++)
    {
    for (idY = min1; idY <= max1; idY++)
      {
      if (!(count%target))
        {
        self->UpdateProgress(count/(50.0*target));
        }
      count++;

      // loop over stencil sub-extents
      iter = 0;
      if (self->GetReverseStencil())
        { // flag that we want the complementary extents
        iter = -1;
        }

      pmin0 = min0;
      pmax0 = max0;
      while ((stencil != 0 &&
              stencil->GetNextExtent(pmin0,pmax0,min0,max0,idY,idZ,iter)) ||
             (stencil == 0 && iter++ == 0))
        {
        // set up pointer for sub extent
        tempPtr = inPtr + (inInc2*(idZ - min2) +
                           inInc1*(idY - min1) +
                           numC*(pmin0 - min0));

        // accumulate over the sub extent
        for (idX = pmin0; idX <= pmax0; idX++)
          {
          // find the bin for this pixel.
          outPtrC = outPtr;
          for (idxC = 0; idxC < numC; ++idxC)
            {
            // Gather statistics
            sum[idxC]+= *tempPtr;
            if (*tempPtr > Max[idxC])
              {
              Max[idxC] = *tempPtr;
              }
            else if (*tempPtr < Min[idxC])
              {
              Min[idxC] = *tempPtr;
              }
            (*VoxelCount)++;
            // compute the index
            outIdx = (int) floor((((double)*tempPtr++ - origin[idxC])
                                  / spacing[idxC]));
            if (outIdx < outExtent[idxC*2] || outIdx > outExtent[idxC*2+1])
              {
              // Out of bin range
              outPtrC = NULL;
              break;
              }
            outPtrC += (outIdx - outExtent[idxC*2]) * outIncs[idxC];
            }
          if (outPtrC)
            {
            ++(*outPtrC);
            }
          }
        }
      }
    }

  if (*VoxelCount) // avoid the div0
    {
    Mean[0] = sum[0] / (double)*VoxelCount;
    Mean[1] = sum[1] / (double)*VoxelCount;
    Mean[2] = sum[2] / (double)*VoxelCount;
    variance = sumSqr[0] / (double)*VoxelCount - ((double) *VoxelCount * Mean[0] * Mean[0] / (double) (*VoxelCount - 1));
    StandardDeviation[1] = sqrt(variance);
    variance = sumSqr[1] / (double)*VoxelCount - ((double) *VoxelCount * Mean[1] * Mean[1] / (double) (*VoxelCount - 1));
    StandardDeviation[1] = sqrt(variance);
    variance = sumSqr[2] / (double)*VoxelCount - ((double) *VoxelCount * Mean[2] * Mean[2] / (double) (*VoxelCount - 1));
    StandardDeviation[2] = sqrt(variance);
    }
  else
    {
    Mean[0] = Mean[1] = Mean[2] = 0.0;
    StandardDeviation[0] = StandardDeviation[1] = StandardDeviation[2] = 0.0;
    }

}

//----------------------------------------------------------------------------
// This method is passed a input and output Data, and executes the filter
// algorithm to fill the output from the input.
// It just executes a switch statement to call the correct function for
// the Datas data types.
void vtkImageAccumulate::ExecuteData(vtkDataObject *vtkNotUsed(out))
{
  void *inPtr;
  void *outPtr;
  vtkImageData *inData = this->GetInput();
  vtkImageData *outData = this->GetOutput();

  vtkDebugMacro(<<"Executing image accumulate");

  // We need to allocate our own scalars since we are overriding
  // the superclasses "Execute()" method.
  outData->SetExtent(outData->GetWholeExtent());
  outData->AllocateScalars();

  inPtr = inData->GetScalarPointerForExtent(inData->GetUpdateExtent());
  outPtr = outData->GetScalarPointer();

  // Components turned into x, y and z
  if (this->GetInput()->GetNumberOfScalarComponents() > 3)
    {
    vtkErrorMacro("This filter can handle upto 3 components");
    return;
    }

  // this filter expects that output is type int.
  if (outData->GetScalarType() != VTK_INT)
    {
    vtkErrorMacro(<< "Execute: out ScalarType " << outData->GetScalarType()
                  << " must be int\n");
    return;
    }

  switch (inData->GetScalarType())
    {
    vtkTemplateMacro10(vtkImageAccumulateExecute, this,
                       inData, (VTK_TT *)(inPtr),
                       outData, (int *)(outPtr),
                       this->Min, this->Max,
                       this->Mean,
                       this->StandardDeviation, &this->VoxelCount);
    default:
      vtkErrorMacro(<< "Execute: Unknown ScalarType");
      return;
    }
}

//----------------------------------------------------------------------------
void vtkImageAccumulate::ExecuteInformation(vtkImageData *input,
                                            vtkImageData *output)
{
  output->SetWholeExtent(this->ComponentExtent);
  output->SetOrigin(this->ComponentOrigin);
  output->SetSpacing(this->ComponentSpacing);
  output->SetNumberOfScalarComponents(1);
  output->SetScalarType(VTK_INT);

  // need to set the spacing and origin of the stencil to match the output
  vtkImageStencilData *stencil = this->GetStencil();
  if (stencil)
    {
    stencil->SetSpacing(input->GetSpacing());
    stencil->SetOrigin(input->GetOrigin());
    }
}

//----------------------------------------------------------------------------
// Get ALL of the input.
void vtkImageAccumulate::ComputeInputUpdateExtent(int inExt[6],
                                                  int outExt[6])
{
  int *wholeExtent;

  outExt = outExt;
  wholeExtent = this->GetInput()->GetWholeExtent();
  memcpy(inExt, wholeExtent, 6*sizeof(int));
}

void vtkImageAccumulate::PrintSelf(ostream& os, vtkIndent indent)
{
  vtkImageToImageFilter::PrintSelf(os,indent);

  os << indent << "Mean: " << this->Mean << "\n";
  os << indent << "Min: " << this->Min << "\n";
  os << indent << "Max: " << this->Max << "\n";
  os << indent << "StandardDeviation: " << this->StandardDeviation << "\n";
  os << indent << "VoxelCount: " << this->VoxelCount << "\n";
  os << indent << "Stencil: " << this->GetStencil() << "\n";
  os << indent << "ReverseStencil: " << (this->ReverseStencil ?
                                         "On\n" : "Off\n");

  os << indent << "ComponentOrigin: ( "
     << this->ComponentOrigin[0] << ", "
     << this->ComponentOrigin[1] << ", "
     << this->ComponentOrigin[2] << " )\n";

  os << indent << "ComponentSpacing: ( "
     << this->ComponentSpacing[0] << ", "
     << this->ComponentSpacing[1] << ", "
     << this->ComponentSpacing[2] << " )\n";

  os << indent << "ComponentExtent: ( "
     << this->ComponentExtent[0] << "," << this->ComponentExtent[1] << " "
     << this->ComponentExtent[2] << "," << this->ComponentExtent[3] << " "
     << this->ComponentExtent[4] << "," << this->ComponentExtent[5] << " }\n";
}

<commit_msg>ERR: bad method signature.<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkImageAccumulate.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$
  Thanks:    Thanks to C. Charles Law who developed this class.

Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen
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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
   of any contributors may be used to endorse or promote products derived
   from this software without specific prior written permission.

 * Modified source versions must be plainly marked as such, and must not be
   misrepresented as being the original software.

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 AUTHORS 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 "vtkImageAccumulate.h"
#include <math.h>
#include <stdlib.h>
#include "vtkObjectFactory.h"

//----------------------------------------------------------------------------
vtkImageAccumulate* vtkImageAccumulate::New()
{
  // First try to create the object from the vtkObjectFactory
  vtkObject* ret = vtkObjectFactory::CreateInstance("vtkImageAccumulate");
  if(ret)
    {
    return (vtkImageAccumulate*)ret;
    }
  // If the factory was unable to create the object, then create it here.
  return new vtkImageAccumulate;
}

//----------------------------------------------------------------------------
// Constructor sets default values
vtkImageAccumulate::vtkImageAccumulate()
{
  int idx;

  for (idx = 0; idx < 3; ++idx)
    {
    this->ComponentSpacing[idx] = 1.0;
    this->ComponentOrigin[idx] = 0.0;
    this->ComponentExtent[idx*2] = 0;
    this->ComponentExtent[idx*2+1] = 0;
    }
  this->ComponentExtent[1] = 255;

  this->ReverseStencil = 0;

  this->Min[0] = this->Min[1] = this->Min[2] = 0.0;
  this->Max[0] = this->Max[1] = this->Max[2] = 0.0;
  this->Mean[0] = this->Mean[1] = this->Mean[2] = 0.0;
  this->StandardDeviation[0] = this->StandardDeviation[1] = this->StandardDeviation[2] = 0.0;
  this->VoxelCount = 0;
}

//----------------------------------------------------------------------------
vtkImageAccumulate::~vtkImageAccumulate()
{
}

//----------------------------------------------------------------------------
void vtkImageAccumulate::SetComponentExtent(int extent[6])
{
  int idx, modified = 0;

  for (idx = 0; idx < 6; ++idx)
    {
    if (this->ComponentExtent[idx] != extent[idx])
      {
      this->ComponentExtent[idx] = extent[idx];
      this->Modified();
      }
    }
  if (modified)
    {
    this->Modified();
    }
}

//----------------------------------------------------------------------------
void vtkImageAccumulate::SetComponentExtent(int minX, int maxX,
                                            int minY, int maxY,
                                            int minZ, int maxZ)
{
  int extent[6];

  extent[0] = minX;  extent[1] = maxX;
  extent[2] = minY;  extent[3] = maxY;
  extent[4] = minZ;  extent[5] = maxZ;
  this->SetComponentExtent(extent);
}

//----------------------------------------------------------------------------
void vtkImageAccumulate::GetComponentExtent(int extent[6])
{
  int idx;

  for (idx = 0; idx < 6; ++idx)
    {
    extent[idx] = this->ComponentExtent[idx];
    }
}

//----------------------------------------------------------------------------
void vtkImageAccumulate::SetStencil(vtkImageStencilData *stencil)
{
  this->vtkProcessObject::SetNthInput(1, stencil);
}

//----------------------------------------------------------------------------
vtkImageStencilData *vtkImageAccumulate::GetStencil()
{
  if (this->NumberOfInputs < 2)
    {
    return NULL;
    }
  else
    {
    return (vtkImageStencilData *)(this->Inputs[1]);
    }
}

//----------------------------------------------------------------------------
// This templated function executes the filter for any type of data.
template <class T>
static void vtkImageAccumulateExecute(vtkImageAccumulate *self,
                                      vtkImageData *inData, T *inPtr,
                                      vtkImageData *outData, int *outPtr,
                                      double Min[3],
                                      double Max[3],
                                      double Mean[3],
                                      double StandardDeviation[3],
                                      long int *VoxelCount)
{
  int idX, idY, idZ, idxC;
  int iter, pmin0, pmax0, min0, max0, min1, max1, min2, max2;
  int inInc0, inInc1, inInc2;
  T *tempPtr;
  int *outPtrC;
  int numC, outIdx, *outExtent, *outIncs;
  float *origin, *spacing;
  unsigned long count = 0;
  unsigned long target;
  double sumSqr[3], variance;

  // variables used to compute statistics (filter handles max 3 components)
  double sum[3];
  sum[0] = sum[1] = sum[2] = 0.0;
  Min[0] = Min[1] = Min[2] = VTK_DOUBLE_MAX;
  Max[0] = Max[1] = Max[2] = VTK_DOUBLE_MIN;
  sumSqr[0] = sumSqr[1] = sumSqr[2] = 0.0;
  StandardDeviation[0] = StandardDeviation[1] = StandardDeviation[2] = 0.0;
  *VoxelCount = 0;

  vtkImageStencilData *stencil = self->GetStencil();

  // Zero count in every bin
  outData->GetExtent(min0, max0, min1, max1, min2, max2);
  memset((void *)outPtr, 0,
         (max0-min0+1)*(max1-min1+1)*(max2-min2+1)*sizeof(int));

  // Get information to march through data
  numC = inData->GetNumberOfScalarComponents();
  inData->GetUpdateExtent(min0, max0, min1, max1, min2, max2);
  inData->GetIncrements(inInc0, inInc1, inInc2);
  outExtent = outData->GetExtent();
  outIncs = outData->GetIncrements();
  origin = outData->GetOrigin();
  spacing = outData->GetSpacing();

  target = (unsigned long)((max2 - min2 + 1)*(max1 - min1 +1)/50.0);
  target++;

  // Loop through input pixels
  for (idZ = min2; idZ <= max2; idZ++)
    {
    for (idY = min1; idY <= max1; idY++)
      {
      if (!(count%target))
        {
        self->UpdateProgress(count/(50.0*target));
        }
      count++;

      // loop over stencil sub-extents
      iter = 0;
      if (self->GetReverseStencil())
        { // flag that we want the complementary extents
        iter = -1;
        }

      pmin0 = min0;
      pmax0 = max0;
      while ((stencil != 0 &&
              stencil->GetNextExtent(pmin0,pmax0,min0,max0,idY,idZ,iter)) ||
             (stencil == 0 && iter++ == 0))
        {
        // set up pointer for sub extent
        tempPtr = inPtr + (inInc2*(idZ - min2) +
                           inInc1*(idY - min1) +
                           numC*(pmin0 - min0));

        // accumulate over the sub extent
        for (idX = pmin0; idX <= pmax0; idX++)
          {
          // find the bin for this pixel.
          outPtrC = outPtr;
          for (idxC = 0; idxC < numC; ++idxC)
            {
            // Gather statistics
            sum[idxC]+= *tempPtr;
            if (*tempPtr > Max[idxC])
              {
              Max[idxC] = *tempPtr;
              }
            else if (*tempPtr < Min[idxC])
              {
              Min[idxC] = *tempPtr;
              }
            (*VoxelCount)++;
            // compute the index
            outIdx = (int) floor((((double)*tempPtr++ - origin[idxC])
                                  / spacing[idxC]));
            if (outIdx < outExtent[idxC*2] || outIdx > outExtent[idxC*2+1])
              {
              // Out of bin range
              outPtrC = NULL;
              break;
              }
            outPtrC += (outIdx - outExtent[idxC*2]) * outIncs[idxC];
            }
          if (outPtrC)
            {
            ++(*outPtrC);
            }
          }
        }
      }
    }

  if (*VoxelCount) // avoid the div0
    {
    Mean[0] = sum[0] / (double)*VoxelCount;
    Mean[1] = sum[1] / (double)*VoxelCount;
    Mean[2] = sum[2] / (double)*VoxelCount;
    variance = sumSqr[0] / (double)*VoxelCount - ((double) *VoxelCount * Mean[0] * Mean[0] / (double) (*VoxelCount - 1));
    StandardDeviation[1] = sqrt(variance);
    variance = sumSqr[1] / (double)*VoxelCount - ((double) *VoxelCount * Mean[1] * Mean[1] / (double) (*VoxelCount - 1));
    StandardDeviation[1] = sqrt(variance);
    variance = sumSqr[2] / (double)*VoxelCount - ((double) *VoxelCount * Mean[2] * Mean[2] / (double) (*VoxelCount - 1));
    StandardDeviation[2] = sqrt(variance);
    }
  else
    {
    Mean[0] = Mean[1] = Mean[2] = 0.0;
    StandardDeviation[0] = StandardDeviation[1] = StandardDeviation[2] = 0.0;
    }

}

//----------------------------------------------------------------------------
// This method is passed a input and output Data, and executes the filter
// algorithm to fill the output from the input.
// It just executes a switch statement to call the correct function for
// the Datas data types.
void vtkImageAccumulate::ExecuteData(vtkDataObject *vtkNotUsed(out))
{
  void *inPtr;
  void *outPtr;
  vtkImageData *inData = this->GetInput();
  vtkImageData *outData = this->GetOutput();

  vtkDebugMacro(<<"Executing image accumulate");

  // We need to allocate our own scalars since we are overriding
  // the superclasses "Execute()" method.
  outData->SetExtent(outData->GetWholeExtent());
  outData->AllocateScalars();

  inPtr = inData->GetScalarPointerForExtent(inData->GetUpdateExtent());
  outPtr = outData->GetScalarPointer();

  // Components turned into x, y and z
  if (this->GetInput()->GetNumberOfScalarComponents() > 3)
    {
    vtkErrorMacro("This filter can handle upto 3 components");
    return;
    }

  // this filter expects that output is type int.
  if (outData->GetScalarType() != VTK_INT)
    {
    vtkErrorMacro(<< "Execute: out ScalarType " << outData->GetScalarType()
                  << " must be int\n");
    return;
    }

  switch (inData->GetScalarType())
    {
    vtkTemplateMacro10(vtkImageAccumulateExecute, this,
                       inData, (VTK_TT *)(inPtr),
                       outData, (int *)(outPtr),
                       this->Min, this->Max,
                       this->Mean,
                       this->StandardDeviation, &this->VoxelCount);
    default:
      vtkErrorMacro(<< "Execute: Unknown ScalarType");
      return;
    }
}

//----------------------------------------------------------------------------
void vtkImageAccumulate::ExecuteInformation(vtkImageData *input,
                                            vtkImageData *output)
{
  output->SetWholeExtent(this->ComponentExtent);
  output->SetOrigin(this->ComponentOrigin);
  output->SetSpacing(this->ComponentSpacing);
  output->SetNumberOfScalarComponents(1);
  output->SetScalarType(VTK_INT);

  // need to set the spacing and origin of the stencil to match the output
  vtkImageStencilData *stencil = this->GetStencil();
  if (stencil)
    {
    stencil->SetSpacing(input->GetSpacing());
    stencil->SetOrigin(input->GetOrigin());
    }
}

//----------------------------------------------------------------------------
// Get ALL of the input.
void vtkImageAccumulate::ComputeInputUpdateExtent(int inExt[6],
                                                  int outExt[6])
{
  int *wholeExtent;

  outExt = outExt;
  wholeExtent = this->GetInput()->GetWholeExtent();
  memcpy(inExt, wholeExtent, 6*sizeof(int));
}

void vtkImageAccumulate::PrintSelf(ostream& os, vtkIndent indent)
{
  vtkImageToImageFilter::PrintSelf(os,indent);

  os << indent << "Mean: " << this->Mean << "\n";
  os << indent << "Min: " << this->Min << "\n";
  os << indent << "Max: " << this->Max << "\n";
  os << indent << "StandardDeviation: " << this->StandardDeviation << "\n";
  os << indent << "VoxelCount: " << this->VoxelCount << "\n";
  os << indent << "Stencil: " << this->GetStencil() << "\n";
  os << indent << "ReverseStencil: " << (this->ReverseStencil ?
                                         "On\n" : "Off\n");

  os << indent << "ComponentOrigin: ( "
     << this->ComponentOrigin[0] << ", "
     << this->ComponentOrigin[1] << ", "
     << this->ComponentOrigin[2] << " )\n";

  os << indent << "ComponentSpacing: ( "
     << this->ComponentSpacing[0] << ", "
     << this->ComponentSpacing[1] << ", "
     << this->ComponentSpacing[2] << " )\n";

  os << indent << "ComponentExtent: ( "
     << this->ComponentExtent[0] << "," << this->ComponentExtent[1] << " "
     << this->ComponentExtent[2] << "," << this->ComponentExtent[3] << " "
     << this->ComponentExtent[4] << "," << this->ComponentExtent[5] << " }\n";
}

<|endoftext|>