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

#include <comphelper/processfactory.hxx>
#include <cppuhelper/implbase2.hxx> // helper for implementations
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/i18n/XInputSequenceChecker.hpp>

#include <tools/list.hxx>

namespace com { namespace sun { namespace star { namespace i18n {

//  ----------------------------------------------------
//  class InputSequenceCheckerImpl
//  ----------------------------------------------------
class InputSequenceCheckerImpl : public cppu::WeakImplHelper2
<
    com::sun::star::i18n::XInputSequenceChecker,
    com::sun::star::lang::XServiceInfo
>
{
public:
    InputSequenceCheckerImpl( const com::sun::star::uno::Reference < com::sun::star::lang::XMultiServiceFactory >& rxMSF );
    InputSequenceCheckerImpl();
    ~InputSequenceCheckerImpl();

    virtual sal_Bool SAL_CALL checkInputSequence(const rtl::OUString& Text, sal_Int32 nStartPos,
        sal_Unicode inputChar, sal_Int16 inputCheckMode) throw(com::sun::star::uno::RuntimeException);

    //XServiceInfo
    virtual rtl::OUString SAL_CALL getImplementationName() throw( com::sun::star::uno::RuntimeException );
    virtual sal_Bool SAL_CALL supportsService(const rtl::OUString& ServiceName)
        throw( com::sun::star::uno::RuntimeException );
    virtual com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL getSupportedServiceNames()
        throw( com::sun::star::uno::RuntimeException );

protected:
    sal_Int16 checkMode;
    sal_Char *serviceName;

private :
    struct lookupTableItem {
        lookupTableItem(const sal_Char* rLanguage, const com::sun::star::uno::Reference < com::sun::star::i18n::XInputSequenceChecker >& rxISC) :
            aLanguage(rLanguage), xISC(rxISC) {}
        const sal_Char* aLanguage;
        com::sun::star::uno::Reference < com::sun::star::i18n::XInputSequenceChecker > xISC;
    };
    List lookupTable;
    lookupTableItem *cachedItem;

    com::sun::star::uno::Reference < com::sun::star::lang::XMultiServiceFactory > xMSF;

    com::sun::star::uno::Reference< com::sun::star::i18n::XInputSequenceChecker >& SAL_CALL getInputSequenceChecker(sal_Char* rLanguage)
        throw (com::sun::star::uno::RuntimeException);
    sal_Char* SAL_CALL getLanguageByScripType(sal_Unicode cChar, sal_Unicode nChar);
};

} } } }

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

#include <comphelper/processfactory.hxx>
#include <cppuhelper/implbase2.hxx> // helper for implementations
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/i18n/XInputSequenceChecker.hpp>

#include <vector>

namespace com { namespace sun { namespace star { namespace i18n {

//  ----------------------------------------------------
//  class InputSequenceCheckerImpl
//  ----------------------------------------------------
class InputSequenceCheckerImpl : public cppu::WeakImplHelper2
<
    com::sun::star::i18n::XInputSequenceChecker,
    com::sun::star::lang::XServiceInfo
>
{
public:
    InputSequenceCheckerImpl( const com::sun::star::uno::Reference < com::sun::star::lang::XMultiServiceFactory >& rxMSF );
    InputSequenceCheckerImpl();
    ~InputSequenceCheckerImpl();

    virtual sal_Bool SAL_CALL checkInputSequence(const rtl::OUString& Text, sal_Int32 nStartPos,
        sal_Unicode inputChar, sal_Int16 inputCheckMode) throw(com::sun::star::uno::RuntimeException);

    //XServiceInfo
    virtual rtl::OUString SAL_CALL getImplementationName() throw( com::sun::star::uno::RuntimeException );
    virtual sal_Bool SAL_CALL supportsService(const rtl::OUString& ServiceName)
        throw( com::sun::star::uno::RuntimeException );
    virtual com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL getSupportedServiceNames()
        throw( com::sun::star::uno::RuntimeException );

protected:
    sal_Int16 checkMode;
    const sal_Char *serviceName;

private :
    struct lookupTableItem {
        lookupTableItem(const sal_Char* rLanguage, const com::sun::star::uno::Reference < com::sun::star::i18n::XInputSequenceChecker >& rxISC) :
            aLanguage(rLanguage), xISC(rxISC) {}
        const sal_Char* aLanguage;
        com::sun::star::uno::Reference < com::sun::star::i18n::XInputSequenceChecker > xISC;
    };
    std::vector<lookupTableItem*> lookupTable;
    lookupTableItem *cachedItem;

    com::sun::star::uno::Reference < com::sun::star::lang::XMultiServiceFactory > xMSF;

    com::sun::star::uno::Reference< com::sun::star::i18n::XInputSequenceChecker >& SAL_CALL getInputSequenceChecker(sal_Char* rLanguage)
        throw (com::sun::star::uno::RuntimeException);
    sal_Char* SAL_CALL getLanguageByScripType(sal_Unicode cChar, sal_Unicode nChar);
};

} } } }

#endif // _I18N_BREAKITERATOR_HXX_
<|endoftext|>


<commit_before>#include <sys/socket.h>

#include "utils.h"

#include "client_http.h"

//
// Xapian http client
//

HttpClient::HttpClient(ev::loop_ref *loop, int sock_, DatabasePool *database_pool_, double active_timeout_, double idle_timeout_)
	: BaseClient(loop, sock_, database_pool_, active_timeout_, idle_timeout_)
{
	parser.data = this;
	http_parser_init(&parser, HTTP_REQUEST);
	LOG_CONN(this, "Got connection (sock=%d), %d http client(s) connected.\n", sock, ++total_clients);
}

HttpClient::~HttpClient()
{
	total_clients--;
}

void HttpClient::on_read(const char *buf, ssize_t received)
{
	size_t parsed = http_parser_execute(&parser, &settings, buf, received);
	if (parsed == received) {
		if (parser.state == 1 || parser.state == 18) { // dead or message_complete
			try {
				//					LOG_HTTP_PROTO(this, "METHOD: %d\n", parser.method);
				//					LOG_HTTP_PROTO(this, "PATH: '%s'\n", repr(path).c_str());
				//					LOG_HTTP_PROTO(this, "BODY: '%s'\n", repr(body).c_str());
				char tmp[20];
				std::string body("OK!");
				std::string response;
				response += "HTTP/";
				sprintf(tmp, "%d.%d", parser.http_major, parser.http_minor);
				response += tmp;
				response += " 200 OK\r\n";
				response += "Content-Length: ";
				sprintf(tmp, "%ld", body.size());
				response += tmp;
				response += "\r\n";
				write(response + "\r\n" + body);
				if (parser.state == 1) close();
			} catch (...) {
				LOG_ERR(this, "ERROR!\n");
			}
		}
	} else {
		enum http_errno err = HTTP_PARSER_ERRNO(&parser);
		const char *desc = http_errno_description(err);
		const char *msg = err != HPE_OK ? desc : "incomplete request";
		LOG_HTTP_PROTO(this, msg);
		// Handle error. Just close the connection.
		destroy();
	}
}

//
// HTTP parser callbacks.
//

const http_parser_settings HttpClient::settings = {
	.on_message_begin = HttpClient::on_info,
	.on_url = HttpClient::on_data,
	.on_status = HttpClient::on_data,
	.on_header_field = HttpClient::on_data,
	.on_header_value = HttpClient::on_data,
	.on_headers_complete = HttpClient::on_info,
	.on_body = HttpClient::on_data,
	.on_message_complete = HttpClient::on_info
};

int HttpClient::on_info(http_parser* p) {
	HttpClient *self = static_cast<HttpClient *>(p->data);

	LOG_HTTP_PROTO_PARSER(self, "%3d. (INFO)\n", p->state);

	switch (p->state) {
		case 18:  // message_complete
			break;
		case 19:  // message_begin
			self->path.clear();
			self->body.clear();
			break;
	}

	return 0;
}

int HttpClient::on_data(http_parser* p, const char *at, size_t length) {
	HttpClient *self = static_cast<HttpClient *>(p->data);

	LOG_HTTP_PROTO_PARSER(self, "%3d. %s\n", p->state, repr(at, length).c_str());

	switch (p->state) {
		case 32: // path
			self->path = std::string(at, length);
			break;
		case 62: // data
			self->body = std::string(at, length);
			break;
	}

	return 0;
}
<commit_msg>Added cJSON and example in HttpClient<commit_after>#include <sys/socket.h>

#include "utils.h"
#include "cJSON.h"

#include "client_http.h"

//
// Xapian http client
//

HttpClient::HttpClient(ev::loop_ref *loop, int sock_, DatabasePool *database_pool_, double active_timeout_, double idle_timeout_)
	: BaseClient(loop, sock_, database_pool_, active_timeout_, idle_timeout_)
{
	parser.data = this;
	http_parser_init(&parser, HTTP_REQUEST);
	LOG_CONN(this, "Got connection (sock=%d), %d http client(s) connected.\n", sock, ++total_clients);
}

HttpClient::~HttpClient()
{
	total_clients--;
}

void HttpClient::on_read(const char *buf, ssize_t received)
{
	size_t parsed = http_parser_execute(&parser, &settings, buf, received);
	if (parsed == received) {
		if (parser.state == 1 || parser.state == 18) { // dead or message_complete
			try {
				//					LOG_HTTP_PROTO(this, "METHOD: %d\n", parser.method);
				//					LOG_HTTP_PROTO(this, "PATH: '%s'\n", repr(path).c_str());
				//					LOG_HTTP_PROTO(this, "BODY: '%s'\n", repr(body).c_str());

				std::string content;
				cJSON *json = cJSON_Parse(body.c_str());
				cJSON *query = json ? cJSON_GetObjectItem(json, "query") : NULL;
				cJSON *term = query ? cJSON_GetObjectItem(query, "term") : NULL;
				cJSON *text = term ? cJSON_GetObjectItem(term, "text") : NULL;
				if (text) {
					content = "OK: ";
					content += text->valuestring;
				} else {
					content = "ERROR!"
					LOG_HTTP_PROTO("Error before: [%s]\n", cJSON_GetErrorPtr());
				}
				cJSON_Delete(json);

				char tmp[20];
				std::string response;
				response += "HTTP/";
				sprintf(tmp, "%d.%d", parser.http_major, parser.http_minor);
				response += tmp;
				response += " 200 OK\r\n";
				response += "Content-Length: ";
				sprintf(tmp, "%ld", content.size());
				response += tmp;
				response += "\r\n";
				write(response + "\r\n" + content);
				if (parser.state == 1) close();
			} catch (...) {
				LOG_ERR(this, "ERROR!\n");
			}
		}
	} else {
		enum http_errno err = HTTP_PARSER_ERRNO(&parser);
		const char *desc = http_errno_description(err);
		const char *msg = err != HPE_OK ? desc : "incomplete request";
		LOG_HTTP_PROTO(this, msg);
		// Handle error. Just close the connection.
		destroy();
	}
}

