<commit_before>
/*!
	\file

	\author Igor Mironchik (igor.mironchik at gmail dot com).

	Copyright (c) 2017 Igor Mironchik

	Permission is hereby granted, free of charge, to any person
	obtaining a copy of this software and associated documentation
	files (the "Software"), to deal in the Software without
	restriction, including without limitation the rights to use,
	copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the
	Software is furnished to do so, subject to the following
	conditions:

	The above copyright notice and this permission notice shall be
	included in all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
	EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
	OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
	NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
	HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
	WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
	FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
	OTHER DEALINGS IN THE SOFTWARE.
*/

#ifndef CFGFILE__TYPES_HPP__INCLUDED
#define CFGFILE__TYPES_HPP__INCLUDED

// C++ include.
#include <string>
#include <iostream>
#include <cwctype>
#include <cctype>

#ifdef CFGFILE_QT_SUPPORT
// Qt include.
#include <QString>
#include <QTextStream>
#endif // CFGFILE_QT_SUPPORT

namespace cfgfile {

//
// wstring_trait_t
//

//! Trait for std::wstring support.
struct wstring_trait_t final {
	//! String type.
	using string_t = std::wstring;

	//! Char type.
	using char_t = string_t::value_type;

	//! Out stream type.
	using ostream_t = std::wostream;

	//! In stream type.
	using istream_t = std::wistream;

	//! Type of pos in stream.
	using pos_t = std::streamoff;

	static inline string_t to_string( pos_t pos )
	{
		return std::to_wstring( pos );
	}

	static inline string_t from_ascii( const std::string & str )
	{
		std::wstring res;
		res.assign( str.cbegin(), str.cend() );

		return res;
	}

	static inline char_t from_ascii( char ch )
	{
		return (char_t) ch;
	}

	static inline void noskipws( istream_t & stream )
	{
		stream >> std::noskipws;
	}

	static inline bool is_at_end( istream_t & stream )
	{
		char_t tmp = 0;

		stream >> tmp;

		if( tmp )
		{
			stream.putback( tmp );

			return false;
		}
		else
			return true;
	}

	static inline bool is_space( char_t ch )
	{
		return std::iswspace( ch );
	}

	static inline void to_begin( istream_t & stream )
	{
		stream.seekg( 0 );
	}
}; // struct wstring_trait_t

//
// string_trait_t
//

//! Trait for std::string support.
struct string_trait_t final {
	//! String type.
	using string_t = std::string;

	//! Char type.
	using char_t = string_t::value_type;

	//! Input stream type.
	using istream_t = std::istream;

	//! Type of pos in stream.
	using pos_t = std::streamoff;

	//! Output stream type.
	using ostream_t = std::ostream;

	static inline string_t to_string( pos_t pos )
	{
		return std::to_string( pos );
	}

	static inline string_t from_ascii( const std::string & str )
	{
		return str;
	}

	static inline char_t from_ascii( char ch )
	{
		return ch;
	}

	static inline void noskipws( istream_t & stream )
	{
		stream >> std::noskipws;
	}

	static inline bool is_at_end( istream_t & stream )
	{
		char_t tmp = 0;

		stream >> tmp;

		if( tmp )
		{
			stream.putback( tmp );

			return false;
		}
		else
			return true;
	}

	static inline bool is_space( char_t ch )
	{
		return std::isspace( (unsigned char) ch );
	}

	static inline void to_begin( istream_t & stream )
	{
		stream.seekg( 0 );
	}
}; // struct string_trait_t

#ifdef CFGFILE_QT_SUPPORT

//
// qstring_wrapper_t
//

//! QString wrapper.
class qstring_wrapper_t {
public:
	using size_type = int;

	qstring_wrapper_t()
	{
	}

	qstring_wrapper_t( size_type size, QChar ch )
		:	m_str( size, ch )
	{
	}

	qstring_wrapper_t( const char * str )
		:	m_str( str )
	{
	}

	qstring_wrapper_t( const QString & other )
		:	m_str( other )
	{
	}

	qstring_wrapper_t( const QChar * unicode, size_type size = -1 )
		:	m_str( unicode, size )
	{
	}

	qstring_wrapper_t( QChar ch )
		:	m_str( ch )
	{
	}

	qstring_wrapper_t( QLatin1String str )
		:	m_str( str )
	{
	}

	qstring_wrapper_t( const QByteArray & ba )
		:	m_str( ba )
	{
	}

	operator QString ()
	{
		return m_str;
	}

	operator QString () const
	{
		return m_str;
	}

	inline bool empty() const
	{
		return m_str.isEmpty();
	}

	static const int npos = -1;

	inline int find( QChar ch ) const
	{
		return m_str.indexOf( ch );
	}

	inline int find( const qstring_wrapper_t & str ) const
	{
		return m_str.indexOf( str.m_str );
	}

	inline int rfind( const qstring_wrapper_t & str ) const
	{
		return m_str.lastIndexOf( str.m_str );
	}

	inline int rfind( QChar ch ) const
	{
		return m_str.lastIndexOf( ch );
	}

	qstring_wrapper_t & replace( size_type pos, size_type count,
		const qstring_wrapper_t & v )
	{
		m_str.replace( pos, count, v.m_str );

		return *this;
	}

	inline QString::iterator begin()
	{
		return m_str.begin();
	}

	inline QString::iterator end()
	{
		return m_str.end();
	}

	inline QString::const_iterator begin() const
	{
		return m_str.begin();
	}

	inline QString::const_iterator end() const
	{
		return m_str.end();
	}

	inline QString::const_iterator cbegin() const
	{
		return m_str.begin();
	}

	inline QString::const_iterator cend() const
	{
		return m_str.end();
	}

	inline size_type length() const
	{
		return m_str.length();
	}

	inline const QChar at( int position ) const
	{
		return m_str.at( position );
	}

	inline qstring_wrapper_t substr( size_type pos, size_type count = npos ) const
	{
		return m_str.mid( pos, count );
	}

	friend bool operator == ( const qstring_wrapper_t & s1,
		const qstring_wrapper_t & s2 )
	{
		return ( s1.m_str == s2.m_str );
	}

	friend qstring_wrapper_t operator + ( const qstring_wrapper_t & s1,
		const qstring_wrapper_t & s2 )
	{
		return qstring_wrapper_t( s1.m_str + s2.m_str );
	}

	friend qstring_wrapper_t operator + ( const qstring_wrapper_t & s1,
		const char * s2 )
	{
		return qstring_wrapper_t( s1.m_str + s2 );
	}

	friend qstring_wrapper_t operator + ( const char * s1,
		const qstring_wrapper_t & s2 )
	{
		return qstring_wrapper_t( s1 + s2.m_str );
	}

	friend qstring_wrapper_t operator + ( const qstring_wrapper_t & s1,
		const char ch )
	{
		return qstring_wrapper_t( s1.m_str + ch );
	}

	friend qstring_wrapper_t operator + ( const char ch,
		const qstring_wrapper_t & s2 )
	{
		return qstring_wrapper_t( ch + s2.m_str );
	}

	friend QTextStream & operator << ( QTextStream & to,
		const qstring_wrapper_t & what )
	{
		to << what.m_str;

		return to;
	}

	inline const QChar operator [] ( size_type pos ) const
	{
		return m_str[ pos ];
	}

	inline qstring_wrapper_t & append( const qstring_wrapper_t & other )
	{
		m_str.append( other.m_str );

		return *this;
	}

	inline qstring_wrapper_t & append( size_type count, QChar ch )
	{
		m_str.append( QString( count, ch ) );

		return *this;
	}

	inline void clear()
	{
		m_str.clear();
	}

	inline void push_back( QChar ch )
	{
		m_str.append( ch );
	}

private:
	//! Actual string.
	QString m_str;
}; // class qstring_wrapper_t

//
// qstring_trait_t
//

//! Trait for QString support.
struct qstring_trait_t final {
	//! String type.
	using string_t = qstring_wrapper_t;

	//! Char type.
	using char_t = QChar;

	//! Out stream type.
	using ostream_t = QTextStream;

	//! In stream type.
	using istream_t = QTextStream;

	//! Type of pos in stream.
	using pos_t = qint64;

	static inline string_t to_string( pos_t pos )
	{
		return QString::number( pos );
	}

	static inline string_t from_ascii( const std::string & str )
	{
		return qstring_wrapper_t( QString( str.c_str() ) );
	}

	static inline char_t from_ascii( char ch )
	{
		return QLatin1Char( ch );
	}

	static inline void noskipws( istream_t & )
	{
	}

	static inline bool is_at_end( istream_t & stream )
	{
		return stream.atEnd();
	}

	static inline bool is_space( char_t ch )
	{
		return ch.isSpace();
	}

	static inline void to_begin( istream_t & stream )
	{
		stream.seek( 0 );
	}
}; // struct qstring_trait_t

#endif // CFGFILE_QT_SUPPORT

//
// DISABLE_COPY
//

//! Macro for disabling copy.
#define DISABLE_COPY( Class ) \
	Class( const Class & ) = delete; \
	Class & operator= ( const Class & ) = delete;

} /* namespace cfgfile */

#endif // CFGFILE__TYPES_HPP__INCLUDED
<commit_msg>Supressed warnings.<commit_after>
/*!
	\file

	\author Igor Mironchik (igor.mironchik at gmail dot com).

	Copyright (c) 2017 Igor Mironchik

	Permission is hereby granted, free of charge, to any person
	obtaining a copy of this software and associated documentation
	files (the "Software"), to deal in the Software without
	restriction, including without limitation the rights to use,
	copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the
	Software is furnished to do so, subject to the following
	conditions:

	The above copyright notice and this permission notice shall be
	included in all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
	EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
	OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
	NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
	HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
	WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
	FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
	OTHER DEALINGS IN THE SOFTWARE.
*/

#ifndef CFGFILE__TYPES_HPP__INCLUDED
#define CFGFILE__TYPES_HPP__INCLUDED

// C++ include.
#include <string>
#include <iostream>
#include <cwctype>
#include <cctype>

#ifdef CFGFILE_QT_SUPPORT
// Qt include.
#include <QString>
#include <QTextStream>
#endif // CFGFILE_QT_SUPPORT

namespace cfgfile {

//
// wstring_trait_t
//

//! Trait for std::wstring support.
struct wstring_trait_t final {
	//! String type.
	using string_t = std::wstring;

	//! Char type.
	using char_t = string_t::value_type;

	//! Out stream type.
	using ostream_t = std::wostream;

	//! In stream type.
	using istream_t = std::wistream;

	//! Type of pos in stream.
	using pos_t = std::streamoff;

	static inline string_t to_string( pos_t pos )
	{
		return std::to_wstring( pos );
	}

	static inline string_t from_ascii( const std::string & str )
	{
		std::wstring res;
		res.assign( str.cbegin(), str.cend() );

		return res;
	}

	static inline char_t from_ascii( char ch )
	{
		return (char_t) ch;
	}

	static inline void noskipws( istream_t & stream )
	{
		stream >> std::noskipws;
	}

	static inline bool is_at_end( istream_t & stream )
	{
		char_t tmp = 0;

		stream >> tmp;

		if( tmp )
		{
			stream.putback( tmp );

			return false;
		}
		else
			return true;
	}

	static inline bool is_space( char_t ch )
	{
		return ( std::iswspace( ch ) != 0 );
	}

	static inline void to_begin( istream_t & stream )
	{
		stream.seekg( 0 );
	}
}; // struct wstring_trait_t

//
// string_trait_t
//

//! Trait for std::string support.
struct string_trait_t final {
	//! String type.
	using string_t = std::string;

	//! Char type.
	using char_t = string_t::value_type;

	//! Input stream type.
	using istream_t = std::istream;

	//! Type of pos in stream.
	using pos_t = std::streamoff;

	//! Output stream type.
	using ostream_t = std::ostream;

	static inline string_t to_string( pos_t pos )
	{
		return std::to_string( pos );
	}

	static inline string_t from_ascii( const std::string & str )
	{
		return str;
	}

	static inline char_t from_ascii( char ch )
	{
		return ch;
	}

	static inline void noskipws( istream_t & stream )
	{
		stream >> std::noskipws;
	}

	static inline bool is_at_end( istream_t & stream )
	{
		char_t tmp = 0;

		stream >> tmp;

		if( tmp )
		{
			stream.putback( tmp );

			return false;
		}
		else
			return true;
	}

