<commit_before>#include "console.h"
#include "variables.h"
#include "command.h"
#include "special_command.h"
#include "alias.h"
#include "util/text.h"
#include "util/macros.h"
#include "consoleitem.h"

#include "console-grammar.h"
#include "gusanos/allegro.h"

#include <algorithm>
#include <fstream>
#include <string>
#include <stack>
#include <cctype>

#include <sstream>
#include <iostream>
#include <algorithm>

using namespace std;

/////////////////////////////// Console //////////////////////////////////////

//============================= LIFECYCLE ====================================

Console::Console()
: m_logMaxSize(256)
{

	//m_MaxMsgLength=40;
}

Console::Console(int logMaxSize)
: m_logMaxSize(logMaxSize)
{

	//m_MaxMsgLength=MaxMsgLength;
}

Console::~Console()
{
	// Delete the registered variables
/*
	map<string, ConsoleItem*>::iterator tempvar = items.begin();
	while (tempvar != items.end())
	{
		delete tempvar->second;
		tempvar++;
	}*/

	foreach(i, items)
	{
		delete i->second;
	}

	//items.clear();
}

//============================= INTERFACE ====================================

void Console::registerItem(std::string const& name, ConsoleItem* item)
{
	item->m_owner = this;
	items[name] = item;
}

void Console::registerVariable(Variable* var)
{
	string const& name = var->getName();
	if (!name.empty())
	{
		std::map<std::string, ConsoleItem*, IStrCompare>::iterator i = items.find(name);
		if(i != items.end())
		{
			// Replace old variable
			delete i->second;
		}

		registerItem(name, var);

		// register also at OLX
		const static std::string dummyDefault("");
		CScriptableVars::RegisterVars("Gusanos") ((DynamicVar<std::string>*)var, name, dummyDefault);

	}
	else
	{
		delete var; // Empty name
	}
}

void Console::registerCommand(std::string const& name, GusCommand* command)
{
	if (!name.empty() && items.find(name) == items.end())
	{
		registerItem(name, command);
	}
	else
		delete command;
}

void Console::registerSpecialCommand(const std::string &name, int index, std::string (*func)(int,const std::list<std::string>&))
{
	if (!name.empty())
	{
		ItemMap::iterator tempItem = items.find(name);
		if (tempItem == items.end())
		{
			//items[name] = new SpecialCommand(index,func);
			registerItem(name, new SpecialCommand(index, func));
		}
	}
}

void Console::registerAlias(const std::string &name, const std::string &action)
{
	if (!name.empty())
	{
		ItemMap::iterator tempItem = items.find(name);
		if (tempItem == items.end()
		|| !tempItem->second->isLocked())
		{
			if(tempItem != items.end())
				delete tempItem->second;
			registerItem(name, new Alias(name, action));
		}
	}
}
/*
struct IsTemporary
{
	bool operator()(std::pair<std::string, ConsoleItem*> const& x) const
	{
		return x.second->temp;
	}
};
*/
void Console::clearTemporaries()
{
	//std::remove_if(items.begin(), items.end(), IsTemporary());

	foreach_delete(i, items)
	{
		if(i->second->temp)
		{
			delete i->second;
			items.erase(i);
		}
	}
}

struct TestHandler : public ConsoleGrammarBase
{
	TestHandler(std::istream& str_, Console& console_, bool parseRelease_ = false)
	: str(str_), console(console_), parseRelease(parseRelease_)
	{
		next();
	}

	int cur()
	{
		return c;
	}

	void next()
	{
		c = str.get();
		if(c == std::istream::traits_type::eof())
			c = -1;
	}

	std::string invoke(std::string const& name, std::list<std::string> const& args)
	{
		return console.invoke(name, args, parseRelease);
	}

	int c;
	std::istream& str;
	Console& console;
	bool parseRelease;
};

void Console::parseLine(const string &text, bool parseRelease)
{
	std::istringstream ss(text);
	ConsoleGrammar<TestHandler> handler((TestHandler(ss, *this, parseRelease)));

	try
	{
		addLogMsg(handler.block());
	}
	catch(SyntaxError error)
	{
		addLogMsg(text);
		std::streamoff pos = handler.str.tellg();
		if(pos > 0)
		{
			addLogMsg(std::string(pos - 1, '-') + '^');
			addLogMsg(error.what());
		}
		else
		{
			addLogMsg(error.what() + string(" at end of input"));
		}
	}
}

std::string Console::invoke(string const& name, list<string> const& args, bool parseRelease)
{
	if(!parseRelease || name[0] == '+')
	{
		std::string nameCopy(name);
		if(parseRelease)
			nameCopy[0] = '-';

		ItemMap::iterator tempItem = items.find(nameCopy);
		if (tempItem != items.end())
		{
			return tempItem->second->invoke(args);
		} else
			return "UNKNOWN COMMAND: " + name;
	}

	return "";
}

/*
void Console::parse(list<string> &args, bool parseRelease)
{
	string itemName;
	string arguments;
	string retString;

	if (!args.empty())
	{
		itemName = *args.begin();
		if ( !parseRelease || (itemName[0] == '+') )
		{
			if (parseRelease) itemName[0]='-';
			map<string, ConsoleItem*>::iterator tempItem = items.find(itemName);
			if (tempItem != items.end())
			{
				args.pop_front();
				retString = tempItem->second->invoke(args);
				addLogMsg(retString);
			}else
			{
				addLogMsg("UNKNOWN COMMAND \"" + itemName + "\"" );
			}
		}
	}
}
*/

void Console::addLogMsg(const string &msg)
{
	if (!msg.empty())
	{
		cout << "Gus con: " << msg << endl;

		if(log.size() >= m_logMaxSize)
			log.pop_front();

		log.push_back(msg);
	}
}

void Console::analizeKeyEvent(bool state, char key)
{
	if (state == true)
		parseLine(bindTable.getBindingAction(key));
	else
		parseLine(bindTable.getBindingAction(key), true);
}

void Console::bind(char key, const string &action)
{
	bindTable.bind(key , action);
}

char Console::getKeyForBinding(std::string const& action)
{
	return bindTable.getKeyForAction(action);
}

std::string Console::getActionForBinding(char key)
{
	return bindTable.getBindingAction(key);
}

int Console::executeConfig(const string &filename)
{
	ifstream file;
	OpenGameFileR(file, filename.c_str());

	if (file.is_open() && file.good())
	{
		string text2Parse;
		//...parse the file
		while (portable_getline(file, text2Parse))
		{
			//getline(file,text2Parse);
			//std::transform(text2Parse.begin(), text2Parse.end(), text2Parse.begin(), (int(*)(int)) toupper);
			parseLine(text2Parse);
		}

		return 1;
	}

	return 0;
};

struct CompletionHandler : public ConsoleGrammarBase
{
	struct State
	{
		State()
		{
		}

		State(string::const_iterator b_)
		: commandComplete(false), argumentComplete(false), beginArgument(b_), beginCommand(b_), argumentIdx(0)
		{
		}

		bool commandComplete;
		bool argumentComplete;
		std::string command;
		std::string argument;
		string::const_iterator beginArgument;
		string::const_iterator beginCommand;
		int argumentIdx;
	};

	CompletionHandler(
		string::const_iterator b_,
		string::const_iterator e_,
		Console& console_
	)
	: b(b_), e(e_), current(b_), console(console_), beginPrefix(b_), endPrefix(b_)
	{
		c = (unsigned char)*b;
	}

	int cur()
	{
		return c;
	}

	void next()
	{
		++b;
		if(b == e)
		{
			if(!current.commandComplete)
			{
				current.command = std::string(current.beginCommand, b);
			}
			else if(!current.argumentComplete)
			{
				if(current.beginArgument != e)
					current.argument = std::string(current.beginArgument, b);
				else
					endPrefix = b;
			}

			throw current;
		}
		c = (unsigned char)*b;
	}

	void inCommand()
	{
		states.push(current);
		current.commandComplete = false;
		current.beginCommand = b;
		endPrefix = b;
	}

	void inArguments(std::string const& command)
	{
		current.commandComplete = true;
		current.argumentIdx = 0;
		current.argumentComplete = false;
		current.argument = "";
		current.beginArgument = e;
		current.command = command;
	}

	void inArgument(int idx)
	{
		current.commandComplete = true;
		current.argumentComplete = false;
		current.argumentIdx = idx;
		current.beginArgument = b;
		endPrefix = b;
	}

	void outArgument(int idx, std::string const& argument)
	{
		current.argumentComplete = false;
		current.argumentIdx = idx + 1;
		current.argument = "";
		current.beginArgument = e;
	}

	void outCommand()
	{
		if(!states.empty())
		{
			current = states.top();
			states.pop();
		}
	}

	std::string prefix()
	{
		return std::string(beginPrefix, endPrefix);
	}

	int c;
	string::const_iterator b;
	string::const_iterator e;
	State current;
	Console& console;
	string::const_iterator beginPrefix;
	string::const_iterator endPrefix;

	std::stack<State> states;
};

struct ItemGetText
{
	template<class IteratorT>
	std::string const& operator()(IteratorT i) const
	{
		return i->first;
	}
};

std::string Console::completeCommand(std::string const& b)
{
	return shellComplete(items, b.begin(), b.end()
		, ItemGetText(), ConsoleAddLines(*this));
}

string Console::autoComplete(string const& text)
{
	string returnText = text;

	if ( !text.empty() )
	{
		ConsoleGrammar<CompletionHandler> handler((CompletionHandler(text.begin(), text.end(), *this)));

		try
		{
			handler.block();
		}
		catch(CompletionHandler::State result)
		{
			if(result.commandComplete)
			{
				ItemMap::const_iterator item = items.find(result.command);

				if(item != items.end())
				{
					return handler.prefix() + item->second->completeArgument(result.argumentIdx, result.argument);
				}

				return text;
			}
			else
			{
				return handler.prefix() + completeCommand(result.command);
			}
		}
		catch(SyntaxError error)
		{
			return text;
		}
	}

	return text;
}

void Console::listItems(const string &text)
{
	if ( !text.empty() )
	{
		// Find the first item that matches that text
		ItemMap::iterator item = items.lower_bound( text );
		if( item != items.end() && text == item->first.substr(0, text.length()) ) // If found
		{
			// Temp item to check if there is only 1 item matching the given text
			ItemMap::iterator tempItem = item;
			tempItem++;

			// If the temp item is equal to the first item found it means that there are more than 1 items that match
			if ( tempItem != items.end() )
			if ( tempItem->first.substr(0, text.length() ) == item->first.substr(0, text.length()) )
			{

				addLogMsg("]");

				// Add a message with the name of all the matching items
				while ( item != items.end() && text == item->first.substr(0, text.length() ) )
				{
					addLogMsg(item->first);
					item++;
				}
			}
		}
	}
}

//============================= PRIVATE ======================================

<commit_msg>gus console (also gus console scripts): ignore comments<commit_after>#include "console.h"
#include "variables.h"
#include "command.h"
#include "special_command.h"
#include "alias.h"
#include "util/text.h"
#include "util/macros.h"
#include "consoleitem.h"

#include "console-grammar.h"
#include "gusanos/allegro.h"

#include <algorithm>
#include <fstream>
#include <string>
#include <stack>
#include <cctype>

#include <sstream>
#include <iostream>
#include <algorithm>

using namespace std;

/////////////////////////////// Console //////////////////////////////////////

