<commit_before>/*************************************************************************/
/*  ip_unix.cpp                                                          */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md)    */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#include "ip_unix.h"

#if defined(UNIX_ENABLED) || defined(WINDOWS_ENABLED)

#include <string.h>

#ifdef WINDOWS_ENABLED
#include <stdio.h>
#include <winsock2.h>
// Needs to be included after winsocks2.h
#include <windows.h>
#include <ws2tcpip.h>
#ifndef UWP_ENABLED
#if defined(__MINGW32__) && (!defined(__MINGW64_VERSION_MAJOR) || __MINGW64_VERSION_MAJOR < 4)
// MinGW-w64 on Ubuntu 12.04 (our Travis build env) has bugs in this code where
// some includes are missing in dependencies of iphlpapi.h for WINVER >= 0x0600 (Vista).
// We don't use this Vista code for now, so working it around by disabling it.
// MinGW-w64 >= 4.0 seems to be better judging by its headers.
#undef _WIN32_WINNT
#define _WIN32_WINNT 0x0501 // Windows XP, disable Vista API
#include <iphlpapi.h>
#undef _WIN32_WINNT
#define _WIN32_WINNT 0x0600 // Re-enable Vista API
#else
#include <iphlpapi.h>
#endif // MINGW hack
#endif
#else // UNIX
#include <net/if.h>
#include <netdb.h>
#ifdef ANDROID_ENABLED
// We could drop this file once we up our API level to 24,
// where the NDK's ifaddrs.h supports to needed getifaddrs.
#include "thirdparty/misc/ifaddrs-android.h"
#else
#ifdef __FreeBSD__
#include <sys/types.h>
#endif
#include <ifaddrs.h>
#endif
#include <arpa/inet.h>
#include <sys/socket.h>
#ifdef __FreeBSD__
#include <netinet/in.h>
#endif
#endif

static IP_Address _sockaddr2ip(struct sockaddr *p_addr) {

	IP_Address ip;

	if (p_addr->sa_family == AF_INET) {
		struct sockaddr_in *addr = (struct sockaddr_in *)p_addr;
		ip.set_ipv4((uint8_t *)&(addr->sin_addr));
	} else if (p_addr->sa_family == AF_INET6) {
		struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)p_addr;
		ip.set_ipv6(addr6->sin6_addr.s6_addr);
	};

	return ip;
};

IP_Address IP_Unix::_resolve_hostname(const String &p_hostname, Type p_type) {

	struct addrinfo hints;
	struct addrinfo *result;

	memset(&hints, 0, sizeof(struct addrinfo));
	if (p_type == TYPE_IPV4) {
		hints.ai_family = AF_INET;
	} else if (p_type == TYPE_IPV6) {
		hints.ai_family = AF_INET6;
		hints.ai_flags = 0;
	} else {
		hints.ai_family = AF_UNSPEC;
		hints.ai_flags = AI_ADDRCONFIG;
	};
	hints.ai_flags &= ~AI_NUMERICHOST;

	int s = getaddrinfo(p_hostname.utf8().get_data(), NULL, &hints, &result);
	if (s != 0) {
		ERR_PRINT("getaddrinfo failed! Cannot resolve hostname.");
		return IP_Address();
	};

	if (result == NULL || result->ai_addr == NULL) {
		ERR_PRINT("Invalid response from getaddrinfo");
		if (result)
			freeaddrinfo(result);
		return IP_Address();
	};

	IP_Address ip = _sockaddr2ip(result->ai_addr);

	freeaddrinfo(result);

	return ip;
}

#if defined(WINDOWS_ENABLED)

#if defined(UWP_ENABLED)

void IP_Unix::get_local_interfaces(Map<String, Interface_Info> *r_interfaces) const {

	using namespace Windows::Networking;
	using namespace Windows::Networking::Connectivity;

	// Returns addresses, not interfaces.
	auto hostnames = NetworkInformation::GetHostNames();

	for (int i = 0; i < hostnames->Size; i++) {

		auto hostname = hostnames->GetAt(i);

		if (hostname->Type != HostNameType::Ipv4 && hostname->Type != HostNameType::Ipv6)
			continue;

		String name = hostname->RawName->Data();
		Map<String, Interface_Info>::Element *E = r_interfaces->find(name);
		if (!E) {
			Interface_Info info;
			info.name = name;
			info.name_friendly = hostname->DisplayName->Data();
			info.index = 0;
			E = r_interfaces->insert(name, info);
			ERR_CONTINUE(!E);
		}

		Interface_Info &info = E->get();

		IP_Address ip = IP_Address(hostname->CanonicalName->Data());
		info.ip_addresses.push_front(ip);
	}
}

#else

void IP_Unix::get_local_interfaces(Map<String, Interface_Info> *r_interfaces) const {

	ULONG buf_size = 1024;
	IP_ADAPTER_ADDRESSES *addrs;

	while (true) {

		addrs = (IP_ADAPTER_ADDRESSES *)memalloc(buf_size);
		int err = GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER | GAA_FLAG_SKIP_FRIENDLY_NAME,
				NULL, addrs, &buf_size);
		if (err == NO_ERROR) {
			break;
		};
		memfree(addrs);
		if (err == ERROR_BUFFER_OVERFLOW) {
			continue; // will go back and alloc the right size
		};

		ERR_EXPLAIN("Call to GetAdaptersAddresses failed with error " + itos(err));
		ERR_FAIL();
		return;
	};

	IP_ADAPTER_ADDRESSES *adapter = addrs;

	while (adapter != NULL) {

		Interface_Info info;
		info.name = adapter->AdapterName;
		info.name_friendly = adapter->FriendlyName;
		info.index = String::num_uint64(adapter->IfIndex);

		IP_ADAPTER_UNICAST_ADDRESS *address = adapter->FirstUnicastAddress;
		while (address != NULL) {
			int family = address->Address.lpSockaddr->sa_family;
			if (family != AF_INET && family != AF_INET6)
				continue;
			info.ip_addresses.push_front(_sockaddr2ip(address->Address.lpSockaddr));
			address = address->Next;
		}
		adapter = adapter->Next;
		// Only add interface if it has at least one IP
		if (info.ip_addresses.size() > 0)
			r_interfaces->insert(info.name, info);
	};

	memfree(addrs);
};

#endif

#else // UNIX

void IP_Unix::get_local_interfaces(Map<String, Interface_Info> *r_interfaces) const {

	struct ifaddrs *ifAddrStruct = NULL;
	struct ifaddrs *ifa = NULL;
	int family;

	getifaddrs(&ifAddrStruct);

	for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next) {
		if (!ifa->ifa_addr)
			continue;

		family = ifa->ifa_addr->sa_family;

		if (family != AF_INET && family != AF_INET6)
			continue;

		Map<String, Interface_Info>::Element *E = r_interfaces->find(ifa->ifa_name);
		if (!E) {
			Interface_Info info;
			info.name = ifa->ifa_name;
			info.name_friendly = ifa->ifa_name;
			info.index = String::num_uint64(if_nametoindex(ifa->ifa_name));
			E = r_interfaces->insert(ifa->ifa_name, info);
			ERR_CONTINUE(!E);
		}

		Interface_Info &info = E->get();
		info.ip_addresses.push_front(_sockaddr2ip(ifa->ifa_addr));
	}

	if (ifAddrStruct != NULL) freeifaddrs(ifAddrStruct);
}
#endif

void IP_Unix::make_default() {

	_create = _create_unix;
}

IP *IP_Unix::_create_unix() {

	return memnew(IP_Unix);
}

IP_Unix::IP_Unix() {
}

#endif
<commit_msg>Fix ip_unix.cpp inclusion order for OpenBSD.<commit_after>/*************************************************************************/
/*  ip_unix.cpp                                                          */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md)    */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#include "ip_unix.h"

#if defined(UNIX_ENABLED) || defined(WINDOWS_ENABLED)

#include <string.h>