	static inline bool is_space( char_t ch )
	{
		return ( std::isspace( (int) ch ) != 0 );
	}

	static inline void to_begin( istream_t & stream )
	{
		stream.seekg( 0 );
	}
}; // struct string_trait_t

#ifdef CFGFILE_QT_SUPPORT

//
// qstring_wrapper_t
//

//! QString wrapper.
class qstring_wrapper_t {
public:
	using size_type = int;

	qstring_wrapper_t()
	{
	}

	qstring_wrapper_t( size_type size, QChar ch )
		:	m_str( size, ch )
	{
	}

	qstring_wrapper_t( const char * str )
		:	m_str( str )
	{
	}

	qstring_wrapper_t( const QString & other )
		:	m_str( other )
	{
	}

	qstring_wrapper_t( const QChar * unicode, size_type size = -1 )
		:	m_str( unicode, size )
	{
	}

	qstring_wrapper_t( QChar ch )
		:	m_str( ch )
	{
	}

	qstring_wrapper_t( QLatin1String str )
		:	m_str( str )
	{
	}

	qstring_wrapper_t( const QByteArray & ba )
		:	m_str( ba )
	{
	}

	operator QString ()
	{
		return m_str;
	}

	operator QString () const
	{
		return m_str;
	}

	inline bool empty() const
	{
		return m_str.isEmpty();
	}

	static const int npos = -1;

	inline int find( QChar ch ) const
	{
		return m_str.indexOf( ch );
	}

	inline int find( const qstring_wrapper_t & str ) const
	{
		return m_str.indexOf( str.m_str );
	}

	inline int rfind( const qstring_wrapper_t & str ) const
	{
		return m_str.lastIndexOf( str.m_str );
	}

	inline int rfind( QChar ch ) const
	{
		return m_str.lastIndexOf( ch );
	}

	qstring_wrapper_t & replace( size_type pos, size_type count,
		const qstring_wrapper_t & v )
	{
		m_str.replace( pos, count, v.m_str );

		return *this;
	}

	inline QString::iterator begin()
	{
		return m_str.begin();
	}

	inline QString::iterator end()
	{
		return m_str.end();
	}

	inline QString::const_iterator begin() const
	{
		return m_str.begin();
	}

	inline QString::const_iterator end() const
	{
		return m_str.end();
	}

	inline QString::const_iterator cbegin() const
	{
		return m_str.begin();
	}

	inline QString::const_iterator cend() const
	{
		return m_str.end();
	}

	inline size_type length() const
	{
		return m_str.length();
	}

	inline const QChar at( int position ) const
	{
		return m_str.at( position );
	}

	inline qstring_wrapper_t substr( size_type pos, size_type count = npos ) const
	{
		return m_str.mid( pos, count );
	}

	friend bool operator == ( const qstring_wrapper_t & s1,
		const qstring_wrapper_t & s2 )
	{
		return ( s1.m_str == s2.m_str );
	}

	friend qstring_wrapper_t operator + ( const qstring_wrapper_t & s1,
		const qstring_wrapper_t & s2 )
	{
		return qstring_wrapper_t( s1.m_str + s2.m_str );
	}

	friend qstring_wrapper_t operator + ( const qstring_wrapper_t & s1,
		const char * s2 )
	{
		return qstring_wrapper_t( s1.m_str + s2 );
	}

	friend qstring_wrapper_t operator + ( const char * s1,
		const qstring_wrapper_t & s2 )
	{
		return qstring_wrapper_t( s1 + s2.m_str );
	}

	friend qstring_wrapper_t operator + ( const qstring_wrapper_t & s1,
		const char ch )
	{
		return qstring_wrapper_t( s1.m_str + ch );
	}

	friend qstring_wrapper_t operator + ( const char ch,
		const qstring_wrapper_t & s2 )
	{
		return qstring_wrapper_t( ch + s2.m_str );
	}

	friend QTextStream & operator << ( QTextStream & to,
		const qstring_wrapper_t & what )
	{
		to << what.m_str;

		return to;
	}

	inline const QChar operator [] ( size_type pos ) const
	{
		return m_str[ pos ];
	}

	inline qstring_wrapper_t & append( const qstring_wrapper_t & other )
	{
		m_str.append( other.m_str );

		return *this;
	}

	inline qstring_wrapper_t & append( size_type count, QChar ch )
	{
		m_str.append( QString( count, ch ) );

		return *this;
	}

	inline void clear()
	{
		m_str.clear();
	}

	inline void push_back( QChar ch )
	{
		m_str.append( ch );
	}

private:
	//! Actual string.
	QString m_str;
}; // class qstring_wrapper_t

//
// qstring_trait_t
//

//! Trait for QString support.
struct qstring_trait_t final {
	//! String type.
	using string_t = qstring_wrapper_t;

	//! Char type.
	using char_t = QChar;

	//! Out stream type.
	using ostream_t = QTextStream;

	//! In stream type.
	using istream_t = QTextStream;

	//! Type of pos in stream.
	using pos_t = qint64;

	static inline string_t to_string( pos_t pos )
	{
		return QString::number( pos );
	}

	static inline string_t from_ascii( const std::string & str )
	{
		return qstring_wrapper_t( QString( str.c_str() ) );
	}

	static inline char_t from_ascii( char ch )
	{
		return QLatin1Char( ch );
	}

	static inline void noskipws( istream_t & )
	{
	}

	static inline bool is_at_end( istream_t & stream )
	{
		return stream.atEnd();
	}

	static inline bool is_space( char_t ch )
	{
		return ch.isSpace();
	}

	static inline void to_begin( istream_t & stream )
	{
		stream.seek( 0 );
	}
}; // struct qstring_trait_t

#endif // CFGFILE_QT_SUPPORT

//
// DISABLE_COPY
//

//! Macro for disabling copy.
#define DISABLE_COPY( Class ) \
	Class( const Class & ) = delete; \
	Class & operator= ( const Class & ) = delete;

} /* namespace cfgfile */

#endif // CFGFILE__TYPES_HPP__INCLUDED
<|endoftext|>


<commit_before>#include <vector>
#include <string>
#include <ncurses.h>
#include <iostream>
#include <stdexcept>

using std::string;

void die(const string& msg);

class Marquee
{
private:
	int row;
	string text;
	unsigned int position;
public:
	Marquee(int row, const string& text) : row(row), text(text), position(0) {
		if(this->text.empty()) {
			throw std::length_error("Text was empty");
		}
	}
	void Draw();
};

void Marquee::Draw()
{
	if (this->position==this->text.length()) {
		this->position=0;
	}
	mvdelch(this->row, 0);
	mvinsch(this->row, COLS-1, this->text[this->position]);
	++this->position;
}

int main(void)
{
	initscr();
	const string text("WARNING * ");

	std::vector<Marquee> marquees;
	for (int i=0; i < 10; i++)
		marquees.push_back(Marquee(i, text));

	while(true) {
		refresh();
		for (std::vector<Marquee>::iterator it=marquees.begin(); it != marquees.end(); ++it) {
			(*it).Draw();
		}
		napms(100);
	}

	endwin();
	return 0;
}

void die(const string& v)
{
	endwin();
	std::cerr << v << std::endl;
	exit(1);
}
<commit_msg>Interesting 'Main Menu'<commit_after>#include <vector>
#include <cmath>
#include <string>
#include <ncurses.h>
#include <iostream>
#include <stdexcept>

using std::string;
using std::vector;

void die(const string& msg);

int main(void)
{
	initscr();

	vector<string> options;
	options.push_back("Read the News");
	options.push_back("Fill the Bucket");
	options.push_back("Save the Options");
	options.push_back("Exit");

	mvaddstr(0, 0, "Main Menu");

	for (unsigned int i = 0; i < options.size(); i++) {
		mvprintw(4+(i*2), 10, "%d. %s", i+1, options[i].c_str());
	}

	mvprintw(4+(options.size()*2)+1, 10, "Use arrow keys to move; Enter to select:");

	keypad(stdscr, TRUE);
	nodelay(stdscr, TRUE);
	noecho();

	int selection = 0;
	while(true) {
		int ch = getch();
		mvchgat(4+(selection*2), 10+3, options[selection].length(), 0, 0, NULL);
		switch(ch) {
			case KEY_DOWN:
				selection++;
				break;
			case KEY_UP:
				selection--;
				break;
		}
		selection=std::min(std::max(selection, 0), (int)(options.size()-1));
		mvchgat(4+(selection*2), 10+3, options[selection].length(), A_REVERSE, 0, NULL);
	}

	endwin();
	return 0;
}

void die(const string& v)
{
	endwin();
	std::cerr << v << std::endl;
	exit(1);
}
<|endoftext|>