//============================= LIFECYCLE ====================================

Console::Console()
: m_logMaxSize(256)
{

	//m_MaxMsgLength=40;
}

Console::Console(int logMaxSize)
: m_logMaxSize(logMaxSize)
{

	//m_MaxMsgLength=MaxMsgLength;
}

Console::~Console()
{
	// Delete the registered variables
/*
	map<string, ConsoleItem*>::iterator tempvar = items.begin();
	while (tempvar != items.end())
	{
		delete tempvar->second;
		tempvar++;
	}*/

	foreach(i, items)
	{
		delete i->second;
	}

	//items.clear();
}

//============================= INTERFACE ====================================

void Console::registerItem(std::string const& name, ConsoleItem* item)
{
	item->m_owner = this;
	items[name] = item;
}

void Console::registerVariable(Variable* var)
{
	string const& name = var->getName();
	if (!name.empty())
	{
		std::map<std::string, ConsoleItem*, IStrCompare>::iterator i = items.find(name);
		if(i != items.end())
		{
			// Replace old variable
			delete i->second;
		}

		registerItem(name, var);

		// register also at OLX
		const static std::string dummyDefault("");
		CScriptableVars::RegisterVars("Gusanos") ((DynamicVar<std::string>*)var, name, dummyDefault);

	}
	else
	{
		delete var; // Empty name
	}
}

void Console::registerCommand(std::string const& name, GusCommand* command)
{
	if (!name.empty() && items.find(name) == items.end())
	{
		registerItem(name, command);
	}
	else
		delete command;
}

void Console::registerSpecialCommand(const std::string &name, int index, std::string (*func)(int,const std::list<std::string>&))
{
	if (!name.empty())
	{
		ItemMap::iterator tempItem = items.find(name);
		if (tempItem == items.end())
		{
			//items[name] = new SpecialCommand(index,func);
			registerItem(name, new SpecialCommand(index, func));
		}
	}
}

void Console::registerAlias(const std::string &name, const std::string &action)
{
	if (!name.empty())
	{
		ItemMap::iterator tempItem = items.find(name);
		if (tempItem == items.end()
		|| !tempItem->second->isLocked())
		{
			if(tempItem != items.end())
				delete tempItem->second;
			registerItem(name, new Alias(name, action));
		}
	}
}
/*
struct IsTemporary
{
	bool operator()(std::pair<std::string, ConsoleItem*> const& x) const
	{
		return x.second->temp;
	}
};
*/
void Console::clearTemporaries()
{
	//std::remove_if(items.begin(), items.end(), IsTemporary());

	foreach_delete(i, items)
	{
		if(i->second->temp)
		{
			delete i->second;
			items.erase(i);
		}
	}
}

struct TestHandler : public ConsoleGrammarBase
{
	TestHandler(std::istream& str_, Console& console_, bool parseRelease_ = false)
	: str(str_), console(console_), parseRelease(parseRelease_)
	{
		next();
	}

	int cur()
	{
		return c;
	}

	void next()
	{
		c = str.get();
		if(c == std::istream::traits_type::eof())
			c = -1;
	}

	std::string invoke(std::string const& name, std::list<std::string> const& args)
	{
		return console.invoke(name, args, parseRelease);
	}

	int c;
	std::istream& str;
	Console& console;
	bool parseRelease;
};

void Console::parseLine(const string &text, bool parseRelease)
{
	if(text == "") return;
	if(text[0] == '#') return; // comment

	std::istringstream ss(text);
	ConsoleGrammar<TestHandler> handler((TestHandler(ss, *this, parseRelease)));

	try
	{
		addLogMsg(handler.block());
	}
	catch(SyntaxError error)
	{
		addLogMsg(text);
		std::streamoff pos = handler.str.tellg();
		if(pos > 0)
		{
			addLogMsg(std::string(pos - 1, '-') + '^');
			addLogMsg(error.what());
		}
		else
		{
			addLogMsg(error.what() + string(" at end of input"));
		}
	}
}

std::string Console::invoke(string const& name, list<string> const& args, bool parseRelease)
{
	if(!parseRelease || name[0] == '+')
	{
		std::string nameCopy(name);
		if(parseRelease)
			nameCopy[0] = '-';

		ItemMap::iterator tempItem = items.find(nameCopy);
		if (tempItem != items.end())
		{
			return tempItem->second->invoke(args);
		} else
			return "UNKNOWN COMMAND: " + name;
	}

	return "";
}

/*
void Console::parse(list<string> &args, bool parseRelease)
{
	string itemName;
	string arguments;
	string retString;

	if (!args.empty())
	{
		itemName = *args.begin();
		if ( !parseRelease || (itemName[0] == '+') )
		{
			if (parseRelease) itemName[0]='-';
			map<string, ConsoleItem*>::iterator tempItem = items.find(itemName);
			if (tempItem != items.end())
			{
				args.pop_front();
				retString = tempItem->second->invoke(args);
				addLogMsg(retString);
			}else
			{
				addLogMsg("UNKNOWN COMMAND \"" + itemName + "\"" );
			}
		}
	}
}
*/

void Console::addLogMsg(const string &msg)
{
	if (!msg.empty())
	{
		cout << "Gus con: " << msg << endl;

		if(log.size() >= m_logMaxSize)
			log.pop_front();

		log.push_back(msg);
	}
}

void Console::analizeKeyEvent(bool state, char key)
{
	if (state == true)
		parseLine(bindTable.getBindingAction(key));
	else
		parseLine(bindTable.getBindingAction(key), true);
}

void Console::bind(char key, const string &action)
{
	bindTable.bind(key , action);
}

char Console::getKeyForBinding(std::string const& action)
{
	return bindTable.getKeyForAction(action);
}

std::string Console::getActionForBinding(char key)
{
	return bindTable.getBindingAction(key);
}

int Console::executeConfig(const string &filename)
{
	ifstream file;
	OpenGameFileR(file, filename.c_str());

	if (file.is_open() && file.good())
	{
		string text2Parse;
		//...parse the file
		while (portable_getline(file, text2Parse))
		{
			//getline(file,text2Parse);
			//std::transform(text2Parse.begin(), text2Parse.end(), text2Parse.begin(), (int(*)(int)) toupper);
			parseLine(text2Parse);
		}

		return 1;
	}

	return 0;
};

struct CompletionHandler : public ConsoleGrammarBase
{
	struct State
	{
		State()
		{
		}

		State(string::const_iterator b_)
		: commandComplete(false), argumentComplete(false), beginArgument(b_), beginCommand(b_), argumentIdx(0)
		{
		}

		bool commandComplete;
		bool argumentComplete;
		std::string command;
		std::string argument;
		string::const_iterator beginArgument;
		string::const_iterator beginCommand;
		int argumentIdx;
	};

	CompletionHandler(
		string::const_iterator b_,
		string::const_iterator e_,
		Console& console_
	)
	: b(b_), e(e_), current(b_), console(console_), beginPrefix(b_), endPrefix(b_)
	{
		c = (unsigned char)*b;
	}

	int cur()
	{
		return c;
	}

	void next()
	{
		++b;
		if(b == e)
		{
			if(!current.commandComplete)
			{
				current.command = std::string(current.beginCommand, b);
			}
			else if(!current.argumentComplete)
			{
				if(current.beginArgument != e)
					current.argument = std::string(current.beginArgument, b);
				else
					endPrefix = b;
			}

			throw current;
		}
		c = (unsigned char)*b;
	}

	void inCommand()
	{
		states.push(current);
		current.commandComplete = false;
		current.beginCommand = b;
		endPrefix = b;
	}

	void inArguments(std::string const& command)
	{
		current.commandComplete = true;
		current.argumentIdx = 0;
		current.argumentComplete = false;
		current.argument = "";
		current.beginArgument = e;
		current.command = command;
	}

	void inArgument(int idx)
	{
		current.commandComplete = true;
		current.argumentComplete = false;
		current.argumentIdx = idx;
		current.beginArgument = b;
		endPrefix = b;
	}

	void outArgument(int idx, std::string const& argument)
	{
		current.argumentComplete = false;
		current.argumentIdx = idx + 1;
		current.argument = "";
		current.beginArgument = e;
	}

	void outCommand()
	{
		if(!states.empty())
		{
			current = states.top();
			states.pop();
		}
	}

	std::string prefix()
	{
		return std::string(beginPrefix, endPrefix);
	}

	int c;
	string::const_iterator b;
	string::const_iterator e;
	State current;
	Console& console;
	string::const_iterator beginPrefix;
	string::const_iterator endPrefix;

	std::stack<State> states;
};

struct ItemGetText
{
	template<class IteratorT>
	std::string const& operator()(IteratorT i) const
	{
		return i->first;
	}
};

std::string Console::completeCommand(std::string const& b)
{
	return shellComplete(items, b.begin(), b.end()
		, ItemGetText(), ConsoleAddLines(*this));
}

string Console::autoComplete(string const& text)
{
	string returnText = text;

	if ( !text.empty() )
	{
		ConsoleGrammar<CompletionHandler> handler((CompletionHandler(text.begin(), text.end(), *this)));

		try
		{
			handler.block();
		}
		catch(CompletionHandler::State result)
		{
			if(result.commandComplete)
			{
				ItemMap::const_iterator item = items.find(result.command);

				if(item != items.end())
				{
					return handler.prefix() + item->second->completeArgument(result.argumentIdx, result.argument);
				}

				return text;
			}
			else
			{
				return handler.prefix() + completeCommand(result.command);
			}
		}
		catch(SyntaxError error)
		{
			return text;
		}
	}

	return text;
}

void Console::listItems(const string &text)
{
	if ( !text.empty() )
	{
		// Find the first item that matches that text
		ItemMap::iterator item = items.lower_bound( text );
		if( item != items.end() && text == item->first.substr(0, text.length()) ) // If found
		{
			// Temp item to check if there is only 1 item matching the given text
			ItemMap::iterator tempItem = item;
			tempItem++;

			// If the temp item is equal to the first item found it means that there are more than 1 items that match
			if ( tempItem != items.end() )
			if ( tempItem->first.substr(0, text.length() ) == item->first.substr(0, text.length()) )
			{

				addLogMsg("]");

				// Add a message with the name of all the matching items
				while ( item != items.end() && text == item->first.substr(0, text.length() ) )
				{
					addLogMsg(item->first);
					item++;
				}
			}
		}
	}
}

//============================= PRIVATE ======================================

<|endoftext|>


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

#ifndef ARY_ITRANGE_HXX
#define ARY_ITRANGE_HXX

// USED SERVICES
    // BASE CLASSES
    // COMPONENTS
    // PARAMETERS
#include <utility>

namespace ary
{

template <typename ITER>
class IteratorRange
{
  public:
                        IteratorRange(
                            ITER                i_begin,
                            ITER                i_end )
                                                :   itCurrent(i_begin),
                                                    itEnd(i_end)
                                                {}
                        IteratorRange(
                            std::pair<ITER,ITER>
                                                i_range )
                                                :   itCurrent(i_range.first),
                                                    itEnd(i_range.second)
                                                {}

                        operator bool() const   { return itCurrent != itEnd; }
    IteratorRange &     operator++()            { ++itCurrent; return *this; }

    ITER                cur() const             { return itCurrent; }
    ITER                end() const             { return itEnd; }

  private:
    // DATA
    ITER                itCurrent;
    ITER                itEnd;
};

}   // namespace ary