//
// HTTP parser callbacks.
//

const http_parser_settings HttpClient::settings = {
	.on_message_begin = HttpClient::on_info,
	.on_url = HttpClient::on_data,
	.on_status = HttpClient::on_data,
	.on_header_field = HttpClient::on_data,
	.on_header_value = HttpClient::on_data,
	.on_headers_complete = HttpClient::on_info,
	.on_body = HttpClient::on_data,
	.on_message_complete = HttpClient::on_info
};

int HttpClient::on_info(http_parser* p) {
	HttpClient *self = static_cast<HttpClient *>(p->data);

	LOG_HTTP_PROTO_PARSER(self, "%3d. (INFO)\n", p->state);

	switch (p->state) {
		case 18:  // message_complete
			break;
		case 19:  // message_begin
			self->path.clear();
			self->body.clear();
			break;
	}

	return 0;
}

int HttpClient::on_data(http_parser* p, const char *at, size_t length) {
	HttpClient *self = static_cast<HttpClient *>(p->data);

	LOG_HTTP_PROTO_PARSER(self, "%3d. %s\n", p->state, repr(at, length).c_str());

	switch (p->state) {
		case 32: // path
			self->path = std::string(at, length);
			break;
		case 62: // data
			self->body = std::string(at, length);
			break;
	}

	return 0;
}
<|endoftext|>


<commit_before>/************************************************************************
	filename: 	CEGUIComboDropList.cpp
	created:	13/6/2004
	author:		Paul D Turner

	purpose:	Implements the Combobox Drop-List widget base class
*************************************************************************/
/*************************************************************************
    Crazy Eddie's GUI System (http://crayzedsgui.sourceforge.net)
    Copyright (C)2004 Paul D Turner (crayzed@users.sourceforge.net)

    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.1 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*************************************************************************/
#include "elements/CEGUIComboDropList.h"
#include "elements/CEGUIScrollbar.h"

// Start of CEGUI namespace section
namespace CEGUI
{
/*************************************************************************
	Constants
*************************************************************************/
// Event names
const utf8	ComboDropList::EventListSelectionAccepted[]		= "ListSelectionAccepted";

/*************************************************************************
	Constructor for ComboDropList base class
*************************************************************************/
ComboDropList::ComboDropList(const String& type, const String& name) :
	Listbox(type, name)
{
	d_autoArm = false;
	d_armed = false;

	addComboDropListEvents();
	hide();
}

/*************************************************************************
	Destructor for ComboDropList base class
*************************************************************************/
ComboDropList::~ComboDropList(void)
{
}

/*************************************************************************
	Initialise the Window based object ready for use.
*************************************************************************/
void ComboDropList::initialise(void)
{
	Listbox::initialise();

	// set-up scroll bars so they return capture to us.
	d_vertScrollbar->setRestoreCapture(true);
	d_horzScrollbar->setRestoreCapture(true);
}

/*************************************************************************
	Add drop-list specific events
*************************************************************************/
void ComboDropList::addComboDropListEvents(void)
{
	addEvent(EventListSelectionAccepted);
}

/*************************************************************************
	Handler for when list selection is confirmed.
*************************************************************************/
void ComboDropList::onListSelectionAccepted(WindowEventArgs& e)
{
	fireEvent(EventListSelectionAccepted, e);
}

/*************************************************************************
	Handler for mouse movement events
*************************************************************************/
void ComboDropList::onMouseMove(MouseEventArgs& e)
{
	Listbox::onMouseMove(e);

	// if mouse is within our area (but not our children)
	if (isHit(e.position))
	{
		if (getChildAtPosition(e.position) == NULL)
		{
			// handle auto-arm
			if (d_autoArm)
			{
				d_armed = true;
			}

			if (d_armed)
			{
				//
				// Convert mouse position to absolute window pixels
				//
				Point localPos(screenToWindow(e.position));

				if (getMetricsMode() == Relative)
				{
					localPos = relativeToAbsolute(localPos);
				}

				// check for an item under the mouse
				ListboxItem* selItem = getItemAtPoint(localPos);

				// if an item is under mouse, select it
				if (selItem != NULL)
				{
					setItemSelectState(selItem, true);
				}
				else
				{
					clearAllSelections();
				}

			}
		}

		e.handled = true;
	}
	// not within the list area
	else
	{
		// if left mouse button is down, clear any selection
		if (e.sysKeys & LeftMouse)
		{
			clearAllSelections();
		}

	}

}

/*************************************************************************
	Handler for mouse button pressed events
*************************************************************************/
void ComboDropList::onMouseButtonDown(MouseEventArgs& e)
{
	Listbox::onMouseButtonDown(e);

	if (e.button == LeftButton)
	{
		if (!isHit(e.position))
		{
			clearAllSelections();
			releaseInput();
		}
		else
		{
			d_armed = true;
		}

		e.handled = true;
	}

}

/*************************************************************************
	Handler for mouse button release events
*************************************************************************/
void ComboDropList::onMouseButtonUp(MouseEventArgs& e)
{
	Listbox::onMouseButtonUp(e);

	if (e.button == LeftButton)
	{
		if (d_armed)
		{
			releaseInput();

			// if something was selected, confirm that selection.
			if (getSelectedCount() > 0)
			{
				WindowEventArgs args(this);
				onListSelectionAccepted(args);
			}

		}
		// if we are not already armed, in response to a left button up event, we auto-arm.
		else
		{
			d_armed = true;
		}

		e.handled = true;
	}

}

/*************************************************************************
	Handler for when input capture is lost
*************************************************************************/
void ComboDropList::onCaptureLost(WindowEventArgs& e)
{
	Listbox::onCaptureLost(e);
	d_armed = false;
	hide();
	e.handled = true;
}

/*************************************************************************
	Handler for when window is activated
*************************************************************************/
void ComboDropList::onActivated(ActivationEventArgs& e)
{
	Listbox::onActivated(e);
}

} // End of  CEGUI namespace section
<commit_msg>Bug Fix: onMouseButonUp was not testing if position of mouse was over child windows, resulting in incorrect behaviour.<commit_after>/************************************************************************
	filename: 	CEGUIComboDropList.cpp
	created:	13/6/2004
	author:		Paul D Turner

	purpose:	Implements the Combobox Drop-List widget base class
*************************************************************************/
/*************************************************************************
    Crazy Eddie's GUI System (http://crayzedsgui.sourceforge.net)
    Copyright (C)2004 Paul D Turner (crayzed@users.sourceforge.net)

    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.1 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*************************************************************************/
#include "elements/CEGUIComboDropList.h"
#include "elements/CEGUIScrollbar.h"

// Start of CEGUI namespace section
namespace CEGUI
{
/*************************************************************************
	Constants
*************************************************************************/
// Event names
const utf8	ComboDropList::EventListSelectionAccepted[]		= "ListSelectionAccepted";

/*************************************************************************
	Constructor for ComboDropList base class
*************************************************************************/
ComboDropList::ComboDropList(const String& type, const String& name) :
	Listbox(type, name)
{
	d_autoArm = false;
	d_armed = false;

	addComboDropListEvents();
	hide();
}

/*************************************************************************
	Destructor for ComboDropList base class
*************************************************************************/
ComboDropList::~ComboDropList(void)
{
}

/*************************************************************************
	Initialise the Window based object ready for use.
*************************************************************************/
void ComboDropList::initialise(void)
{
	Listbox::initialise();

	// set-up scroll bars so they return capture to us.
	d_vertScrollbar->setRestoreCapture(true);
	d_horzScrollbar->setRestoreCapture(true);
}

/*************************************************************************
	Add drop-list specific events
*************************************************************************/
void ComboDropList::addComboDropListEvents(void)
{
	addEvent(EventListSelectionAccepted);
}

/*************************************************************************
	Handler for when list selection is confirmed.
*************************************************************************/
void ComboDropList::onListSelectionAccepted(WindowEventArgs& e)
{
	fireEvent(EventListSelectionAccepted, e);
}

/*************************************************************************
	Handler for mouse movement events
*************************************************************************/
void ComboDropList::onMouseMove(MouseEventArgs& e)
{
	Listbox::onMouseMove(e);

	// if mouse is within our area (but not our children)
	if (isHit(e.position))
	{
		if (getChildAtPosition(e.position) == NULL)
		{
			// handle auto-arm
			if (d_autoArm)
			{
				d_armed = true;
			}

			if (d_armed)
			{
				//
				// Convert mouse position to absolute window pixels
				//
				Point localPos(screenToWindow(e.position));

				if (getMetricsMode() == Relative)
				{
					localPos = relativeToAbsolute(localPos);
				}

				// check for an item under the mouse
				ListboxItem* selItem = getItemAtPoint(localPos);

				// if an item is under mouse, select it
				if (selItem != NULL)
				{
					setItemSelectState(selItem, true);
				}
				else
				{
					clearAllSelections();
				}

			}
		}

		e.handled = true;
	}
	// not within the list area
	else
	{
		// if left mouse button is down, clear any selection
		if (e.sysKeys & LeftMouse)
		{
			clearAllSelections();
		}

	}

}

/*************************************************************************
	Handler for mouse button pressed events
*************************************************************************/
void ComboDropList::onMouseButtonDown(MouseEventArgs& e)
{
	Listbox::onMouseButtonDown(e);

	if (e.button == LeftButton)
	{
		if (!isHit(e.position))
		{
			clearAllSelections();
			releaseInput();
		}
		else
		{
			d_armed = true;
		}

		e.handled = true;
	}

}

/*************************************************************************
	Handler for mouse button release events
*************************************************************************/
void ComboDropList::onMouseButtonUp(MouseEventArgs& e)
{
	Listbox::onMouseButtonUp(e);

	if (e.button == LeftButton)
	{
		if (d_armed && (getChildAtPosition(e.position) == NULL))
		{
			releaseInput();

			// if something was selected, confirm that selection.
			if (getSelectedCount() > 0)
			{
				WindowEventArgs args(this);
				onListSelectionAccepted(args);
			}

		}
		// if we are not already armed, in response to a left button up event, we auto-arm.
		else
		{
			d_armed = true;
		}

		e.handled = true;
	}

}

/*************************************************************************
	Handler for when input capture is lost
*************************************************************************/
void ComboDropList::onCaptureLost(WindowEventArgs& e)
{
	Listbox::onCaptureLost(e);
	d_armed = false;
	hide();
	e.handled = true;
}

/*************************************************************************
	Handler for when window is activated
*************************************************************************/
void ComboDropList::onActivated(ActivationEventArgs& e)
{
	Listbox::onActivated(e);
}

} // End of  CEGUI namespace section
<|endoftext|>