#ifdef WINDOWS_ENABLED
#include <stdio.h>
#include <winsock2.h>
// Needs to be included after winsocks2.h
#include <windows.h>
#include <ws2tcpip.h>
#ifndef UWP_ENABLED
#if defined(__MINGW32__) && (!defined(__MINGW64_VERSION_MAJOR) || __MINGW64_VERSION_MAJOR < 4)
// MinGW-w64 on Ubuntu 12.04 (our Travis build env) has bugs in this code where
// some includes are missing in dependencies of iphlpapi.h for WINVER >= 0x0600 (Vista).
// We don't use this Vista code for now, so working it around by disabling it.
// MinGW-w64 >= 4.0 seems to be better judging by its headers.
#undef _WIN32_WINNT
#define _WIN32_WINNT 0x0501 // Windows XP, disable Vista API
#include <iphlpapi.h>
#undef _WIN32_WINNT
#define _WIN32_WINNT 0x0600 // Re-enable Vista API
#else
#include <iphlpapi.h>
#endif // MINGW hack
#endif
#else // UNIX
#include <netdb.h>
#ifdef ANDROID_ENABLED
// We could drop this file once we up our API level to 24,
// where the NDK's ifaddrs.h supports to needed getifaddrs.
#include "thirdparty/misc/ifaddrs-android.h"
#else
#ifdef __FreeBSD__
#include <sys/types.h>
#endif
#include <ifaddrs.h>
#endif
#include <arpa/inet.h>
#include <sys/socket.h>
#ifdef __FreeBSD__
#include <netinet/in.h>
#endif
#include <net/if.h> // Order is important on OpenBSD, leave as last
#endif

static IP_Address _sockaddr2ip(struct sockaddr *p_addr) {

	IP_Address ip;

	if (p_addr->sa_family == AF_INET) {
		struct sockaddr_in *addr = (struct sockaddr_in *)p_addr;
		ip.set_ipv4((uint8_t *)&(addr->sin_addr));
	} else if (p_addr->sa_family == AF_INET6) {
		struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)p_addr;
		ip.set_ipv6(addr6->sin6_addr.s6_addr);
	};

	return ip;
};

IP_Address IP_Unix::_resolve_hostname(const String &p_hostname, Type p_type) {

	struct addrinfo hints;
	struct addrinfo *result;

	memset(&hints, 0, sizeof(struct addrinfo));
	if (p_type == TYPE_IPV4) {
		hints.ai_family = AF_INET;
	} else if (p_type == TYPE_IPV6) {
		hints.ai_family = AF_INET6;
		hints.ai_flags = 0;
	} else {
		hints.ai_family = AF_UNSPEC;
		hints.ai_flags = AI_ADDRCONFIG;
	};
	hints.ai_flags &= ~AI_NUMERICHOST;

	int s = getaddrinfo(p_hostname.utf8().get_data(), NULL, &hints, &result);
	if (s != 0) {
		ERR_PRINT("getaddrinfo failed! Cannot resolve hostname.");
		return IP_Address();
	};

	if (result == NULL || result->ai_addr == NULL) {
		ERR_PRINT("Invalid response from getaddrinfo");
		if (result)
			freeaddrinfo(result);
		return IP_Address();
	};

	IP_Address ip = _sockaddr2ip(result->ai_addr);

	freeaddrinfo(result);

	return ip;
}

#if defined(WINDOWS_ENABLED)

#if defined(UWP_ENABLED)

void IP_Unix::get_local_interfaces(Map<String, Interface_Info> *r_interfaces) const {

	using namespace Windows::Networking;
	using namespace Windows::Networking::Connectivity;

	// Returns addresses, not interfaces.
	auto hostnames = NetworkInformation::GetHostNames();

	for (int i = 0; i < hostnames->Size; i++) {

		auto hostname = hostnames->GetAt(i);

		if (hostname->Type != HostNameType::Ipv4 && hostname->Type != HostNameType::Ipv6)
			continue;

		String name = hostname->RawName->Data();
		Map<String, Interface_Info>::Element *E = r_interfaces->find(name);
		if (!E) {
			Interface_Info info;
			info.name = name;
			info.name_friendly = hostname->DisplayName->Data();
			info.index = 0;
			E = r_interfaces->insert(name, info);
			ERR_CONTINUE(!E);
		}

		Interface_Info &info = E->get();

		IP_Address ip = IP_Address(hostname->CanonicalName->Data());
		info.ip_addresses.push_front(ip);
	}
}

#else

void IP_Unix::get_local_interfaces(Map<String, Interface_Info> *r_interfaces) const {

	ULONG buf_size = 1024;
	IP_ADAPTER_ADDRESSES *addrs;

	while (true) {

		addrs = (IP_ADAPTER_ADDRESSES *)memalloc(buf_size);
		int err = GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER | GAA_FLAG_SKIP_FRIENDLY_NAME,
				NULL, addrs, &buf_size);
		if (err == NO_ERROR) {
			break;
		};
		memfree(addrs);
		if (err == ERROR_BUFFER_OVERFLOW) {
			continue; // will go back and alloc the right size
		};

		ERR_EXPLAIN("Call to GetAdaptersAddresses failed with error " + itos(err));
		ERR_FAIL();
		return;
	};

	IP_ADAPTER_ADDRESSES *adapter = addrs;

	while (adapter != NULL) {

		Interface_Info info;
		info.name = adapter->AdapterName;
		info.name_friendly = adapter->FriendlyName;
		info.index = String::num_uint64(adapter->IfIndex);

		IP_ADAPTER_UNICAST_ADDRESS *address = adapter->FirstUnicastAddress;
		while (address != NULL) {
			int family = address->Address.lpSockaddr->sa_family;
			if (family != AF_INET && family != AF_INET6)
				continue;
			info.ip_addresses.push_front(_sockaddr2ip(address->Address.lpSockaddr));
			address = address->Next;
		}
		adapter = adapter->Next;
		// Only add interface if it has at least one IP
		if (info.ip_addresses.size() > 0)
			r_interfaces->insert(info.name, info);
	};

	memfree(addrs);
};

#endif

#else // UNIX

void IP_Unix::get_local_interfaces(Map<String, Interface_Info> *r_interfaces) const {

	struct ifaddrs *ifAddrStruct = NULL;
	struct ifaddrs *ifa = NULL;
	int family;

	getifaddrs(&ifAddrStruct);

	for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next) {
		if (!ifa->ifa_addr)
			continue;

		family = ifa->ifa_addr->sa_family;

		if (family != AF_INET && family != AF_INET6)
			continue;

		Map<String, Interface_Info>::Element *E = r_interfaces->find(ifa->ifa_name);
		if (!E) {
			Interface_Info info;
			info.name = ifa->ifa_name;
			info.name_friendly = ifa->ifa_name;
			info.index = String::num_uint64(if_nametoindex(ifa->ifa_name));
			E = r_interfaces->insert(ifa->ifa_name, info);
			ERR_CONTINUE(!E);
		}

		Interface_Info &info = E->get();
		info.ip_addresses.push_front(_sockaddr2ip(ifa->ifa_addr));
	}

	if (ifAddrStruct != NULL) freeifaddrs(ifAddrStruct);
}
#endif

void IP_Unix::make_default() {

	_create = _create_unix;
}

IP *IP_Unix::_create_unix() {

	return memnew(IP_Unix);
}

IP_Unix::IP_Unix() {
}

#endif
<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999-2000 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. 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.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
 * ITS 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.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
#if !defined(XALANSOURCETREEATTRNS_HEADER_GUARD_1357924680)
#define XALANSOURCETREEATTRNS_HEADER_GUARD_1357924680

#include <XalanSourceTree/XalanSourceTreeDefinitions.hpp>

#include <XalanSourceTree/XalanSourceTreeAttr.hpp>

/*
 * <meta name="usage" content="experimental"/>
 *
 * Base class for the Xalan source tree Attr interface.
 *
 * This class is experimental and subject to change!!
 */

class XALAN_XALANSOURCETREE_EXPORT XalanSourceTreeAttrNS : public XalanSourceTreeAttr
{
public:

	/**
	 * Constructor.
	 *
	 * @param theName The name of the attribute
	 * @param theLocalName The local name of the attribute
	 * @param theNamespaceURI The namespace URI of the attribute
	 * @param thePrefix The namespace prefix of the attribute
	 * @param theValue The value of the attribute
	 * @param theOwnerElement The element that owns the instance
	 * @param theIndex The document-order index of the node.
	 */
	XalanSourceTreeAttrNS(
			const XalanDOMString&		theName,
			const XalanDOMString&		theLocalName,
			const XalanDOMString&		theNamespaceURI,
			const XalanDOMString&		thePrefix,
			const XalanDOMString&		theValue,
			XalanSourceTreeElement*		theOwnerElement = 0,
			unsigned int				theIndex = 0);