#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.114); FILE MERGED 2005/09/05 13:08:55 rt 1.2.114.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: itrange.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 15:53:58 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef ARY_ITRANGE_HXX
#define ARY_ITRANGE_HXX

// USED SERVICES
    // BASE CLASSES
    // COMPONENTS
    // PARAMETERS
#include <utility>

namespace ary
{

template <typename ITER>
class IteratorRange
{
  public:
                        IteratorRange(
                            ITER                i_begin,
                            ITER                i_end )
                                                :   itCurrent(i_begin),
                                                    itEnd(i_end)
                                                {}
                        IteratorRange(
                            std::pair<ITER,ITER>
                                                i_range )
                                                :   itCurrent(i_range.first),
                                                    itEnd(i_range.second)
                                                {}

                        operator bool() const   { return itCurrent != itEnd; }
    IteratorRange &     operator++()            { ++itCurrent; return *this; }

    ITER                cur() const             { return itCurrent; }
    ITER                end() const             { return itEnd; }

  private:
    // DATA
    ITER                itCurrent;
    ITER                itEnd;
};

}   // namespace ary

#endif
<|endoftext|>


<commit_before>#include "analyser_ogg.h"
#include <mist/opus.h>

/// \TODO EW EW EW EW EW EW EW EW EW EW EW

void AnalyserOGG::init(Util::Config &conf){
  Analyser::init(conf);
}

AnalyserOGG::AnalyserOGG(Util::Config &conf) : Analyser(conf){}

bool AnalyserOGG::parsePacket(){
  if (!oggPage.read(stdin)){return false;}

  // We now have an Ogg page
  // Print it, if we're at high detail level.
  DETAIL_HI("%s", oggPage.toPrettyString().c_str());

  // attempt to detect codec if this is the first page of a stream
  if (oggPage.getHeaderType() & OGG::BeginOfStream){
    if (memcmp("theora", oggPage.getSegment(0) + 1, 6) == 0){
      sn2Codec[oggPage.getBitstreamSerialNumber()] = "Theora";
    }
    if (memcmp("vorbis", oggPage.getSegment(0) + 1, 6) == 0){
      sn2Codec[oggPage.getBitstreamSerialNumber()] = "Vorbis";
    }
    if (memcmp("OpusHead", oggPage.getSegment(0), 8) == 0){
      sn2Codec[oggPage.getBitstreamSerialNumber()] = "Opus";
    }
    if (sn2Codec[oggPage.getBitstreamSerialNumber()] != ""){
      INFO_MSG("Bitstream %llu recognized as %s", oggPage.getBitstreamSerialNumber(),
               sn2Codec[oggPage.getBitstreamSerialNumber()]);
    }else{
      WARN_MSG("Bitstream %llu not recognized!", oggPage.getBitstreamSerialNumber());
    }
  }

  if (sn2Codec[oggPage.getBitstreamSerialNumber()] == "Theora"){
    if (detail >= 2){
      std::cout << "  Theora data" << std::endl;
    }
    static unsigned int numParts = 0;
    static unsigned int keyCount = 0;
    for (unsigned int i = 0; i < oggPage.getAllSegments().size(); i++){
      theora::header tmpHeader((char *)oggPage.getSegment(i), oggPage.getAllSegments()[i].size());
      if (tmpHeader.isHeader()){
        if (tmpHeader.getHeaderType() == 0){kfgshift = tmpHeader.getKFGShift();}
      }else{
        if (!(oggPage.getHeaderType() == OGG::Continued) &&
            tmpHeader.getFTYPE() == 0){// if keyframe
          if (detail >= 3){
            std::cout << "keyframe " << keyCount << " has " << numParts << " parts and granule " << (oggPage.getGranulePosition() >> kfgshift) << std::endl;
          }
          numParts = 0;
          keyCount++;
        }
        if (oggPage.getHeaderType() != OGG::Continued || i){numParts++;}
      }
      if (detail >= 2){
        std::cout << tmpHeader.toPrettyString(4);
      }
    }
  }else if (sn2Codec[oggPage.getBitstreamSerialNumber()] == "Vorbis"){
    if (detail >= 2){
      std::cout << "  Vorbis data" << std::endl;
    }
    for (unsigned int i = 0; i < oggPage.getAllSegments().size(); i++){
      int len = oggPage.getAllSegments()[i].size();
      vorbis::header tmpHeader((char *)oggPage.getSegment(i), len);
      if (tmpHeader.isHeader() && detail >= 2){std::cout << tmpHeader.toPrettyString(4);}
    }
  }else if (sn2Codec[oggPage.getBitstreamSerialNumber()] == "Opus"){
    if (detail >= 2){
      std::cout << "  Opus data" << std::endl;
    }
    int offset = 0;
    for (unsigned int i = 0; i < oggPage.getAllSegments().size(); i++){
      int len = oggPage.getAllSegments()[i].size();
      const char *part = oggPage.getSegment(i);
      if (len >= 8 && memcmp(part, "Opus", 4) == 0){
        if (memcmp(part, "OpusHead", 8) == 0 && detail >= 2){
          std::cout << "  Version: " << (int)(part[8]) << std::endl;
          std::cout << "  Channels: " << (int)(part[9]) << std::endl;
          std::cout << "  Pre-skip: " << (int)(part[10] + (part[11] << 8)) << std::endl;
          std::cout << "  Orig. sample rate: "
                    << (int)(part[12] + (part[13] << 8) + (part[14] << 16) + (part[15] << 24))
                    << std::endl;
          std::cout << "  Gain: " << (int)(part[16] + (part[17] << 8)) << std::endl;
          std::cout << "  Channel map: " << (int)(part[18]) << std::endl;
          if (part[18] > 0){
            std::cout << "  Channel map family " << (int)(part[18])
                      << " not implemented - output incomplete" << std::endl;
          }
        }
        if (memcmp(part, "OpusTags", 8) == 0 && detail >= 3){
          unsigned int vendor_len = part[8] + (part[9] << 8) + (part[10] << 16) + (part[11] << 24);
          std::cout << "  Vendor: " << std::string(part + 12, vendor_len) << std::endl;
          const char *str_data = part + 12 + vendor_len;
          unsigned int strings =
              str_data[0] + (str_data[1] << 8) + (str_data[2] << 16) + (str_data[3] << 24);
          std::cout << "  Tags: (" << strings << ")" << std::endl;
          str_data += 4;
          for (unsigned int j = 0; j < strings; j++){
            unsigned int strlen =
                str_data[0] + (str_data[1] << 8) + (str_data[2] << 16) + (str_data[3] << 24);
            str_data += 4;
            std::cout << "    [" << j << "] " << std::string((char *)str_data, strlen) << std::endl;
            str_data += strlen;
          }
        }
      }else{
        if (detail >= 4){
          std::cout << "  " << Opus::Opus_prettyPacket(part, len) << std::endl;
        }
      }
      offset += len;
    }
  }
  return true;
}

<commit_msg>Fixed a compile warning<commit_after>#include "analyser_ogg.h"
#include <mist/opus.h>

/// \TODO EW EW EW EW EW EW EW EW EW EW EW

void AnalyserOGG::init(Util::Config &conf){
  Analyser::init(conf);
}

AnalyserOGG::AnalyserOGG(Util::Config &conf) : Analyser(conf){}

bool AnalyserOGG::parsePacket(){
  if (!oggPage.read(stdin)){return false;}

  // We now have an Ogg page
  // Print it, if we're at high detail level.
  DETAIL_HI("%s", oggPage.toPrettyString().c_str());

  // attempt to detect codec if this is the first page of a stream
  if (oggPage.getHeaderType() & OGG::BeginOfStream){
    if (memcmp("theora", oggPage.getSegment(0) + 1, 6) == 0){
      sn2Codec[oggPage.getBitstreamSerialNumber()] = "Theora";
    }
    if (memcmp("vorbis", oggPage.getSegment(0) + 1, 6) == 0){
      sn2Codec[oggPage.getBitstreamSerialNumber()] = "Vorbis";
    }
    if (memcmp("OpusHead", oggPage.getSegment(0), 8) == 0){
      sn2Codec[oggPage.getBitstreamSerialNumber()] = "Opus";
    }
    if (sn2Codec[oggPage.getBitstreamSerialNumber()] != ""){
      INFO_MSG("Bitstream %llu recognized as %s", oggPage.getBitstreamSerialNumber(),
               sn2Codec[oggPage.getBitstreamSerialNumber()].c_str());
    }else{
      WARN_MSG("Bitstream %llu not recognized!", oggPage.getBitstreamSerialNumber());
    }
  }

  if (sn2Codec[oggPage.getBitstreamSerialNumber()] == "Theora"){
    if (detail >= 2){
      std::cout << "  Theora data" << std::endl;
    }
    static unsigned int numParts = 0;
    static unsigned int keyCount = 0;
    for (unsigned int i = 0; i < oggPage.getAllSegments().size(); i++){
      theora::header tmpHeader((char *)oggPage.getSegment(i), oggPage.getAllSegments()[i].size());
      if (tmpHeader.isHeader()){
        if (tmpHeader.getHeaderType() == 0){kfgshift = tmpHeader.getKFGShift();}
      }else{
        if (!(oggPage.getHeaderType() == OGG::Continued) &&
            tmpHeader.getFTYPE() == 0){// if keyframe
          if (detail >= 3){
            std::cout << "keyframe " << keyCount << " has " << numParts << " parts and granule " << (oggPage.getGranulePosition() >> kfgshift) << std::endl;
          }
          numParts = 0;
          keyCount++;
        }
        if (oggPage.getHeaderType() != OGG::Continued || i){numParts++;}
      }
      if (detail >= 2){
        std::cout << tmpHeader.toPrettyString(4);
      }
    }
  }else if (sn2Codec[oggPage.getBitstreamSerialNumber()] == "Vorbis"){
    if (detail >= 2){
      std::cout << "  Vorbis data" << std::endl;
    }
    for (unsigned int i = 0; i < oggPage.getAllSegments().size(); i++){
      int len = oggPage.getAllSegments()[i].size();
      vorbis::header tmpHeader((char *)oggPage.getSegment(i), len);
      if (tmpHeader.isHeader() && detail >= 2){std::cout << tmpHeader.toPrettyString(4);}
    }
  }else if (sn2Codec[oggPage.getBitstreamSerialNumber()] == "Opus"){
    if (detail >= 2){
      std::cout << "  Opus data" << std::endl;
    }
    int offset = 0;
    for (unsigned int i = 0; i < oggPage.getAllSegments().size(); i++){
      int len = oggPage.getAllSegments()[i].size();
      const char *part = oggPage.getSegment(i);
      if (len >= 8 && memcmp(part, "Opus", 4) == 0){
        if (memcmp(part, "OpusHead", 8) == 0 && detail >= 2){
          std::cout << "  Version: " << (int)(part[8]) << std::endl;
          std::cout << "  Channels: " << (int)(part[9]) << std::endl;
          std::cout << "  Pre-skip: " << (int)(part[10] + (part[11] << 8)) << std::endl;
          std::cout << "  Orig. sample rate: "
                    << (int)(part[12] + (part[13] << 8) + (part[14] << 16) + (part[15] << 24))
                    << std::endl;
          std::cout << "  Gain: " << (int)(part[16] + (part[17] << 8)) << std::endl;
          std::cout << "  Channel map: " << (int)(part[18]) << std::endl;
          if (part[18] > 0){
            std::cout << "  Channel map family " << (int)(part[18])
                      << " not implemented - output incomplete" << std::endl;
          }
        }
        if (memcmp(part, "OpusTags", 8) == 0 && detail >= 3){
          unsigned int vendor_len = part[8] + (part[9] << 8) + (part[10] << 16) + (part[11] << 24);
          std::cout << "  Vendor: " << std::string(part + 12, vendor_len) << std::endl;
          const char *str_data = part + 12 + vendor_len;
          unsigned int strings =
              str_data[0] + (str_data[1] << 8) + (str_data[2] << 16) + (str_data[3] << 24);
          std::cout << "  Tags: (" << strings << ")" << std::endl;
          str_data += 4;
          for (unsigned int j = 0; j < strings; j++){
            unsigned int strlen =
                str_data[0] + (str_data[1] << 8) + (str_data[2] << 16) + (str_data[3] << 24);
            str_data += 4;
            std::cout << "    [" << j << "] " << std::string((char *)str_data, strlen) << std::endl;
            str_data += strlen;
          }
        }
      }else{
        if (detail >= 4){
          std::cout << "  " << Opus::Opus_prettyPacket(part, len) << std::endl;
        }
      }
      offset += len;
    }
  }
  return true;
}