<commit_before>#include "configcore.h"

// PDTK
#include <cxxutils/syslogstream.h>

#ifndef MCFS_PATH
#define MCFS_PATH               "/mc"
#endif

#ifndef CONFIG_USERNAME
#define CONFIG_USERNAME         "config"
#endif

#ifdef ANONYMOUS_SOCKET
#undef ANONYMOUS_SOCKET
#endif
#define ANONYMOUS_SOCKET        "\0"

#ifndef CONFIG_IO_SOCKET
#define CONFIG_IO_SOCKET        MCFS_PATH "/" CONFIG_USERNAME "/io"
#endif

#ifndef CONFIG_DIRECTOR_SOCKET
#define CONFIG_DIRECTOR_SOCKET  MCFS_PATH "/" CONFIG_USERNAME "/director"
#endif

ConfigCore::ConfigCore(void)
{
  if(m_config_server.bind(CONFIG_IO_SOCKET))
    posix::syslog << posix::priority::info << "Config daemon bound to socket file " << CONFIG_IO_SOCKET << posix::eom;
  else if(m_config_server.bind(ANONYMOUS_SOCKET CONFIG_IO_SOCKET))
    posix::syslog << posix::priority::info << "Config daemon bound to anonymous socket " << CONFIG_IO_SOCKET << posix::eom;
  else
    posix::syslog << posix::priority::error << "Unable to bind Config daemon to " << CONFIG_IO_SOCKET << posix::eom;

  if(m_director_server.bind(CONFIG_DIRECTOR_SOCKET))
    posix::syslog << posix::priority::info << "Config daemon bound to " << CONFIG_DIRECTOR_SOCKET << posix::eom;
  else if(m_director_server.bind(ANONYMOUS_SOCKET CONFIG_DIRECTOR_SOCKET))
    posix::syslog << posix::priority::info << "Config daemon bound to anonymous socket " << CONFIG_DIRECTOR_SOCKET << posix::eom;
  else
    posix::syslog << posix::priority::error << "Unable to bind Config daemon to " << CONFIG_DIRECTOR_SOCKET << posix::eom;
}
<commit_msg>component rename<commit_after>#include "configcore.h"

// PDTK
#include <cxxutils/syslogstream.h>

#ifndef SCFS_PATH
#define SCFS_PATH               "/svc"
#endif

#ifndef CONFIG_USERNAME
#define CONFIG_USERNAME         "config"
#endif

#ifdef ANONYMOUS_SOCKET
#undef ANONYMOUS_SOCKET
#endif
#define ANONYMOUS_SOCKET        "\0"

#ifndef CONFIG_IO_SOCKET
#define CONFIG_IO_SOCKET        SCFS_PATH "/" CONFIG_USERNAME "/io"
#endif

#ifndef CONFIG_DIRECTOR_SOCKET
#define CONFIG_DIRECTOR_SOCKET  SCFS_PATH "/" CONFIG_USERNAME "/director"
#endif

ConfigCore::ConfigCore(void)
{
  if(m_config_server.bind(CONFIG_IO_SOCKET))
    posix::syslog << posix::priority::info << "Config daemon bound to socket file " << CONFIG_IO_SOCKET << posix::eom;
  else if(m_config_server.bind(ANONYMOUS_SOCKET CONFIG_IO_SOCKET))
    posix::syslog << posix::priority::info << "Config daemon bound to anonymous socket " << CONFIG_IO_SOCKET << posix::eom;
  else
    posix::syslog << posix::priority::error << "Unable to bind Config daemon to " << CONFIG_IO_SOCKET << posix::eom;

  if(m_director_server.bind(CONFIG_DIRECTOR_SOCKET))
    posix::syslog << posix::priority::info << "Config daemon bound to " << CONFIG_DIRECTOR_SOCKET << posix::eom;
  else if(m_director_server.bind(ANONYMOUS_SOCKET CONFIG_DIRECTOR_SOCKET))
    posix::syslog << posix::priority::info << "Config daemon bound to anonymous socket " << CONFIG_DIRECTOR_SOCKET << posix::eom;
  else
    posix::syslog << posix::priority::error << "Unable to bind Config daemon to " << CONFIG_DIRECTOR_SOCKET << posix::eom;
}
<|endoftext|>


<commit_before>#include "testlib.h"
#include <iostream>

using namespace std;

int main(int argc, char* argv[])
{
    setName("Interactor A+B");
    registerInteraction(argc, argv);

    // reads number of queries from test (input) file
    int n = inf.readInt();
    for (int i = 0; i < n; i++)
    {
        // reads query from test (input) file
        int a = inf.readInt();
        int b = inf.readInt();

        // writes query to the solution, endl makes flush
        cout << a << " " << b << endl;

        // writes output file to be verified by checker later
        tout << ouf.readInt() << endl;
    }

    // just message
    quitf(_ok, "%d queries processed", n);
}
<commit_msg>Formatting interactors<commit_after>#include "testlib.h"
#include <iostream>

using namespace std;

int main(int argc, char* argv[]) {
    setName("Interactor A+B");
    registerInteraction(argc, argv);

    // reads number of queries from test (input) file
    int n = inf.readInt();
    for (int i = 0; i < n; i++) {
        // reads query from test (input) file
        int a = inf.readInt();
        int b = inf.readInt();

        // writes query to the solution, endl makes flush
        cout << a << " " << b << endl;

        // writes output file to be verified by checker later
        tout << ouf.readInt() << endl;
    }

    // just message
    quitf(_ok, "%d queries processed", n);
}
<|endoftext|>


<commit_before><commit_msg>tpce: caught a memory leak source<commit_after><|endoftext|>


<commit_before>/*

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

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

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

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

*/

#ifndef TORRENT_TORRENT_HANDLE_HPP_INCLUDED
#define TORRENT_TORRENT_HANDLE_HPP_INCLUDED

#include <vector>

#ifdef _MSC_VER
#pragma warning(push, 1)
#endif

#include <boost/date_time/posix_time/posix_time.hpp>

#ifdef _MSC_VER
#pragma warning(pop)
#endif

#include "libtorrent/peer_id.hpp"
#include "libtorrent/peer_info.hpp"
#include "libtorrent/piece_picker.hpp"
#include "libtorrent/torrent_info.hpp"
#include "libtorrent/config.hpp"

namespace libtorrent
{
	namespace aux
	{
		struct session_impl;
		struct checker_impl;
	}

	struct TORRENT_EXPORT duplicate_torrent: std::exception
	{
		virtual const char* what() const throw()
		{ return "torrent already exists in session"; }
	};

	struct TORRENT_EXPORT invalid_handle: std::exception
	{
		virtual const char* what() const throw()
		{ return "invalid torrent handle used"; }
	};

	struct TORRENT_EXPORT torrent_status
	{
		torrent_status()
			: state(queued_for_checking)
			, paused(false)
			, progress(0.f)
			, total_download(0)
			, total_upload(0)
			, total_payload_download(0)
			, total_payload_upload(0)
			, total_failed_bytes(0)
			, total_redundant_bytes(0)
			, download_rate(0)
			, upload_rate(0)
			, download_payload_rate(0)
			, upload_payload_rate(0)
			, num_peers(0)
			, num_complete(-1)
			, num_incomplete(-1)
			, pieces(0)
			, num_pieces(0)
			, total_done(0)
			, total_wanted_done(0)
			, total_wanted(0)
			, num_seeds(0)
			, distributed_copies(0.f)
			, block_size(0)
		{}

		enum state_t
		{
			queued_for_checking,
			checking_files,
			connecting_to_tracker,
			downloading_metadata,
			downloading,
			finished,
			seeding,
			allocating
		};

		state_t state;
		bool paused;
		float progress;
		boost::posix_time::time_duration next_announce;
		boost::posix_time::time_duration announce_interval;

		std::string current_tracker;

		// transferred this session!
		// total, payload plus protocol
		size_type total_download;
		size_type total_upload;

		// payload only
		size_type total_payload_download;
		size_type total_payload_upload;

		// the amount of payload bytes that
		// has failed their hash test
		size_type total_failed_bytes;

		// the number of payload bytes that
		// has been received redundantly.
		size_type total_redundant_bytes;

		// current transfer rate
		// payload plus protocol
		float download_rate;
		float upload_rate;

		// the rate of payload that is
		// sent and received
		float download_payload_rate;
		float upload_payload_rate;

		// the number of peers this torrent
		// is connected to.
		int num_peers;

		// if the tracker sends scrape info in its
		// announce reply, these fields will be
		// set to the total number of peers that
		// have the whole file and the total number
		// of peers that are still downloading
		int num_complete;
		int num_incomplete;

		const std::vector<bool>* pieces;

		// this is the number of pieces the client has
		// downloaded. it is equal to:
		// std::accumulate(pieces->begin(), pieces->end());
		int num_pieces;

		// the number of bytes of the file we have
		// including pieces that may have been filtered
		// after we downloaded them
		size_type total_done;

		// the number of bytes we have of those that we
		// want. i.e. not counting bytes from pieces that
		// are filtered as not wanted.
		size_type total_wanted_done;

		// the total number of bytes we want to download
		// this may be smaller than the total torrent size
		// in case any pieces are filtered as not wanted
		size_type total_wanted;

		// the number of peers this torrent is connected to
		// that are seeding.
		int num_seeds;

		// the number of distributed copies of the file.
		// note that one copy may be spread out among many peers.
		//
		// the whole number part tells how many copies
		//   there are of the rarest piece(s)
		//
		// the fractional part tells the fraction of pieces that
		//   have more copies than the rarest piece(s).
		float distributed_copies;

		// the block size that is used in this torrent. i.e.
		// the number of bytes each piece request asks for
		// and each bit in the download queue bitfield represents
		int block_size;
	};