	virtual
	~XalanSourceTreeAttrNS();

#if defined(XALAN_NO_COVARIANT_RETURN_TYPE)
	virtual XalanNode*
#else
	virtual XalanSourceTreeAttr*
#endif
	cloneNode(bool deep) const;

	virtual const XalanDOMString&
	getNamespaceURI() const;

	virtual const XalanDOMString&
	getPrefix() const;

	virtual const XalanDOMString&
	getLocalName() const;

protected:

	XalanSourceTreeAttrNS(
			const XalanSourceTreeAttrNS&	theSource,
			bool							deep = false);

	XalanSourceTreeAttrNS(
			const XalanSourceTreeAttr&	theSource,
			bool						deep = false);

private:

	// Not defined...
	XalanSourceTreeAttrNS&
	operator=(const XalanSourceTreeAttrNS&	theSource);

	bool
	operator==(const XalanSourceTreeAttrNS&		theRHS) const;

	// Data members...
	const XalanDOMString&	m_localName;

	const XalanDOMString&	m_prefix;

	const XalanDOMString&	m_namespaceURI;
};

#endif	// !defined(XALANSOURCETREEATTRNS_HEADER_GUARD_1357924680)
<commit_msg>Return type differnet in cpp and hpp for function cloneNode. Error on HP.<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999-2000 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. 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.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
 * ITS 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.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
#if !defined(XALANSOURCETREEATTRNS_HEADER_GUARD_1357924680)
#define XALANSOURCETREEATTRNS_HEADER_GUARD_1357924680

#include <XalanSourceTree/XalanSourceTreeDefinitions.hpp>

#include <XalanSourceTree/XalanSourceTreeAttr.hpp>

/*
 * <meta name="usage" content="experimental"/>
 *
 * Base class for the Xalan source tree Attr interface.
 *
 * This class is experimental and subject to change!!
 */

class XALAN_XALANSOURCETREE_EXPORT XalanSourceTreeAttrNS : public XalanSourceTreeAttr
{
public:

	/**
	 * Constructor.
	 *
	 * @param theName The name of the attribute
	 * @param theLocalName The local name of the attribute
	 * @param theNamespaceURI The namespace URI of the attribute
	 * @param thePrefix The namespace prefix of the attribute
	 * @param theValue The value of the attribute
	 * @param theOwnerElement The element that owns the instance
	 * @param theIndex The document-order index of the node.
	 */
	XalanSourceTreeAttrNS(
			const XalanDOMString&		theName,
			const XalanDOMString&		theLocalName,
			const XalanDOMString&		theNamespaceURI,
			const XalanDOMString&		thePrefix,
			const XalanDOMString&		theValue,
			XalanSourceTreeElement*		theOwnerElement = 0,
			unsigned int				theIndex = 0);

	virtual
	~XalanSourceTreeAttrNS();

#if defined(XALAN_NO_COVARIANT_RETURN_TYPE)
	virtual XalanNode*
#else
	virtual XalanSourceTreeAttrNS*
#endif
	cloneNode(bool deep) const;

	virtual const XalanDOMString&
	getNamespaceURI() const;

	virtual const XalanDOMString&
	getPrefix() const;

	virtual const XalanDOMString&
	getLocalName() const;

protected:

	XalanSourceTreeAttrNS(
			const XalanSourceTreeAttrNS&	theSource,
			bool							deep = false);

	XalanSourceTreeAttrNS(
			const XalanSourceTreeAttr&	theSource,
			bool						deep = false);

private:

	// Not defined...
	XalanSourceTreeAttrNS&
	operator=(const XalanSourceTreeAttrNS&	theSource);

	bool
	operator==(const XalanSourceTreeAttrNS&		theRHS) const;

	// Data members...
	const XalanDOMString&	m_localName;

	const XalanDOMString&	m_prefix;

	const XalanDOMString&	m_namespaceURI;
};

#endif	// !defined(XALANSOURCETREEATTRNS_HEADER_GUARD_1357924680)
<|endoftext|>


<commit_before>/***********************************************************************
    filename:   CEGUIDynamicModule.cpp
    created:    Tue Mar 7 2006
    author:     Paul D Turner <paul@cegui.org.uk>
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team
 *
 *   Permission is hereby granted, free of charge, to any person obtaining
 *   a copy of this software and associated documentation files (the
 *   "Software"), to deal in the Software without restriction, including
 *   without limitation the rights to use, copy, modify, merge, publish,
 *   distribute, sublicense, and/or sell copies of the Software, and to
 *   permit persons to whom the Software is furnished to do so, subject to
 *   the following conditions:
 *
 *   The above copyright notice and this permission notice shall be
 *   included in all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *   OTHER DEALINGS IN THE SOFTWARE.
 ***************************************************************************/
#include "CEGUI/DynamicModule.h"
#include "CEGUI/Base.h"
#include "CEGUI/String.h"
#include "CEGUI/Exceptions.h"
#include <stdlib.h>

#if defined(__WIN32__) || defined(_WIN32)
#   if defined(_MSC_VER)
#       pragma warning(disable : 4552)  // warning: operator has no effect; expected operator with side-effect
#   endif
#   define WIN32_LEAN_AND_MEAN
#   include <windows.h>
#   define DYNLIB_LOAD( a ) LoadLibrary( (a).c_str() )
#   define DYNLIB_GETSYM( a, b ) GetProcAddress( a, (b).c_str() )
#   define DYNLIB_UNLOAD( a ) !FreeLibrary( a )
    typedef HMODULE DYNLIB_HANDLE;
#endif

#if defined(__linux__) || defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__HAIKU__) || defined(__CYGWIN__)
#   include "dlfcn.h"
#   define DYNLIB_LOAD( a ) dlopen( (a).c_str(), RTLD_LAZY )
#   define DYNLIB_GETSYM( a, b ) dlsym( a, (b).c_str() )
#   define DYNLIB_UNLOAD( a ) dlclose( a )
    typedef void* DYNLIB_HANDLE;
#endif

// setup default-default path
#ifndef CEGUI_MODULE_DIR
    #define CEGUI_MODULE_DIR "./bin/"
#endif

namespace CEGUI
{
//----------------------------------------------------------------------------//
struct DynamicModule::Impl :
    public AllocatedObject<DynamicModule::Impl>
{
    Impl(const String& name) :
        d_moduleName(name),
        d_handle(0)
    {}

    ~Impl()
    {
        DYNLIB_UNLOAD(d_handle);
    }

    //! Holds the name of the loaded module.
    String d_moduleName;
    //! Handle for the loaded module
    DYNLIB_HANDLE d_handle;
};

//----------------------------------------------------------------------------//
static const char MODULE_DIR_VAR_NAME[] = "CEGUI_MODULE_DIR";

//----------------------------------------------------------------------------//
#if defined(__WIN32__) || defined(_WIN32)
    static const String LibraryExtension(".dll");
#elif defined(__APPLE__)
    static const String LibraryExtension(".dylib");
#else
    static const String LibraryExtension(".so");
#endif

//----------------------------------------------------------------------------//
// return whether module name has it's extension in place
static bool hasDynamicLibraryExtension(const String& name)
{
    const size_t ext_len = LibraryExtension.length();

    if (name.length() < ext_len)
        return false;

    return name.compare(name.length() - ext_len, ext_len, LibraryExtension) == 0;
}
//----------------------------------------------------------------------------//
static void appendDynamicLibraryExtension(String& name)
{
    name.append(LibraryExtension);
}
//----------------------------------------------------------------------------//
static void addLibraryNameSuffixes(String& name)
{
    #ifdef CEGUI_HAS_BUILD_SUFFIX
        name += CEGUI_BUILD_SUFFIX;
    #endif

    appendDynamicLibraryExtension(name);
}

//----------------------------------------------------------------------------//
static String getModuleDirEnvVar()
{
    if (const char* envModuleDir = getenv(MODULE_DIR_VAR_NAME))
        return String(envModuleDir);

    return String();
}

//----------------------------------------------------------------------------//
// Returns a String containing the last failure message from the platform's
// dynamic loading system.
static String getFailureString()
{
    String retMsg;
#if defined(__linux__) || defined (__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__HAIKU__)
    retMsg = dlerror();
#elif defined(__WIN32__) || defined(_WIN32)
    LPVOID msgBuffer;

    if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
                      FORMAT_MESSAGE_FROM_SYSTEM |
                      FORMAT_MESSAGE_IGNORE_INSERTS,
                      0,
                      GetLastError(),
                      MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US),
                      reinterpret_cast<LPTSTR>(&msgBuffer),
                      0,
                      0))
    {
        retMsg = reinterpret_cast<LPTSTR>(msgBuffer);
        LocalFree(msgBuffer);
    }
    else
    {
        retMsg = "Unknown Error";
    }