<|endoftext|>


<commit_before>//system stuff
#include <string>
//ros stuff
#include "ros/ros.h"
#include "sensor_msgs/Joy.h"
#include "capybarauno/capybara_ticks.h"
#include "tf/transform_broadcaster.h"
#include "nav_msgs/Odometry.h"
//own stuff
#include "malComm/mal_comm.h"
#include "malComm/mal_primitives.h"

using namespace std;

int serialFd;
int beatcnt=0;
int beatingheart=0;
struct Packet_Decoder packet_decoder;
struct Packet packet;
struct Speed_Payload speedPayload;
struct State_Payload statePayload;
struct Packet heartbeat_packet;
struct Heartbeat_Payload heartbeat;

ros::Publisher ticks_publisher;
ros::Publisher odom_pub;

capybarauno::capybara_ticks currentTicks;
capybarauno::capybara_ticks previousTicks;

struct configuration{
    string serial_device;
    string published_ticks_topic;
    string cmdvel_topic;
    string subscribed_ticks_topic;
    double kbaseline;
    double kleft;
    double kright;
    string published_odometry_topic;
    string published_link_name;
    string published_odom_link_name;
    int ascii;
    int debug;
    int heartbeat;

};

struct configuration c;
double x,y,t=0;
uint32_t tick_sequence=0;
int firstMessage=1;

void cmdvelCallback(const geometry_msgs::Twist::ConstPtr& twist)
{
    if(!ros::ok()) return;
    //get absolute speed values, expressed in tick per interval
    double translational_velocity = twist->linear.x;
    double rotational_velocity    = -twist->angular.z;
    capybarauno::capybara_ticks ct;
    ct.leftEncoder=(uint16_t)((-translational_velocity+rotational_velocity));
    ct.rightEncoder=(uint16_t)((translational_velocity+rotational_velocity));
    ROS_INFO("CMDVEL %f %f %f %f",twist->linear.x,twist->angular.z,ct.leftEncoder/c.kleft,ct.rightEncoder/c.kleft);
    speedPayload.leftTick=ct.leftEncoder;
    speedPayload.rightTick=ct.rightEncoder;
    packet.speed=speedPayload;
    char buf[255];
    char* pEnd=Packet_write(&packet,buf,c.ascii);
    sendToUart(serialFd,buf,pEnd-buf,0);

}

Packet read_ticks_from_uart(int serialDevice, Packet_Decoder& decoder){
    char chunk;
    int complete=0;
    Packet read_packet;
    while(read(serialDevice, &chunk, 1)>0 && !complete){
        complete = Packet_Decoder_putChar(&decoder,(unsigned char)chunk);
    }
    if(complete){
        Packet_parse(decoder.buffer_start,&read_packet,c.ascii);
    }
    return read_packet;
}

void RobotCommunication_init(){
    initConsts();
    Packet_Decoder_init(&packet_decoder,c.ascii);
    packet.id=Speed_Payload_ID;
    serialFd=openPort((char*)c.serial_device.c_str());
    if(c.debug){
        printf("serial port status: %d\n",serialFd);
        fflush(stdout);
    }
}

void send_heartbeat(int &cnt){
    if(cnt%2==0){
        heartbeat_packet.seq++;
        char heartbuff[255];
        char* pEnd=Packet_write(&heartbeat_packet,heartbuff,c.ascii);
        sendToUart(serialFd,heartbuff,pEnd-heartbuff,0);
//        if(c.debug){
//            printf("SENDING: %s\n",heartbuff);
//            fflush(stdout);
//        }

    }
    cnt++;
}

void sendOdometry(tf::TransformBroadcaster& odom_broadcaster, capybarauno::capybara_ticks ticks){
    uint16_t ult;
    uint16_t urt;
    if(firstMessage){
        previousTicks.leftEncoder=ticks.leftEncoder;
        previousTicks.rightEncoder=ticks.rightEncoder;
        firstMessage=0;
    }
    else{
    ult = ticks.leftEncoder-previousTicks.leftEncoder;
    urt = ticks.rightEncoder-previousTicks.rightEncoder;
    previousTicks.leftEncoder=ticks.leftEncoder;
    previousTicks.rightEncoder=ticks.rightEncoder;
    int16_t lt = (int16_t)ult;
    int16_t rt = (int16_t)urt;

    double left=-(double)lt*c.kleft;
    double right=(double)rt*c.kright;
    double s = (left+right)/2;
    t-=(right-left)/c.kbaseline;
    x+=s*cos(t);
    y+=s*sin(t);
    //ROS_INFO("ODOM: %d %d   ",ult,urt);

    geometry_msgs::Quaternion odom_quat = tf::createQuaternionMsgFromYaw(t);
    geometry_msgs::TransformStamped odom_trans;
    ros::Time current_time = ros::Time::now();
    odom_trans.header.stamp = current_time;
    odom_trans.header.frame_id = c.published_odometry_topic.c_str();
    odom_trans.child_frame_id = c.published_link_name.c_str();
    odom_trans.transform.translation.x = x;
    odom_trans.transform.translation.y = y;
    odom_trans.transform.translation.z = 0.0;
    odom_trans.transform.rotation = odom_quat;
    odom_broadcaster.sendTransform(odom_trans);
    nav_msgs::Odometry odom;
    odom.header.stamp = current_time;
    odom.header.frame_id = c.published_odom_link_name;
    odom.pose.pose.position.x = x;
    odom.pose.pose.position.y = y;
    odom.pose.pose.position.z = 0.0;
    odom.pose.pose.orientation = odom_quat;
    odom_pub.publish(odom);
    }

}

void EchoParameters(){
    printf("%s %s\n","_published_ticks_topic",c.published_ticks_topic.c_str());
    printf("%s %s\n","_subscribed_ticks_topic",c.subscribed_ticks_topic.c_str());
    printf("%s %s\n","_serial_device",c.serial_device.c_str());
    printf("%s %s\n","_published_odometry_topic",c.published_odometry_topic.c_str());
    printf("%s %s\n","_published_link_name",c.published_link_name.c_str());
    printf("%s %s\n","_published_odom_link_name",c.published_odom_link_name.c_str());
    printf("%s %f\n","_kleft",c.kleft);
    printf("%s %f\n","_right",c.kleft);
    printf("%s %f\n","_baseline",c.kbaseline);
    printf("%s %d\n","_ascii",c.ascii);
    printf("%s %d\n","_debug",c.debug);
    printf("%s %d\n","_hearbeat",c.heartbeat);
}

int main(int argc, char **argv)
{
    ros::init(argc, argv, "capybarauno_node",ros::init_options::AnonymousName);
    tf::TransformBroadcaster odom_broadcaster;
    ros::NodeHandle n("~");
    n.param<string>("serial_device", c.serial_device, "/dev/ttyACM0");
    n.param<string>("published_ticks_topic", c.published_ticks_topic, "/robot_ticks");
    n.param<string>("cmdvel_topic", c.cmdvel_topic, "/cmd_vel");
    n.param<string>("published_odometry_topic", c.published_odometry_topic, "/odom");
    n.param<string>("published_link_name", c.published_link_name, "/base_link");
    n.param<string>("published_odom_link_name", c.published_odom_link_name, "/odom");
    n.param<double>("kleft", c.kleft, 0.0058);
    n.param<double>("kright", c.kright, 0.0058);
    n.param<double>("kbaseline", c.kbaseline, 0.2);
    n.param<int>("ascii", c.ascii, 1);
    n.param<int>("heartbeat", c.heartbeat, 1);
    n.param("debug", c.debug, 1);

    EchoParameters();
    RobotCommunication_init();

    heartbeat.beat=1;
    heartbeat_packet.id=Heartbeat_Payload_ID;
    heartbeat_packet.seq=0;
    heartbeat_packet.heartbeat=heartbeat;

    previousTicks.leftEncoder=0;
    previousTicks.rightEncoder=0;
    currentTicks.leftEncoder=0;
    currentTicks.rightEncoder=0;
    ros::Subscriber cmdvel_subscriber = n.subscribe(c.cmdvel_topic.c_str(), 1000, cmdvelCallback);
    ticks_publisher = n.advertise<capybarauno::capybara_ticks>(c.published_ticks_topic.c_str(), 1000);
    odom_pub = n.advertise<nav_msgs::Odometry>(c.published_odometry_topic.c_str(), 1000);
    //ros::ok() used to get the SIGINT ctrl+c
    while(ros::ok()){
        Packet robot_data = read_ticks_from_uart(serialFd,packet_decoder);
        capybarauno::capybara_ticks currentTicks;

        currentTicks.header.seq = robot_data.seq;
        currentTicks.header.stamp = ros::Time::now();
        currentTicks.leftEncoder = robot_data.state.leftEncoder;
        currentTicks.rightEncoder = robot_data.state.rightEncoder;
        //ROS_INFO("TICKS %d %d",currentTicks.leftEncoder,currentTicks.rightEncoder);
        ticks_publisher.publish(currentTicks);
        sendOdometry(odom_broadcaster,currentTicks);
        if(c.heartbeat==1){
            send_heartbeat(beatcnt);
        }
        ros::spinOnce();
        usleep(1000);
    }

    return 0;
}
<commit_msg>joint state publisher<commit_after>//system stuff
#include <string>
//ros stuff
#include "ros/ros.h"
#include "sensor_msgs/Joy.h"
#include "sensor_msgs/JointState.h"
#include "capybarauno/capybara_ticks.h"
#include "tf/transform_broadcaster.h"
#include "nav_msgs/Odometry.h"
//own stuff
#include "malComm/mal_comm.h"
#include "malComm/mal_primitives.h"

using namespace std;

int serialFd;
int beatcnt=0;
int beatingheart=0;
struct Packet_Decoder packet_decoder;
struct Packet packet;
struct Speed_Payload speedPayload;
struct State_Payload statePayload;
struct Packet heartbeat_packet;
struct Heartbeat_Payload heartbeat;

ros::Publisher ticks_publisher;
ros::Publisher joint_ticks_publisher;
ros::Publisher odom_pub;

capybarauno::capybara_ticks currentTicks;
capybarauno::capybara_ticks previousTicks;