<commit_before>/*
    Copyright (c) 2005      Olivier Goffart           <ogoffart@kde.org>

    Kopete    (c) 2005-2007 by the Kopete developers  <kopete-devel@kde.org>

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

#include "contactaddednotifydialog.h"

#include <qlabel.h>
#include <qcheckbox.h>
#include <qapplication.h>

#include <klocale.h>
#include <kcombobox.h>
#include <klineedit.h>
#include <kpushbutton.h>
#include <kiconloader.h>

#include <kabc/addressee.h>

#include "kopetegroup.h"
#include "kopeteaccount.h"
#include "kopeteuiglobal.h"
#include "kopeteprotocol.h"
#include "kopetecontactlist.h"
#include "kopetemetacontact.h"
#include "addressbooklinkwidget.h"
#include "addressbookselectordialog.h"
#include "ui_contactaddednotifywidget.h"

namespace Kopete {

namespace UI {

struct ContactAddedNotifyDialog::Private
{
	Ui::ContactAddedNotifyWidget *widget;
	Account *account;
	QString contactId;
	QString addressbookId;
};

ContactAddedNotifyDialog::ContactAddedNotifyDialog(const QString& contactId,
		const QString& contactNick, Kopete::Account *account, const HideWidgetOptions &hide)
	: KDialog( Global::mainWidget() ), d(new Private())
{
	setCaption( i18n("Someone Has Added You") );
	setButtons( KDialog::Ok | KDialog::Cancel );
    setAttribute( Qt::WA_DeleteOnClose );

	d->widget=new Ui::ContactAddedNotifyWidget;
	QWidget* w = new QWidget(this);
	d->widget->setupUi(w);
	setMainWidget(w);

	d->account=account;
	d->contactId=contactId;
	d->widget->m_label->setText(i18n("<qt> The contact %2 has added you to his/her contact list. (Account %3)</qt>",
			QString(QUrl::toPercentEncoding( account->protocol()->pluginId() )) + QString::fromLatin1(":")
			                 +  QString(QUrl::toPercentEncoding( account->accountId() )) ,
				  contactNick.isEmpty() ? contactId : contactNick + QString::fromLatin1(" < ") + contactId + QString::fromLatin1(" >")  ,
				  account->accountLabel()  	)   );
	if( hide & InfoButton)
		d->widget->m_infoButton->hide() ;
	if( hide & AuthorizeCheckBox )
	{
		d->widget->m_authorizeCb->hide();
		d->widget->m_authorizeCb->setChecked(false);
	}
	if( hide & AddCheckBox )
	{
		d->widget->m_addCb->hide();
		d->widget->m_addCb->setChecked(false);
	}
	if( hide & AddGroupBox )
		d->widget->m_contactInfoBox->hide();

	// Populate the groups list
	QListIterator<Group *> it(Kopete::ContactList::self()->groups());
	while ( it.hasNext() )
	{
		Group *g = it.next();
		QString groupname = g->displayName();
		if ( g->type() == Group::Normal && !groupname.isEmpty() )
		{
			d->widget->m_groupList->addItem(groupname);
		}
	}
	d->widget->m_groupList->setEditText(QString()); //default to top-level

	connect( d->widget->widAddresseeLink, SIGNAL( addresseeChanged( const KABC::Addressee& ) ), this, SLOT( slotAddresseeSelected( const KABC::Addressee& ) ) );
	connect( d->widget->m_infoButton, SIGNAL( clicked() ), this, SLOT( slotInfoClicked() ) );

	connect( this, SIGNAL(okClicked()) , this , SLOT(slotFinished()));

}

ContactAddedNotifyDialog::~ContactAddedNotifyDialog()
{
// deleting the widget is not needed because it has a parent
// which takes care of them
//	delete d->widget;
	delete d;
}

bool ContactAddedNotifyDialog::added() const
{
	return d->widget->m_addCb->isChecked();
}

bool ContactAddedNotifyDialog::authorized() const
{
	return d->widget->m_authorizeCb->isChecked();
}

QString ContactAddedNotifyDialog::displayName() const
{
	return d->widget->m_displayNameEdit->text();
}

Group *ContactAddedNotifyDialog::group() const
{
	QString grpName=d->widget->m_groupList->currentText();
	if(grpName.isEmpty())
		return Group::topLevel();

	return ContactList::self()->findGroup( grpName  );
}

MetaContact *ContactAddedNotifyDialog::addContact() const
{
	if(!added() || !d->account)
		return 0L;

	MetaContact *metacontact=d->account->addContact(d->contactId, displayName(), group());
	if(!metacontact)
		return 0L;

	metacontact->setKabcId(d->addressbookId);

	return metacontact;
}

void ContactAddedNotifyDialog::slotAddresseeSelected( const KABC::Addressee & addr )
{
	if ( !addr.isEmpty() )
	{
		d->addressbookId = addr.uid();
	}
}

void ContactAddedNotifyDialog::slotInfoClicked()
{
	emit infoClicked(d->contactId);
}

void ContactAddedNotifyDialog::slotFinished()
{
	emit applyClicked(d->contactId);
}

} // namespace UI
} // namespace Kopete
#include "contactaddednotifydialog.moc"
<commit_msg>We must delete it<commit_after>/*
    Copyright (c) 2005      Olivier Goffart           <ogoffart@kde.org>

    Kopete    (c) 2005-2007 by the Kopete developers  <kopete-devel@kde.org>

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

#include "contactaddednotifydialog.h"

#include <qlabel.h>
#include <qcheckbox.h>
#include <qapplication.h>

#include <klocale.h>
#include <kcombobox.h>
#include <klineedit.h>
#include <kpushbutton.h>
#include <kiconloader.h>

#include <kabc/addressee.h>

#include "kopetegroup.h"
#include "kopeteaccount.h"
#include "kopeteuiglobal.h"
#include "kopeteprotocol.h"
#include "kopetecontactlist.h"
#include "kopetemetacontact.h"
#include "addressbooklinkwidget.h"
#include "addressbookselectordialog.h"
#include "ui_contactaddednotifywidget.h"

namespace Kopete {

namespace UI {

struct ContactAddedNotifyDialog::Private
{
	Ui::ContactAddedNotifyWidget *widget;
	Account *account;
	QString contactId;
	QString addressbookId;
};

ContactAddedNotifyDialog::ContactAddedNotifyDialog(const QString& contactId,
		const QString& contactNick, Kopete::Account *account, const HideWidgetOptions &hide)
	: KDialog( Global::mainWidget() ), d(new Private())
{
	setCaption( i18n("Someone Has Added You") );
	setButtons( KDialog::Ok | KDialog::Cancel );
    setAttribute( Qt::WA_DeleteOnClose );

	d->widget=new Ui::ContactAddedNotifyWidget;
	QWidget* w = new QWidget(this);
	d->widget->setupUi(w);
	setMainWidget(w);

	d->account=account;
	d->contactId=contactId;
	d->widget->m_label->setText(i18n("<qt> The contact %2 has added you to his/her contact list. (Account %3)</qt>",
			QString(QUrl::toPercentEncoding( account->protocol()->pluginId() )) + QString::fromLatin1(":")
			                 +  QString(QUrl::toPercentEncoding( account->accountId() )) ,
				  contactNick.isEmpty() ? contactId : contactNick + QString::fromLatin1(" < ") + contactId + QString::fromLatin1(" >")  ,
				  account->accountLabel()  	)   );
	if( hide & InfoButton)
		d->widget->m_infoButton->hide() ;
	if( hide & AuthorizeCheckBox )
	{
		d->widget->m_authorizeCb->hide();
		d->widget->m_authorizeCb->setChecked(false);
	}
	if( hide & AddCheckBox )
	{
		d->widget->m_addCb->hide();
		d->widget->m_addCb->setChecked(false);
	}
	if( hide & AddGroupBox )
		d->widget->m_contactInfoBox->hide();

	// Populate the groups list
	QListIterator<Group *> it(Kopete::ContactList::self()->groups());
	while ( it.hasNext() )
	{
		Group *g = it.next();
		QString groupname = g->displayName();
		if ( g->type() == Group::Normal && !groupname.isEmpty() )
		{
			d->widget->m_groupList->addItem(groupname);
		}
	}
	d->widget->m_groupList->setEditText(QString()); //default to top-level

	connect( d->widget->widAddresseeLink, SIGNAL( addresseeChanged( const KABC::Addressee& ) ), this, SLOT( slotAddresseeSelected( const KABC::Addressee& ) ) );
	connect( d->widget->m_infoButton, SIGNAL( clicked() ), this, SLOT( slotInfoClicked() ) );

	connect( this, SIGNAL(okClicked()) , this , SLOT(slotFinished()));

}

ContactAddedNotifyDialog::~ContactAddedNotifyDialog()
{
	delete d->widget;
	delete d;
}

bool ContactAddedNotifyDialog::added() const
{
	return d->widget->m_addCb->isChecked();
}

bool ContactAddedNotifyDialog::authorized() const
{
	return d->widget->m_authorizeCb->isChecked();
}

QString ContactAddedNotifyDialog::displayName() const
{
	return d->widget->m_displayNameEdit->text();
}

Group *ContactAddedNotifyDialog::group() const
{
	QString grpName=d->widget->m_groupList->currentText();
	if(grpName.isEmpty())
		return Group::topLevel();

	return ContactList::self()->findGroup( grpName  );
}

MetaContact *ContactAddedNotifyDialog::addContact() const
{
	if(!added() || !d->account)
		return 0L;

	MetaContact *metacontact=d->account->addContact(d->contactId, displayName(), group());
	if(!metacontact)
		return 0L;

	metacontact->setKabcId(d->addressbookId);

	return metacontact;
}

void ContactAddedNotifyDialog::slotAddresseeSelected( const KABC::Addressee & addr )
{
	if ( !addr.isEmpty() )
	{
		d->addressbookId = addr.uid();
	}
}

void ContactAddedNotifyDialog::slotInfoClicked()
{
	emit infoClicked(d->contactId);
}

void ContactAddedNotifyDialog::slotFinished()
{
	emit applyClicked(d->contactId);
}

} // namespace UI
} // namespace Kopete
#include "contactaddednotifydialog.moc"
<|endoftext|>


<commit_before>/** @file
    @brief Implementation for class that tracks and identifies LEDs.

    @date 2015

    @author
    Sensics, Inc.
    <http://sensics.com/osvr>
*/

// Copyright 2015 Sensics, Inc.
//
// Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Internal Includes
#include "BeaconBasedPoseEstimator.h"

// Library/third-party includes
#include <osvr/Util/QuatlibInteropC.h>

// Standard includes
// - none

namespace osvr {
namespace vbtracker {

    // clang-format off
    // Default 3D locations for the beacons on an OSVR HDK face plate, in
    // millimeters
    const DoubleVecVec OsvrHdkLedLocations_SENSOR0 = {
        {-85, 3, 24.09},
        { -83.2, -14.01, 13.89 },
        { -47, 51, 24.09 },
        { 47, 51, 24.09 },
        { 86.6, 2.65, 24.09 },
        { 85.5, -14.31, 13.89 },
        { 85.2, 19.68, 13.89 },
        { 21, 51, 13.09 },
        { -21, 51, 13.09 },
        { -84.2, 19.99, 13.89 },
        { -60.41, 47.55, 44.6 },
        { -80.42, 20.48, 42.9 },
        { -82.01, 2.74, 42.4 },
        { -80.42, -14.99, 42.9 },
        { -60.41, -10.25, 48.1 },
        { -60.41, 15.75, 48.1 },
        { -30.41, 32.75, 50.5 },
        { -31.41, 47.34, 47 },
        { -0.41, -15.25, 51.3 },
        { -30.41, -27.25, 50.5 },
        { -60.44, -41.65, 45.1 },
        { -22.41, -41.65, 47.8 },
        { 21.59, -41.65, 47.8 },
        { 59.59, -41.65, 45.1 },
        { 79.63, -14.98, 42.9 },
        { 29.59, -27.25, 50.5 },
        { 81.19, 2.74, 42.4 },
        { 79.61, 20.48, 42.9 },
        { 59.59, 47.55, 44.6 },
        { 30.59, 47.55, 47 },
        { 29.59, 32.75, 50.5 },
        { -0.41, 20.75, 51.3 },
        { 59.59, 15.75, 48.1 },
        { 59.59, -10.25, 48.1 }
    };

    // Default 3D locations for the beacons on an OSVR HDK back plate, in
    // millimeters
    const DoubleVecVec OsvrHdkLedLocations_SENSOR1 = {
        {1, 23.8, 0},
        { 11, 5.8, 0 },
        { 9, -23.8, 0 },
        { 0, -8.8, 0 },
        { -9, -23.8, 0 },
        { -12, 5.8, 0 }
    };
    // clang-format on

    BeaconBasedPoseEstimator::BeaconBasedPoseEstimator(
        const DoubleVecVec &cameraMatrix, const std::vector<double> &distCoeffs,
        const DoubleVecVec &beacons) {
        SetBeacons(beacons);
        SetCameraMatrix(cameraMatrix);
        SetDistCoeffs(distCoeffs);
        m_gotPose = false;
    }

    bool BeaconBasedPoseEstimator::SetBeacons(const DoubleVecVec &beacons) {
        // Our existing pose won't match anymore.
        m_gotPose = false;

        for (int i = 0; i < beacons.size(); i++) {
            if (beacons[i].size() != 3) {
                m_beacons.clear();
                return false;
            }
            cv::Point3f p(static_cast<float>(beacons[i][0]),
                          static_cast<float>(beacons[i][1]),
                          static_cast<float>(beacons[i][2]));
            m_beacons.push_back(p);
        }

        return true;
    }

    bool BeaconBasedPoseEstimator::SetCameraMatrix(
        const DoubleVecVec &cameraMatrix) {
        // Our existing pose won't match anymore.
        m_gotPose = false;

        // Construct the camera matrix from the vectors we received.
        if (cameraMatrix.size() != 3) {
            return false;
        }
        for (size_t i = 0; i < cameraMatrix.size(); i++) {
            if (cameraMatrix[i].size() != 3) {
                return false;
            }
        }
        cv::Mat newCameraMatrix(static_cast<int>(cameraMatrix.size()),
                                static_cast<int>(cameraMatrix[0].size()),
                                CV_64F);
        for (int i = 0; i < cameraMatrix.size(); i++) {
            for (int j = 0; j < cameraMatrix[i].size(); j++) {
                newCameraMatrix.at<double>(i, j) = cameraMatrix[i][j];
            }
        }

        m_cameraMatrix = newCameraMatrix;
        //    std::cout << "XXX cameraMatrix =" << std::endl << m_cameraMatrix
        //    << std::endl;
        return true;
    }

    bool BeaconBasedPoseEstimator::SetDistCoeffs(
        const std::vector<double> &distCoeffs) {
        // Our existing pose won't match anymore.
        m_gotPose = false;

        // Construct the distortion matrix from the vectors we received.
        if (distCoeffs.size() < 5) {
            return false;
        }
        cv::Mat newDistCoeffs(static_cast<int>(distCoeffs.size()), 1, CV_64F);
        for (int i = 0; i < distCoeffs.size(); i++) {
            newDistCoeffs.at<double>(i, 0) = distCoeffs[i];
        }

        m_distCoeffs = newDistCoeffs;
        //    std::cout << "XXX distCoeffs =" << std::endl << m_distCoeffs <<
        //    std::endl;
        return true;
    }

    static const int OUTLIERS_PERMITTED = 2;
    /// We want at least five corresponding points (this is somewhat arbitrary,
    /// but must be at least 5 to allow for 2 outliers below).
    static const int MIN_OBJECT_POINTS = OUTLIERS_PERMITTED + 3;

    bool
    BeaconBasedPoseEstimator::EstimatePoseFromLeds(const LedGroup &leds,
                                                   OSVR_PoseState &outPose) {
        auto ret = m_estimatePoseFromLeds(leds, outPose);
        m_gotPose = ret;
        return ret;
    }