#else
    retMsg = "Unknown Error";
#endif
    return retMsg;
}

//----------------------------------------------------------------------------//
static DYNLIB_HANDLE DynLibLoad(const String& name)
{
    DYNLIB_HANDLE handle = 0;

    // prefer whatever location is set in CEGUI_MODULE_DIR environment var
    const String envModuleDir(getModuleDirEnvVar());

    if (!envModuleDir.empty())
        handle = DYNLIB_LOAD(envModuleDir + '/' + name);

    if (!handle)
    #ifdef __APPLE__
        // on apple, look in the app bundle frameworks directory
        handle = DYNLIB_LOAD("@executable_path/../Frameworks/" + name);

        if (!handle)
    #endif
        // try loading without any explicit location (i.e. use OS search path)
        handle = DYNLIB_LOAD(name);

    // finally, try using the compiled-in module directory
    if (!handle)
        handle = DYNLIB_LOAD(CEGUI_MODULE_DIR + name);

    return handle;
}

//----------------------------------------------------------------------------//
DynamicModule::DynamicModule(const String& name) :
    d_pimpl(CEGUI_NEW_AO Impl(name))
{
	if (name.empty())
		return;

    if (!hasDynamicLibraryExtension(d_pimpl->d_moduleName))
        addLibraryNameSuffixes(d_pimpl->d_moduleName);

    d_pimpl->d_handle = DynLibLoad(d_pimpl->d_moduleName);

#if defined(__linux__) || defined(__APPLE__) || defined(__MINGW32__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__HAIKU__)
    // see if adding a leading 'lib' helps us to open the library
    if (!d_pimpl->d_handle && d_pimpl->d_moduleName.compare(0, 3, "lib") != 0)
    {
        d_pimpl->d_moduleName.insert(0, "lib");
        d_pimpl->d_handle = DynLibLoad(d_pimpl->d_moduleName);
    }
#endif

    // check for library load failure
    if (!d_pimpl->d_handle)
        CEGUI_THROW(GenericException("Failed to load module '" +
            d_pimpl->d_moduleName + "': " + getFailureString()));
}

//----------------------------------------------------------------------------//
DynamicModule::~DynamicModule()
{
    CEGUI_DELETE_AO d_pimpl;
}

//----------------------------------------------------------------------------//
const String& DynamicModule::getModuleName() const
{
    return d_pimpl->d_moduleName;
}

//----------------------------------------------------------------------------//
void* DynamicModule::getSymbolAddress(const String& symbol) const
{
    return (void*)DYNLIB_GETSYM(d_pimpl->d_handle, symbol);
}

//----------------------------------------------------------------------------//

}
<commit_msg>Fix CEGUI compilation with Cygwin<commit_after>/***********************************************************************
    filename:   CEGUIDynamicModule.cpp
    created:    Tue Mar 7 2006
    author:     Paul D Turner <paul@cegui.org.uk>
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team
 *
 *   Permission is hereby granted, free of charge, to any person obtaining
 *   a copy of this software and associated documentation files (the
 *   "Software"), to deal in the Software without restriction, including
 *   without limitation the rights to use, copy, modify, merge, publish,
 *   distribute, sublicense, and/or sell copies of the Software, and to
 *   permit persons to whom the Software is furnished to do so, subject to
 *   the following conditions:
 *
 *   The above copyright notice and this permission notice shall be
 *   included in all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *   OTHER DEALINGS IN THE SOFTWARE.
 ***************************************************************************/
#include "CEGUI/DynamicModule.h"
#include "CEGUI/Base.h"
#include "CEGUI/String.h"
#include "CEGUI/Exceptions.h"
#include <stdlib.h>

#if defined(__WIN32__) || defined(_WIN32)
#   if defined(_MSC_VER)
#       pragma warning(disable : 4552)  // warning: operator has no effect; expected operator with side-effect
#   endif
#   define WIN32_LEAN_AND_MEAN
#   include <windows.h>
#   define DYNLIB_LOAD( a ) LoadLibrary( (a).c_str() )
#   define DYNLIB_GETSYM( a, b ) GetProcAddress( a, (b).c_str() )
#   define DYNLIB_UNLOAD( a ) !FreeLibrary( a )
    typedef HMODULE DYNLIB_HANDLE;
#endif

#if defined(__linux__) || defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__HAIKU__) || defined(__CYGWIN__)
#   include "dlfcn.h"
#   define DYNLIB_LOAD( a ) dlopen( (a).c_str(), RTLD_LAZY )
#   define DYNLIB_GETSYM( a, b ) dlsym( a, (b).c_str() )
#   define DYNLIB_UNLOAD( a ) dlclose( a )
    typedef void* DYNLIB_HANDLE;
#endif

// setup default-default path
#ifndef CEGUI_MODULE_DIR
    #define CEGUI_MODULE_DIR "./bin/"
#endif

namespace CEGUI
{
//----------------------------------------------------------------------------//
struct DynamicModule::Impl :
    public AllocatedObject<DynamicModule::Impl>
{
    Impl(const String& name) :
        d_moduleName(name),
        d_handle(0)
    {}

    ~Impl()
    {
        DYNLIB_UNLOAD(d_handle);
    }

    //! Holds the name of the loaded module.
    String d_moduleName;
    //! Handle for the loaded module
    DYNLIB_HANDLE d_handle;
};

//----------------------------------------------------------------------------//
static const char MODULE_DIR_VAR_NAME[] = "CEGUI_MODULE_DIR";

//----------------------------------------------------------------------------//
#if defined(__WIN32__) || defined(_WIN32) || defined(__CYGWIN__)
    static const String LibraryExtension(".dll");
#elif defined(__APPLE__)
    static const String LibraryExtension(".dylib");
#else
    static const String LibraryExtension(".so");
#endif

//----------------------------------------------------------------------------//
// return whether module name has it's extension in place
static bool hasDynamicLibraryExtension(const String& name)
{
    const size_t ext_len = LibraryExtension.length();

    if (name.length() < ext_len)
        return false;

    return name.compare(name.length() - ext_len, ext_len, LibraryExtension) == 0;
}
//----------------------------------------------------------------------------//
static void appendDynamicLibraryExtension(String& name)
{
    name.append(LibraryExtension);
}
//----------------------------------------------------------------------------//
static void addLibraryNameSuffixes(String& name)
{
    #ifdef CEGUI_HAS_BUILD_SUFFIX
        name += CEGUI_BUILD_SUFFIX;
    #endif

    appendDynamicLibraryExtension(name);
}

//----------------------------------------------------------------------------//
static String getModuleDirEnvVar()
{
    if (const char* envModuleDir = getenv(MODULE_DIR_VAR_NAME))
        return String(envModuleDir);

    return String();
}

//----------------------------------------------------------------------------//
// Returns a String containing the last failure message from the platform's
// dynamic loading system.
static String getFailureString()
{
    String retMsg;
#if defined(__linux__) || defined (__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__HAIKU__) || defined(__CYGWIN__)
    retMsg = dlerror();
#elif defined(__WIN32__) || defined(_WIN32)
    LPVOID msgBuffer;

    if (FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
                      FORMAT_MESSAGE_FROM_SYSTEM |
                      FORMAT_MESSAGE_IGNORE_INSERTS,
                      0,
                      GetLastError(),
                      MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US),
                      reinterpret_cast<LPTSTR>(&msgBuffer),
                      0,
                      0))
    {
        retMsg = reinterpret_cast<LPTSTR>(msgBuffer);
        LocalFree(msgBuffer);
    }
    else
    {
        retMsg = "Unknown Error";
    }
#else
    retMsg = "Unknown Error";