struct configuration{
    string serial_device;
    string published_ticks_topic;
    string published_joint_ticks_topic;
    string cmdvel_topic;
    string subscribed_ticks_topic;
    double kbaseline;
    double kleft;
    double kright;
    string published_odometry_topic;
    string published_link_name;
    string published_odom_link_name;
    int ascii;
    int debug;
    int heartbeat;

};

struct configuration c;
double x,y,t=0;
uint32_t tick_sequence=0;
int firstMessage=1;

void cmdvelCallback(const geometry_msgs::Twist::ConstPtr& twist)
{
    if(!ros::ok()) return;
    //get absolute speed values, expressed in tick per interval
    double translational_velocity = twist->linear.x;
    double rotational_velocity    = -twist->angular.z/(c.kbaseline*2);
    capybarauno::capybara_ticks ct;
    ct.leftEncoder=(uint16_t)((-translational_velocity+rotational_velocity)/(c.kleft*1000));
    ct.rightEncoder=(uint16_t)((translational_velocity+rotational_velocity)/(c.kright*1000));
    //ROS_INFO("CMDVEL %f %f %d %d",twist->linear.x,twist->angular.z,ct.leftEncoder,ct.rightEncoder);
    speedPayload.leftTick=ct.leftEncoder;
    speedPayload.rightTick=ct.rightEncoder;
    packet.speed=speedPayload;
    char buf[255];
    char* pEnd=Packet_write(&packet,buf,c.ascii);
    sendToUart(serialFd,buf,pEnd-buf,0);

}

Packet read_ticks_from_uart(int serialDevice, Packet_Decoder& decoder){
    char chunk;
    int complete=0;
    Packet read_packet;
    while(read(serialDevice, &chunk, 1)>0 && !complete){
        complete = Packet_Decoder_putChar(&decoder,(unsigned char)chunk);
    }
    if(complete){
        Packet_parse(decoder.buffer_start,&read_packet,c.ascii);
    }
    return read_packet;
}

void RobotCommunication_init(){
    initConsts();
    Packet_Decoder_init(&packet_decoder,c.ascii);
    packet.id=Speed_Payload_ID;
    serialFd=openPort((char*)c.serial_device.c_str());
    if(c.debug){
        printf("serial port status: %d\n",serialFd);
        fflush(stdout);
    }
}

void send_heartbeat(int &cnt){
    if(cnt%2==0){
        heartbeat_packet.seq++;
        char heartbuff[255];
        char* pEnd=Packet_write(&heartbeat_packet,heartbuff,c.ascii);
        sendToUart(serialFd,heartbuff,pEnd-heartbuff,0);
//        if(c.debug){
//            printf("SENDING: %s\n",heartbuff);
//            fflush(stdout);
//        }

    }
    cnt++;
}

void sendOdometry(tf::TransformBroadcaster& odom_broadcaster, capybarauno::capybara_ticks ticks){
    uint16_t ult;
    uint16_t urt;
    if(firstMessage){
        previousTicks.leftEncoder=ticks.leftEncoder;
        previousTicks.rightEncoder=ticks.rightEncoder;
        firstMessage=0;
    }
    else{
    ult = ticks.leftEncoder-previousTicks.leftEncoder;
    urt = ticks.rightEncoder-previousTicks.rightEncoder;
    previousTicks.leftEncoder=ticks.leftEncoder;
    previousTicks.rightEncoder=ticks.rightEncoder;
    int16_t lt = (int16_t)ult;
    int16_t rt = (int16_t)urt;

    double left=-(double)lt*c.kleft;
    double right=(double)rt*c.kright;
    double s = (left+right)/2;
    t-=(right-left)/c.kbaseline;
    x+=s*cos(t);
    y+=s*sin(t);
    ROS_INFO("ODOM: %f",t);

    geometry_msgs::Quaternion odom_quat = tf::createQuaternionMsgFromYaw(t);
    geometry_msgs::TransformStamped odom_trans;
    ros::Time current_time = ros::Time::now();
    odom_trans.header.stamp = current_time;
    odom_trans.header.frame_id = c.published_odometry_topic.c_str();
    odom_trans.child_frame_id = c.published_link_name.c_str();
    odom_trans.transform.translation.x = x;
    odom_trans.transform.translation.y = y;
    odom_trans.transform.translation.z = 0.0;
    odom_trans.transform.rotation = odom_quat;
    odom_broadcaster.sendTransform(odom_trans);
    nav_msgs::Odometry odom;
    odom.header.stamp = current_time;
    odom.header.frame_id = c.published_odom_link_name;
    odom.pose.pose.position.x = x;
    odom.pose.pose.position.y = y;
    odom.pose.pose.position.z = 0.0;
    odom.pose.pose.orientation = odom_quat;
    odom_pub.publish(odom);
    }

}

void EchoParameters(){
    printf("%s %s\n","_published_ticks_topic",c.published_ticks_topic.c_str());
    printf("%s %s\n","_published_joint_ticks_topic",c.published_joint_ticks_topic.c_str());
    printf("%s %s\n","_subscribed_ticks_topic",c.subscribed_ticks_topic.c_str());
    printf("%s %s\n","_serial_device",c.serial_device.c_str());
    printf("%s %s\n","_published_odometry_topic",c.published_odometry_topic.c_str());
    printf("%s %s\n","_published_link_name",c.published_link_name.c_str());
    printf("%s %s\n","_published_odom_link_name",c.published_odom_link_name.c_str());
    printf("%s %f\n","_kleft",c.kleft);
    printf("%s %f\n","_kright",c.kright);
    printf("%s %f\n","_baseline",c.kbaseline);
    printf("%s %d\n","_ascii",c.ascii);
    printf("%s %d\n","_debug",c.debug);
    printf("%s %d\n","_hearbeat",c.heartbeat);
}