    bool
    BeaconBasedPoseEstimator::m_estimatePoseFromLeds(const LedGroup &leds,
                                                     OSVR_PoseState &outPose) {
        // We need to get a pair of matched vectors of points: 2D locations
        // with in the image and 3D locations in model space.  There needs to
        // be a correspondence between the points in these vectors, such that
        // the ith element in one matches the ith element in the other.  We
        // make these by looking up the locations of LEDs with known identifiers
        // and pushing both onto the vectors at the same time.

        std::vector<cv::Point3f> objectPoints;
        std::vector<cv::Point2f> imagePoints;
        auto const beaconsSize = m_beacons.size();
        for (auto const &led : leds) {
            if (!led.identified()) {
                continue;
            }
            auto id = led.getID();
            if (id < beaconsSize) {
                imagePoints.push_back(led.getLocation());
                objectPoints.push_back(m_beacons[id]);
            }
        }

        // Make sure we have enough points to do our estimation.
        if (objectPoints.size() < MIN_OBJECT_POINTS) {
            return false;
        }

        // Produce an estimate of the translation and rotation needed to take
        // points from model space into camera space.  We allow for at most
        // OUTLIERS_PERMITTED outliers. Even in simulation data, we sometimes
        // find duplicate IDs for LEDs, indicating that we are getting
        // mis-identified ones sometimes.
        cv::solvePnPRansac(
            objectPoints, imagePoints, m_cameraMatrix, m_distCoeffs, m_rvec,
            m_tvec, false, 100, 8.0f,
            static_cast<int>(objectPoints.size() - OUTLIERS_PERMITTED));

        //    std::cout << "XXX tvec = " << m_tvec << std::endl;
        //    std::cout << "XXX rvec = " << m_rvec << std::endl;

        //==========================================================================
        // Convert this into an OSVR representation of the transformation that
        // gives the pose of the HDK origin in the camera coordinate system,
        // switching units to meters and encoding the angle in a unit
        // quaternion.
        // The matrix described by rvec and tvec takes points in model space
        // (the space where the LEDs are defined, which is in mm away from an
        // implied origin) into a coordinate system where the center is at the
        // camera's origin, with X to the right, Y down, and Z in the direction
        // that the camera is facing (but still in the original units of mm):
        //  |Xc|   |r11 r12 r13 t1| |Xm|
        //  |Yc| = |r21 r22 r23 t2|*|Ym|
        //  |Zc|   |r31 r32 r33 t3| |Zm|
        //                          |1 |
        //  That is, it rotates into the camera coordinate system and then adds
        // the translation, which is in the camera coordinate system.
        //  We want the tranformation that takes points in the coordinate system
        // of the tracker's "source" (the camera) and moves them into the
        // coordinate system of the tracker's "sensor" (the HDK), which is the
        // inverse of the transformation described above scaled to move from mm
        // to meters.

        // Compose the transform that we will invert, in original units.
        // We start by making a 3x3 rotation matrix out of the rvec, which
        // is done by a function that for some reason is named Rodrigues.
        cv::Mat rot;
        cv::Rodrigues(m_rvec, rot);

        // TODO: Replace this code with Eigen code.

        if (rot.type() != CV_64F) {
            return false;
        }

        // Get the forward transform
        q_xyz_quat_type forward;
        forward.xyz[Q_X] = m_tvec.at<double>(0);
        forward.xyz[Q_Y] = m_tvec.at<double>(1);
        forward.xyz[Q_Z] = m_tvec.at<double>(2);

        // Fill in a 4x4 matrix that starts as the identity
        // matrix with the 3x3 part from the rotation matrix.
        q_matrix_type rot4x4;
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 4; j++) {
                if ((i < 3) && (j < 3)) {
                    rot4x4[i][j] = rot.at<double>(i, j);
                } else {
                    if (i == j) {
                        rot4x4[i][j] = 1;
                    } else {
                        rot4x4[i][j] = 0;
                    }
                }
            }
        }
        q_from_row_matrix(forward.quat, rot4x4);

        // Invert it.
        q_xyz_quat_type inverse;
        q_xyz_quat_invert(&inverse, &forward);

        // Scale to meters
        q_vec_scale(inverse.xyz, 1e-3, inverse.xyz);

        //==============================================================
        // Put into OSVR format.
        osvrPose3FromQuatlib(&outPose, &inverse);
        return true;
    }

    bool BeaconBasedPoseEstimator::ProjectBeaconsToImage(
        std::vector<cv::Point2f> &out) {
        // Make sure we have a pose.  Otherwise, we can't do anything.
        if (!m_gotPose) {
            return false;
        }

        cv::projectPoints(m_beacons, m_rvec, m_tvec, m_cameraMatrix,
                          m_distCoeffs, out);
        return true;
    }

} // End namespace vbtracker
} // End namespace osvr
<commit_msg>Removing the transformation inversion in the original code, so we produce estimates of the sensor in camera space.  We still convert to meters.  Issue: The Y axis is inverted; we seem to be in a left-handed space with OpenCV.<commit_after>/** @file
    @brief Implementation for class that tracks and identifies LEDs.

    @date 2015

    @author
    Sensics, Inc.
    <http://sensics.com/osvr>
*/

// Copyright 2015 Sensics, Inc.
//
// Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Internal Includes
#include "BeaconBasedPoseEstimator.h"

// Library/third-party includes
#include <osvr/Util/QuatlibInteropC.h>

// Standard includes
// - none

namespace osvr {
namespace vbtracker {

    // clang-format off
    // Default 3D locations for the beacons on an OSVR HDK face plate, in
    // millimeters
    const DoubleVecVec OsvrHdkLedLocations_SENSOR0 = {
        {-85, 3, 24.09},
        { -83.2, -14.01, 13.89 },
        { -47, 51, 24.09 },
        { 47, 51, 24.09 },
        { 86.6, 2.65, 24.09 },
        { 85.5, -14.31, 13.89 },
        { 85.2, 19.68, 13.89 },
        { 21, 51, 13.09 },
        { -21, 51, 13.09 },
        { -84.2, 19.99, 13.89 },
        { -60.41, 47.55, 44.6 },
        { -80.42, 20.48, 42.9 },
        { -82.01, 2.74, 42.4 },
        { -80.42, -14.99, 42.9 },
        { -60.41, -10.25, 48.1 },
        { -60.41, 15.75, 48.1 },
        { -30.41, 32.75, 50.5 },
        { -31.41, 47.34, 47 },
        { -0.41, -15.25, 51.3 },
        { -30.41, -27.25, 50.5 },
        { -60.44, -41.65, 45.1 },
        { -22.41, -41.65, 47.8 },
        { 21.59, -41.65, 47.8 },
        { 59.59, -41.65, 45.1 },
        { 79.63, -14.98, 42.9 },
        { 29.59, -27.25, 50.5 },
        { 81.19, 2.74, 42.4 },
        { 79.61, 20.48, 42.9 },
        { 59.59, 47.55, 44.6 },
        { 30.59, 47.55, 47 },
        { 29.59, 32.75, 50.5 },
        { -0.41, 20.75, 51.3 },
        { 59.59, 15.75, 48.1 },
        { 59.59, -10.25, 48.1 }
    };

    // Default 3D locations for the beacons on an OSVR HDK back plate, in
    // millimeters
    const DoubleVecVec OsvrHdkLedLocations_SENSOR1 = {
        {1, 23.8, 0},
        { 11, 5.8, 0 },
        { 9, -23.8, 0 },
        { 0, -8.8, 0 },
        { -9, -23.8, 0 },
        { -12, 5.8, 0 }
    };
    // clang-format on

    BeaconBasedPoseEstimator::BeaconBasedPoseEstimator(
        const DoubleVecVec &cameraMatrix, const std::vector<double> &distCoeffs,
        const DoubleVecVec &beacons) {
        SetBeacons(beacons);
        SetCameraMatrix(cameraMatrix);
        SetDistCoeffs(distCoeffs);
        m_gotPose = false;
    }

    bool BeaconBasedPoseEstimator::SetBeacons(const DoubleVecVec &beacons) {
        // Our existing pose won't match anymore.
        m_gotPose = false;

        for (int i = 0; i < beacons.size(); i++) {
            if (beacons[i].size() != 3) {
                m_beacons.clear();
                return false;
            }
            cv::Point3f p(static_cast<float>(beacons[i][0]),
                          static_cast<float>(beacons[i][1]),
                          static_cast<float>(beacons[i][2]));
            m_beacons.push_back(p);
        }

        return true;
    }

    bool BeaconBasedPoseEstimator::SetCameraMatrix(
        const DoubleVecVec &cameraMatrix) {
        // Our existing pose won't match anymore.
        m_gotPose = false;

        // Construct the camera matrix from the vectors we received.
        if (cameraMatrix.size() != 3) {
            return false;
        }
        for (size_t i = 0; i < cameraMatrix.size(); i++) {
            if (cameraMatrix[i].size() != 3) {
                return false;
            }
        }
        cv::Mat newCameraMatrix(static_cast<int>(cameraMatrix.size()),
                                static_cast<int>(cameraMatrix[0].size()),
                                CV_64F);
        for (int i = 0; i < cameraMatrix.size(); i++) {
            for (int j = 0; j < cameraMatrix[i].size(); j++) {
                newCameraMatrix.at<double>(i, j) = cameraMatrix[i][j];
            }
        }

        m_cameraMatrix = newCameraMatrix;
        //    std::cout << "XXX cameraMatrix =" << std::endl << m_cameraMatrix
        //    << std::endl;
        return true;
    }

    bool BeaconBasedPoseEstimator::SetDistCoeffs(
        const std::vector<double> &distCoeffs) {
        // Our existing pose won't match anymore.
        m_gotPose = false;

        // Construct the distortion matrix from the vectors we received.
        if (distCoeffs.size() < 5) {
            return false;
        }
        cv::Mat newDistCoeffs(static_cast<int>(distCoeffs.size()), 1, CV_64F);
        for (int i = 0; i < distCoeffs.size(); i++) {
            newDistCoeffs.at<double>(i, 0) = distCoeffs[i];
        }

        m_distCoeffs = newDistCoeffs;
        //    std::cout << "XXX distCoeffs =" << std::endl << m_distCoeffs <<
        //    std::endl;
        return true;
    }

    static const int OUTLIERS_PERMITTED = 2;
    /// We want at least five corresponding points (this is somewhat arbitrary,
    /// but must be at least 5 to allow for 2 outliers below).
    static const int MIN_OBJECT_POINTS = OUTLIERS_PERMITTED + 3;

    bool
    BeaconBasedPoseEstimator::EstimatePoseFromLeds(const LedGroup &leds,
                                                   OSVR_PoseState &outPose) {
        auto ret = m_estimatePoseFromLeds(leds, outPose);
        m_gotPose = ret;
        return ret;
    }