	struct TORRENT_EXPORT partial_piece_info
	{
		enum { max_blocks_per_piece = piece_picker::max_blocks_per_piece };
		int piece_index;
		int blocks_in_piece;
		std::bitset<max_blocks_per_piece> requested_blocks;
		std::bitset<max_blocks_per_piece> finished_blocks;
		tcp::endpoint peer[max_blocks_per_piece];
		int num_downloads[max_blocks_per_piece];
	};

	struct TORRENT_EXPORT torrent_handle
	{
		friend class invariant_access;
		friend class aux::session_impl;
		friend class torrent;

		torrent_handle(): m_ses(0), m_chk(0) {}

		void get_peer_info(std::vector<peer_info>& v) const;
		bool send_chat_message(tcp::endpoint ip, std::string message) const;
		torrent_status status() const;
		void get_download_queue(std::vector<partial_piece_info>& queue) const;

		// fills the specified vector with the download progress [0, 1]
		// of each file in the torrent. The files are ordered as in
		// the torrent_info.
		void file_progress(std::vector<float>& progress);

		std::vector<announce_entry> const& trackers() const;
		void replace_trackers(std::vector<announce_entry> const&) const;

		void add_url_seed(std::string const& url);

		bool has_metadata() const;
		const torrent_info& get_torrent_info() const;
		bool is_valid() const;

		bool is_seed() const;
		bool is_paused() const;
		void pause() const;
		void resume() const;

		// marks the piece with the given index as filtered
		// it will not be downloaded
		void filter_piece(int index, bool filter) const;
		void filter_pieces(std::vector<bool> const& pieces) const;
		bool is_piece_filtered(int index) const;
		std::vector<bool> filtered_pieces() const;

		// marks the file with the given index as filtered
		// it will not be downloaded
		void filter_files(std::vector<bool> const& files) const;

		// set the interface to bind outgoing connections
		// to.
		void use_interface(const char* net_interface) const;

		entry write_resume_data() const;

		// kind of similar to get_torrent_info() but this
		// is lower level, returning the exact info-part of
		// the .torrent file. When hashed, this buffer
		// will produce the info hash. The reference is valid
		// only as long as the torrent is running.
		std::vector<char> const& metadata() const;

		// forces this torrent to reannounce
		// (make a rerequest from the tracker)
		void force_reannounce() const;

		// forces a reannounce in the specified amount of time.
		// This overrides the default announce interval, and no
		// announce will take place until the given time has
		// timed out.
		void force_reannounce(boost::posix_time::time_duration) const;

		// TODO: add a feature where the user can tell the torrent
		// to finish all pieces currently in the pipeline, and then
		// abort the torrent.

		void set_upload_limit(int limit) const;
		void set_download_limit(int limit) const;
		void set_sequenced_download_threshold(int threshold) const;

		void set_peer_upload_limit(tcp::endpoint ip, int limit) const;
		void set_peer_download_limit(tcp::endpoint ip, int limit) const;

		// manually connect a peer
		void connect_peer(tcp::endpoint const& adr) const;

		// valid ratios are 0 (infinite ratio) or [ 1.0 , inf )
		// the ratio is uploaded / downloaded. less than 1 is not allowed
		void set_ratio(float up_down_ratio) const;

		boost::filesystem::path save_path() const;

		// -1 means unlimited unchokes
		void set_max_uploads(int max_uploads) const;

		// -1 means unlimited connections
		void set_max_connections(int max_connections) const;

		void set_tracker_login(std::string const& name
			, std::string const& password) const;

		// post condition: save_path() == save_path if true is returned
		bool move_storage(boost::filesystem::path const& save_path) const;

		const sha1_hash& info_hash() const
		{ return m_info_hash; }

		bool operator==(const torrent_handle& h) const
		{ return m_info_hash == h.m_info_hash; }

		bool operator!=(const torrent_handle& h) const
		{ return m_info_hash != h.m_info_hash; }

		bool operator<(const torrent_handle& h) const
		{ return m_info_hash < h.m_info_hash; }

	private:

		torrent_handle(aux::session_impl* s,
			aux::checker_impl* c,
			const sha1_hash& h)
			: m_ses(s)
			, m_chk(c)
			, m_info_hash(h)
		{
			assert(m_ses != 0);
		}

#ifndef NDEBUG
		void check_invariant() const;
#endif

		aux::session_impl* m_ses;
		aux::checker_impl* m_chk;
		sha1_hash m_info_hash;

	};

}

#endif // TORRENT_TORRENT_HANDLE_HPP_INCLUDED
<commit_msg>fixed warning on msvc8<commit_after>/*

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

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

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

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

*/

#ifndef TORRENT_TORRENT_HANDLE_HPP_INCLUDED
#define TORRENT_TORRENT_HANDLE_HPP_INCLUDED

#include <vector>

#ifdef _MSC_VER
#pragma warning(push, 1)
#endif

#include <boost/date_time/posix_time/posix_time.hpp>

#ifdef _MSC_VER
#pragma warning(pop)
#endif

#include "libtorrent/peer_id.hpp"
#include "libtorrent/peer_info.hpp"
#include "libtorrent/piece_picker.hpp"
#include "libtorrent/torrent_info.hpp"
#include "libtorrent/config.hpp"

namespace libtorrent
{
	namespace aux
	{
		struct session_impl;
		struct checker_impl;
	}

	struct TORRENT_EXPORT duplicate_torrent: std::exception
	{
		virtual const char* what() const throw()
		{ return "torrent already exists in session"; }
	};

	struct TORRENT_EXPORT invalid_handle: std::exception
	{
		virtual const char* what() const throw()
		{ return "invalid torrent handle used"; }
	};

	struct TORRENT_EXPORT torrent_status
	{
		torrent_status()
			: state(queued_for_checking)
			, paused(false)
			, progress(0.f)
			, total_download(0)
			, total_upload(0)
			, total_payload_download(0)
			, total_payload_upload(0)
			, total_failed_bytes(0)
			, total_redundant_bytes(0)
			, download_rate(0)
			, upload_rate(0)
			, download_payload_rate(0)
			, upload_payload_rate(0)
			, num_peers(0)
			, num_complete(-1)
			, num_incomplete(-1)
			, pieces(0)
			, num_pieces(0)
			, total_done(0)
			, total_wanted_done(0)
			, total_wanted(0)
			, num_seeds(0)
			, distributed_copies(0.f)
			, block_size(0)
		{}

		enum state_t
		{
			queued_for_checking,
			checking_files,
			connecting_to_tracker,
			downloading_metadata,
			downloading,
			finished,
			seeding,
			allocating
		};

		state_t state;
		bool paused;
		float progress;
		boost::posix_time::time_duration next_announce;
		boost::posix_time::time_duration announce_interval;

		std::string current_tracker;

		// transferred this session!
		// total, payload plus protocol
		size_type total_download;
		size_type total_upload;

		// payload only
		size_type total_payload_download;
		size_type total_payload_upload;

		// the amount of payload bytes that
		// has failed their hash test
		size_type total_failed_bytes;

		// the number of payload bytes that
		// has been received redundantly.
		size_type total_redundant_bytes;

		// current transfer rate
		// payload plus protocol
		float download_rate;
		float upload_rate;

		// the rate of payload that is
		// sent and received
		float download_payload_rate;
		float upload_payload_rate;

		// the number of peers this torrent
		// is connected to.
		int num_peers;

		// if the tracker sends scrape info in its
		// announce reply, these fields will be
		// set to the total number of peers that
		// have the whole file and the total number
		// of peers that are still downloading
		int num_complete;
		int num_incomplete;

		const std::vector<bool>* pieces;

		// this is the number of pieces the client has
		// downloaded. it is equal to:
		// std::accumulate(pieces->begin(), pieces->end());
		int num_pieces;

		// the number of bytes of the file we have
		// including pieces that may have been filtered
		// after we downloaded them
		size_type total_done;

		// the number of bytes we have of those that we
		// want. i.e. not counting bytes from pieces that
		// are filtered as not wanted.
		size_type total_wanted_done;

		// the total number of bytes we want to download
		// this may be smaller than the total torrent size
		// in case any pieces are filtered as not wanted
		size_type total_wanted;

		// the number of peers this torrent is connected to
		// that are seeding.
		int num_seeds;

		// the number of distributed copies of the file.
		// note that one copy may be spread out among many peers.
		//
		// the whole number part tells how many copies
		//   there are of the rarest piece(s)
		//
		// the fractional part tells the fraction of pieces that
		//   have more copies than the rarest piece(s).
		float distributed_copies;

		// the block size that is used in this torrent. i.e.
		// the number of bytes each piece request asks for
		// and each bit in the download queue bitfield represents
		int block_size;
	};

	struct TORRENT_EXPORT partial_piece_info
	{
		enum { max_blocks_per_piece = piece_picker::max_blocks_per_piece };
		int piece_index;
		int blocks_in_piece;
		std::bitset<max_blocks_per_piece> requested_blocks;
		std::bitset<max_blocks_per_piece> finished_blocks;
		tcp::endpoint peer[max_blocks_per_piece];
		int num_downloads[max_blocks_per_piece];
	};

	struct TORRENT_EXPORT torrent_handle
	{
		friend class invariant_access;
		friend struct aux::session_impl;
		friend class torrent;

		torrent_handle(): m_ses(0), m_chk(0) {}

		void get_peer_info(std::vector<peer_info>& v) const;
		bool send_chat_message(tcp::endpoint ip, std::string message) const;
		torrent_status status() const;
		void get_download_queue(std::vector<partial_piece_info>& queue) const;

		// fills the specified vector with the download progress [0, 1]
		// of each file in the torrent. The files are ordered as in
		// the torrent_info.
		void file_progress(std::vector<float>& progress);

		std::vector<announce_entry> const& trackers() const;
		void replace_trackers(std::vector<announce_entry> const&) const;

		void add_url_seed(std::string const& url);

		bool has_metadata() const;
		const torrent_info& get_torrent_info() const;
		bool is_valid() const;

		bool is_seed() const;
		bool is_paused() const;
		void pause() const;
		void resume() const;

		// marks the piece with the given index as filtered
		// it will not be downloaded
		void filter_piece(int index, bool filter) const;
		void filter_pieces(std::vector<bool> const& pieces) const;
		bool is_piece_filtered(int index) const;
		std::vector<bool> filtered_pieces() const;

		// marks the file with the given index as filtered
		// it will not be downloaded
		void filter_files(std::vector<bool> const& files) const;

		// set the interface to bind outgoing connections
		// to.
		void use_interface(const char* net_interface) const;

		entry write_resume_data() const;