#endif
    return retMsg;
}

//----------------------------------------------------------------------------//
static DYNLIB_HANDLE DynLibLoad(const String& name)
{
    DYNLIB_HANDLE handle = 0;

    // prefer whatever location is set in CEGUI_MODULE_DIR environment var
    const String envModuleDir(getModuleDirEnvVar());

    if (!envModuleDir.empty())
        handle = DYNLIB_LOAD(envModuleDir + '/' + name);

    if (!handle)
    #ifdef __APPLE__
        // on apple, look in the app bundle frameworks directory
        handle = DYNLIB_LOAD("@executable_path/../Frameworks/" + name);

        if (!handle)
    #endif
        // try loading without any explicit location (i.e. use OS search path)
        handle = DYNLIB_LOAD(name);

    // finally, try using the compiled-in module directory
    if (!handle)
        handle = DYNLIB_LOAD(CEGUI_MODULE_DIR + name);

    return handle;
}

//----------------------------------------------------------------------------//
DynamicModule::DynamicModule(const String& name) :
    d_pimpl(CEGUI_NEW_AO Impl(name))
{
	if (name.empty())
		return;

    if (!hasDynamicLibraryExtension(d_pimpl->d_moduleName))
        addLibraryNameSuffixes(d_pimpl->d_moduleName);

    d_pimpl->d_handle = DynLibLoad(d_pimpl->d_moduleName);

#if defined(__linux__) || defined(__APPLE__) || defined(__MINGW32__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__HAIKU__)
    // see if adding a leading 'lib' helps us to open the library
    if (!d_pimpl->d_handle && d_pimpl->d_moduleName.compare(0, 3, "lib") != 0)
    {
        d_pimpl->d_moduleName.insert(0, "lib");
        d_pimpl->d_handle = DynLibLoad(d_pimpl->d_moduleName);
    }
#endif

#if defined(__CYGWIN__)
    // see if adding a leading 'cyg' helps us to open the library
    if (!d_pimpl->d_handle && d_pimpl->d_moduleName.compare(0, 3, "cyg") != 0)
    {
        d_pimpl->d_moduleName.insert(0, "cyg");
        d_pimpl->d_handle = DynLibLoad(d_pimpl->d_moduleName);
    }
#endif

    // check for library load failure
    if (!d_pimpl->d_handle)
        CEGUI_THROW(GenericException("Failed to load module '" +
            d_pimpl->d_moduleName + "': " + getFailureString()));
}

//----------------------------------------------------------------------------//
DynamicModule::~DynamicModule()
{
    CEGUI_DELETE_AO d_pimpl;
}

//----------------------------------------------------------------------------//
const String& DynamicModule::getModuleName() const
{
    return d_pimpl->d_moduleName;
}

//----------------------------------------------------------------------------//
void* DynamicModule::getSymbolAddress(const String& symbol) const
{
    return (void*)DYNLIB_GETSYM(d_pimpl->d_handle, symbol);
}

//----------------------------------------------------------------------------//

}
<|endoftext|>


<commit_before>/*

Copyright (c) 2007, 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.

*/

namespace libtorrent
{

	TORRENT_EXPORT bool inflate_gzip(
		char const* in, int size
		, std::vector<char>& buffer
		, int maximum_size
		, std::string& error);

}

<commit_msg>gzip.hpp fix<commit_after>/*

Copyright (c) 2007, 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_GZIP_HPP_INCLUDED
#define TORRENT_GZIP_HPP_INCLUDED

#include "libtorrent/config.hpp"
#include <string>
#include <vector>

namespace libtorrent
{

	TORRENT_EXPORT bool inflate_gzip(
		char const* in, int size
		, std::vector<char>& buffer
		, int maximum_size
		, std::string& error);

}

#endif

<|endoftext|>


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

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

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

#include "mitkPluginActivator.h"

#include <QtPlugin>

#include "QmitkMITKIGTNavigationToolManagerView.h"
#include "QmitkMITKIGTTrackingToolboxView.h"
#include "QmitkNavigationDataPlayerView.h"

#include <mitkPersistenceService.h> //Workaround for bug in persistence module (see bug 16643 for details)
                                    //CAN BE REMOVED WHEN THE BUG IS FIXED

namespace mitk {

void PluginActivator::start(ctkPluginContext* context)
{
  mitk::PersistenceService::LoadModule(); //Workaround for bug in persistence module (see bug 16643 for details)
                                          //CAN BE REMOVED WHEN THE BUG IS FIXED

  BERRY_REGISTER_EXTENSION_CLASS(QmitkMITKIGTNavigationToolManagerView, context)
  BERRY_REGISTER_EXTENSION_CLASS( QmitkMITKIGTTrackingToolboxView , context)
  BERRY_REGISTER_EXTENSION_CLASS( QmitkNavigationDataPlayerView , context)

}

void PluginActivator::stop(ctkPluginContext* context)
{
  Q_UNUSED(context)
}

}

Q_EXPORT_PLUGIN2(org_mitk_gui_qt_igttracking, mitk::PluginActivator)
<commit_msg>disabled persistence because of bug 17806<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

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

#include "mitkPluginActivator.h"

#include <QtPlugin>

#include "QmitkMITKIGTNavigationToolManagerView.h"
#include "QmitkMITKIGTTrackingToolboxView.h"
#include "QmitkNavigationDataPlayerView.h"

//#include <mitkPersistenceService.h> //Workaround for bug in persistence module (see bug 16643 for details)
                                    //CAN BE REMOVED WHEN THE BUG IS FIXED

namespace mitk {

void PluginActivator::start(ctkPluginContext* context)
{
 // mitk::PersistenceService::LoadModule(); //Workaround for bug in persistence module (see bug 16643 for details)
                                          //CAN BE REMOVED WHEN THE BUG IS FIXED

  BERRY_REGISTER_EXTENSION_CLASS(QmitkMITKIGTNavigationToolManagerView, context)
  BERRY_REGISTER_EXTENSION_CLASS( QmitkMITKIGTTrackingToolboxView , context)
  BERRY_REGISTER_EXTENSION_CLASS( QmitkNavigationDataPlayerView , context)

}

void PluginActivator::stop(ctkPluginContext* context)
{
  Q_UNUSED(context)
}

}

Q_EXPORT_PLUGIN2(org_mitk_gui_qt_igttracking, mitk::PluginActivator)
<|endoftext|>


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

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

Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen.

This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.

The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.

IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.

=========================================================================*/
#include <math.h>
#include "vtkImageRegion.h"
#include "vtkImageCache.h"
#include "vtkImageNonMaximumSuppression.h"

//----------------------------------------------------------------------------
// Description:
// Construct an instance of vtkImageNonMaximumSuppression fitler.
vtkImageNonMaximumSuppression::vtkImageNonMaximumSuppression()
{
  this->NumberOfFilteredAxes = 3;
  this->NumberOfExecutionAxes = 3;

  this->SetOutputScalarType(VTK_FLOAT);
}

//----------------------------------------------------------------------------
// Options do not include YZ ...
void vtkImageNonMaximumSuppression::SetNumberOfFilteredAxes(int num)
{
  if (this->NumberOfFilteredAxes != num)
    {
    this->NumberOfFilteredAxes = num;
    this->Modified();
    }
}

//----------------------------------------------------------------------------
// Description:
// This method is passed a region that holds the image extent of this filters
// input, and changes the region to hold the image extent of this filters
// output.
void vtkImageNonMaximumSuppression::ExecuteImageInformation()
{
  int extent[8];
  int idx, axis;

  this->Inputs[0]->GetWholeExtent(extent);
  if ( ! this->HandleBoundaries)
    {
    // shrink output image extent.
    for (idx = 0; idx < this->NumberOfFilteredAxes; ++idx)
      {
      axis = this->FilteredAxes[idx];
      extent[axis*2] += 1;
      extent[axis*2+1] -= 1;
      }
    }

  this->Output->SetNumberOfScalarComponents(1);
  this->Output->SetWholeExtent(extent);
}