    bool
    BeaconBasedPoseEstimator::m_estimatePoseFromLeds(const LedGroup &leds,
                                                     OSVR_PoseState &outPose) {
        // We need to get a pair of matched vectors of points: 2D locations
        // with in the image and 3D locations in model space.  There needs to
        // be a correspondence between the points in these vectors, such that
        // the ith element in one matches the ith element in the other.  We
        // make these by looking up the locations of LEDs with known identifiers
        // and pushing both onto the vectors at the same time.

        std::vector<cv::Point3f> objectPoints;
        std::vector<cv::Point2f> imagePoints;
        auto const beaconsSize = m_beacons.size();
        for (auto const &led : leds) {
            if (!led.identified()) {
                continue;
            }
            auto id = led.getID();
            if (id < beaconsSize) {
                imagePoints.push_back(led.getLocation());
                objectPoints.push_back(m_beacons[id]);
            }
        }

        // Make sure we have enough points to do our estimation.
        if (objectPoints.size() < MIN_OBJECT_POINTS) {
            return false;
        }

        // Produce an estimate of the translation and rotation needed to take
        // points from model space into camera space.  We allow for at most
        // OUTLIERS_PERMITTED outliers. Even in simulation data, we sometimes
        // find duplicate IDs for LEDs, indicating that we are getting
        // mis-identified ones sometimes.
        cv::solvePnPRansac(
            objectPoints, imagePoints, m_cameraMatrix, m_distCoeffs, m_rvec,
            m_tvec, false, 100, 8.0f,
            static_cast<int>(objectPoints.size() - OUTLIERS_PERMITTED));

        //    std::cout << "XXX tvec = " << m_tvec << std::endl;
        //    std::cout << "XXX rvec = " << m_rvec << std::endl;

        //==========================================================================
        // Convert this into an OSVR representation of the transformation that
        // gives the pose of the HDK origin in the camera coordinate system,
        // switching units to meters and encoding the angle in a unit
        // quaternion.
        // The matrix described by rvec and tvec takes points in model space
        // (the space where the LEDs are defined, which is in mm away from an
        // implied origin) into a coordinate system where the center is at the
        // camera's origin, with X to the right, Y down, and Z in the direction
        // that the camera is facing (but still in the original units of mm):
        //  |Xc|   |r11 r12 r13 t1| |Xm|
        //  |Yc| = |r21 r22 r23 t2|*|Ym|
        //  |Zc|   |r31 r32 r33 t3| |Zm|
        //                          |1 |
        //  That is, it rotates into the camera coordinate system and then adds
        // the translation, which is in the camera coordinate system.
        //  This is the transformation we want, since it reports the sensor's
        // position and orientation in camera space, except that we want to convert
        // the units into meters and the orientation into a Quaternion.

        // Compose the transform in original units.
        // We start by making a 3x3 rotation matrix out of the rvec, which
        // is done by a function that for some reason is named Rodrigues.
        cv::Mat rot;
        cv::Rodrigues(m_rvec, rot);

        // TODO: Replace this code with Eigen code.

        if (rot.type() != CV_64F) {
            return false;
        }

        // Get the forward transform
        q_xyz_quat_type forward;
        forward.xyz[Q_X] = m_tvec.at<double>(0);
        forward.xyz[Q_Y] = m_tvec.at<double>(1);
        forward.xyz[Q_Z] = m_tvec.at<double>(2);

        // Fill in a 4x4 matrix that starts as the identity
        // matrix with the 3x3 part from the rotation matrix.
        q_matrix_type rot4x4;
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 4; j++) {
                if ((i < 3) && (j < 3)) {
                    rot4x4[i][j] = rot.at<double>(i, j);
                } else {
                    if (i == j) {
                        rot4x4[i][j] = 1;
                    } else {
                        rot4x4[i][j] = 0;
                    }
                }
            }
        }
        q_from_row_matrix(forward.quat, rot4x4);

        // Scale to meters
        q_vec_scale(forward.xyz, 1e-3, forward.xyz);

        //==============================================================
        // Put into OSVR format.
        osvrPose3FromQuatlib(&outPose, &forward);
        return true;
    }

    bool BeaconBasedPoseEstimator::ProjectBeaconsToImage(
        std::vector<cv::Point2f> &out) {
        // Make sure we have a pose.  Otherwise, we can't do anything.
        if (!m_gotPose) {
            return false;
        }

        cv::projectPoints(m_beacons, m_rvec, m_tvec, m_cameraMatrix,
                          m_distCoeffs, out);
        return true;
    }

} // End namespace vbtracker
} // End namespace osvr
<|endoftext|>


<commit_before>/* Copyright (C) 2005-2011 Fabio Riccardi */

// standard
#include <cstdio>
#include <sys/types.h>
#ifdef  DEBUG
#include <iostream>
#endif

extern "C" {
#   include <jpeglib.h>
}

// local
#include "LC_JNIUtils.h"
#include "LC_JPEGException.h"
#include "LC_JPEGReader.h"
#include "util.h"

#define MAX(a,b)    ( (a) > (b) ? (a) : (b) )

using namespace std;

/**
 * Construct an LC_JPEGReader.
 */
LC_JPEGReader::LC_JPEGReader() {
    m_file = 0;
    m_src = 0;
    m_startedDecompress = false;

    jpeg_create_decompress( &cinfo );
    //
    // Change things so we're handling errors in our own way.
    //
    cinfo.err = jpeg_std_error( &m_errMgr );
    m_errMgr.error_exit = &LC_error_exit;
}

/**
 * Destruct an LC_JPEGReader.
 */
LC_JPEGReader::~LC_JPEGReader() {
#ifdef DEBUG
    cerr << "~LC_JPEGReader()" << endl;
#endif
    try {
        if ( m_startedDecompress )
            jpeg_finish_decompress( &cinfo );
        jpeg_destroy_decompress( &cinfo );
    }
    catch ( LC_JPEGException const& ) {
        //
        // We will have thrown a Java exception by this point, but we want to
        // finish our clean-up, so keep going.
        //
    }
    if ( m_file )
        ::fclose( m_file );
    delete m_src;
}

/**
 * Set the width, height, and colorsPerPixel fields in the LCJPEGReader Java
 * object.
 */
void LC_JPEGReader::setFields( JNIEnv *env, jobject jLCJPEGReader ) {
#ifdef DEBUG
    cerr << "LC_JPEGReader::setFields(): width=" << cinfo.output_width
         <<                          ", height=" << cinfo.output_height
         <<                  ", colorsPerPixel=" << cinfo.output_components
         <<                      ", colorSpace=" << cinfo.out_color_space
         << endl;
#endif
    LC_setIntField( env, jLCJPEGReader, "m_width" , cinfo.output_width );
    LC_setIntField( env, jLCJPEGReader, "m_height", cinfo.output_height );
    LC_setIntField(
        env, jLCJPEGReader, "m_colorsPerPixel", cinfo.output_components
    );
    LC_setIntField( env, jLCJPEGReader, "m_colorSpace", cinfo.out_color_space );
}

/**
 * Read the JPEG header and start decompression.
 */
void LC_JPEGReader::start_decompress( int maxWidth, int maxHeight ) {
    jpeg_read_header( &cinfo, TRUE );

    if ( maxWidth > 0 && maxHeight > 0 ) {
        jpeg_calc_output_dimensions( &cinfo );

        int scale =
            MAX( cinfo.output_width/maxWidth, cinfo.output_height/maxHeight );

        if ( scale >= 8 )
            scale = 8;
        else if ( scale >= 4 )
            scale = 4;
        else if ( scale >= 2 )
            scale = 2;
        else
            scale = 1;

        if ( scale != 1 ) {
            cinfo.scale_num = 1;
            cinfo.scale_denom = scale;
            jpeg_calc_output_dimensions( &cinfo );
        }
    }
    jpeg_start_decompress( &cinfo );
    m_startedDecompress = true;
}

/* vim:set et sw=4 ts=4: */
<commit_msg>Avoid huge memory usage on progressive JPEGs<commit_after>/* Copyright (C) 2005-2011 Fabio Riccardi */

// standard
#include <cstdio>
#include <sys/types.h>
#ifdef  DEBUG
#include <iostream>
#endif

extern "C" {
#   include <jpeglib.h>
}

// local
#include "LC_JNIUtils.h"
#include "LC_JPEGException.h"
#include "LC_JPEGReader.h"
#include "util.h"

#define MAX(a,b)    ( (a) > (b) ? (a) : (b) )

using namespace std;

/**
 * Construct an LC_JPEGReader.
 */
LC_JPEGReader::LC_JPEGReader() {
    m_file = 0;
    m_src = 0;
    m_startedDecompress = false;

    jpeg_create_decompress( &cinfo );
    //
    // Change things so we're handling errors in our own way.
    //
    cinfo.err = jpeg_std_error( &m_errMgr );
    m_errMgr.error_exit = &LC_error_exit;
}

/**
 * Destruct an LC_JPEGReader.
 */
LC_JPEGReader::~LC_JPEGReader() {
#ifdef DEBUG
    cerr << "~LC_JPEGReader()" << endl;
#endif
    if ( m_startedDecompress ) {
        try {
            jpeg_finish_decompress( &cinfo );
        }
        catch ( LC_JPEGException const& ) {
            //
            // We will have thrown a Java exception by this point, but we want to
            // finish our clean-up, so keep going.
            //
        }
    }
    jpeg_destroy_decompress( &cinfo );
    if ( m_file )
        ::fclose( m_file );
    delete m_src;
}

/**
 * Set the width, height, and colorsPerPixel fields in the LCJPEGReader Java
 * object.
 */
void LC_JPEGReader::setFields( JNIEnv *env, jobject jLCJPEGReader ) {
#ifdef DEBUG
    cerr << "LC_JPEGReader::setFields(): width=" << cinfo.output_width
         <<                          ", height=" << cinfo.output_height
         <<                  ", colorsPerPixel=" << cinfo.output_components
         <<                      ", colorSpace=" << cinfo.out_color_space
         << endl;
#endif
    LC_setIntField( env, jLCJPEGReader, "m_width" , cinfo.output_width );
    LC_setIntField( env, jLCJPEGReader, "m_height", cinfo.output_height );
    LC_setIntField(
        env, jLCJPEGReader, "m_colorsPerPixel", cinfo.output_components
    );
    LC_setIntField( env, jLCJPEGReader, "m_colorSpace", cinfo.out_color_space );
}

/**
 * Read the JPEG header and start decompression.
 */
void LC_JPEGReader::start_decompress( int maxWidth, int maxHeight ) {
    jpeg_read_header( &cinfo, TRUE );

    if ( maxWidth > 0 && maxHeight > 0 ) {
        jpeg_calc_output_dimensions( &cinfo );

        int scale =
            MAX( cinfo.output_width/maxWidth, cinfo.output_height/maxHeight );

        if ( scale >= 8 )
            scale = 8;
        else if ( scale >= 4 )
            scale = 4;
        else if ( scale >= 2 )
            scale = 2;
        else
            scale = 1;

        if ( scale != 1 ) {
            cinfo.scale_num = 1;
            cinfo.scale_denom = scale;
            jpeg_calc_output_dimensions( &cinfo );
        }
    }
    jpeg_start_decompress( &cinfo );
    m_startedDecompress = true;
}

/* vim:set et sw=4 ts=4: */
<|endoftext|>


<commit_before>
#include "astutil.h"
#include "bb.h"
#include "expr.h"
#include "optimizations.h"
#include "passes.h"
#include "stmt.h"
#include "view.h"

//
// Static function declarations.
//
static bool deadBlockElimination(FnSymbol* fn);
// static void deadGotoElimination(FnSymbol* fn);

// Static variables.
static unsigned deadBlockCount;

//
// Removes local variables that are only targets for moves, but are
// never used anywhere.
//
static bool isDeadVariable(Symbol* var,
                           Map<Symbol*,Vec<SymExpr*>*>& defMap,
                           Map<Symbol*,Vec<SymExpr*>*>& useMap) {
  if (var->type->symbol->hasFlag(FLAG_REF)) {
    Vec<SymExpr*>* uses = useMap.get(var);
    Vec<SymExpr*>* defs = defMap.get(var);
    return (!uses || uses->n == 0) && (!defs || defs->n <= 1);
  } else {
    Vec<SymExpr*>* uses = useMap.get(var);
    return !uses || uses->n == 0;
  }
}

void deadVariableElimination(FnSymbol* fn) {
  Vec<Symbol*> symSet;
  Vec<SymExpr*> symExprs;
  collectSymbolSetSymExprVec(fn, symSet, symExprs);

  Map<Symbol*,Vec<SymExpr*>*> defMap;
  Map<Symbol*,Vec<SymExpr*>*> useMap;
  buildDefUseMaps(symSet, symExprs, defMap, useMap);

  forv_Vec(Symbol, sym, symSet) if (isVarSymbol(sym)) {
    if (isDeadVariable(sym, defMap, useMap)) {
      for_defs(se, defMap, sym) {
        CallExpr* call = toCallExpr(se->parentExpr);
        INT_ASSERT(call && call->isPrimitive(PRIM_MOVE));
        Expr* rhs = call->get(2)->remove();
        if (!isSymExpr(rhs))
          call->replace(rhs);
        else
          call->remove();
      }
      sym->defPoint->remove();
    }
  }

  freeDefUseMaps(defMap, useMap);
}

//
// Removes expression statements that have no effect.
//
void deadExpressionElimination(FnSymbol* fn) {
  Vec<BaseAST*> asts;
  collect_asts(fn, asts);
  forv_Vec(BaseAST, ast, asts) {
    Expr *expr = toExpr(ast);
    if (expr && expr->parentExpr == NULL) // expression already removed
      continue;
    if (SymExpr* expr = toSymExpr(ast)) {
      if (expr == expr->getStmtExpr())
        expr->remove();
    } else if (CallExpr* expr = toCallExpr(ast)) {
      if (expr->isPrimitive(PRIM_CAST) ||
          expr->isPrimitive(PRIM_GET_MEMBER_VALUE) ||
          expr->isPrimitive(PRIM_GET_MEMBER) ||
          expr->isPrimitive(PRIM_GET_REF) ||
          expr->isPrimitive(PRIM_SET_REF))
        if (expr == expr->getStmtExpr())
          expr->remove();
      if (expr->isPrimitive(PRIM_MOVE))
        if (SymExpr* lhs = toSymExpr(expr->get(1)))
          if (SymExpr* rhs = toSymExpr(expr->get(2)))
            if (lhs->var == rhs->var)
              expr->remove();
    } else if (CondStmt* cond = toCondStmt(ast)) {
      cond->fold_cond_stmt();
    }
  }
}