		// kind of similar to get_torrent_info() but this
		// is lower level, returning the exact info-part of
		// the .torrent file. When hashed, this buffer
		// will produce the info hash. The reference is valid
		// only as long as the torrent is running.
		std::vector<char> const& metadata() const;

		// forces this torrent to reannounce
		// (make a rerequest from the tracker)
		void force_reannounce() const;

		// forces a reannounce in the specified amount of time.
		// This overrides the default announce interval, and no
		// announce will take place until the given time has
		// timed out.
		void force_reannounce(boost::posix_time::time_duration) const;

		// TODO: add a feature where the user can tell the torrent
		// to finish all pieces currently in the pipeline, and then
		// abort the torrent.

		void set_upload_limit(int limit) const;
		void set_download_limit(int limit) const;
		void set_sequenced_download_threshold(int threshold) const;

		void set_peer_upload_limit(tcp::endpoint ip, int limit) const;
		void set_peer_download_limit(tcp::endpoint ip, int limit) const;

		// manually connect a peer
		void connect_peer(tcp::endpoint const& adr) const;

		// valid ratios are 0 (infinite ratio) or [ 1.0 , inf )
		// the ratio is uploaded / downloaded. less than 1 is not allowed
		void set_ratio(float up_down_ratio) const;

		boost::filesystem::path save_path() const;

		// -1 means unlimited unchokes
		void set_max_uploads(int max_uploads) const;

		// -1 means unlimited connections
		void set_max_connections(int max_connections) const;

		void set_tracker_login(std::string const& name
			, std::string const& password) const;

		// post condition: save_path() == save_path if true is returned
		bool move_storage(boost::filesystem::path const& save_path) const;

		const sha1_hash& info_hash() const
		{ return m_info_hash; }

		bool operator==(const torrent_handle& h) const
		{ return m_info_hash == h.m_info_hash; }

		bool operator!=(const torrent_handle& h) const
		{ return m_info_hash != h.m_info_hash; }

		bool operator<(const torrent_handle& h) const
		{ return m_info_hash < h.m_info_hash; }

	private:

		torrent_handle(aux::session_impl* s,
			aux::checker_impl* c,
			const sha1_hash& h)
			: m_ses(s)
			, m_chk(c)
			, m_info_hash(h)
		{
			assert(m_ses != 0);
		}

#ifndef NDEBUG
		void check_invariant() const;
#endif

		aux::session_impl* m_ses;
		aux::checker_impl* m_chk;
		sha1_hash m_info_hash;

	};

}

#endif // TORRENT_TORRENT_HANDLE_HPP_INCLUDED
<|endoftext|>


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

#ifndef MTAC_LIVE_REGISTERS_PROBLEM_H
#define MTAC_LIVE_REGISTERS_PROBLEM_H

#include <memory>
#include <iostream>
#include <unordered_set>

#include "assert.hpp"

#include "mtac/DataFlowProblem.hpp"

//Necessary for hash
#include "ltac/Register.hpp"
#include "ltac/FloatRegister.hpp"
#include "ltac/PseudoRegister.hpp"
#include "ltac/PseudoFloatRegister.hpp"

namespace eddic {

namespace ltac {

template<typename Reg, typename FloatReg>
struct LiveRegisterValues {
    std::unordered_set<Reg> registers;
    std::unordered_set<FloatReg> float_registers;

    void insert(const Reg& reg){
        registers.insert(reg);
    }

    void insert(const FloatReg& reg){
        float_registers.insert(reg);
    }

    auto find(const Reg& reg) -> decltype(registers.find(reg)) {
        return registers.find(reg);
    }

    auto find(const FloatReg& reg) -> decltype(float_registers.find(reg)) {
        return float_registers.find(reg);
    }

    auto end() -> decltype(registers.end()) {
        return registers.end();
    }

    auto fend() -> decltype(float_registers.end()) {
        return float_registers.end();
    }

    void erase(const Reg& reg){
        registers.erase(reg);
    }

    void erase(const FloatReg& reg){
        float_registers.erase(reg);
    }

    std::size_t size(){
        return (static_cast<std::size_t>(std::numeric_limits<unsigned short>::max()) + 1) * registers.size() + float_registers.size();
    }
};

//Liveness analysis on Hard Registers

struct LiveRegistersProblem : public mtac::DataFlowProblem<mtac::DataFlowType::Low_Backward, LiveRegisterValues<ltac::Register, ltac::FloatRegister>> {
    ProblemDomain Boundary(mtac::Function& function) override;
    ProblemDomain Init(mtac::Function& function) override;

    void meet(ProblemDomain& in, const ProblemDomain& out) override;

    ProblemDomain transfer(mtac::basic_block_p basic_block, ltac::Statement& statement, ProblemDomain& in) override;
    ProblemDomain transfer(mtac::basic_block_p, std::shared_ptr<mtac::Quadruple>&, ProblemDomain&) override { eddic_unreachable("Not MTAC"); };

    bool optimize(ltac::Statement& statement, std::shared_ptr<mtac::DataFlowResults<ProblemDomain>> results) override;
    bool optimize(mtac::Function& function, std::shared_ptr<mtac::DataFlowResults<ProblemDomain>> ) override { eddic_unreachable("Not MTAC"); };
};

//Liveness analysis on Pseudo Registers

struct LivePseudoRegistersProblem : public mtac::DataFlowProblem<mtac::DataFlowType::Low_Backward, LiveRegisterValues<ltac::PseudoRegister, ltac::PseudoFloatRegister>> {
    ProblemDomain Boundary(mtac::Function& function) override;
    ProblemDomain Init(mtac::Function& function) override;

    void meet(ProblemDomain& in, const ProblemDomain& out) override;

    ProblemDomain transfer(mtac::basic_block_p basic_block, ltac::Statement& statement, ProblemDomain& in) override;
    ProblemDomain transfer(mtac::basic_block_p, std::shared_ptr<mtac::Quadruple>&, ProblemDomain&) override { eddic_unreachable("Not MTAC"); };

    bool optimize(ltac::Statement& statement, std::shared_ptr<mtac::DataFlowResults<ProblemDomain>> results) override;
    bool optimize(mtac::Function& function, std::shared_ptr<mtac::DataFlowResults<ProblemDomain>> ) override { eddic_unreachable("Not MTAC"); };
};

template<typename Reg, typename FloatReg>
std::ostream& operator<<(std::ostream& stream, const LiveRegisterValues<Reg, FloatReg>& value){
    stream << "set{";

    for(auto& v : value.registers){
        stream << v << ", ";
    }

    for(auto& v : value.float_registers){
        stream << v << ", ";
    }

    return stream << "}";
}

} //end of mtac

} //end of eddic

#endif
<commit_msg>Fix warnings<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#ifndef MTAC_LIVE_REGISTERS_PROBLEM_H
#define MTAC_LIVE_REGISTERS_PROBLEM_H

#include <memory>
#include <iostream>
#include <unordered_set>

#include "assert.hpp"

#include "mtac/DataFlowProblem.hpp"

//Necessary for hash
#include "ltac/Register.hpp"
#include "ltac/FloatRegister.hpp"
#include "ltac/PseudoRegister.hpp"
#include "ltac/PseudoFloatRegister.hpp"

namespace eddic {

namespace ltac {

template<typename Reg, typename FloatReg>
struct LiveRegisterValues {
    std::unordered_set<Reg> registers;
    std::unordered_set<FloatReg> float_registers;

    void insert(const Reg& reg){
        registers.insert(reg);
    }

    void insert(const FloatReg& reg){
        float_registers.insert(reg);
    }

    auto find(const Reg& reg) -> decltype(registers.find(reg)) {
        return registers.find(reg);
    }

    auto find(const FloatReg& reg) -> decltype(float_registers.find(reg)) {
        return float_registers.find(reg);
    }

    auto end() -> decltype(registers.end()) {
        return registers.end();
    }

    auto fend() -> decltype(float_registers.end()) {
        return float_registers.end();
    }

    void erase(const Reg& reg){
        registers.erase(reg);
    }

    void erase(const FloatReg& reg){
        float_registers.erase(reg);
    }

    std::size_t size(){
        return (static_cast<std::size_t>(std::numeric_limits<unsigned short>::max()) + 1) * registers.size() + float_registers.size();
    }
};

//Liveness analysis on Hard Registers

struct LiveRegistersProblem : public mtac::DataFlowProblem<mtac::DataFlowType::Low_Backward, LiveRegisterValues<ltac::Register, ltac::FloatRegister>> {
    ProblemDomain Boundary(mtac::Function& function) override;
    ProblemDomain Init(mtac::Function& function) override;

    void meet(ProblemDomain& in, const ProblemDomain& out) override;

    ProblemDomain transfer(mtac::basic_block_p basic_block, ltac::Statement& statement, ProblemDomain& in) override;
    ProblemDomain transfer(mtac::basic_block_p, std::shared_ptr<mtac::Quadruple>&, ProblemDomain&) override { eddic_unreachable("Not MTAC"); };

    bool optimize(ltac::Statement& statement, std::shared_ptr<mtac::DataFlowResults<ProblemDomain>> results) override;
    bool optimize(mtac::Function&, std::shared_ptr<mtac::DataFlowResults<ProblemDomain>> ) override { eddic_unreachable("Not MTAC"); };
};

//Liveness analysis on Pseudo Registers

struct LivePseudoRegistersProblem : public mtac::DataFlowProblem<mtac::DataFlowType::Low_Backward, LiveRegisterValues<ltac::PseudoRegister, ltac::PseudoFloatRegister>> {
    ProblemDomain Boundary(mtac::Function& function) override;
    ProblemDomain Init(mtac::Function& function) override;

    void meet(ProblemDomain& in, const ProblemDomain& out) override;

    ProblemDomain transfer(mtac::basic_block_p basic_block, ltac::Statement& statement, ProblemDomain& in) override;
    ProblemDomain transfer(mtac::basic_block_p, std::shared_ptr<mtac::Quadruple>&, ProblemDomain&) override { eddic_unreachable("Not MTAC"); };

    bool optimize(ltac::Statement& statement, std::shared_ptr<mtac::DataFlowResults<ProblemDomain>> results) override;
    bool optimize(mtac::Function&, std::shared_ptr<mtac::DataFlowResults<ProblemDomain>> ) override { eddic_unreachable("Not MTAC"); };
};

template<typename Reg, typename FloatReg>
std::ostream& operator<<(std::ostream& stream, const LiveRegisterValues<Reg, FloatReg>& value){
    stream << "set{";

    for(auto& v : value.registers){
        stream << v << ", ";
    }

    for(auto& v : value.float_registers){
        stream << v << ", ";
    }

    return stream << "}";
}

} //end of mtac

} //end of eddic