//----------------------------------------------------------------------------
// Description:
// This method computes the input extent necessary to generate the output.
void vtkImageNonMaximumSuppression::ComputeRequiredInputUpdateExtent(
						     int whichInput)
{
  int extent[8];
  int *wholeExtent;
  int idx, axis;

  wholeExtent = this->Inputs[0]->GetWholeExtent();
  this->Output->GetUpdateExtent(extent);

  // grow input image extent.
  for (idx = 0; idx < this->NumberOfFilteredAxes; ++idx)
    {
    axis = this->FilteredAxes[idx];
    extent[axis*2] -= 1;
    extent[axis*2+1] += 1;
    if (this->HandleBoundaries)
      {
      // we must clip extent with whole extent if we hanlde boundaries.
      if (extent[axis*2] < wholeExtent[axis*2])
	{
	extent[axis*2] = wholeExtent[axis*2];
	}
      if (extent[idx*2 + 1] > wholeExtent[idx*2 + 1])
	{
	extent[idx*2 + 1] = wholeExtent[idx*2 + 1];
	}
      }
    }

  this->Inputs[whichInput]->SetUpdateExtent(extent);
  // different components
  if (whichInput == 0)
    {
    this->Inputs[0]->SetNumberOfScalarComponents(1);
    }
  else
    {
    this->Inputs[1]->SetNumberOfScalarComponents(this->NumberOfFilteredAxes);
    }
}

//----------------------------------------------------------------------------
// Description:
// This method executes the filter for boundary pixels.
void vtkImageNonMaximumSuppression::Execute(vtkImageRegion *inRegion1,
					    vtkImageRegion *inRegion2,
					    vtkImageRegion *outRegion)
{
  int idx;
  int *wholeExtent, *incs;
  int outIdxs[VTK_IMAGE_DIMENSIONS], *idxs;
  // For looping though output (and input) pixels.
  int min0, max0, min1, max1, min2, max2, min3, max3;
  int outIdx0, outIdx1, outIdx2, outIdx3;
  int outInc0, outInc1, outInc2, outInc3;
  float *outPtr0, *outPtr1, *outPtr2, *outPtr3;
  int in1Inc0, in1Inc1, in1Inc2, in1Inc3;
  float *in1Ptr0, *in1Ptr1, *in1Ptr2, *in1Ptr3;
  int in2Inc0, in2Inc1, in2Inc2, in2Inc3, in2IncV;
  float *in2Ptr0, *in2Ptr1, *in2Ptr2, *in2Ptr3, *in2PtrV;
  int neighborA, neighborB;
  float d, normalizeFactor, vector[VTK_IMAGE_DIMENSIONS], *ratio;

  // This filter expects that output and input are type float.
  if (outRegion->GetScalarType() != VTK_FLOAT ||
      inRegion1->GetScalarType() != VTK_FLOAT ||
      inRegion2->GetScalarType() != VTK_FLOAT)
    {
    vtkErrorMacro(<< "Execute: output ScalarType, "
                  << vtkImageScalarTypeNameMacro(outRegion->GetScalarType())
                  << ", must be float");
    return;
    }

  // Gradient is computed with data spacing (world coordinates)
  ratio = inRegion2->GetSpacing();

  // Get information to march through data
  inRegion1->GetIncrements(in1Inc0, in1Inc1, in1Inc2, in1Inc3);
  inRegion2->GetIncrements(in2Inc0, in2Inc1, in2Inc2, in2Inc3, in2IncV);
  outRegion->GetIncrements(outInc0, outInc1, outInc2, outInc3);
  outRegion->GetExtent(min0, max0, min1, max1, min2, max2, min3, max3);

  // We want the input pixel to correspond to output
  in1Ptr3 = (float *)(inRegion1->GetScalarPointer(min0, min1, min2, min3));
  in2Ptr3 = (float *)(inRegion2->GetScalarPointer(min0, min1, min2, min3));
  outPtr3 = (float *)(outRegion->GetScalarPointer());

  // loop through pixels of output
  for (outIdx3 = min3; outIdx3 <= max3; ++outIdx3)
    {
    outIdxs[3] = outIdx3;
    outPtr2 = outPtr3;
    in1Ptr2 = in1Ptr3;
    in2Ptr2 = in2Ptr3;
    for (outIdx2 = min2; outIdx2 <= max2; ++outIdx2)
      {
      outIdxs[2] = outIdx2;
      outPtr1 = outPtr2;
      in1Ptr1 = in1Ptr2;
      in2Ptr1 = in2Ptr2;
      for (outIdx1 = min1; outIdx1 <= max1; ++outIdx1)
	{
	outIdxs[1] = outIdx1;
	outPtr0 = outPtr1;
	in1Ptr0 = in1Ptr1;
	in2Ptr0 = in2Ptr1;
	for (outIdx0 = min0; outIdx0 <= max0; ++outIdx0)
	  {
	  outIdxs[0] = outIdx0;

	  // Use vector (in2) to determine which neighbors to use.
	  in2PtrV = in2Ptr0;
	  idxs = outIdxs;
	  incs = inRegion1->GetIncrements();
	  wholeExtent = inRegion1->GetWholeExtent();
	  neighborA = neighborB = 0;
	  // Convert vector to pixel units and normalize.
	  normalizeFactor = 0.0;
	  for (idx = 0; idx < this->NumberOfFilteredAxes; ++idx)
	    {
	    // d units dI/world  -> dI
	    d = vector[idx] = *in2PtrV * ratio[idx];
	    normalizeFactor += d * d;
	    in2PtrV += in2IncV;
	    }
	  normalizeFactor = 1.0 / sqrt(normalizeFactor);
	  for (idx = 0; idx < this->NumberOfFilteredAxes; ++idx)
	    {
	    d = vector[idx] * normalizeFactor;
	    // Vector points positive along this axis?
	    // (can point along multiple axes)
	    if (d > 0.5)
	      {
	      if (*idxs < wholeExtent[1])  // max
		{
		neighborA += *incs;
		}
	      if (*idxs > *wholeExtent)  // min
		{
		neighborB -= *incs;
		}
	      }
	    // Vector points negative along this axis?
	    else if (d < -0.5)
	      {
	      if (*idxs < wholeExtent[1])  // max
		{
		neighborB += *incs;
		}
	      if (*idxs > *wholeExtent)  //min
		{
		neighborA -= *incs;
		}
	      }
	    // Increment pointers
	    ++idxs;
	    ++incs;
	    wholeExtent += 2;
	    }

	  // Set Output Magnitude
	  if (in1Ptr0[neighborA] > *in1Ptr0 || in1Ptr0[neighborB] > *in1Ptr0)
	    {
	    *outPtr0 = 0.0;
	    }
	  else
	    {
	    *outPtr0 = *in1Ptr0;
	    // also check for them being equal is neighbor with larger ptr
	    if ((neighborA > neighborB)&&(in1Ptr0[neighborA] == *in1Ptr0))
	      {
	      *outPtr0 = 0.0;
	      }
	    if ((neighborB > neighborA)&&(in1Ptr0[neighborB] == *in1Ptr0))
	      {
	      *outPtr0 = 0.0;
	      }
	    }

	  outPtr0 += outInc0;
	  in1Ptr0 += in1Inc0;
	  in2Ptr0 += in2Inc0;
	  }
	outPtr1 += outInc1;
	in1Ptr1 += in1Inc1;
	in2Ptr1 += in2Inc1;
	}
      outPtr2 += outInc2;
      in1Ptr2 += in1Inc2;
      in2Ptr2 += in2Inc2;
      }
    outPtr3 += outInc3;
    in1Ptr3 += in1Inc3;
    in2Ptr3 += in2Inc3;
    }
}

<commit_msg>made HandleBoundaries on by default<commit_after>/*=========================================================================

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

Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen.

This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.

The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.

IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.

=========================================================================*/
#include <math.h>
#include "vtkImageRegion.h"
#include "vtkImageCache.h"
#include "vtkImageNonMaximumSuppression.h"

//----------------------------------------------------------------------------
// Description:
// Construct an instance of vtkImageNonMaximumSuppression fitler.
vtkImageNonMaximumSuppression::vtkImageNonMaximumSuppression()
{
  this->NumberOfFilteredAxes = 3;
  this->NumberOfExecutionAxes = 3;
  this->HandleBoundaries = 1;
  this->SetOutputScalarType(VTK_FLOAT);
}

//----------------------------------------------------------------------------
// Options do not include YZ ...
void vtkImageNonMaximumSuppression::SetNumberOfFilteredAxes(int num)
{
  if (this->NumberOfFilteredAxes != num)
    {
    this->NumberOfFilteredAxes = num;
    this->Modified();
    }
}