void deadCodeElimination(FnSymbol* fn)
{
  buildBasicBlocks(fn);

  Map<SymExpr*,Vec<SymExpr*>*> DU;
  Map<SymExpr*,Vec<SymExpr*>*> UD;
  buildDefUseChains(fn, DU, UD);

  Map<Expr*,Expr*> exprMap;
  Vec<Expr*> liveCode;
  Vec<Expr*> workSet;
  forv_Vec(BasicBlock, bb, *fn->basicBlocks) {
    forv_Vec(Expr, expr, bb->exprs) {
      bool essential = false;
      Vec<BaseAST*> asts;
      collect_asts(expr, asts);
      forv_Vec(BaseAST, ast, asts) {
        if (CallExpr* call = toCallExpr(ast)) {
          // mark function calls and essential primitives as essential
          if (call->isResolved() ||
              (call->primitive && call->primitive->isEssential))
            essential = true;
          // mark assignments to global variables as essential
          if (call->isPrimitive(PRIM_MOVE))
            if (SymExpr* se = toSymExpr(call->get(1)))
              if (!DU.get(se) || // DU chain only contains locals
                  !se->var->type->refType) // reference issue
                essential = true;
        }
        if (Expr* sub = toExpr(ast)) {
          exprMap.put(sub, expr);
          if (BlockStmt* block = toBlockStmt(sub->parentExpr))
            if (block->blockInfo == sub)
              essential = true;
          if (CondStmt* cond = toCondStmt(sub->parentExpr))
            if (cond->condExpr == sub)
              essential = true;
        }
      }
      if (essential) {
        liveCode.set_add(expr);
        workSet.add(expr);
      }
    }
  }

  forv_Vec(Expr, expr, workSet) {
    Vec<SymExpr*> symExprs;
    collectSymExprs(expr, symExprs);
    forv_Vec(SymExpr, se, symExprs) {
      if (Vec<SymExpr*>* defs = UD.get(se)) {
        forv_Vec(SymExpr, def, *defs) {
          Expr* expr = exprMap.get(def);
          if (!liveCode.set_in(expr)) {
            liveCode.set_add(expr);
            workSet.add(expr);
          }
        }
      }
    }
  }

  // This removes dead expressions from each block.
  forv_Vec(BasicBlock, bb, *fn->basicBlocks) {
    forv_Vec(Expr, expr, bb->exprs) {
      if (isSymExpr(expr) || isCallExpr(expr))
        if (!liveCode.set_in(expr))
          expr->remove();
    }
  }

  freeDefUseChains(DU, UD);
}

void deadCodeElimination() {
  if (!fNoDeadCodeElimination) {
    deadBlockCount = 0;
    forv_Vec(FnSymbol, fn, gFnSymbols) {
      bool change = false;
      do {
        change = deadBlockElimination(fn);
      } while (change);
//      deadGotoElimination(fn);
      deadCodeElimination(fn);
      deadVariableElimination(fn);
      deadExpressionElimination(fn);
    }

    if (fReportDeadBlocks)
      printf("\tRemoved %d dead blocks.\n", deadBlockCount);
  }
}

// Look for and remove unreachable blocks.
static bool deadBlockElimination(FnSymbol* fn)
{
  // We need the basic block information to be right here.
  buildBasicBlocks(fn);

  bool change = false;
  forv_Vec(BasicBlock, bb, *fn->basicBlocks)
  {
    // Ignore the first block.
    if (bb == fn->basicBlocks->v[0])
      continue;

    // If this block has no predecessors, then it is dead.
    if (bb->ins.count() == 0)
    {
      if (bb->exprs.n > 0)
      {
        change = true;
        ++deadBlockCount;

        // Remove all of its expressions.
        forv_Vec(Expr, expr, bb->exprs)
        {
          if (! expr->parentExpr)
            continue;	// This node is no longer in the tree.

          CondStmt* cond = toCondStmt(expr->parentExpr);
          if (cond && cond->condExpr == expr)
            // If expr is the condition expression in an if statement,
            // then remove the entire if.
            cond->remove();
          else
            expr->remove();
        }
      }

      // Get more out of one pass by removing this BB from the predecessor
      // lists of its successors.
      forv_Vec(BasicBlock, succ, bb->outs)
        succ->ins.set_remove(bb);

      // We leave the "dead" bb structure in place.
      // The next time we construct basic blocks for this fn, it should be gone.
    }
  }

  return change;
}

// Look for pointless gotos and remove them.
// Probably the best way to do this is to scan the AST and remove gotos
// whose target labels follow immediately.
#if 0
static void deadGotoElimination(FnSymbol* fn)
{
  // We recompute basic blocks because deadBlockElimination may cause them
  // to be out of sequence.
  buildBasicBlocks(fn);
  forv_Vec(BasicBlock, bb, *fn->basicBlocks)
  {
    // Get the last expression in the block as a goto.
    int last = bb->exprs.length() - 1;
    if (last < 0)
      continue;

    Expr* e = bb->exprs.v[last];
    GotoStmt* s = toGotoStmt(e);
    if (!s)
      continue;

    // If there is only one successor to this block and it is the next block,
    // then the goto must point to it and is therefore pointless [sts].
    // This test should be more foolproof using the structure of the AST.
    if (bb->outs.n == 1 && bb->outs.v[0]->id == bb->id + 1)
      e->remove();
  }
}
#endif
<commit_msg>Remove a TAB.<commit_after>
#include "astutil.h"
#include "bb.h"
#include "expr.h"
#include "optimizations.h"
#include "passes.h"
#include "stmt.h"
#include "view.h"

//
// Static function declarations.
//
static bool deadBlockElimination(FnSymbol* fn);
// static void deadGotoElimination(FnSymbol* fn);

// Static variables.
static unsigned deadBlockCount;

//
// Removes local variables that are only targets for moves, but are
// never used anywhere.
//
static bool isDeadVariable(Symbol* var,
                           Map<Symbol*,Vec<SymExpr*>*>& defMap,
                           Map<Symbol*,Vec<SymExpr*>*>& useMap) {
  if (var->type->symbol->hasFlag(FLAG_REF)) {
    Vec<SymExpr*>* uses = useMap.get(var);
    Vec<SymExpr*>* defs = defMap.get(var);
    return (!uses || uses->n == 0) && (!defs || defs->n <= 1);
  } else {
    Vec<SymExpr*>* uses = useMap.get(var);
    return !uses || uses->n == 0;
  }
}

void deadVariableElimination(FnSymbol* fn) {
  Vec<Symbol*> symSet;
  Vec<SymExpr*> symExprs;
  collectSymbolSetSymExprVec(fn, symSet, symExprs);

  Map<Symbol*,Vec<SymExpr*>*> defMap;
  Map<Symbol*,Vec<SymExpr*>*> useMap;
  buildDefUseMaps(symSet, symExprs, defMap, useMap);

  forv_Vec(Symbol, sym, symSet) if (isVarSymbol(sym)) {
    if (isDeadVariable(sym, defMap, useMap)) {
      for_defs(se, defMap, sym) {
        CallExpr* call = toCallExpr(se->parentExpr);
        INT_ASSERT(call && call->isPrimitive(PRIM_MOVE));
        Expr* rhs = call->get(2)->remove();
        if (!isSymExpr(rhs))
          call->replace(rhs);
        else
          call->remove();
      }
      sym->defPoint->remove();
    }
  }

  freeDefUseMaps(defMap, useMap);
}

//
// Removes expression statements that have no effect.
//
void deadExpressionElimination(FnSymbol* fn) {
  Vec<BaseAST*> asts;
  collect_asts(fn, asts);
  forv_Vec(BaseAST, ast, asts) {
    Expr *expr = toExpr(ast);
    if (expr && expr->parentExpr == NULL) // expression already removed
      continue;
    if (SymExpr* expr = toSymExpr(ast)) {
      if (expr == expr->getStmtExpr())
        expr->remove();
    } else if (CallExpr* expr = toCallExpr(ast)) {
      if (expr->isPrimitive(PRIM_CAST) ||
          expr->isPrimitive(PRIM_GET_MEMBER_VALUE) ||
          expr->isPrimitive(PRIM_GET_MEMBER) ||
          expr->isPrimitive(PRIM_GET_REF) ||
          expr->isPrimitive(PRIM_SET_REF))
        if (expr == expr->getStmtExpr())
          expr->remove();
      if (expr->isPrimitive(PRIM_MOVE))
        if (SymExpr* lhs = toSymExpr(expr->get(1)))
          if (SymExpr* rhs = toSymExpr(expr->get(2)))
            if (lhs->var == rhs->var)
              expr->remove();
    } else if (CondStmt* cond = toCondStmt(ast)) {
      cond->fold_cond_stmt();
    }
  }
}

void deadCodeElimination(FnSymbol* fn)
{
  buildBasicBlocks(fn);

  Map<SymExpr*,Vec<SymExpr*>*> DU;
  Map<SymExpr*,Vec<SymExpr*>*> UD;
  buildDefUseChains(fn, DU, UD);

  Map<Expr*,Expr*> exprMap;
  Vec<Expr*> liveCode;
  Vec<Expr*> workSet;
  forv_Vec(BasicBlock, bb, *fn->basicBlocks) {
    forv_Vec(Expr, expr, bb->exprs) {
      bool essential = false;
      Vec<BaseAST*> asts;
      collect_asts(expr, asts);
      forv_Vec(BaseAST, ast, asts) {
        if (CallExpr* call = toCallExpr(ast)) {
          // mark function calls and essential primitives as essential
          if (call->isResolved() ||
              (call->primitive && call->primitive->isEssential))
            essential = true;
          // mark assignments to global variables as essential
          if (call->isPrimitive(PRIM_MOVE))
            if (SymExpr* se = toSymExpr(call->get(1)))
              if (!DU.get(se) || // DU chain only contains locals
                  !se->var->type->refType) // reference issue
                essential = true;
        }
        if (Expr* sub = toExpr(ast)) {
          exprMap.put(sub, expr);
          if (BlockStmt* block = toBlockStmt(sub->parentExpr))
            if (block->blockInfo == sub)
              essential = true;
          if (CondStmt* cond = toCondStmt(sub->parentExpr))
            if (cond->condExpr == sub)
              essential = true;
        }
      }
      if (essential) {
        liveCode.set_add(expr);
        workSet.add(expr);
      }
    }
  }

  forv_Vec(Expr, expr, workSet) {
    Vec<SymExpr*> symExprs;
    collectSymExprs(expr, symExprs);
    forv_Vec(SymExpr, se, symExprs) {
      if (Vec<SymExpr*>* defs = UD.get(se)) {
        forv_Vec(SymExpr, def, *defs) {
          Expr* expr = exprMap.get(def);
          if (!liveCode.set_in(expr)) {
            liveCode.set_add(expr);
            workSet.add(expr);
          }
        }
      }
    }
  }

  // This removes dead expressions from each block.
  forv_Vec(BasicBlock, bb, *fn->basicBlocks) {
    forv_Vec(Expr, expr, bb->exprs) {
      if (isSymExpr(expr) || isCallExpr(expr))
        if (!liveCode.set_in(expr))
          expr->remove();
    }
  }

  freeDefUseChains(DU, UD);
}

void deadCodeElimination() {
  if (!fNoDeadCodeElimination) {
    deadBlockCount = 0;
    forv_Vec(FnSymbol, fn, gFnSymbols) {
      bool change = false;
      do {
        change = deadBlockElimination(fn);
      } while (change);
//      deadGotoElimination(fn);
      deadCodeElimination(fn);
      deadVariableElimination(fn);
      deadExpressionElimination(fn);
    }

    if (fReportDeadBlocks)
      printf("\tRemoved %d dead blocks.\n", deadBlockCount);
  }
}