#endif
<|endoftext|>


<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2011 Artem Pavlenko
 *
 * 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.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#ifndef GRID_RENDERER_HPP
#define GRID_RENDERER_HPP

// mapnik
#include <mapnik/config.hpp>
#include <mapnik/feature_style_processor.hpp>
#include <mapnik/font_engine_freetype.hpp>
#include <mapnik/label_collision_detector.hpp>
#include <mapnik/map.hpp>
#include <mapnik/rule.hpp> // for all symbolizers
#include <mapnik/grid/grid.hpp>

// boost
#include <boost/utility.hpp>
#include <boost/scoped_ptr.hpp>

// FIXME
// forward declare so that
// apps using mapnik do not
// need agg headers
namespace agg {
struct trans_affine;
}

namespace mapnik {

class marker;

struct grid_rasterizer;

template <typename T>
class MAPNIK_DECL grid_renderer : public feature_style_processor<grid_renderer<T> >,
                                  private boost::noncopyable
{

public:
    typedef grid_renderer<T> processor_impl_type;
    grid_renderer(Map const& m, T & pixmap, double scale_factor=1.0, unsigned offset_x=0, unsigned offset_y=0);
    ~grid_renderer();
    void start_map_processing(Map const& map);
    void end_map_processing(Map const& map);
    void start_layer_processing(layer const& lay, box2d<double> const& query_extent);
    void end_layer_processing(layer const& lay);
    void start_style_processing(feature_type_style const& st) {}
    void end_style_processing(feature_type_style const& st) {}
    void render_marker(mapnik::feature_impl & feature, unsigned int step, pixel_position const& pos, marker const& marker, const agg::trans_affine & tr, double opacity, composite_mode_e comp_op);

    void process(point_symbolizer const& sym,
                 mapnik::feature_impl & feature,
                 proj_transform const& prj_trans);
    void process(line_symbolizer const& sym,
                 mapnik::feature_impl & feature,
                 proj_transform const& prj_trans);
    void process(line_pattern_symbolizer const& sym,
                 mapnik::feature_impl & feature,
                 proj_transform const& prj_trans);
    void process(polygon_symbolizer const& sym,
                 mapnik::feature_impl & feature,
                 proj_transform const& prj_trans);
    void process(polygon_pattern_symbolizer const& sym,
                 mapnik::feature_impl & feature,
                 proj_transform const& prj_trans);
    void process(raster_symbolizer const& sym,
                 mapnik::feature_impl & feature,
                 proj_transform const& prj_trans);
    void process(shield_symbolizer const& sym,
                 mapnik::feature_impl & feature,
                 proj_transform const& prj_trans);
    void process(text_symbolizer const& sym,
                 mapnik::feature_impl & feature,
                 proj_transform const& prj_trans);
    void process(building_symbolizer const& sym,
                 mapnik::feature_impl & feature,
                 proj_transform const& prj_trans);
    void process(markers_symbolizer const& sym,
                 mapnik::feature_impl & feature,
                 proj_transform const& prj_trans);
    inline bool process(rule::symbolizers const& /*syms*/,
                        mapnik::feature_impl & /*feature*/,
                        proj_transform const& /*prj_trans*/)
    {
        // grid renderer doesn't support processing of multiple symbolizers.
        return false;
    };
    void painted(bool painted)
    {
        pixmap_.painted(painted);
    }

private:
    T & pixmap_;
    unsigned width_;
    unsigned height_;
    double scale_factor_;
    CoordTransform t_;
    freetype_engine font_engine_;
    face_manager<freetype_engine> font_manager_;
    boost::shared_ptr<label_collision_detector4> detector_;
    boost::scoped_ptr<grid_rasterizer> ras_ptr;
    box2d<double> query_extent_;
    void setup(Map const& m);
};
}

#endif //GRID_RENDERER_HPP
<commit_msg>make public the grid_renderer buffer type like AGG renderer<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2011 Artem Pavlenko
 *
 * 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.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#ifndef GRID_RENDERER_HPP
#define GRID_RENDERER_HPP

// mapnik
#include <mapnik/config.hpp>
#include <mapnik/feature_style_processor.hpp>
#include <mapnik/font_engine_freetype.hpp>
#include <mapnik/label_collision_detector.hpp>
#include <mapnik/map.hpp>
#include <mapnik/rule.hpp> // for all symbolizers
#include <mapnik/grid/grid.hpp>

// boost
#include <boost/utility.hpp>
#include <boost/scoped_ptr.hpp>

// FIXME
// forward declare so that
// apps using mapnik do not
// need agg headers
namespace agg {
struct trans_affine;
}

namespace mapnik {

class marker;

struct grid_rasterizer;

template <typename T>
class MAPNIK_DECL grid_renderer : public feature_style_processor<grid_renderer<T> >,
                                  private boost::noncopyable
{

public:
    typedef T buffer_type;
    typedef grid_renderer<T> processor_impl_type;
    grid_renderer(Map const& m, T & pixmap, double scale_factor=1.0, unsigned offset_x=0, unsigned offset_y=0);
    ~grid_renderer();
    void start_map_processing(Map const& map);
    void end_map_processing(Map const& map);
    void start_layer_processing(layer const& lay, box2d<double> const& query_extent);
    void end_layer_processing(layer const& lay);
    void start_style_processing(feature_type_style const& st) {}
    void end_style_processing(feature_type_style const& st) {}
    void render_marker(mapnik::feature_impl & feature, unsigned int step, pixel_position const& pos, marker const& marker, const agg::trans_affine & tr, double opacity, composite_mode_e comp_op);

    void process(point_symbolizer const& sym,
                 mapnik::feature_impl & feature,
                 proj_transform const& prj_trans);
    void process(line_symbolizer const& sym,
                 mapnik::feature_impl & feature,
                 proj_transform const& prj_trans);
    void process(line_pattern_symbolizer const& sym,
                 mapnik::feature_impl & feature,
                 proj_transform const& prj_trans);
    void process(polygon_symbolizer const& sym,
                 mapnik::feature_impl & feature,
                 proj_transform const& prj_trans);
    void process(polygon_pattern_symbolizer const& sym,
                 mapnik::feature_impl & feature,
                 proj_transform const& prj_trans);
    void process(raster_symbolizer const& sym,
                 mapnik::feature_impl & feature,
                 proj_transform const& prj_trans);
    void process(shield_symbolizer const& sym,
                 mapnik::feature_impl & feature,
                 proj_transform const& prj_trans);
    void process(text_symbolizer const& sym,
                 mapnik::feature_impl & feature,
                 proj_transform const& prj_trans);
    void process(building_symbolizer const& sym,
                 mapnik::feature_impl & feature,
                 proj_transform const& prj_trans);
    void process(markers_symbolizer const& sym,
                 mapnik::feature_impl & feature,
                 proj_transform const& prj_trans);
    inline bool process(rule::symbolizers const& /*syms*/,
                        mapnik::feature_impl & /*feature*/,
                        proj_transform const& /*prj_trans*/)
    {
        // grid renderer doesn't support processing of multiple symbolizers.
        return false;
    };
    void painted(bool painted)
    {
        pixmap_.painted(painted);
    }

private:
    buffer_type & pixmap_;
    unsigned width_;
    unsigned height_;
    double scale_factor_;
    CoordTransform t_;
    freetype_engine font_engine_;
    face_manager<freetype_engine> font_manager_;
    boost::shared_ptr<label_collision_detector4> detector_;
    boost::scoped_ptr<grid_rasterizer> ras_ptr;
    box2d<double> query_extent_;
    void setup(Map const& m);
};
}

#endif //GRID_RENDERER_HPP
<|endoftext|>


<commit_before>/*=========================================================================
 *
 *  Copyright RTK Consortium
 *
 *  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.txt
 *
 *  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.
 *
 *=========================================================================*/

#ifndef rtkForwardWarpImageFilter_hxx
#define rtkForwardWarpImageFilter_hxx

#include "rtkForwardWarpImageFilter.h"
#include "rtkHomogeneousMatrix.h"

#include <itkImageRegionConstIterator.h>
#include <itkImageRegionConstIteratorWithIndex.h>
#include <itkNeighborhoodIterator.h>
#include <itkConstantBoundaryCondition.h>
#include <itkLinearInterpolateImageFunction.h>
#include <itkMacro.h>