//----------------------------------------------------------------------------
// Description:
// This method is passed a region that holds the image extent of this filters
// input, and changes the region to hold the image extent of this filters
// output.
void vtkImageNonMaximumSuppression::ExecuteImageInformation()
{
  int extent[8];
  int idx, axis;

  this->Inputs[0]->GetWholeExtent(extent);
  if ( ! this->HandleBoundaries)
    {
    // shrink output image extent.
    for (idx = 0; idx < this->NumberOfFilteredAxes; ++idx)
      {
      axis = this->FilteredAxes[idx];
      extent[axis*2] += 1;
      extent[axis*2+1] -= 1;
      }
    }

  this->Output->SetNumberOfScalarComponents(1);
  this->Output->SetWholeExtent(extent);
}

//----------------------------------------------------------------------------
// Description:
// This method computes the input extent necessary to generate the output.
void vtkImageNonMaximumSuppression::ComputeRequiredInputUpdateExtent(
						     int whichInput)
{
  int extent[8];
  int *wholeExtent;
  int idx, axis;

  wholeExtent = this->Inputs[0]->GetWholeExtent();
  this->Output->GetUpdateExtent(extent);

  // grow input image extent.
  for (idx = 0; idx < this->NumberOfFilteredAxes; ++idx)
    {
    axis = this->FilteredAxes[idx];
    extent[axis*2] -= 1;
    extent[axis*2+1] += 1;
    if (this->HandleBoundaries)
      {
      // we must clip extent with whole extent if we hanlde boundaries.
      if (extent[axis*2] < wholeExtent[axis*2])
	{
	extent[axis*2] = wholeExtent[axis*2];
	}
      if (extent[idx*2 + 1] > wholeExtent[idx*2 + 1])
	{
	extent[idx*2 + 1] = wholeExtent[idx*2 + 1];
	}
      }
    }

  this->Inputs[whichInput]->SetUpdateExtent(extent);
  // different components
  if (whichInput == 0)
    {
    this->Inputs[0]->SetNumberOfScalarComponents(1);
    }
  else
    {
    this->Inputs[1]->SetNumberOfScalarComponents(this->NumberOfFilteredAxes);
    }
}

//----------------------------------------------------------------------------
// Description:
// This method executes the filter for boundary pixels.
void vtkImageNonMaximumSuppression::Execute(vtkImageRegion *inRegion1,
					    vtkImageRegion *inRegion2,
					    vtkImageRegion *outRegion)
{
  int idx;
  int *wholeExtent, *incs;
  int outIdxs[VTK_IMAGE_DIMENSIONS], *idxs;
  // For looping though output (and input) pixels.
  int min0, max0, min1, max1, min2, max2, min3, max3;
  int outIdx0, outIdx1, outIdx2, outIdx3;
  int outInc0, outInc1, outInc2, outInc3;
  float *outPtr0, *outPtr1, *outPtr2, *outPtr3;
  int in1Inc0, in1Inc1, in1Inc2, in1Inc3;
  float *in1Ptr0, *in1Ptr1, *in1Ptr2, *in1Ptr3;
  int in2Inc0, in2Inc1, in2Inc2, in2Inc3, in2IncV;
  float *in2Ptr0, *in2Ptr1, *in2Ptr2, *in2Ptr3, *in2PtrV;
  int neighborA, neighborB;
  float d, normalizeFactor, vector[VTK_IMAGE_DIMENSIONS], *ratio;

  // This filter expects that output and input are type float.
  if (outRegion->GetScalarType() != VTK_FLOAT ||
      inRegion1->GetScalarType() != VTK_FLOAT ||
      inRegion2->GetScalarType() != VTK_FLOAT)
    {
    vtkErrorMacro(<< "Execute: output ScalarType, "
                  << vtkImageScalarTypeNameMacro(outRegion->GetScalarType())
                  << ", must be float");
    return;
    }

  // Gradient is computed with data spacing (world coordinates)
  ratio = inRegion2->GetSpacing();

  // Get information to march through data
  inRegion1->GetIncrements(in1Inc0, in1Inc1, in1Inc2, in1Inc3);
  inRegion2->GetIncrements(in2Inc0, in2Inc1, in2Inc2, in2Inc3, in2IncV);
  outRegion->GetIncrements(outInc0, outInc1, outInc2, outInc3);
  outRegion->GetExtent(min0, max0, min1, max1, min2, max2, min3, max3);

  // We want the input pixel to correspond to output
  in1Ptr3 = (float *)(inRegion1->GetScalarPointer(min0, min1, min2, min3));
  in2Ptr3 = (float *)(inRegion2->GetScalarPointer(min0, min1, min2, min3));
  outPtr3 = (float *)(outRegion->GetScalarPointer());

  // loop through pixels of output
  for (outIdx3 = min3; outIdx3 <= max3; ++outIdx3)
    {
    outIdxs[3] = outIdx3;
    outPtr2 = outPtr3;
    in1Ptr2 = in1Ptr3;
    in2Ptr2 = in2Ptr3;
    for (outIdx2 = min2; outIdx2 <= max2; ++outIdx2)
      {
      outIdxs[2] = outIdx2;
      outPtr1 = outPtr2;
      in1Ptr1 = in1Ptr2;
      in2Ptr1 = in2Ptr2;
      for (outIdx1 = min1; outIdx1 <= max1; ++outIdx1)
	{
	outIdxs[1] = outIdx1;
	outPtr0 = outPtr1;
	in1Ptr0 = in1Ptr1;
	in2Ptr0 = in2Ptr1;
	for (outIdx0 = min0; outIdx0 <= max0; ++outIdx0)
	  {
	  outIdxs[0] = outIdx0;

	  // Use vector (in2) to determine which neighbors to use.
	  in2PtrV = in2Ptr0;
	  idxs = outIdxs;
	  incs = inRegion1->GetIncrements();
	  wholeExtent = inRegion1->GetWholeExtent();
	  neighborA = neighborB = 0;
	  // Convert vector to pixel units and normalize.
	  normalizeFactor = 0.0;
	  for (idx = 0; idx < this->NumberOfFilteredAxes; ++idx)
	    {
	    // d units dI/world  -> dI
	    d = vector[idx] = *in2PtrV * ratio[idx];
	    normalizeFactor += d * d;
	    in2PtrV += in2IncV;
	    }
	  normalizeFactor = 1.0 / sqrt(normalizeFactor);
	  for (idx = 0; idx < this->NumberOfFilteredAxes; ++idx)
	    {
	    d = vector[idx] * normalizeFactor;
	    // Vector points positive along this axis?
	    // (can point along multiple axes)
	    if (d > 0.5)
	      {
	      if (*idxs < wholeExtent[1])  // max
		{
		neighborA += *incs;
		}
	      if (*idxs > *wholeExtent)  // min
		{
		neighborB -= *incs;
		}
	      }
	    // Vector points negative along this axis?
	    else if (d < -0.5)
	      {
	      if (*idxs < wholeExtent[1])  // max
		{
		neighborB += *incs;
		}
	      if (*idxs > *wholeExtent)  //min
		{
		neighborA -= *incs;
		}
	      }
	    // Increment pointers
	    ++idxs;
	    ++incs;
	    wholeExtent += 2;
	    }

	  // Set Output Magnitude
	  if (in1Ptr0[neighborA] > *in1Ptr0 || in1Ptr0[neighborB] > *in1Ptr0)
	    {
	    *outPtr0 = 0.0;
	    }
	  else
	    {
	    *outPtr0 = *in1Ptr0;
	    // also check for them being equal is neighbor with larger ptr
	    if ((neighborA > neighborB)&&(in1Ptr0[neighborA] == *in1Ptr0))
	      {
	      *outPtr0 = 0.0;
	      }
	    if ((neighborB > neighborA)&&(in1Ptr0[neighborB] == *in1Ptr0))
	      {
	      *outPtr0 = 0.0;
	      }
	    }

	  outPtr0 += outInc0;
	  in1Ptr0 += in1Inc0;
	  in2Ptr0 += in2Inc0;
	  }
	outPtr1 += outInc1;
	in1Ptr1 += in1Inc1;
	in2Ptr1 += in2Inc1;
	}
      outPtr2 += outInc2;
      in1Ptr2 += in1Inc2;
      in2Ptr2 += in2Inc2;
      }
    outPtr3 += outInc3;
    in1Ptr3 += in1Inc3;
    in2Ptr3 += in2Inc3;
    }
}