// Look for and remove unreachable blocks.
static bool deadBlockElimination(FnSymbol* fn)
{
  // We need the basic block information to be right here.
  buildBasicBlocks(fn);

  bool change = false;
  forv_Vec(BasicBlock, bb, *fn->basicBlocks)
  {
    // Ignore the first block.
    if (bb == fn->basicBlocks->v[0])
      continue;

    // If this block has no predecessors, then it is dead.
    if (bb->ins.count() == 0)
    {
      if (bb->exprs.n > 0)
      {
        change = true;
        ++deadBlockCount;

        // Remove all of its expressions.
        forv_Vec(Expr, expr, bb->exprs)
        {
          if (! expr->parentExpr)
            continue;   // This node is no longer in the tree.

          CondStmt* cond = toCondStmt(expr->parentExpr);
          if (cond && cond->condExpr == expr)
            // If expr is the condition expression in an if statement,
            // then remove the entire if.
            cond->remove();
          else
            expr->remove();
        }
      }

      // Get more out of one pass by removing this BB from the predecessor
      // lists of its successors.
      forv_Vec(BasicBlock, succ, bb->outs)
        succ->ins.set_remove(bb);

      // We leave the "dead" bb structure in place.
      // The next time we construct basic blocks for this fn, it should be gone.
    }
  }

  return change;
}

// Look for pointless gotos and remove them.
// Probably the best way to do this is to scan the AST and remove gotos
// whose target labels follow immediately.
#if 0
static void deadGotoElimination(FnSymbol* fn)
{
  // We recompute basic blocks because deadBlockElimination may cause them
  // to be out of sequence.
  buildBasicBlocks(fn);
  forv_Vec(BasicBlock, bb, *fn->basicBlocks)
  {
    // Get the last expression in the block as a goto.
    int last = bb->exprs.length() - 1;
    if (last < 0)
      continue;

    Expr* e = bb->exprs.v[last];
    GotoStmt* s = toGotoStmt(e);
    if (!s)
      continue;

    // If there is only one successor to this block and it is the next block,
    // then the goto must point to it and is therefore pointless [sts].
    // This test should be more foolproof using the structure of the AST.
    if (bb->outs.n == 1 && bb->outs.v[0]->id == bb->id + 1)
      e->remove();
  }
}
#endif
<|endoftext|>


<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <cmath>

#include "nativeCode.h" // generated by javah via maven-native-plugin

#include "JwMat.h"
#include "jni_helper.h"
#include "cv_helper.h"

using namespace std;

JNIEXPORT void JNICALL Java_de_serviceflow_frankenstein_plugin_opencv_jni_ExternalSample_init
  (JNIEnv* env, jobject obj)
{
  JwMat* mat = JwMat::matptr;
  if (mat == NULL) {
	 JwMat::matptr = new JwMat(env);
  }
}

void CircleRowT1(int x,  int y, int radius, long rowptr, int xmid, int channels, int frameId);

// draw row of circle at "ymid + y" from -x to +x at xmid offset
void CircleRowT1(int x,  int y, int radius, long rowptr, int xmid, int channels, int frameId) {

  int keyHue = ((frameId - 1) % 256);

  jbyte * data = (jbyte *)rowptr;
  int i = (xmid-x) * channels;
  for (int xx=-x; xx<=x; xx++, i+= channels) {
    //

    int h = atan2(xx, y) * 128 / 3.141592653589793238462643383279 + 128;
    int v = 255 - 255 * (xx * xx + y * y) / (radius * radius);
    int s = 2 * (CLAMP(v, 0, 255) - 128);
    if (s<0)
       s = 255 + s;
    else {
      s = 255 - s;
      v = 255 - v;
    }

    int range = 3;
    int hlower = keyHue - range;
    int hupper = keyHue + range;

    // if ( (h > hlower && h < hupper) || (hlower<0 && h>255+hlower) || (hupper>255 && h<hupper-255))
    {
      int distance = keyHue - h;
      if (distance<0)
        distance = -distance;
      if (distance>127)
        distance  = 255 - distance;

      v = v * range * 255 / (range + distance) / 255;
    }
    //else
    //{
//      v = 0;
    //}

    data[i+0] = CLAMP(h, 0, 255);
    data[i+1] = CLAMP(s, 0, 255);
    data[i+2] = CLAMP(v, 0, 255);
  }

}

void CircleRow(int x,  int y, int radius, long rowptr, int xmid, int channels, int frameId);

// draw row of circle at "ymid + y" from -x to +x at xmid offset
void CircleRow(int x,  int y, int radius, long rowptr, int xmid, int channels, int frameId) {

  jbyte * data = (jbyte *)rowptr;
  int i = (xmid-x) * channels;
  for (int xx=-x; xx<=x; xx++, i+= channels) {
    //

    int h = atan2(xx, y) * 128 / 3.141592653589793238462643383279 + 128;
    int v = 255 - 255 * (xx * xx + y * y) / (radius * radius);
    int s = 2 * (CLAMP(v, 0, 255) - 128);
    if (s<0)
       s = 255 + s;
    else
      s = 255 - s;
    data[i+0] = CLAMP(h, 0, 255);
    data[i+1] = CLAMP(s, 0, 255);
    data[i+2] = CLAMP(v, 0, 255);
  }

}

JNIEXPORT void JNICALL Java_de_serviceflow_frankenstein_plugin_opencv_jni_ExternalSample_process
  (JNIEnv* env, jobject obj,
   jobject matobj, jint frameId, jobject context)
{
  JwMat* mat = JwMat::matptr;
  int cols = mat->cols(env, matobj);
  int rows = mat->rows(env, matobj);
//  cout << "rows=" << rows << ", cols=" << cols << endl;

  int channels = mat->channels(env, matobj);
  if (channels<3) {
	  J_THROW("java/lang/Error", "Expecting HSV Mat. channels < 3: "+mat->channels(env, matobj));
      return;
  }

  long dataAddr = mat->dataAddr(env, matobj);
  long step1 = mat->step1(env, matobj);

  // Black background
  long rowPtr = dataAddr;
  for(int y = 0; y < rows; y++)
  {
    jbyte * data = (jbyte *)rowPtr;
    for (int x = 0; x < cols; x++)
    {
      int i = x * channels;
      data[i+2] = 0; // value -> black
    }
    rowPtr += step1;
  }

  int radius = cols > rows ? (rows>>1) - 1 : (cols>>1) - 1;

  // midpoint circle
  int x = 0;
  int y = radius;
  long rowPtr1 = dataAddr + step1 * (rows>>1);
  long rowPtr2 = rowPtr1;
  long rowPtr3 = rowPtr1;
  long rowPtr4 = rowPtr1;
  rowPtr1 -= step1 * y;
  rowPtr2 += step1 * y;
  int d = 1 - radius;
  CircleRowT1(x, y, radius, rowPtr1, cols>>1, channels, frameId);
  CircleRowT1(x, -y, radius, rowPtr2, cols>>1, channels, frameId);
  CircleRowT1(y, x, radius, rowPtr3, cols>>1, channels, frameId);
  CircleRowT1(y, -x, radius, rowPtr4, cols>>1, channels, frameId);
  while (y > x) {
    if (d<0) {
      d+=2*x+3;
      x++;
      rowPtr3 -= step1;
      rowPtr4 += step1;
    }
    else {
      d+=2*(x-y)+5;
      x++;
      rowPtr3 -= step1;
      rowPtr4 += step1;
      y--;
      rowPtr1 += step1;
      rowPtr2 -= step1;
    }
    CircleRowT1(x, y, radius, rowPtr1, cols>>1, channels, frameId);
    CircleRowT1(x, -y, radius, rowPtr2, cols>>1, channels, frameId);
    CircleRowT1(y, x, radius, rowPtr3, cols>>1, channels, frameId);
    CircleRowT1(y, -x, radius, rowPtr4, cols>>1, channels, frameId);
  }
}

<commit_msg>color space example recovered<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <cmath>

#include "nativeCode.h" // generated by javah via maven-native-plugin

#include "JwMat.h"
#include "jni_helper.h"
#include "cv_helper.h"

using namespace std;

JNIEXPORT void JNICALL Java_de_serviceflow_frankenstein_plugin_opencv_jni_ExternalSample_init
  (JNIEnv* env, jobject obj)
{
  JwMat* mat = JwMat::matptr;
  if (mat == NULL) {
	 JwMat::matptr = new JwMat(env);
  }
}

void CircleRow(int x,  int y, int radius, long rowptr, int xmid, int channels, int frameId);

// draw row of circle at "ymid + y" from -x to +x at xmid offset
void CircleRow(int x,  int y, int radius, long rowptr, int xmid, int channels, int frameId) {

  jbyte * data = (jbyte *)rowptr;
  int i = (xmid-x) * channels;
  for (int xx=-x; xx<=x; xx++, i+= channels) {
    //

    int h = atan2(xx, y) * 128 / 3.141592653589793238462643383279 + 128;
    int v = 255 - 255 * (xx * xx + y * y) / (radius * radius);
    int s = 2 * (CLAMP(v, 0, 255) - 128);
    if (s<0)
       s = 255 + s;
    else
      s = 255 - s;
    data[i+0] = CLAMP(h, 0, 255);
    data[i+1] = CLAMP(s, 0, 255);
    data[i+2] = CLAMP(v, 0, 255);
  }

}

JNIEXPORT void JNICALL Java_de_serviceflow_frankenstein_plugin_opencv_jni_ExternalSample_process
  (JNIEnv* env, jobject obj,
   jobject matobj, jint frameId, jobject context)
{
  JwMat* mat = JwMat::matptr;
  int cols = mat->cols(env, matobj);
  int rows = mat->rows(env, matobj);
//  cout << "rows=" << rows << ", cols=" << cols << endl;

  int channels = mat->channels(env, matobj);
  if (channels<3) {
	  J_THROW("java/lang/Error", "Expecting HSV Mat. channels < 3: "+mat->channels(env, matobj));
      return;
  }

  long dataAddr = mat->dataAddr(env, matobj);
  long step1 = mat->step1(env, matobj);

  // Black background
  long rowPtr = dataAddr;
  for(int y = 0; y < rows; y++)
  {
    jbyte * data = (jbyte *)rowPtr;
    for (int x = 0; x < cols; x++)
    {
      int i = x * channels;
      data[i+2] = 0; // value -> black
    }
    rowPtr += step1;
  }

  int radius = cols > rows ? (rows>>1) - 1 : (cols>>1) - 1;

  // midpoint circle
  int x = 0;
  int y = radius;
  long rowPtr1 = dataAddr + step1 * (rows>>1);
  long rowPtr2 = rowPtr1;
  long rowPtr3 = rowPtr1;
  long rowPtr4 = rowPtr1;
  rowPtr1 -= step1 * y;
  rowPtr2 += step1 * y;
  int d = 1 - radius;
  CircleRow(x, y, radius, rowPtr1, cols>>1, channels, frameId);
  CircleRow(x, -y, radius, rowPtr2, cols>>1, channels, frameId);
  CircleRow(y, x, radius, rowPtr3, cols>>1, channels, frameId);
  CircleRow(y, -x, radius, rowPtr4, cols>>1, channels, frameId);
  while (y > x) {
    if (d<0) {
      d+=2*x+3;
      x++;
      rowPtr3 -= step1;
      rowPtr4 += step1;
    }
    else {
      d+=2*(x-y)+5;
      x++;
      rowPtr3 -= step1;
      rowPtr4 += step1;
      y--;
      rowPtr1 += step1;
      rowPtr2 -= step1;
    }
    CircleRow(x, y, radius, rowPtr1, cols>>1, channels, frameId);
    CircleRow(x, -y, radius, rowPtr2, cols>>1, channels, frameId);
    CircleRow(y, x, radius, rowPtr3, cols>>1, channels, frameId);
    CircleRow(y, -x, radius, rowPtr4, cols>>1, channels, frameId);
  }
}

<|endoftext|>


<commit_before>//! \file
/*
**  Copyright (C) - Triton
**
**  This program is under the terms of the Apache License 2.0.
*/

#ifndef TRITON_SYMBOLICEXPRESSION_H
#define TRITON_SYMBOLICEXPRESSION_H

#include <memory>
#include <string>

#include <triton/ast.hpp>
#include <triton/dllexport.hpp>
#include <triton/memoryAccess.hpp>
#include <triton/register.hpp>
#include <triton/symbolicEnums.hpp>
#include <triton/tritonTypes.hpp>

//! The Triton namespace
namespace triton {
/*!
 *  \addtogroup triton
 *  @{
 */