namespace rtk
{

template <class TInputImage, class TOutputImage, class TDVF>
ForwardWarpImageFilter<TInputImage, TOutputImage, TDVF>
::ForwardWarpImageFilter()
{
  m_Protected_DefFieldSizeSame = false;
  m_Protected_EndIndex.Fill(0);
  m_Protected_StartIndex.Fill(0);
}

template <class TInputImage, class TOutputImage, class TDVF>
void
ForwardWarpImageFilter<TInputImage, TOutputImage, TDVF>
::Protected_EvaluateDisplacementAtPhysicalPoint(const PointType & point, DisplacementType &output)
{

  DisplacementFieldPointer fieldPtr = this->GetDisplacementField();

  itk::ContinuousIndex< double, TDVF::ImageDimension > index;
  fieldPtr->TransformPhysicalPointToContinuousIndex(point, index);
  unsigned int dim;  // index over dimension
  /**
   * Compute base index = closest index below point
   * Compute distance from point to base index
   */
  typename TDVF::IndexType baseIndex;
  typename TDVF::IndexType neighIndex;
  double    distance[TDVF::ImageDimension];

  for ( dim = 0; dim < TDVF::ImageDimension; dim++ )
    {
    baseIndex[dim] = itk::Math::Floor< typename TDVF::IndexValueType >(index[dim]);

    if ( baseIndex[dim] >=  this->m_Protected_StartIndex[dim] )
      {
      if ( baseIndex[dim] <  this->m_Protected_EndIndex[dim] )
        {
        distance[dim] = index[dim] - static_cast< double >( baseIndex[dim] );
        }
      else
        {
        baseIndex[dim] = this->m_Protected_EndIndex[dim];
        distance[dim] = 0.0;
        }
      }
    else
      {
      baseIndex[dim] = this->m_Protected_StartIndex[dim];
      distance[dim] = 0.0;
      }
    }

  /**
   * Interpolated value is the weight some of each of the surrounding
   * neighbors. The weight for each neighbour is the fraction overlap
   * of the neighbor pixel with respect to a pixel centered on point.
   */
  output.Fill(0);

  double       totalOverlap = 0.0;
  unsigned int numNeighbors(1 << TInputImage::ImageDimension);

  for ( unsigned int counter = 0; counter < numNeighbors; counter++ )
    {
    double       overlap = 1.0;    // fraction overlap
    unsigned int upper = counter;  // each bit indicates upper/lower neighbour

    // get neighbor index and overlap fraction
    for ( dim = 0; dim < TDVF::ImageDimension; dim++ )
      {
      if ( upper & 1 )
        {
        neighIndex[dim] = baseIndex[dim] + 1;
        overlap *= distance[dim];
        }
      else
        {
        neighIndex[dim] = baseIndex[dim];
        overlap *= 1.0 - distance[dim];
        }

      upper >>= 1;
      }

    // get neighbor value only if overlap is not zero
    if ( overlap )
      {
      const DisplacementType input =
        fieldPtr->GetPixel(neighIndex);
      for ( unsigned int k = 0; k < TDVF::ImageDimension; k++ )
        {
        output[k] += overlap * static_cast< double >( input[k] );
        }
      totalOverlap += overlap;
      }

    if ( totalOverlap == 1.0 )
      {
      // finished
      break;
      }
    }
}

template <class TInputImage, class TOutputImage, class TDVF>
void
ForwardWarpImageFilter<TInputImage, TOutputImage, TDVF>
::GenerateData()
{
  Superclass::BeforeThreadedGenerateData();
  DisplacementFieldPointer fieldPtr = this->GetDisplacementField();

  // Connect input image to interpolator
  m_Protected_StartIndex = fieldPtr->GetBufferedRegion().GetIndex();
  for ( unsigned i = 0; i < TDVF::ImageDimension; i++ )
    {
    m_Protected_EndIndex[i] = m_Protected_StartIndex[i]
                    + fieldPtr->GetBufferedRegion().GetSize()[i] - 1;
    }

  typename Superclass::InputImageConstPointer  inputPtr = this->GetInput();
  typename Superclass::OutputImagePointer      outputPtr = this->GetOutput();

  outputPtr->SetRegions(outputPtr->GetRequestedRegion());
  outputPtr->Allocate();
  outputPtr->FillBuffer(0);

  // Allocate an image with the same metadata as the output
  // to accumulate the weights during splat, and divide by the total weights at the end
  typename TOutputImage::Pointer accumulate = TOutputImage::New();
  accumulate->SetRegions(outputPtr->GetRequestedRegion());
  accumulate->Allocate();
  accumulate->FillBuffer(0);

  // iterator for the output image
  itk::ImageRegionConstIteratorWithIndex< TOutputImage > inputIt(
        inputPtr, inputPtr->GetBufferedRegion());
  itk::ImageRegionIterator< DisplacementFieldType >  fieldIt(fieldPtr, fieldPtr->GetBufferedRegion());
  typename TOutputImage::IndexType        index;
  typename TOutputImage::IndexType        baseIndex;
  typename TOutputImage::IndexType        neighIndex;
  double                                  distance[TInputImage::ImageDimension];
  typename TOutputImage::PointType        point;
  typename Superclass::DisplacementType displacement;
  itk::NumericTraits<typename Superclass::DisplacementType>::SetLength(displacement, TInputImage::ImageDimension);

  unsigned int numNeighbors(1 << TInputImage::ImageDimension);

  // There is a bug in the ITK WarpImageFilter: m_DefFieldSizeSame
  // is computed without taking origin, spacing and direction into
  // account. So we perform a more thorough comparison between
  // output and DVF than in itkWarpImageFilter::BeforeThreadedGenerateData()
  bool skipEvaluateDisplacementAtContinuousIndex =
      ( (outputPtr->GetLargestPossibleRegion() == this->GetDisplacementField()->GetLargestPossibleRegion())
     && (outputPtr->GetSpacing() == this->GetDisplacementField()->GetSpacing())
     && (outputPtr->GetOrigin() == this->GetDisplacementField()->GetOrigin())
     && (outputPtr->GetDirection() == this->GetDisplacementField()->GetDirection())   );

  while ( !inputIt.IsAtEnd() )
    {
    // get the input image index
    index = inputIt.GetIndex();
    inputPtr->TransformIndexToPhysicalPoint(index, point);

    if (skipEvaluateDisplacementAtContinuousIndex)
      displacement = fieldIt.Get();
    else
      this->Protected_EvaluateDisplacementAtPhysicalPoint(point, displacement);

    for ( unsigned int j = 0; j < TInputImage::ImageDimension; j++ )
      point[j] += displacement[j];

    itk::ContinuousIndex< double, TInputImage::ImageDimension > continuousIndexInOutput;
    outputPtr->TransformPhysicalPointToContinuousIndex(point, continuousIndexInOutput);

    // compute the base index in output, ie the closest index below point
    // Check if the baseIndex is in the output's requested region, otherwise skip the splat part
    bool skip = false;

    for ( unsigned int j = 0; j < TInputImage::ImageDimension; j++ )
      {
      baseIndex[j] = itk::Math::Floor<int, double>(continuousIndexInOutput[j]);
      distance[j] = continuousIndexInOutput[j] - static_cast< double >(baseIndex[j]);
      if ( (baseIndex[j] < outputPtr->GetRequestedRegion().GetIndex()[j] - 1) ||
           (baseIndex[j] >= outputPtr->GetRequestedRegion().GetIndex()[j] + (int)outputPtr->GetRequestedRegion().GetSize()[j] ))
        skip = true;
      }

    if (!skip)
      {
      // get the splat weights as the overlapping areas between
      for ( unsigned int counter = 0; counter < numNeighbors; counter++ )
        {
        double       overlap = 1.0;    // fraction overlap
        unsigned int upper = counter;  // each bit indicates upper/lower neighbour

        // get neighbor weights as the fraction of overlap
        // of the neighbor pixels with a pixel centered on point
        for ( unsigned int dim = 0; dim < TInputImage::ImageDimension; dim++ )
          {
          if ( upper & 1 )
            {
            neighIndex[dim] = baseIndex[dim] + 1;
            overlap *= distance[dim];
            }
          else
            {
            neighIndex[dim] = baseIndex[dim];
            overlap *= 1.0 - distance[dim];
            }

          upper >>= 1;
          }

        if (outputPtr->GetRequestedRegion().IsInside(neighIndex))
          {
          // Perform splat with this weight, both in output and in the temporary
          // image that accumulates weights
          outputPtr->SetPixel(neighIndex, outputPtr->GetPixel(neighIndex) + overlap * inputIt.Get() );
          accumulate->SetPixel(neighIndex, accumulate->GetPixel(neighIndex) + overlap);
          }
        }
      }

    ++inputIt;
    ++fieldIt;
    }

  // Divide the output by the accumulated weights, if they are non-zero
  itk::ImageRegionIterator< TOutputImage > outputIt(outputPtr, outputPtr->GetRequestedRegion());
  itk::ImageRegionIterator< TOutputImage > accIt(accumulate, outputPtr->GetRequestedRegion());
  while ( !outputIt.IsAtEnd() )
    {
    if (accIt.Get())
      outputIt.Set(outputIt.Get() / accIt.Get());

    ++outputIt;
    ++accIt;
    }

  // Replace the holes with the weighted mean of their neighbors
  itk::Size<TOutputImage::ImageDimension> radius;
  radius.Fill(3);
  unsigned int pixelsInNeighborhood = 1;
  for (unsigned int dim=0; dim< TOutputImage::ImageDimension; dim++)
    pixelsInNeighborhood *= 2 * radius[dim] + 1;

  itk::NeighborhoodIterator< TOutputImage > outputIt2(radius, outputPtr, outputPtr->GetRequestedRegion());
  itk::NeighborhoodIterator< TOutputImage > accIt2(radius, accumulate, outputPtr->GetRequestedRegion());

  itk::ZeroFluxNeumannBoundaryCondition<TInputImage> zeroFlux;
  outputIt2.OverrideBoundaryCondition(&zeroFlux);

  itk::ConstantBoundaryCondition<TInputImage> constant;
  accIt2.OverrideBoundaryCondition(&constant);

  while ( !outputIt2.IsAtEnd() )
    {
    if (!accIt2.GetCenterPixel())
      {
      // Compute the mean of the neighboring pixels, weighted by the accumulated weights
      typename TOutputImage::PixelType value = 0;
      typename TOutputImage::PixelType weight = 0;
      for (unsigned int idx=0; idx<pixelsInNeighborhood; idx++)
        {
        value += accIt2.GetPixel(idx) * outputIt2.GetPixel(idx);
        weight += accIt2.GetPixel(idx);
        }

      // Replace the hole with this value, or zero (if all surrounding pixels were holes)
      if (weight)
        outputIt2.SetCenterPixel(value / weight);
      else
        outputIt2.SetCenterPixel(0);
      }
    ++outputIt2;
    ++accIt2;
    }

  Superclass::AfterThreadedGenerateData();
}

} // end namespace rtk

#endif //rtkForwardWarpImageFilter_hxx
<commit_msg>BUG: Fix DisplacementField const correctness for ITK-v4.13<commit_after>/*=========================================================================
 *
 *  Copyright RTK Consortium
 *
 *  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.txt
 *
 *  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.
 *
 *=========================================================================*/

#ifndef rtkForwardWarpImageFilter_hxx
#define rtkForwardWarpImageFilter_hxx

#include "rtkForwardWarpImageFilter.h"
#include "rtkHomogeneousMatrix.h"

#include <itkImageRegionConstIterator.h>
#include <itkImageRegionConstIteratorWithIndex.h>
#include <itkNeighborhoodIterator.h>
#include <itkConstantBoundaryCondition.h>
#include <itkLinearInterpolateImageFunction.h>
#include <itkMacro.h>