<|endoftext|>


<commit_before>/*
  $Id$
  $URL$

  Copyright (c) 1998 - 2012

  This file is part of tscan

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

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

  You should have received a copy of the GNU General Public License
  along with this program; if not, see <http://www.gnu.org/licenses/>.

  For questions and suggestions, see:

  or send mail to:

*/

#include <cstdio> // for remove()
#include <cstring> // for strerror()
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <iostream>
#include <fstream>
#include "config.h"
#include "libfolia/folia.h"
#include "libfolia/document.h"
#include "tscan/Alpino.h"

using namespace std;
//using namespace TiCC;
using namespace folia;

void addSU( xmlNode *n, vector<Word*>& words, FoliaElement *s ){
  if ( Name( n ) == "node" ){
    KWargs atts = getAttributes( n );
    string cls = atts["cat"];
    bool leaf = false;
    if ( cls.empty() ){
      cls = atts["lcat"];
      leaf = true;
    }
    if ( !cls.empty() ){
      FoliaElement *e =
	s->append( new SyntacticUnit( s->doc(), "cls='" + cls + "'" ) );
      if ( leaf ){
	string posS = atts["begin"];
	int start = stringTo<int>( posS );
	e->append( words[start] );
      }
      else {
	xmlNode *pnt = n->children;
	while ( pnt ){
	  addSU( pnt, words, e );
	  pnt = pnt->next;
	}
      }
    }
  }
}

void extractSyntax( xmlNode *node, folia::Sentence *s ){
  Document *doc = s->doc();
  doc->declare( AnnotationType::SYNTAX,
		"myset",
		"annotator='alpino'" );
  vector<Word*> words = s->words();
  FoliaElement *layer = s->append( new SyntaxLayer( doc ) );
  FoliaElement *sent = layer->append( new SyntacticUnit( doc, "cls='s'" ) );
  xmlNode *pnt = node->children;
  while ( pnt ){
    addSU( pnt, words, sent );
    pnt = pnt->next;
  }
}

void extractDependency( xmlNode *node, folia::Sentence *s ){
}

void extractAndAppendParse( xmlDoc *doc, folia::Sentence *s ){
  cerr << "extract the Alpino results!" << endl;
  xmlNode *root = xmlDocGetRootElement( doc );
  xmlNode *pnt = root->children;
  while ( pnt ){
    if ( folia::Name( pnt ) == "node" ){
      cerr << "founds a node" << endl;
      // 1 top node i hope
      extractSyntax( pnt, s );
      cerr << "added syntax " << s->xmlstring() << endl;
      extractDependency( pnt, s );
      break;
    }
    pnt = pnt->next;
  }
}

bool AlpinoParse( folia::Sentence *s ){
  string txt = folia::UnicodeToUTF8(s->text());
  cerr << "parse line: " << txt << endl;
  struct stat sbuf;
  int res = stat( "/tmp/alpino", &sbuf );
  if ( !S_ISDIR(sbuf.st_mode) ){
    res = mkdir( "/tmp/alpino/", S_IRWXU|S_IRWXG );
  }
  res = stat( "/tmp/alpino/parses", &sbuf );
  if ( !S_ISDIR(sbuf.st_mode) ){
    res = mkdir( "/tmp/alpino/parses",  S_IRWXU|S_IRWXG );
  }
  ofstream os( "/tmp/alpino/tempparse.txt" );
  os << txt;
  os.close();
  string parseCmd = "Alpino -fast -flag treebank /tmp/alpino/parses end_hook=xml -parse < /tmp/alpino/tempparse.txt -notk > /dev/null 2>&1";
  res = system( parseCmd.c_str() );
  cerr << "parse res: " << res << endl;
  remove( "/tmp/alpino/tempparse.txt" );
  xmlDoc *xmldoc = xmlReadFile( "/tmp/alpino/parses/1.xml", 0, XML_PARSE_NOBLANKS );
  if ( xmldoc ){
    extractAndAppendParse( xmldoc, s );
  }
  return (xmldoc != 0 );
}

<commit_msg>we need the tokenized sentence!<commit_after>/*
  $Id$
  $URL$

  Copyright (c) 1998 - 2012

  This file is part of tscan

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

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

  You should have received a copy of the GNU General Public License
  along with this program; if not, see <http://www.gnu.org/licenses/>.

  For questions and suggestions, see:

  or send mail to:

*/

#include <cstdio> // for remove()
#include <cstring> // for strerror()
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <iostream>
#include <fstream>
#include "config.h"
#include "libfolia/folia.h"
#include "libfolia/document.h"
#include "tscan/Alpino.h"

using namespace std;
//using namespace TiCC;
using namespace folia;

void addSU( xmlNode *n, vector<Word*>& words, FoliaElement *s ){
  if ( Name( n ) == "node" ){
    KWargs atts = getAttributes( n );
    string cls = atts["cat"];
    bool leaf = false;
    if ( cls.empty() ){
      cls = atts["lcat"];
      leaf = true;
    }
    if ( !cls.empty() ){
      FoliaElement *e =
	s->append( new SyntacticUnit( s->doc(), "cls='" + cls + "'" ) );
      if ( leaf ){
	string posS = atts["begin"];
	int start = stringTo<int>( posS );
	e->append( words[start] );
      }
      else {
	xmlNode *pnt = n->children;
	while ( pnt ){
	  addSU( pnt, words, e );
	  pnt = pnt->next;
	}
      }
    }
  }
}

void extractSyntax( xmlNode *node, folia::Sentence *s ){
  Document *doc = s->doc();
  doc->declare( AnnotationType::SYNTAX,
		"myset",
		"annotator='alpino'" );
  vector<Word*> words = s->words();
  FoliaElement *layer = s->append( new SyntaxLayer( doc ) );
  FoliaElement *sent = layer->append( new SyntacticUnit( doc, "cls='s'" ) );
  xmlNode *pnt = node->children;
  while ( pnt ){
    addSU( pnt, words, sent );
    pnt = pnt->next;
  }
}

void extractDependency( xmlNode *node, folia::Sentence *s ){
}

void extractAndAppendParse( xmlDoc *doc, folia::Sentence *s ){
  cerr << "extract the Alpino results!" << endl;
  xmlNode *root = xmlDocGetRootElement( doc );
  xmlNode *pnt = root->children;
  while ( pnt ){
    if ( folia::Name( pnt ) == "node" ){
      cerr << "founds a node" << endl;
      // 1 top node i hope
      extractSyntax( pnt, s );
      cerr << "added syntax " << s->xmlstring() << endl;
      extractDependency( pnt, s );
      break;
    }
    pnt = pnt->next;
  }
}

bool AlpinoParse( folia::Sentence *s ){
  string txt = folia::UnicodeToUTF8(s->toktext());
  cerr << "parse line: " << txt << endl;
  struct stat sbuf;
  int res = stat( "/tmp/alpino", &sbuf );
  if ( !S_ISDIR(sbuf.st_mode) ){
    res = mkdir( "/tmp/alpino/", S_IRWXU|S_IRWXG );
  }
  res = stat( "/tmp/alpino/parses", &sbuf );
  if ( !S_ISDIR(sbuf.st_mode) ){
    res = mkdir( "/tmp/alpino/parses",  S_IRWXU|S_IRWXG );
  }
  ofstream os( "/tmp/alpino/tempparse.txt" );
  os << txt;
  os.close();
  string parseCmd = "Alpino -fast -flag treebank /tmp/alpino/parses end_hook=xml -parse < /tmp/alpino/tempparse.txt -notk > /dev/null 2>&1";
  res = system( parseCmd.c_str() );
  cerr << "parse res: " << res << endl;
  remove( "/tmp/alpino/tempparse.txt" );
  xmlDoc *xmldoc = xmlReadFile( "/tmp/alpino/parses/1.xml", 0, XML_PARSE_NOBLANKS );
  if ( xmldoc ){
    extractAndAppendParse( xmldoc, s );
  }
  return (xmldoc != 0 );
}

<|endoftext|>