int main(int argc, char **argv)
{
    ros::init(argc, argv, "capybarauno_node",ros::init_options::AnonymousName);
    tf::TransformBroadcaster odom_broadcaster;
    ros::NodeHandle n("~");
    n.param<string>("serial_device", c.serial_device, "/dev/ttyACM0");
    n.param<string>("published_ticks_topic", c.published_ticks_topic, "/robot_ticks");
    n.param<string>("published_joint_ticks_topic", c.published_joint_ticks_topic, "/joint_robot_ticks");
    n.param<string>("cmdvel_topic", c.cmdvel_topic, "/cmd_vel");
    n.param<string>("published_odometry_topic", c.published_odometry_topic, "/odom");
    n.param<string>("published_link_name", c.published_link_name, "/base_link");
    n.param<string>("published_odom_link_name", c.published_odom_link_name, "/odom");
    n.param<double>("kleft", c.kleft, 0.0058);
    n.param<double>("kright", c.kright, 0.0058);
    n.param<double>("kbaseline", c.kbaseline, 0.2);
    n.param<int>("ascii", c.ascii, 1);
    n.param<int>("heartbeat", c.heartbeat, 1);
    n.param("debug", c.debug, 1);

    EchoParameters();
    RobotCommunication_init();

    heartbeat.beat=1;
    heartbeat_packet.id=Heartbeat_Payload_ID;
    heartbeat_packet.seq=0;
    heartbeat_packet.heartbeat=heartbeat;

    previousTicks.leftEncoder=0;
    previousTicks.rightEncoder=0;
    currentTicks.leftEncoder=0;
    currentTicks.rightEncoder=0;
    ros::Subscriber cmdvel_subscriber = n.subscribe(c.cmdvel_topic.c_str(), 1000, cmdvelCallback);
    ticks_publisher = n.advertise<capybarauno::capybara_ticks>(c.published_ticks_topic.c_str(), 1000);
    joint_ticks_publisher = n.advertise<sensor_msgs::JointState>(c.published_joint_ticks_topic.c_str(), 1000);
    odom_pub = n.advertise<nav_msgs::Odometry>(c.published_odometry_topic.c_str(), 1000);
    //ros::ok() used to get the SIGINT ctrl+c
    while(ros::ok()){
        Packet robot_data = read_ticks_from_uart(serialFd,packet_decoder);
        capybarauno::capybara_ticks currentTicks;
        sensor_msgs::JointState currentJointTicks;
        currentTicks.header.seq = robot_data.seq;
        currentTicks.header.stamp = ros::Time::now();
        currentTicks.leftEncoder = robot_data.state.leftEncoder;
        currentTicks.rightEncoder = robot_data.state.rightEncoder;
        currentJointTicks.name.resize(2);
        currentJointTicks.position.resize(2);
        currentJointTicks.name[0]="left";
        currentJointTicks.name[1]="right";
        currentJointTicks.position[0]=(double)robot_data.state.leftEncoder;
        currentJointTicks.position[1]=(double)robot_data.state.rightEncoder;
        joint_ticks_publisher.publish(currentJointTicks);
        ticks_publisher.publish(currentTicks);
        sendOdometry(odom_broadcaster,currentTicks);
        if(c.heartbeat==1){
            send_heartbeat(beatcnt);
        }
        ros::spinOnce();
        usleep(1000);
    }

    return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: aqua_clipboard.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 16:54:24 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

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

#ifndef _AQUA_CLIPBOARD_HXX_
#include "aqua_clipboard.hxx"
#endif

using namespace com::sun::star::datatransfer;
using namespace com::sun::star::datatransfer::clipboard;
using namespace com::sun::star::lang;
using namespace com::sun::star::uno;
using namespace cppu;
using namespace osl;
using namespace rtl;
using namespace aqua;

AquaClipboard::AquaClipboard() :
    WeakComponentImplHelper3< XClipboardEx, XClipboardNotifier, XServiceInfo >( m_aMutex )
{
}

Reference< XTransferable > SAL_CALL AquaClipboard::getContents() throw( RuntimeException )
{
    MutexGuard aGuard( m_aMutex );

    return m_aTransferable;
}

void SAL_CALL AquaClipboard::setContents( const Reference< XTransferable >& xTransferable, const Reference< XClipboardOwner >& xClipboardOwner ) throw( RuntimeException )
{
    MutexGuard aGuard( m_aMutex );

    m_aTransferable = xTransferable;
}

OUString SAL_CALL AquaClipboard::getName() throw( RuntimeException )
{
    return OUString();
}

sal_Int8 SAL_CALL AquaClipboard::getRenderingCapabilities() throw( RuntimeException )
{
    return 0;
}

void SAL_CALL AquaClipboard::addClipboardListener( const Reference< XClipboardListener >& listener ) throw( RuntimeException )
{
}

void SAL_CALL AquaClipboard::removeClipboardListener( const Reference< XClipboardListener >& listener ) throw( RuntimeException )
{
}

OUString SAL_CALL AquaClipboard::getImplementationName() throw( RuntimeException )
{
    return OUString::createFromAscii( AQUA_CLIPBOARD_IMPL_NAME );
}

sal_Bool SAL_CALL AquaClipboard::supportsService( const OUString& ServiceName ) throw( RuntimeException )
{
    return sal_False;
}

Sequence< OUString > SAL_CALL AquaClipboard::getSupportedServiceNames() throw( RuntimeException )
{
    Sequence< OUString > aRet(1);
    aRet[0] = OUString::createFromAscii( AQUA_CLIPBOARD_SERVICE_NAME );
    return aRet;
}

<commit_msg>INTEGRATION: CWS aquavcl01 (1.4.6); FILE MERGED 2007/06/28 14:09:19 tra 1.4.6.4: #i77593#support for copy&paste of pictures, OLE data exchanges with MS Office etc. 2007/06/14 12:06:18 tra 1.4.6.3: Work in progress, checked in to have it saved in the repos. 2007/05/27 10:02:02 tra 1.4.6.2: Need to implement XFlushableClipboard 2007/05/24 19:53:30 tra 1.4.6.1: Implementing paste system -> OOo<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: aqua_clipboard.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2007-07-05 09:11:49 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

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

#ifndef _AQUA_CLIPBOARD_HXX_
#include "aqua_clipboard.hxx"
#endif

#include "DataFlavorMapping.hxx"
#include "OSXTransferable.hxx"

#include <boost/assert.hpp>

using namespace com::sun::star::datatransfer;
using namespace com::sun::star::datatransfer::clipboard;
using namespace com::sun::star::lang;
using namespace com::sun::star::uno;
using namespace cppu;
using namespace osl;
using namespace rtl;
using namespace aqua;
using namespace std;

const EventTypeSpec appActivatedEvent = { kEventClassApplication, kEventAppActivated };

AquaClipboard::AquaClipboard(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > ServiceManager) :
  WeakComponentImplHelper4< XClipboardEx, XClipboardNotifier, XFlushableClipboard, XServiceInfo >(m_aMutex),
  mrServiceMgr(ServiceManager)
{
  if (PasteboardCreate(kPasteboardClipboard, &mrClipboard) != noErr)
    {
      throw RuntimeException(OUString(RTL_CONSTASCII_USTRINGPARAM("AquaClipboard: Cannot create Mac OS X system cliboard")),
                             static_cast<XClipboardEx*>(this));
    }

  /* We need to register ourself for application activated events.
     This is the suggested way is to check for clipboard modifications
     during this event.
   */
  if (InstallApplicationEventHandler(NewEventHandlerUPP(handleAppActivatedEvent),
                                     1,
                                     &appActivatedEvent,
                                     this,
                                     &mrAppActivatedHdl) != noErr)
    {
      CFRelease(mrClipboard);
      throw RuntimeException(OUString(RTL_CONSTASCII_USTRINGPARAM("AquaClipboard: Cannot register for application activated events")),
                             static_cast<XClipboardEx*>(this));
    }

  mrXMimeCntFactory = Reference<XMimeContentTypeFactory>(mrServiceMgr->createInstance(
      OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.datatransfer.MimeContentTypeFactory"))), UNO_QUERY);

  if (!mrXMimeCntFactory.is())
    throw RuntimeException(OUString(RTL_CONSTASCII_USTRINGPARAM("AquaClipboard: Cannot create com.sun.star.datatransfer.MimeContentTypeFactory")),
                           static_cast<XClipboardEx*>(this));

  mpDataFlavorMapper = DataFlavorMapperPtr_t(new DataFlavorMapper(mrServiceMgr));
}

AquaClipboard::~AquaClipboard()
{
  RemoveEventHandler(mrAppActivatedHdl);
  CFRelease(mrClipboard);
}

Reference< XTransferable > SAL_CALL AquaClipboard::getContents() throw( RuntimeException )
{
  MutexGuard aGuard(m_aMutex);

  // Shortcut: If we are clipboard owner already we don't need
  // to drag the data through the system clipboard
  if (mXClipboardContent.is())
    {
      return mXClipboardContent;
    }
  else
    {
      return Reference<XTransferable>(new OSXTransferable(mrServiceMgr, mrXMimeCntFactory, mpDataFlavorMapper));
    }
}

void SAL_CALL AquaClipboard::setContents(const Reference<XTransferable>& xTransferable,
                                         const Reference<XClipboardOwner>& xClipboardOwner)
  throw( RuntimeException )
{
    MutexGuard aGuard( m_aMutex );

    // if we are already the owner of the clipboard
    // then fire lost ownership event
    if (mXClipboardContent.is())
      {
        fireLostClipboardOwnershipEvent();
      }

    if (PasteboardClear(mrClipboard) != noErr)
      {
        throw RuntimeException(OUString(RTL_CONSTASCII_USTRINGPARAM("AquaClipboard: Cannot set clipboard content")),
                               static_cast<XClipboardEx*>(this));
      }

    mXClipboardContent = xTransferable;
    mXClipboardOwner = xClipboardOwner;

    // An empty transferable means clear the clipboard, so we can
    // return here
    if (!mXClipboardContent.is())
      {
        return;
      }

    Sequence<DataFlavor> flavorList = mXClipboardContent->getTransferDataFlavors();
    sal_Int32 nClipboardFlavors = flavorList.getLength();

    if (nClipboardFlavors > 0 &&
        PasteboardSetPromiseKeeper(mrClipboard, AquaClipboard::clipboardPromiseKeeperCallback, this) != noErr)
      {
        throw RuntimeException(OUString(RTL_CONSTASCII_USTRINGPARAM("AquaClipboard: Cannot set clipboard prmise keeper callback")),
                               static_cast<XClipboardEx*>(this));
      }

    // We always only have one clipboard item to add but with multiple flavors
    for (sal_Int32 i = 0; i < nClipboardFlavors; i++)
      {
        CFStringRef systemFlavor = mpDataFlavorMapper->openOfficeToSystemFlavor(flavorList[i]);

        if (systemFlavor != NULL)
          {
            OSStatus ret = PasteboardPutItemFlavor(mrClipboard,
                                                   (PasteboardItemID)1,
                                                   systemFlavor,
                                                   kPasteboardPromisedData,
                                                   kPasteboardFlavorNoFlags);
            if (ret != noErr)
              {
                throw RuntimeException(OUString(RTL_CONSTASCII_USTRINGPARAM("AquaClipboard: Cannot set clipboard contents")),
                                       static_cast<XClipboardEx*>(this));
              }
          }
      }
}

OUString SAL_CALL AquaClipboard::getName() throw( RuntimeException )
{
  return OUString();
}

sal_Int8 SAL_CALL AquaClipboard::getRenderingCapabilities() throw( RuntimeException )
{
    return 0;
}

void SAL_CALL AquaClipboard::addClipboardListener( const Reference< XClipboardListener >& listener ) throw( RuntimeException )
{
  MutexGuard aGuard(m_aMutex);

  if (!listener.is())
     throw IllegalArgumentException(OUString(RTL_CONSTASCII_USTRINGPARAM("empty reference")),
                                   static_cast<XClipboardEx*>(this), 1);

  mClipboardListeners.push_back(listener);
}

void SAL_CALL AquaClipboard::removeClipboardListener( const Reference< XClipboardListener >& listener ) throw( RuntimeException )
{
  MutexGuard aGuard(m_aMutex);

  if (!listener.is())
     throw IllegalArgumentException(OUString(RTL_CONSTASCII_USTRINGPARAM("empty reference")),
                                   static_cast<XClipboardEx*>(this), 1);

  mClipboardListeners.remove(listener);
}

OSStatus AquaClipboard::handleAppActivatedEvent(EventHandlerCallRef inHandlerCallRef, EventRef inEvent, void* inUserData)
{
  AquaClipboard* pAquaClipboard = reinterpret_cast<AquaClipboard*>(inUserData);

  BOOST_ASSERT(pAquaClipboard && "Invalid argument");

  PasteboardSyncFlags syncFlags = PasteboardSynchronize(pAquaClipboard->mrClipboard);

  if (syncFlags & kPasteboardModified)
    {
      pAquaClipboard->fireClipboardChangedEvent();
    }

  if (pAquaClipboard->mXClipboardContent.is() && !(syncFlags & kPasteboardClientIsOwner))
    {
      pAquaClipboard->fireLostClipboardOwnershipEvent();
    }

  // we are just silent listener to this event
  // let others really handle it
  return eventNotHandledErr;
}

void AquaClipboard::fireClipboardChangedEvent()
{
    ClearableMutexGuard aGuard(m_aMutex);
    // copy the clipboard listener list
    list<Reference< XClipboardListener > > listeners(mClipboardListeners);
    aGuard.clear();

    Reference<XTransferable> content = getContents();

    ClipboardEvent aEvent(static_cast<OWeakObject*>(this), content);

    while(listeners.begin() != listeners.end())
    {
        if(listeners.front().is())
            listeners.front()->changedContents(aEvent);
        listeners.pop_front();
    }
}

void AquaClipboard::fireLostClipboardOwnershipEvent()
{
  try
    {
      // Fire event only if a lost owner ship handler has been registered
      if (mXClipboardOwner.is())
        {
          mXClipboardOwner->lostOwnership(static_cast<XClipboardEx*>(this), mXClipboardContent);
        }
    }
  catch(RuntimeException&)
    {
      OSL_ENSURE( sal_False, "AquaClipboard: fireLostClipboardOwnershipEvent, RuntimeException caught" );
    }

  // Reset the references to clipboard owner and content
  mXClipboardOwner = Reference<XClipboardOwner>();
  mXClipboardContent = Reference<XTransferable>();
}

OSStatus AquaClipboard::clipboardPromiseKeeperCallback(PasteboardRef inPasteboard,
                                                       PasteboardItemID itemID,
                                                       CFStringRef inFlavor,
                                                       void* inContext)
{
  AquaClipboard* pAquaClipboard = reinterpret_cast<AquaClipboard*>(inContext);

  DataProviderPtr_t pdp = pAquaClipboard->mpDataFlavorMapper->getDataProvider(inFlavor, pAquaClipboard->mXClipboardContent);
  OSStatus rc = badPasteboardFlavorErr;
  CFDataRef sysData = NULL;

  if ((pdp.get()) && ((sysData = pdp->getSystemData()) != NULL))
    {
      rc = PasteboardPutItemFlavor(pAquaClipboard->mrClipboard, (PasteboardItemID)1, inFlavor, sysData, 0);
      CFRelease(sysData);
    }

  return rc;
}

//------------------------------------------------
// XFlushableClipboard
//------------------------------------------------

void SAL_CALL AquaClipboard::flushClipboard()
  throw(RuntimeException)
{
  PasteboardResolvePromises(mrClipboard);
}

OUString SAL_CALL AquaClipboard::getImplementationName() throw( RuntimeException )
{
    return OUString::createFromAscii( AQUA_CLIPBOARD_IMPL_NAME );
}

sal_Bool SAL_CALL AquaClipboard::supportsService( const OUString& ServiceName ) throw( RuntimeException )
{
    return sal_False;
}

Sequence< OUString > SAL_CALL AquaClipboard::getSupportedServiceNames() throw( RuntimeException )
{
    Sequence< OUString > aRet(1);
    aRet[0] = OUString::createFromAscii( AQUA_CLIPBOARD_SERVICE_NAME );
    return aRet;
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: aqua_clipboard.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 18:08:09 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _AQUA_CLIPBOARD_HXX_
#include "aqua_clipboard.hxx"
#endif

using namespace com::sun::star::datatransfer;
using namespace com::sun::star::datatransfer::clipboard;
using namespace com::sun::star::lang;
using namespace com::sun::star::uno;
using namespace cppu;
using namespace osl;
using namespace rtl;
using namespace aqua;

AquaClipboard::AquaClipboard() :
    WeakComponentImplHelper3< XClipboardEx, XClipboardNotifier, XServiceInfo >( m_aMutex )
{
}

Reference< XTransferable > SAL_CALL AquaClipboard::getContents() throw( RuntimeException )
{
    MutexGuard aGuard( m_aMutex );

    return m_aTransferable;
}

void SAL_CALL AquaClipboard::setContents( const Reference< XTransferable >& xTransferable, const Reference< XClipboardOwner >& xClipboardOwner ) throw( RuntimeException )
{
    MutexGuard aGuard( m_aMutex );

    m_aTransferable = xTransferable;
}

OUString SAL_CALL AquaClipboard::getName() throw( RuntimeException )
{
    return OUString();
}

sal_Int8 SAL_CALL AquaClipboard::getRenderingCapabilities() throw( RuntimeException )
{
    return 0;
}

void SAL_CALL AquaClipboard::addClipboardListener( const Reference< XClipboardListener >& listener ) throw( RuntimeException )
{
}

void SAL_CALL AquaClipboard::removeClipboardListener( const Reference< XClipboardListener >& listener ) throw( RuntimeException )
{
}

OUString SAL_CALL AquaClipboard::getImplementationName() throw( RuntimeException )
{
    return OUString::createFromAscii( AQUA_CLIPBOARD_IMPL_NAME );
}

sal_Bool SAL_CALL AquaClipboard::supportsService( const OUString& ServiceName ) throw( RuntimeException )
{
    return sal_False;
}

Sequence< OUString > SAL_CALL AquaClipboard::getSupportedServiceNames() throw( RuntimeException )
{
    Sequence< OUString > aRet(1);
    aRet[0] = OUString::createFromAscii( AQUA_CLIPBOARD_SERVICE_NAME );
    return aRet;
}

<commit_msg>INTEGRATION: CWS pchfix02 (1.3.40); FILE MERGED 2006/09/01 17:25:33 kaib 1.3.40.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: aqua_clipboard.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 16:54:24 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

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

#ifndef _AQUA_CLIPBOARD_HXX_
#include "aqua_clipboard.hxx"
#endif

using namespace com::sun::star::datatransfer;
using namespace com::sun::star::datatransfer::clipboard;
using namespace com::sun::star::lang;
using namespace com::sun::star::uno;
using namespace cppu;
using namespace osl;
using namespace rtl;
using namespace aqua;

AquaClipboard::AquaClipboard() :
    WeakComponentImplHelper3< XClipboardEx, XClipboardNotifier, XServiceInfo >( m_aMutex )
{
}

Reference< XTransferable > SAL_CALL AquaClipboard::getContents() throw( RuntimeException )
{
    MutexGuard aGuard( m_aMutex );

    return m_aTransferable;
}

void SAL_CALL AquaClipboard::setContents( const Reference< XTransferable >& xTransferable, const Reference< XClipboardOwner >& xClipboardOwner ) throw( RuntimeException )
{
    MutexGuard aGuard( m_aMutex );

    m_aTransferable = xTransferable;
}

OUString SAL_CALL AquaClipboard::getName() throw( RuntimeException )
{
    return OUString();
}

sal_Int8 SAL_CALL AquaClipboard::getRenderingCapabilities() throw( RuntimeException )
{
    return 0;
}

void SAL_CALL AquaClipboard::addClipboardListener( const Reference< XClipboardListener >& listener ) throw( RuntimeException )
{
}

void SAL_CALL AquaClipboard::removeClipboardListener( const Reference< XClipboardListener >& listener ) throw( RuntimeException )
{
}

OUString SAL_CALL AquaClipboard::getImplementationName() throw( RuntimeException )
{
    return OUString::createFromAscii( AQUA_CLIPBOARD_IMPL_NAME );
}

sal_Bool SAL_CALL AquaClipboard::supportsService( const OUString& ServiceName ) throw( RuntimeException )
{
    return sal_False;
}

Sequence< OUString > SAL_CALL AquaClipboard::getSupportedServiceNames() throw( RuntimeException )
{
    Sequence< OUString > aRet(1);
    aRet[0] = OUString::createFromAscii( AQUA_CLIPBOARD_SERVICE_NAME );
    return aRet;
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: aqua_clipboard.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-20 05:58:48 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _AQUA_CLIPBOARD_HXX_
#define _AQUA_CLIPBOARD_HXX_

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

#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif

#ifndef _CPPUHELPER_COMPBASE3_HXX_
#include <cppuhelper/compbase3.hxx>
#endif

#ifndef _COM_SUN_STAR_DATATRANSFER_XTRANSFERABLE_HPP_
#include <com/sun/star/datatransfer/XTransferable.hpp>
#endif

#ifndef _COM_SUN_STAR_DATATRANSFER_CLIPBOARD_XCLIPBOARDEX_HPP_
#include <com/sun/star/datatransfer/clipboard/XClipboardEx.hpp>
#endif

#ifndef _COM_SUN_STAR_DATATRANSFER_CLIPBOARD_XCLIPBOARDOWNER_HPP_
#include <com/sun/star/datatransfer/clipboard/XClipboardOwner.hpp>
#endif

#ifndef _COM_SUN_STAR_DATATRANSFER_CLIPBOARD_XCLIPBOARDLISTENER_HPP_
#include <com/sun/star/datatransfer/clipboard/XClipboardListener.hpp>
#endif

#ifndef _COM_SUN_STAR_DATATRANSFER_CLIPBOARD_XCLIPBOARDNOTIFIER_HPP_
#include <com/sun/star/datatransfer/clipboard/XClipboardNotifier.hpp>
#endif

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

// the service names
#define AQUA_CLIPBOARD_SERVICE_NAME "com.sun.star.datatransfer.clipboard.SystemClipboard"

// the implementation names
#define AQUA_CLIPBOARD_IMPL_NAME "com.sun.star.datatransfer.clipboard.AquaClipboard"

// the registry key names
#define AQUA_CLIPBOARD_REGKEY_NAME "/com.sun.star.datatransfer.clipboard.AquaClipboard/UNO/SERVICES/com.sun.star.datatransfer.clipboard.SystemClipboard"

namespace aqua {

class AquaClipboard :
    public cppu::WeakComponentImplHelper3< ::com::sun::star::datatransfer::clipboard::XClipboardEx, ::com::sun::star::datatransfer::clipboard::XClipboardNotifier, ::com::sun::star::lang::XServiceInfo >
{
public:
    AquaClipboard();

    virtual ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::XTransferable > SAL_CALL getContents()
        throw( ::com::sun::star::uno::RuntimeException );
    virtual void SAL_CALL setContents( const ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::XTransferable >& xTransferable, const ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::clipboard::XClipboardOwner >& xClipboardOwner )
        throw( ::com::sun::star::uno::RuntimeException );
    virtual ::rtl::OUString SAL_CALL getName()
        throw( ::com::sun::star::uno::RuntimeException );
    virtual sal_Int8 SAL_CALL getRenderingCapabilities()
        throw( ::com::sun::star::uno::RuntimeException );
    virtual void SAL_CALL addClipboardListener( const ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::clipboard::XClipboardListener >& listener )
        throw( ::com::sun::star::uno::RuntimeException );
    virtual void SAL_CALL removeClipboardListener( const ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::clipboard::XClipboardListener >& listener )
        throw( ::com::sun::star::uno::RuntimeException );
    virtual ::rtl::OUString SAL_CALL getImplementationName()
        throw(::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName )
        throw(::com::sun::star::uno::RuntimeException);

    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames()
        throw(::com::sun::star::uno::RuntimeException);

private:
    ::osl::Mutex m_aMutex;
    ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::XTransferable > m_aTransferable;
};

} // namespace aqua

#endif
<commit_msg>INTEGRATION: CWS aquavcl01 (1.4.12); FILE MERGED 2007/06/14 12:06:18 tra 1.4.12.4: Work in progress, checked in to have it saved in the repos. 2007/05/27 10:02:02 tra 1.4.12.3: Need to implement XFlushableClipboard 2007/05/24 19:53:30 tra 1.4.12.2: Implementing paste system -> OOo 2006/03/12 19:50:48 tra 1.4.12.1: correct include file<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: aqua_clipboard.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2007-07-05 09:12:04 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _AQUA_CLIPBOARD_HXX_
#define _AQUA_CLIPBOARD_HXX_

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

#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif

#ifndef _CPPUHELPER_COMPBASE3_HXX_
#include <cppuhelper/compbase4.hxx>
#endif

#ifndef _COM_SUN_STAR_DATATRANSFER_XTRANSFERABLE_HPP_
#include <com/sun/star/datatransfer/XTransferable.hpp>
#endif

#ifndef _COM_SUN_STAR_DATATRANSFER_CLIPBOARD_XCLIPBOARDEX_HPP_
#include <com/sun/star/datatransfer/clipboard/XClipboardEx.hpp>
#endif

#ifndef _COM_SUN_STAR_DATATRANSFER_CLIPBOARD_XCLIPBOARDOWNER_HPP_
#include <com/sun/star/datatransfer/clipboard/XClipboardOwner.hpp>
#endif

#ifndef _COM_SUN_STAR_DATATRANSFER_CLIPBOARD_XCLIPBOARDLISTENER_HPP_
#include <com/sun/star/datatransfer/clipboard/XClipboardListener.hpp>
#endif

#ifndef _COM_SUN_STAR_DATATRANSFER_CLIPBOARD_XCLIPBOARDNOTIFIER_HPP_
#include <com/sun/star/datatransfer/clipboard/XClipboardNotifier.hpp>
#endif

#ifndef _COM_SUN_STAR_DATATRANSFER_XMIMECONTENTTYPEFACTORY_HPP_
#include <com/sun/star/datatransfer/XMimeContentTypeFactory.hpp>
#endif

#ifndef _COM_SUN_STAR_DATATRANSFER_CLIPBOARD_XFLUSHABLECLIPBOARD_HPP_
#include <com/sun/star/datatransfer/clipboard/XFlushableClipboard.hpp>
#endif

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

#include "DataFlavorMapping.hxx"

#include <premac.h>
    #include <Carbon/Carbon.h>
    #include <ApplicationServices/ApplicationServices.h>
#include <postmac.h>

#include <list>

// the service names
#define AQUA_CLIPBOARD_SERVICE_NAME "com.sun.star.datatransfer.clipboard.SystemClipboard"

// the implementation names
#define AQUA_CLIPBOARD_IMPL_NAME "com.sun.star.datatransfer.clipboard.AquaClipboard"

// the registry key names
#define AQUA_CLIPBOARD_REGKEY_NAME "/com.sun.star.datatransfer.clipboard.AquaClipboard/UNO/SERVICES/com.sun.star.datatransfer.clipboard.SystemClipboard"

namespace aqua {

class AquaClipboard :
    public cppu::WeakComponentImplHelper4< ::com::sun::star::datatransfer::clipboard::XClipboardEx,
                                           ::com::sun::star::datatransfer::clipboard::XClipboardNotifier,
                                           ::com::sun::star::datatransfer::clipboard::XFlushableClipboard,
                                           ::com::sun::star::lang::XServiceInfo >
{
public:
    AquaClipboard(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > ServiceManager);

   ~AquaClipboard();

    //------------------------------------------------
    // XClipboard
    //------------------------------------------------

    virtual ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::XTransferable > SAL_CALL getContents()
        throw( ::com::sun::star::uno::RuntimeException );

    virtual void SAL_CALL setContents( const ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::XTransferable >& xTransferable,
                                       const ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::clipboard::XClipboardOwner >& xClipboardOwner )
        throw( ::com::sun::star::uno::RuntimeException );

    virtual ::rtl::OUString SAL_CALL getName()
        throw( ::com::sun::star::uno::RuntimeException );

    //------------------------------------------------
    // XClipboardEx
    //------------------------------------------------

    virtual sal_Int8 SAL_CALL getRenderingCapabilities()
        throw( ::com::sun::star::uno::RuntimeException );

    //------------------------------------------------
    // XClipboardNotifier
    //------------------------------------------------

    virtual void SAL_CALL addClipboardListener( const ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::clipboard::XClipboardListener >& listener )
        throw( ::com::sun::star::uno::RuntimeException );

    virtual void SAL_CALL removeClipboardListener( const ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::clipboard::XClipboardListener >& listener )
        throw( ::com::sun::star::uno::RuntimeException );

    //------------------------------------------------
    // XFlushableClipboard
    //------------------------------------------------

    virtual void SAL_CALL flushClipboard( ) throw( com::sun::star::uno::RuntimeException );

    //------------------------------------------------
    // XServiceInfo
    //------------------------------------------------

    virtual ::rtl::OUString SAL_CALL getImplementationName()
        throw(::com::sun::star::uno::RuntimeException);

    virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName )
        throw(::com::sun::star::uno::RuntimeException);

    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames()
        throw(::com::sun::star::uno::RuntimeException);

private:
  /* Notify all registered XClipboardListener that the clipboard content
     has changed.
  */
  void fireClipboardChangedEvent();

  /* Notify the current clipboard owner that he is no longer the clipboard owner.
   */
  void fireLostClipboardOwnershipEvent();

  /* Event handler for application activated events. We need to determine the state of the clipboard
     in this event handler.
  */
  static OSStatus handleAppActivatedEvent(EventHandlerCallRef inHandlerCallRef, EventRef inEvent, void* inUserData);

  /* A clipboard promise keeper handler.
   */
  static OSStatus clipboardPromiseKeeperCallback(PasteboardRef inPasteboard,
                                                 PasteboardItemID itemID,
                                                 CFStringRef inFlavaor,
                                                 void* inContext);
private:
  const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > mrServiceMgr;
  ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::XMimeContentTypeFactory> mrXMimeCntFactory;
  ::std::list< ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::clipboard::XClipboardListener > > mClipboardListeners;
  ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::XTransferable > mXClipboardContent;
  com::sun::star::uno::Reference<com::sun::star::datatransfer::clipboard::XClipboardOwner> mXClipboardOwner;
  DataFlavorMapperPtr_t mpDataFlavorMapper;
  ::osl::Mutex m_aMutex;
  PasteboardRef mrClipboard;
  EventHandlerRef mrAppActivatedHdl;
};

} // namespace aqua

#endif
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015, Lehigh University
 * All rights reserved.
 * See COPYING for license.
 *
 * This file implements resampling TIFF images to be isotropic (uniform
 * voxel size) in batch mode.
 *
 * Usage: ./batch_resample <input_dir> <output_dir> <xy_z_ratio>
 */

#include <iostream>
#include "boost/program_options.hpp"
#include "boost/filesystem.hpp"
#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkBSplineInterpolateImageFunction.h"
#include "itkResampleImageFilter.h"

namespace fs = boost::filesystem;
typedef fs::path Path;

void ResampleImages(const Path &input_dir, const Path &output_dir,
                    double zspacing);
void ResampleImage(const std::string &input_filename,
                   const std::string &output_filename,
                   double zspacing);

int main (int argc, char **argv) {
  if (argc < 4) {
    std::cerr << "Batch Resample 3.7.0.\n"
		"Usage (for TIFF image only): ./batch_resample "
		"<input_dir> <output_dir> <z_spacing (relative to x/y)>" << std::endl;
    return -1;
  }

  Path input_dir(argv[1]);
  Path output_dir(argv[2]);
  double zspacing = atof(argv[3]);

  if (std::fabs(zspacing - 1) < 1e-6) {
    std::cout << "Images are isotropic. Quit." << std::endl;
    return 0;
  }

  if (fs::is_directory(input_dir)) {
    ResampleImages(input_dir, output_dir, zspacing);
  } else {
    std::cout << "Input dir should be a directory instead of a file. Abort."
              << std::endl;
  }
  return 0;
}

void ResampleImages(const Path &input_dir, const Path &output_dir,
                    double zspacing) {
  fs::directory_iterator end_it;
  for (fs::directory_iterator it(input_dir); it != end_it; ++it) {
    if (it->path().extension().string() == std::string(".tif")) {
      Path output_filename = output_dir;
      output_filename += it->path().stem();
      output_filename += "_iso.tif";
      ResampleImage(it->path().string(), output_filename.string(), zspacing);
      std::cout << "\"" << output_filename << "\" written." << std::endl;
    }
  }
}

void ResampleImage(const std::string &input_filename,
                   const std::string &output_filename,
                   double zspacing) {
  typedef itk::Image<unsigned short, 3> ImageType;
  typedef itk::ImageFileReader<ImageType> ReaderType;
  ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileName(input_filename);
  try {
    reader->Update();
  } catch(itk::ExceptionObject &e) {
    std::cerr << "Exception caught when reading an image!" << std::endl;
    std::cerr << e << std::endl;
  }

  typedef itk::BSplineInterpolateImageFunction<ImageType, double, double>
      InterpolatorType;
  InterpolatorType::Pointer interp = InterpolatorType::New();
  interp->SetSplineOrder(3);
  typedef itk::ResampleImageFilter<ImageType, ImageType> ResamplerType;
  ResamplerType::Pointer resampler = ResamplerType::New();
  resampler->SetInterpolator(interp);
  resampler->SetOutputOrigin(reader->GetOutput()->GetOrigin());
  resampler->SetOutputDirection(reader->GetOutput()->GetDirection());

  ImageType::SpacingType input_spacing;
  input_spacing.Fill(1.0);
  input_spacing[2] = zspacing;
  reader->GetOutput()->SetSpacing(input_spacing);

  const ImageType::SizeType &input_size =
      reader->GetOutput()->GetLargestPossibleRegion().GetSize();
  ImageType::SpacingType output_spacing;
  output_spacing.Fill(1.0);
  ImageType::SizeType output_size;
  const unsigned int kDimension = 3;
  for (unsigned i = 0; i < kDimension; ++i) {
    output_size[i] = static_cast<ImageType::SizeValueType>(
        input_size[i] * input_spacing[i]);
  }

  resampler->SetOutputSpacing(output_spacing);
  resampler->SetSize(output_size);
  resampler->SetDefaultPixelValue(0.0);
  resampler->SetInput(reader->GetOutput());

  typedef itk::ImageFileWriter<ImageType> WriterType;
  WriterType::Pointer writer = WriterType::New();
  writer->SetFileName(output_filename);
  writer->SetInput(resampler->GetOutput());

  try {
    writer->Update();
  } catch( itk::ExceptionObject & exp ) {
    std::cerr << "Exception caught when write an image!" << std::endl;
    std::cerr << exp << std::endl;
  }
}
<commit_msg>Changed version number to 3.7.1<commit_after>/**
 * Copyright (c) 2015, Lehigh University
 * All rights reserved.
 * See COPYING for license.
 *
 * This file implements resampling TIFF images to be isotropic (uniform
 * voxel size) in batch mode.
 *
 * Usage: ./batch_resample <input_dir> <output_dir> <xy_z_ratio>
 */

#include <iostream>
#include "boost/program_options.hpp"
#include "boost/filesystem.hpp"
#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkBSplineInterpolateImageFunction.h"
#include "itkResampleImageFilter.h"

namespace fs = boost::filesystem;
typedef fs::path Path;

void ResampleImages(const Path &input_dir, const Path &output_dir,
                    double zspacing);
void ResampleImage(const std::string &input_filename,
                   const std::string &output_filename,
                   double zspacing);

int main (int argc, char **argv) {
  if (argc < 4) {
    std::cerr << "Batch Resample 3.7.1.\n"
		"Usage (for TIFF image only): ./batch_resample "
		"<input_dir> <output_dir> <z_spacing (relative to x/y)>" << std::endl;
    return -1;
  }

  Path input_dir(argv[1]);
  Path output_dir(argv[2]);
  double zspacing = atof(argv[3]);

  if (std::fabs(zspacing - 1) < 1e-6) {
    std::cout << "Images are isotropic. Quit." << std::endl;
    return 0;
  }

  if (fs::is_directory(input_dir)) {
    ResampleImages(input_dir, output_dir, zspacing);
  } else {
    std::cout << "Input dir should be a directory instead of a file. Abort."
              << std::endl;
  }
  return 0;
}

void ResampleImages(const Path &input_dir, const Path &output_dir,
                    double zspacing) {
  fs::directory_iterator end_it;
  for (fs::directory_iterator it(input_dir); it != end_it; ++it) {
    if (it->path().extension().string() == std::string(".tif")) {
      Path output_filename = output_dir;
      output_filename += it->path().stem();
      output_filename += "_iso.tif";
      ResampleImage(it->path().string(), output_filename.string(), zspacing);
      std::cout << "\"" << output_filename << "\" written." << std::endl;
    }
  }
}

void ResampleImage(const std::string &input_filename,
                   const std::string &output_filename,
                   double zspacing) {
  typedef itk::Image<unsigned short, 3> ImageType;
  typedef itk::ImageFileReader<ImageType> ReaderType;
  ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileName(input_filename);
  try {
    reader->Update();
  } catch(itk::ExceptionObject &e) {
    std::cerr << "Exception caught when reading an image!" << std::endl;
    std::cerr << e << std::endl;
  }

  typedef itk::BSplineInterpolateImageFunction<ImageType, double, double>
      InterpolatorType;
  InterpolatorType::Pointer interp = InterpolatorType::New();
  interp->SetSplineOrder(3);
  typedef itk::ResampleImageFilter<ImageType, ImageType> ResamplerType;
  ResamplerType::Pointer resampler = ResamplerType::New();
  resampler->SetInterpolator(interp);
  resampler->SetOutputOrigin(reader->GetOutput()->GetOrigin());
  resampler->SetOutputDirection(reader->GetOutput()->GetDirection());

  ImageType::SpacingType input_spacing;
  input_spacing.Fill(1.0);
  input_spacing[2] = zspacing;
  reader->GetOutput()->SetSpacing(input_spacing);

  const ImageType::SizeType &input_size =
      reader->GetOutput()->GetLargestPossibleRegion().GetSize();
  ImageType::SpacingType output_spacing;
  output_spacing.Fill(1.0);
  ImageType::SizeType output_size;
  const unsigned int kDimension = 3;
  for (unsigned i = 0; i < kDimension; ++i) {
    output_size[i] = static_cast<ImageType::SizeValueType>(
        input_size[i] * input_spacing[i]);
  }

  resampler->SetOutputSpacing(output_spacing);
  resampler->SetSize(output_size);
  resampler->SetDefaultPixelValue(0.0);
  resampler->SetInput(reader->GetOutput());

  typedef itk::ImageFileWriter<ImageType> WriterType;
  WriterType::Pointer writer = WriterType::New();
  writer->SetFileName(output_filename);
  writer->SetInput(resampler->GetOutput());

  try {
    writer->Update();
  } catch( itk::ExceptionObject & exp ) {
    std::cerr << "Exception caught when write an image!" << std::endl;
    std::cerr << exp << std::endl;
  }
}
<|endoftext|>