namespace rtk
{

template <class TInputImage, class TOutputImage, class TDVF>
ForwardWarpImageFilter<TInputImage, TOutputImage, TDVF>
::ForwardWarpImageFilter()
{
  m_Protected_DefFieldSizeSame = false;
  m_Protected_EndIndex.Fill(0);
  m_Protected_StartIndex.Fill(0);
}

template <class TInputImage, class TOutputImage, class TDVF>
void
ForwardWarpImageFilter<TInputImage, TOutputImage, TDVF>
::Protected_EvaluateDisplacementAtPhysicalPoint(const PointType & point, DisplacementType &output)
{

  const DisplacementFieldType* fieldPtr = this->GetDisplacementField();

  itk::ContinuousIndex< double, TDVF::ImageDimension > index;
  fieldPtr->TransformPhysicalPointToContinuousIndex(point, index);
  unsigned int dim;  // index over dimension
  /**
   * Compute base index = closest index below point
   * Compute distance from point to base index
   */
  typename TDVF::IndexType baseIndex;
  typename TDVF::IndexType neighIndex;
  double    distance[TDVF::ImageDimension];

  for ( dim = 0; dim < TDVF::ImageDimension; dim++ )
    {
    baseIndex[dim] = itk::Math::Floor< typename TDVF::IndexValueType >(index[dim]);

    if ( baseIndex[dim] >=  this->m_Protected_StartIndex[dim] )
      {
      if ( baseIndex[dim] <  this->m_Protected_EndIndex[dim] )
        {
        distance[dim] = index[dim] - static_cast< double >( baseIndex[dim] );
        }
      else
        {
        baseIndex[dim] = this->m_Protected_EndIndex[dim];
        distance[dim] = 0.0;
        }
      }
    else
      {
      baseIndex[dim] = this->m_Protected_StartIndex[dim];
      distance[dim] = 0.0;
      }
    }

  /**
   * Interpolated value is the weight some of each of the surrounding
   * neighbors. The weight for each neighbour is the fraction overlap
   * of the neighbor pixel with respect to a pixel centered on point.
   */
  output.Fill(0);

  double       totalOverlap = 0.0;
  unsigned int numNeighbors(1 << TInputImage::ImageDimension);

  for ( unsigned int counter = 0; counter < numNeighbors; counter++ )
    {
    double       overlap = 1.0;    // fraction overlap
    unsigned int upper = counter;  // each bit indicates upper/lower neighbour

    // get neighbor index and overlap fraction
    for ( dim = 0; dim < TDVF::ImageDimension; dim++ )
      {
      if ( upper & 1 )
        {
        neighIndex[dim] = baseIndex[dim] + 1;
        overlap *= distance[dim];
        }
      else
        {
        neighIndex[dim] = baseIndex[dim];
        overlap *= 1.0 - distance[dim];
        }

      upper >>= 1;
      }

    // get neighbor value only if overlap is not zero
    if ( overlap )
      {
      const DisplacementType input =
        fieldPtr->GetPixel(neighIndex);
      for ( unsigned int k = 0; k < TDVF::ImageDimension; k++ )
        {
        output[k] += overlap * static_cast< double >( input[k] );
        }
      totalOverlap += overlap;
      }

    if ( totalOverlap == 1.0 )
      {
      // finished
      break;
      }
    }
}

template <class TInputImage, class TOutputImage, class TDVF>
void
ForwardWarpImageFilter<TInputImage, TOutputImage, TDVF>
::GenerateData()
{
  Superclass::BeforeThreadedGenerateData();
  const DisplacementFieldType* fieldPtr = this->GetDisplacementField();

  // Connect input image to interpolator
  m_Protected_StartIndex = fieldPtr->GetBufferedRegion().GetIndex();
  for ( unsigned i = 0; i < TDVF::ImageDimension; i++ )
    {
    m_Protected_EndIndex[i] = m_Protected_StartIndex[i]
                    + fieldPtr->GetBufferedRegion().GetSize()[i] - 1;
    }

  typename Superclass::InputImageConstPointer  inputPtr = this->GetInput();
  typename Superclass::OutputImagePointer      outputPtr = this->GetOutput();

  outputPtr->SetRegions(outputPtr->GetRequestedRegion());
  outputPtr->Allocate();
  outputPtr->FillBuffer(0);

  // Allocate an image with the same metadata as the output
  // to accumulate the weights during splat, and divide by the total weights at the end
  typename TOutputImage::Pointer accumulate = TOutputImage::New();
  accumulate->SetRegions(outputPtr->GetRequestedRegion());
  accumulate->Allocate();
  accumulate->FillBuffer(0);

  // iterator for the output image
  itk::ImageRegionConstIteratorWithIndex< TOutputImage > inputIt(
        inputPtr, inputPtr->GetBufferedRegion());
  itk::ImageRegionIterator< const DisplacementFieldType >  fieldIt(fieldPtr, fieldPtr->GetBufferedRegion());
  typename TOutputImage::IndexType        index;
  typename TOutputImage::IndexType        baseIndex;
  typename TOutputImage::IndexType        neighIndex;
  double                                  distance[TInputImage::ImageDimension];
  typename TOutputImage::PointType        point;
  typename Superclass::DisplacementType displacement;
  itk::NumericTraits<typename Superclass::DisplacementType>::SetLength(displacement, TInputImage::ImageDimension);

  unsigned int numNeighbors(1 << TInputImage::ImageDimension);

  // There is a bug in the ITK WarpImageFilter: m_DefFieldSizeSame
  // is computed without taking origin, spacing and direction into
  // account. So we perform a more thorough comparison between
  // output and DVF than in itkWarpImageFilter::BeforeThreadedGenerateData()
  bool skipEvaluateDisplacementAtContinuousIndex =
      ( (outputPtr->GetLargestPossibleRegion() == this->GetDisplacementField()->GetLargestPossibleRegion())
     && (outputPtr->GetSpacing() == this->GetDisplacementField()->GetSpacing())
     && (outputPtr->GetOrigin() == this->GetDisplacementField()->GetOrigin())
     && (outputPtr->GetDirection() == this->GetDisplacementField()->GetDirection())   );

  while ( !inputIt.IsAtEnd() )
    {
    // get the input image index
    index = inputIt.GetIndex();
    inputPtr->TransformIndexToPhysicalPoint(index, point);

    if (skipEvaluateDisplacementAtContinuousIndex)
      displacement = fieldIt.Get();
    else
      this->Protected_EvaluateDisplacementAtPhysicalPoint(point, displacement);

    for ( unsigned int j = 0; j < TInputImage::ImageDimension; j++ )
      point[j] += displacement[j];

    itk::ContinuousIndex< double, TInputImage::ImageDimension > continuousIndexInOutput;
    outputPtr->TransformPhysicalPointToContinuousIndex(point, continuousIndexInOutput);

    // compute the base index in output, ie the closest index below point
    // Check if the baseIndex is in the output's requested region, otherwise skip the splat part
    bool skip = false;

    for ( unsigned int j = 0; j < TInputImage::ImageDimension; j++ )
      {
      baseIndex[j] = itk::Math::Floor<int, double>(continuousIndexInOutput[j]);
      distance[j] = continuousIndexInOutput[j] - static_cast< double >(baseIndex[j]);
      if ( (baseIndex[j] < outputPtr->GetRequestedRegion().GetIndex()[j] - 1) ||
           (baseIndex[j] >= outputPtr->GetRequestedRegion().GetIndex()[j] + (int)outputPtr->GetRequestedRegion().GetSize()[j] ))
        skip = true;
      }

    if (!skip)
      {
      // get the splat weights as the overlapping areas between
      for ( unsigned int counter = 0; counter < numNeighbors; counter++ )
        {
        double       overlap = 1.0;    // fraction overlap
        unsigned int upper = counter;  // each bit indicates upper/lower neighbour

        // get neighbor weights as the fraction of overlap
        // of the neighbor pixels with a pixel centered on point
        for ( unsigned int dim = 0; dim < TInputImage::ImageDimension; dim++ )
          {
          if ( upper & 1 )
            {
            neighIndex[dim] = baseIndex[dim] + 1;
            overlap *= distance[dim];
            }
          else
            {
            neighIndex[dim] = baseIndex[dim];
            overlap *= 1.0 - distance[dim];
            }

          upper >>= 1;
          }

        if (outputPtr->GetRequestedRegion().IsInside(neighIndex))
          {
          // Perform splat with this weight, both in output and in the temporary
          // image that accumulates weights
          outputPtr->SetPixel(neighIndex, outputPtr->GetPixel(neighIndex) + overlap * inputIt.Get() );
          accumulate->SetPixel(neighIndex, accumulate->GetPixel(neighIndex) + overlap);
          }
        }
      }

    ++inputIt;
    ++fieldIt;
    }

  // Divide the output by the accumulated weights, if they are non-zero
  itk::ImageRegionIterator< TOutputImage > outputIt(outputPtr, outputPtr->GetRequestedRegion());
  itk::ImageRegionIterator< TOutputImage > accIt(accumulate, outputPtr->GetRequestedRegion());
  while ( !outputIt.IsAtEnd() )
    {
    if (accIt.Get())
      outputIt.Set(outputIt.Get() / accIt.Get());

    ++outputIt;
    ++accIt;
    }

  // Replace the holes with the weighted mean of their neighbors
  itk::Size<TOutputImage::ImageDimension> radius;
  radius.Fill(3);
  unsigned int pixelsInNeighborhood = 1;
  for (unsigned int dim=0; dim< TOutputImage::ImageDimension; dim++)
    pixelsInNeighborhood *= 2 * radius[dim] + 1;

  itk::NeighborhoodIterator< TOutputImage > outputIt2(radius, outputPtr, outputPtr->GetRequestedRegion());
  itk::NeighborhoodIterator< TOutputImage > accIt2(radius, accumulate, outputPtr->GetRequestedRegion());

  itk::ZeroFluxNeumannBoundaryCondition<TInputImage> zeroFlux;
  outputIt2.OverrideBoundaryCondition(&zeroFlux);

  itk::ConstantBoundaryCondition<TInputImage> constant;
  accIt2.OverrideBoundaryCondition(&constant);

  while ( !outputIt2.IsAtEnd() )
    {
    if (!accIt2.GetCenterPixel())
      {
      // Compute the mean of the neighboring pixels, weighted by the accumulated weights
      typename TOutputImage::PixelType value = 0;
      typename TOutputImage::PixelType weight = 0;
      for (unsigned int idx=0; idx<pixelsInNeighborhood; idx++)
        {
        value += accIt2.GetPixel(idx) * outputIt2.GetPixel(idx);
        weight += accIt2.GetPixel(idx);
        }

      // Replace the hole with this value, or zero (if all surrounding pixels were holes)
      if (weight)
        outputIt2.SetCenterPixel(value / weight);
      else
        outputIt2.SetCenterPixel(0);
      }
    ++outputIt2;
    ++accIt2;
    }

  Superclass::AfterThreadedGenerateData();
}

} // end namespace rtk

#endif //rtkForwardWarpImageFilter_hxx
<|endoftext|>