  //! The Engines namespace
  namespace engines {
  /*!
   *  \ingroup triton
   *  \addtogroup engines
   *  @{
   */

    //! The Symbolic Execution namespace
    namespace symbolic {
    /*!
     *  \ingroup engines
     *  \addtogroup symbolic
     *  @{
     */

      //! \class SymbolicExpression
      /*! \brief The symbolic expression class */
      class SymbolicExpression {
        protected:
          //! The type of the symbolic expression assignment.
          triton::engines::symbolic::expression_e type;

          //! The root node (AST) of the symbolic expression.
          triton::ast::SharedAbstractNode ast;

          //! The comment of the symbolic expression.
          std::string comment;

          //! The address of the instruction behind the symbolic expression. 0 if empty.
          uint64_t address;

          //! The instruction disassembly where the symbolic expression comes from.
          std::string disassembly;

          //! The symbolic expression id. This id is unique.
          triton::usize id;

          //! The origin memory address if `type` is equal to `triton::engines::symbolic::MEM`, invalid memory otherwise.
          triton::arch::MemoryAccess originMemory;

          //! The origin register if `type` is equal to `triton::engines::symbolic::REG`, `REG_INVALID` otherwise.
          triton::arch::Register originRegister;

        private:
          //! Returns the syntax of a bitvector define
          TRITON_EXPORT std::string getBitvectorDefine(void) const;

          //! Returns the syntax of an array define
          TRITON_EXPORT std::string getArrayDefine(void) const;

        public:
          //! True if the symbolic expression is tainted.
          bool isTainted;

          //! Constructor.
          TRITON_EXPORT SymbolicExpression(const triton::ast::SharedAbstractNode& node,
                                           triton::usize id,
                                           triton::engines::symbolic::expression_e type,
                                           const std::string& comment="");

          //! Constructor by copy.
          TRITON_EXPORT SymbolicExpression(const SymbolicExpression& other);

          //! Operator.
          TRITON_EXPORT SymbolicExpression& operator=(const SymbolicExpression& other);

          //! Returns the symbolic expression id.
          TRITON_EXPORT triton::usize getId(void) const;

          //! Returns true if the symbolic expression is assigned to a memory.
          TRITON_EXPORT bool isMemory(void) const;

          //! Returns true if the symbolic expression is assigned to a register.
          TRITON_EXPORT bool isRegister(void) const;

          //! Returns true if the expression contains a symbolic variable.
          TRITON_EXPORT bool isSymbolized(void) const;

          //! Returns the type of the symbolic expression assignment.
          TRITON_EXPORT triton::engines::symbolic::expression_e getType(void) const;

          //! Returns the SMT AST root node of the symbolic expression. This is the semantics.
          TRITON_EXPORT const triton::ast::SharedAbstractNode& getAst(void) const;

          //! Returns a new SMT AST root node of the symbolic expression. This new instance is a duplicate of the original node and may be changed without changing the original semantics.
          TRITON_EXPORT triton::ast::SharedAbstractNode getNewAst(void) const;

          //! Returns the comment of the symbolic expression.
          TRITON_EXPORT const std::string& getComment(void) const;

          //! Returns the id as string of the symbolic expression according the mode of the AST representation.
          TRITON_EXPORT std::string getFormattedId(void) const;

          //! Returns the comment as string of the symbolic expression according the mode of the AST representation.
          TRITON_EXPORT std::string getFormattedComment(void) const;

          //! Returns the symbolic expression representation as string according the mode of the AST representation.
          TRITON_EXPORT std::string getFormattedExpression(void) const;

          //! Returns the origin memory access if `kind` is equal to `triton::engines::symbolic::MEMORY_EXPRESSION`, invalid memory otherwise.
          TRITON_EXPORT const triton::arch::MemoryAccess& getOriginMemory(void) const;

          //! Returns the origin register if `kind` is equal to `triton::engines::symbolic::REGISTER_EXPRESSION`, invalid register otherwise.
          TRITON_EXPORT const triton::arch::Register& getOriginRegister(void) const;

          //! Sets a root node.
          TRITON_EXPORT void setAst(const triton::ast::SharedAbstractNode& node);

          //! Sets a comment to the symbolic expression.
          TRITON_EXPORT void setComment(const std::string& comment);

          //! Sets the kind of the symbolic expression.
          TRITON_EXPORT void setType(triton::engines::symbolic::expression_e type);

          //! Sets the symbolic expression address.
          TRITON_EXPORT void setAddress(triton::uint64 address);

          //! Get the address of the symbolic expression, if any.
          TRITON_EXPORT triton::uint64 getAddress(void) const;

          //! Sets the origin memory acccess.
          TRITON_EXPORT void setOriginMemory(const triton::arch::MemoryAccess& mem);

          //! Sets the origin register.
          TRITON_EXPORT void setOriginRegister(const triton::arch::Register& reg);

          //! Writes back the instruction disassembly where the symbolic expression comes from.
          TRITON_EXPORT void writeBackDisassembly(const std::string& disassembly);

          //! Gets the instruction disassembly where the symbolic expression comes from.
          TRITON_EXPORT const std::string& getDisassembly(void);
      };

      //! Shared Symbolic Expression.
      using SharedSymbolicExpression = std::shared_ptr<triton::engines::symbolic::SymbolicExpression>;

      //! Weak Symbolic Expression.
      using WeakSymbolicExpression = std::weak_ptr<triton::engines::symbolic::SymbolicExpression>;

      //! Displays a symbolic expression.
      TRITON_EXPORT std::ostream& operator<<(std::ostream& stream, const SymbolicExpression& symExpr);

      //! Displays a symbolic expression.
      TRITON_EXPORT std::ostream& operator<<(std::ostream& stream, const SymbolicExpression* symExpr);

    /*! @} End of symbolic namespace */
    };
  /*! @} End of engines namespace */
  };
/*! @} End of triton namespace */
};

#endif /* TRITON_SYMBOLICEXPRESSION_H */
<commit_msg>Fix type<commit_after>//! \file
/*
**  Copyright (C) - Triton
**
**  This program is under the terms of the Apache License 2.0.
*/

#ifndef TRITON_SYMBOLICEXPRESSION_H
#define TRITON_SYMBOLICEXPRESSION_H

#include <memory>
#include <string>

#include <triton/ast.hpp>
#include <triton/dllexport.hpp>
#include <triton/memoryAccess.hpp>
#include <triton/register.hpp>
#include <triton/symbolicEnums.hpp>
#include <triton/tritonTypes.hpp>

//! The Triton namespace
namespace triton {
/*!
 *  \addtogroup triton
 *  @{
 */

  //! The Engines namespace
  namespace engines {
  /*!
   *  \ingroup triton
   *  \addtogroup engines
   *  @{
   */

    //! The Symbolic Execution namespace
    namespace symbolic {
    /*!
     *  \ingroup engines
     *  \addtogroup symbolic
     *  @{
     */

      //! \class SymbolicExpression
      /*! \brief The symbolic expression class */
      class SymbolicExpression {
        protected:
          //! The type of the symbolic expression assignment.
          triton::engines::symbolic::expression_e type;

          //! The root node (AST) of the symbolic expression.
          triton::ast::SharedAbstractNode ast;

          //! The comment of the symbolic expression.
          std::string comment;

          //! The address of the instruction behind the symbolic expression. -1 if not defined.
          triton::uint64 address;

          //! The instruction disassembly where the symbolic expression comes from.
          std::string disassembly;

          //! The symbolic expression id. This id is unique.
          triton::usize id;

          //! The origin memory address if `type` is equal to `triton::engines::symbolic::MEM`, invalid memory otherwise.
          triton::arch::MemoryAccess originMemory;

          //! The origin register if `type` is equal to `triton::engines::symbolic::REG`, `REG_INVALID` otherwise.
          triton::arch::Register originRegister;

        private:
          //! Returns the syntax of a bitvector define
          TRITON_EXPORT std::string getBitvectorDefine(void) const;

          //! Returns the syntax of an array define
          TRITON_EXPORT std::string getArrayDefine(void) const;

        public:
          //! True if the symbolic expression is tainted.
          bool isTainted;

          //! Constructor.
          TRITON_EXPORT SymbolicExpression(const triton::ast::SharedAbstractNode& node,
                                           triton::usize id,
                                           triton::engines::symbolic::expression_e type,
                                           const std::string& comment="");

          //! Constructor by copy.
          TRITON_EXPORT SymbolicExpression(const SymbolicExpression& other);

          //! Operator.
          TRITON_EXPORT SymbolicExpression& operator=(const SymbolicExpression& other);

          //! Returns the symbolic expression id.
          TRITON_EXPORT triton::usize getId(void) const;

          //! Returns true if the symbolic expression is assigned to a memory.
          TRITON_EXPORT bool isMemory(void) const;

          //! Returns true if the symbolic expression is assigned to a register.
          TRITON_EXPORT bool isRegister(void) const;

          //! Returns true if the expression contains a symbolic variable.
          TRITON_EXPORT bool isSymbolized(void) const;

          //! Returns the type of the symbolic expression assignment.
          TRITON_EXPORT triton::engines::symbolic::expression_e getType(void) const;

          //! Returns the SMT AST root node of the symbolic expression. This is the semantics.
          TRITON_EXPORT const triton::ast::SharedAbstractNode& getAst(void) const;

          //! Returns a new SMT AST root node of the symbolic expression. This new instance is a duplicate of the original node and may be changed without changing the original semantics.
          TRITON_EXPORT triton::ast::SharedAbstractNode getNewAst(void) const;

          //! Returns the comment of the symbolic expression.
          TRITON_EXPORT const std::string& getComment(void) const;

          //! Returns the id as string of the symbolic expression according the mode of the AST representation.
          TRITON_EXPORT std::string getFormattedId(void) const;

          //! Returns the comment as string of the symbolic expression according the mode of the AST representation.
          TRITON_EXPORT std::string getFormattedComment(void) const;

          //! Returns the symbolic expression representation as string according the mode of the AST representation.
          TRITON_EXPORT std::string getFormattedExpression(void) const;

          //! Returns the origin memory access if `kind` is equal to `triton::engines::symbolic::MEMORY_EXPRESSION`, invalid memory otherwise.
          TRITON_EXPORT const triton::arch::MemoryAccess& getOriginMemory(void) const;

          //! Returns the origin register if `kind` is equal to `triton::engines::symbolic::REGISTER_EXPRESSION`, invalid register otherwise.
          TRITON_EXPORT const triton::arch::Register& getOriginRegister(void) const;

          //! Sets a root node.
          TRITON_EXPORT void setAst(const triton::ast::SharedAbstractNode& node);

          //! Sets a comment to the symbolic expression.
          TRITON_EXPORT void setComment(const std::string& comment);

          //! Sets the kind of the symbolic expression.
          TRITON_EXPORT void setType(triton::engines::symbolic::expression_e type);

          //! Sets the symbolic expression address.
          TRITON_EXPORT void setAddress(triton::uint64 address);

          //! Get the address of the symbolic expression, if any.
          TRITON_EXPORT triton::uint64 getAddress(void) const;

          //! Sets the origin memory acccess.
          TRITON_EXPORT void setOriginMemory(const triton::arch::MemoryAccess& mem);

          //! Sets the origin register.
          TRITON_EXPORT void setOriginRegister(const triton::arch::Register& reg);

          //! Writes back the instruction disassembly where the symbolic expression comes from.
          TRITON_EXPORT void writeBackDisassembly(const std::string& disassembly);

          //! Gets the instruction disassembly where the symbolic expression comes from.
          TRITON_EXPORT const std::string& getDisassembly(void);
      };

      //! Shared Symbolic Expression.
      using SharedSymbolicExpression = std::shared_ptr<triton::engines::symbolic::SymbolicExpression>;

      //! Weak Symbolic Expression.
      using WeakSymbolicExpression = std::weak_ptr<triton::engines::symbolic::SymbolicExpression>;

      //! Displays a symbolic expression.
      TRITON_EXPORT std::ostream& operator<<(std::ostream& stream, const SymbolicExpression& symExpr);

      //! Displays a symbolic expression.
      TRITON_EXPORT std::ostream& operator<<(std::ostream& stream, const SymbolicExpression* symExpr);

    /*! @} End of symbolic namespace */
    };
  /*! @} End of engines namespace */
  };
/*! @} End of triton namespace */
};

#endif /* TRITON_SYMBOLICEXPRESSION_H */
<|endoftext|>