<commit_before>/*
 * Copyright (C) 2004-2013 ZNC-MSVC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "znc_msvc.h"
#include <stdio.h>
#include <time.h>
#include <string>
#include <mutex>
#include <map>

//
// localtime_r implementation for Windows (VC 2012 + later)!
//
struct tm* localtime_r(const time_t *timep, struct tm *result)
{
	static __declspec(thread) struct tm l_tm;

	if(timep != nullptr && result != nullptr
		&& localtime_s(&l_tm, timep) == 0)
	{
		memcpy(result, &l_tm, sizeof(struct tm));

		return &l_tm;
	}

	return NULL;
}

//
// gmtime_r implementation for Windows (VC 2012 + later)!
//
struct tm* gmtime_r(const time_t *timep, struct tm *result)
{
	static __declspec(thread) struct tm l_tm;

	if(timep != nullptr && result != nullptr
		&& gmtime_s(&l_tm, timep) == 0)
	{
		memcpy(result, &l_tm, sizeof(struct tm));

		return &l_tm;
	}

	return NULL;
}

//
// ctime_r implementation for Windows (VC 2012 + later)!
//
char* ctime_r(const time_t *timep, char *result)
{
	static __declspec(thread) char buf[30] = {0};

	if(timep != nullptr && result != nullptr
		&& ctime_s(buf, sizeof(buf), timep) == 0)
	{
		memcpy(result, buf, strlen(buf) + 1);

		return buf;
	}

	return NULL;
}

/**
 * get password from console
 * Source: http://svn.openvpn.net/projects/openvpn/obsolete/BETA15/openvpn/io.c
 * License: GNU GPL v2
 * (modified to display * for input)
 **/
std::string getpass(const char *prompt)
{
	HANDLE in = ::GetStdHandle(STD_INPUT_HANDLE);
	HANDLE out = ::GetStdHandle(STD_OUTPUT_HANDLE);
	std::string result;
	DWORD count;

	if(in == INVALID_HANDLE_VALUE || out == INVALID_HANDLE_VALUE)
	{
		return NULL;
	}

	// the total size of the buffer must be less than 64K chars
	if(::WriteConsole(out, prompt, DWORD(strlen(prompt)), &count, NULL))
	{
		int istty = (::GetFileType(in) == FILE_TYPE_CHAR);
		DWORD old_mode;
		char c;

		if(istty)
		{
			if(::GetConsoleMode(in, &old_mode))
			{
				::SetConsoleMode(in, old_mode & ~(ENABLE_ECHO_INPUT | ENABLE_LINE_INPUT));
			}
			else
			{
				istty = 0;
			}
		}

		while(::ReadConsole(in, &c, 1, &count, NULL) && (c != '\r') && (c != '\n'))
		{
			if(c == '\b')
			{
				if(!result.empty())
				{
					::WriteConsole(out, "\b \b", 3, &count, NULL);
					result.erase(result.end() - 1);
				}
			}
			else
			{
				::WriteConsole(out, "*", 1, &count, NULL);
				result += c ;
			}
		}

		::WriteConsole(out, "\r\n", 2, &count, NULL);

		if(istty)
		{
			::SetConsoleMode(in, old_mode);
		}
	}

	return result;
}

/* Microsoft's strftime does not handle user defined error-prone format input very well, and
according to http://msdn.microsoft.com/en-us/library/fe06s4ak%28VS.71%29.aspx is not supposed to,
so we use this wrapper. */
size_t strftime_validating(char *strDest, size_t maxsize, const char *format, const struct tm *timeptr)
{
	std::string l_safeFormat;
	const char* p = format;

	while(*p)
	{
		if(*p == '%')
		{
			bool l_hash = (*(p + 1) == '#');
			char c = *(p + (l_hash ? 2 : 1));

			switch(c)
			{
			case 'a': case 'A': case 'b': case 'B': case 'c': case 'd': case 'H': case 'I': case 'j': case 'm': case 'M':
			case 'p': case 'S': case 'U': case 'w': case 'W': case 'x': case 'X': case 'y': case 'Y': case 'z': case 'Z':
			case '%':
				// formatting code is fine
				if(l_hash)
				{
					l_safeFormat += *p;
					++p;
				}
				// the current loop run will append % (and maybe #), and the next one will do the actual char.
				break;
			default: // replace bad formatting code with itself, escaped, e.g. "%V" --> "%%V"
				l_safeFormat.append("%%");
				++p;
				break;
			}

			// if c == '%', append it in this run to avoid confusion in the next one (p has already been incremented now!)
			if(c == '%')
			{
				l_safeFormat += *p;
				++p;
			}
		}

		if(*p)
		{
			l_safeFormat += *p;
			++p;
		}
	}

	return strftime(strDest, maxsize, l_safeFormat.c_str(), timeptr);
}

//
// setenv implementation for Windows
//
int setenv(const char *envname, const char *envval, int overwrite)
{
	if (!overwrite && getenv(envname) != nullptr)
	{
		return 1;
	}

	return (::SetEnvironmentVariable(envname, envval) ? 1 : 0);
}

//
// unsetenv implementation for Windows
//
int unsetenv(const char *envname)
{
	return (::SetEnvironmentVariable(envname, NULL) ? 1 : 0);
}

//
// rand_r implementation for Windows
//
int rand_r(unsigned int *seedp)
{
	if (seedp)
	{
		srand(*seedp);

		return rand();
	}
	else
	{
		int result;
		rand_s((unsigned int*)&result);
		return result;
	}
}

//
// convert strftime format to ICU format
// http://www.cplusplus.com/reference/ctime/strftime/
// http://userguide.icu-project.org/formatparse/datetime
//
std::string strftime_format_to_icu(const std::string& a_format)
{
	static std::map<const std::string, std::string> cache;
	static std::mutex cache_access;

	cache_access.lock();
	auto found_in_cache = cache.find(a_format);
	if (found_in_cache != cache.end())
	{
		std::string result = found_in_cache->second;
		cache_access.unlock();
		return result;
	}
	cache_access.unlock();

	std::string icu;

	for(std::string::const_iterator it = a_format.begin(); it != a_format.end(); it++)
	{
		char c = *it;

		if (c == '%')
		{
			std::string::const_iterator next = ++it;

			if(next == a_format.end())
			{
				icu += '%';
				break;
			}

			char spec = *next;

			switch(spec)
			{
			case '%': icu += c; break;
			case 'a': icu += "EEE"; break;
			case 'A': icu += "EEEE"; break;
			case 'b':
			case 'h':
				icu += "MMMM"; break;
			case 'B': icu += "MMMMM"; break;
			case 'c': icu += "EEE MMM dd HH:mm:ss yyyy"; break;
			case 'C': icu += "yy"; break;
			case 'd': icu += "dd"; break;
			case 'D': icu += "M/dd/yy"; break;
			case 'e': icu += "dd"; break; // space-padding is not supported by ICU
			case 'F': icu += "yyyy-M-dd"; break;
			case 'g': // two-digit week based not supported by ICU
			case 'G':
				icu += "Y"; break;
			case 'H': icu += "HH"; break;
			case 'I': icu += "hh"; break;
			case 'j': icu += "D"; break;
			case 'm': icu += "MM"; break;
			case 'M': icu += "mm"; break;
			case 'n': icu += '\n'; break;
			case 'p': icu += "a"; break;
			case 'r': icu += "hh:mm:ss a"; break;
			case 'R': icu += "HH:mm"; break;
			case 'S': icu += "ss"; break;
			case 't': icu += "\t"; break;
			case 'T': icu += "HH:mm:ss"; break;
#if 0
			// the following are questionable, if not plain wrong:
			case 'u': icu += "c"; break; // ??
			case 'U': icu += "w"; break; // ??
			case 'V': icu += "w"; break; // ??
			case 'w': icu += "e"; break; // ??
			case 'W': icu += "w"; break; // ??
			// ---
#endif
			case 'x': icu += "yyyy-M-dd"; break;
			case 'X': icu += "HH:mm:ss"; break;
			case 'y': icu += "yy"; break;
			case 'Y': icu += "yyyy"; break;
#if 0
			case 'z': icu += "ZZZZ"; break; // not exactly correct
#endif
			case 'Z': icu += "z"; break;
			default:
				icu += "%'";
				icu += spec;
			}
		}
		else if(!isalpha(c) && c != '\'')
		{
			icu += c;
		}
		else
		{
			// escape:
			icu += "'" + c;
		}
	}

	cache_access.lock();
	cache[a_format] = icu;
	cache_access.unlock();

	return icu;
}
<commit_msg>Fix incorrect time format string conversion.<commit_after>/*
 * Copyright (C) 2004-2013 ZNC-MSVC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "znc_msvc.h"
#include <stdio.h>
#include <time.h>
#include <string>
#include <mutex>
#include <map>

//
// localtime_r implementation for Windows (VC 2012 + later)!
//
struct tm* localtime_r(const time_t *timep, struct tm *result)
{
	static __declspec(thread) struct tm l_tm;

	if(timep != nullptr && result != nullptr
		&& localtime_s(&l_tm, timep) == 0)
	{
		memcpy(result, &l_tm, sizeof(struct tm));

		return &l_tm;
	}

	return NULL;
}

//
// gmtime_r implementation for Windows (VC 2012 + later)!
//
struct tm* gmtime_r(const time_t *timep, struct tm *result)
{
	static __declspec(thread) struct tm l_tm;

	if(timep != nullptr && result != nullptr
		&& gmtime_s(&l_tm, timep) == 0)
	{
		memcpy(result, &l_tm, sizeof(struct tm));

		return &l_tm;
	}

	return NULL;
}

//
// ctime_r implementation for Windows (VC 2012 + later)!
//
char* ctime_r(const time_t *timep, char *result)
{
	static __declspec(thread) char buf[30] = {0};

	if(timep != nullptr && result != nullptr
		&& ctime_s(buf, sizeof(buf), timep) == 0)
	{
		memcpy(result, buf, strlen(buf) + 1);

		return buf;
	}

	return NULL;
}

/**
 * get password from console
 * Source: http://svn.openvpn.net/projects/openvpn/obsolete/BETA15/openvpn/io.c
 * License: GNU GPL v2
 * (modified to display * for input)
 **/
std::string getpass(const char *prompt)
{
	HANDLE in = ::GetStdHandle(STD_INPUT_HANDLE);
	HANDLE out = ::GetStdHandle(STD_OUTPUT_HANDLE);
	std::string result;
	DWORD count;

	if(in == INVALID_HANDLE_VALUE || out == INVALID_HANDLE_VALUE)
	{
		return NULL;
	}

	// the total size of the buffer must be less than 64K chars
	if(::WriteConsole(out, prompt, DWORD(strlen(prompt)), &count, NULL))
	{
		int istty = (::GetFileType(in) == FILE_TYPE_CHAR);
		DWORD old_mode;
		char c;

		if(istty)
		{
			if(::GetConsoleMode(in, &old_mode))
			{
				::SetConsoleMode(in, old_mode & ~(ENABLE_ECHO_INPUT | ENABLE_LINE_INPUT));
			}
			else
			{
				istty = 0;
			}
		}

		while(::ReadConsole(in, &c, 1, &count, NULL) && (c != '\r') && (c != '\n'))
		{
			if(c == '\b')
			{
				if(!result.empty())
				{
					::WriteConsole(out, "\b \b", 3, &count, NULL);
					result.erase(result.end() - 1);
				}
			}
			else
			{
				::WriteConsole(out, "*", 1, &count, NULL);
				result += c ;
			}
		}

		::WriteConsole(out, "\r\n", 2, &count, NULL);

		if(istty)
		{
			::SetConsoleMode(in, old_mode);
		}
	}

	return result;
}

/* Microsoft's strftime does not handle user defined error-prone format input very well, and
according to http://msdn.microsoft.com/en-us/library/fe06s4ak%28VS.71%29.aspx is not supposed to,
so we use this wrapper. */
size_t strftime_validating(char *strDest, size_t maxsize, const char *format, const struct tm *timeptr)
{
	std::string l_safeFormat;
	const char* p = format;

	while(*p)
	{
		if(*p == '%')
		{
			bool l_hash = (*(p + 1) == '#');
			char c = *(p + (l_hash ? 2 : 1));

			switch(c)
			{
			case 'a': case 'A': case 'b': case 'B': case 'c': case 'd': case 'H': case 'I': case 'j': case 'm': case 'M':
			case 'p': case 'S': case 'U': case 'w': case 'W': case 'x': case 'X': case 'y': case 'Y': case 'z': case 'Z':
			case '%':
				// formatting code is fine
				if(l_hash)
				{
					l_safeFormat += *p;
					++p;
				}
				// the current loop run will append % (and maybe #), and the next one will do the actual char.
				break;
			default: // replace bad formatting code with itself, escaped, e.g. "%V" --> "%%V"
				l_safeFormat.append("%%");
				++p;
				break;
			}

			// if c == '%', append it in this run to avoid confusion in the next one (p has already been incremented now!)
			if(c == '%')
			{
				l_safeFormat += *p;
				++p;
			}
		}

		if(*p)
		{
			l_safeFormat += *p;
			++p;
		}
	}

	return strftime(strDest, maxsize, l_safeFormat.c_str(), timeptr);
}

//
// setenv implementation for Windows
//
int setenv(const char *envname, const char *envval, int overwrite)
{
	if (!overwrite && getenv(envname) != nullptr)
	{
		return 1;
	}

	return (::SetEnvironmentVariable(envname, envval) ? 1 : 0);
}

//
// unsetenv implementation for Windows
//
int unsetenv(const char *envname)
{
	return (::SetEnvironmentVariable(envname, NULL) ? 1 : 0);
}

//
// rand_r implementation for Windows
//
int rand_r(unsigned int *seedp)
{
	if (seedp)
	{
		srand(*seedp);

		return rand();
	}
	else
	{
		int result;
		rand_s((unsigned int*)&result);
		return result;
	}
}

//
// convert strftime format to ICU format
// http://www.cplusplus.com/reference/ctime/strftime/
// http://userguide.icu-project.org/formatparse/datetime
//
std::string strftime_format_to_icu(const std::string& a_format)
{
	static std::map<const std::string, std::string> cache;
	static std::mutex cache_access;

	cache_access.lock();
	auto found_in_cache = cache.find(a_format);
	if (found_in_cache != cache.end())
	{
		std::string result = found_in_cache->second;
		cache_access.unlock();
		return result;
	}
	cache_access.unlock();

	std::string icu;
	bool in_literal = false;

	for(std::string::const_iterator it = a_format.begin(); it != a_format.end(); it++)
	{
		char c = *it;

		if (c == '%')
		{
			std::string::const_iterator next = ++it;

			if (in_literal)
			{
				icu += "'";
				in_literal = false;
			}

			if(next == a_format.end())
			{
				icu += '%';
				break;
			}

			char spec = *next;

			switch(spec)
			{
			case '%': icu += c; break;
			case 'a': icu += "EEE"; break;
			case 'A': icu += "EEEE"; break;
			case 'b':
			case 'h':
				icu += "MMMM"; break;
			case 'B': icu += "MMMMM"; break;
			case 'c': icu += "EEE MMM dd HH:mm:ss yyyy"; break;
			case 'C': icu += "yy"; break;
			case 'd': icu += "dd"; break;
			case 'D': icu += "M/dd/yy"; break;
			case 'e': icu += "dd"; break; // space-padding is not supported by ICU
			case 'F': icu += "yyyy-M-dd"; break;
			case 'g': // two-digit week based not supported by ICU
			case 'G':
				icu += "Y"; break;
			case 'H': icu += "HH"; break;
			case 'I': icu += "hh"; break;
			case 'j': icu += "D"; break;
			case 'm': icu += "MM"; break;
			case 'M': icu += "mm"; break;
			case 'n': icu += '\n'; break;
			case 'p': icu += "a"; break;
			case 'r': icu += "hh:mm:ss a"; break;
			case 'R': icu += "HH:mm"; break;
			case 'S': icu += "ss"; break;
			case 't': icu += "\t"; break;
			case 'T': icu += "HH:mm:ss"; break;
#if 0
			// the following are questionable, if not plain wrong:
			case 'u': icu += "c"; break; // ??
			case 'U': icu += "w"; break; // ??
			case 'V': icu += "w"; break; // ??
			case 'w': icu += "e"; break; // ??
			case 'W': icu += "w"; break; // ??
			// ---
#endif
			case 'x': icu += "yyyy-M-dd"; break;
			case 'X': icu += "HH:mm:ss"; break;
			case 'y': icu += "yy"; break;
			case 'Y': icu += "yyyy"; break;
#if 0
			case 'z': icu += "ZZZZ"; break; // not exactly correct
#endif
			case 'Z': icu += "z"; break;
			default:
				;
			}
		}
		else if(isalpha(c))
		{
			if (!in_literal)
			{
				icu += "'";
				in_literal = true;
			}

			icu += c;
		}
		else if (c == '\'')
		{
			// escape:
			icu += "'" + c;
		}
		else
		{
			icu += c;
		}
	}

	if (in_literal)
	{
		icu += "'";
	}

	cache_access.lock();
	cache[a_format] = icu;
	cache_access.unlock();

	return icu;
}
<|endoftext|>


<commit_before><commit_msg>Fix 4dExtract problem w/ intra-exon duplication<commit_after><|endoftext|>


<commit_before>/*
 * MegaMolPlugin.cpp
 * Copyright (C) 2009-2015 by MegaMol Team
 * Alle Rechte vorbehalten.
 */

#include "stdafx.h"
#include "MegaMolPlugin/MegaMolPlugin.h"

#include "mmcore/api/MegaMolCore.std.h"
#include "mmcore/utility/plugins/Plugin200Instance.h"
#include "mmcore/versioninfo.h"
#include "vislib/vislibversion.h"

/* anonymous namespace hides this type from any other object files */
namespace {
    /** Implementing the instance class of this plugin */
    class plugin_instance : public ::megamol::core::utility::plugins::Plugin200Instance {
    public:
        /** ctor */
        plugin_instance(void)
            : ::megamol::core::utility::plugins::Plugin200Instance(

                /* machine-readable plugin assembly name */
                "MegaMolPlugin", // TODO: Change this!

                /* human-readable plugin description */
                "Describing MegaMolPlugin (TODO: Change this!)") {

            // here we could perform addition initialization
        };
        /** Dtor */
        virtual ~plugin_instance(void) {
            // here we could perform addition de-initialization
        }
        /** Registers modules and calls */
        virtual void registerClasses(void) {

            // register modules here:

            //
            // TODO: Register your plugin's modules here
            // like:
            //   this->module_descriptions.RegisterAutoDescription<megamol::MegaMolPlugin::MyModule1>();
            //   this->module_descriptions.RegisterAutoDescription<megamol::MegaMolPlugin::MyModule2>();
            //   ...
            //

            // register calls here:

            //
            // TODO: Register your plugin's calls here
            // like:
            //   this->call_descriptions.RegisterAutoDescription<megamol::MegaMolPlugin::MyCall1>();
            //   this->call_descriptions.RegisterAutoDescription<megamol::MegaMolPlugin::MyCall2>();
            //   ...
            //

        }
        MEGAMOLCORE_PLUGIN200UTIL_IMPLEMENT_plugininstance_connectStatics
    };
}

/*
 * mmplgPluginAPIVersion
 */
MEGAMOLPLUGIN_API int mmplgPluginAPIVersion(void) {
    MEGAMOLCORE_PLUGIN200UTIL_IMPLEMENT_mmplgPluginAPIVersion
}

/*
 * mmplgGetPluginCompatibilityInfo
 */
MEGAMOLPLUGIN_API
::megamol::core::utility::plugins::PluginCompatibilityInfo *
mmplgGetPluginCompatibilityInfo(
        ::megamol::core::utility::plugins::ErrorCallback onError) {
    // compatibility information with core and vislib
    using ::megamol::core::utility::plugins::PluginCompatibilityInfo;
    using ::megamol::core::utility::plugins::LibraryVersionInfo;

    PluginCompatibilityInfo *ci = new PluginCompatibilityInfo;
    ci->libs_cnt = 2;
    ci->libs = new LibraryVersionInfo[2];

    MEGAMOLCORE_PLUGIN200UTIL_Set_LibraryVersionInfo_V4(ci->libs[0], "MegaMolCore", MEGAMOL_CORE_MAJOR_VER, MEGAMOL_CORE_MINOR_VER, MEGAMOL_CORE_MAJOR_REV, MEGAMOL_CORE_MINOR_REV)
    MEGAMOLCORE_PLUGIN200UTIL_Set_LibraryVersionInfo_V4(ci->libs[1], "vislib", VISLIB_VERSION_MAJOR, VISLIB_VERSION_MINOR, VISLIB_VERSION_REVISION, VISLIB_VERSION_BUILD)
    //
    // If you want to test additional compatibilties, add the corresponding versions here
    //

    return ci;
}

/*
 * mmplgReleasePluginCompatibilityInfo
 */
MEGAMOLPLUGIN_API
void mmplgReleasePluginCompatibilityInfo(
        ::megamol::core::utility::plugins::PluginCompatibilityInfo* ci) {
    // release compatiblity data on the correct heap
    MEGAMOLCORE_PLUGIN200UTIL_IMPLEMENT_mmplgReleasePluginCompatibilityInfo(ci)
}

/*
 * mmplgGetPluginInstance
 */
MEGAMOLPLUGIN_API
::megamol::core::utility::plugins::AbstractPluginInstance*
mmplgGetPluginInstance(
        ::megamol::core::utility::plugins::ErrorCallback onError) {
    MEGAMOLCORE_PLUGIN200UTIL_IMPLEMENT_mmplgGetPluginInstance(plugin_instance, onError)
}

/*
 * mmplgReleasePluginInstance
 */
MEGAMOLPLUGIN_API
void mmplgReleasePluginInstance(
        ::megamol::core::utility::plugins::AbstractPluginInstance* pi) {
    MEGAMOLCORE_PLUGIN200UTIL_IMPLEMENT_mmplgReleasePluginInstance(pi)
}
<commit_msg>Updated plugin api<commit_after>/*
 * MegaMolPlugin.cpp
 * Copyright (C) 2009-2015 by MegaMol Team
 * Alle Rechte vorbehalten.
 */

#include "stdafx.h"
#include "MegaMolPlugin/MegaMolPlugin.h"

#include "mmcore/api/MegaMolCore.std.h"
#include "mmcore/utility/plugins/Plugin200Instance.h"
#include "mmcore/versioninfo.h"
#include "vislib/vislibversion.h"

/* anonymous namespace hides this type from any other object files */
namespace {
    /** Implementing the instance class of this plugin */
    class plugin_instance : public ::megamol::core::utility::plugins::Plugin200Instance {
    public:
        /** ctor */
        plugin_instance(void)
            : ::megamol::core::utility::plugins::Plugin200Instance(

                /* machine-readable plugin assembly name */
                "MegaMolPlugin", // TODO: Change this!

                /* human-readable plugin description */
                "Describing MegaMolPlugin (TODO: Change this!)") {

            // here we could perform addition initialization
        };
        /** Dtor */
        virtual ~plugin_instance(void) {
            // here we could perform addition de-initialization
        }
        /** Registers modules and calls */
        virtual void registerClasses(void) {

            // register modules here:

            //
            // TODO: Register your plugin's modules here
            // like:
            //   this->module_descriptions.RegisterAutoDescription<megamol::MegaMolPlugin::MyModule1>();
            //   this->module_descriptions.RegisterAutoDescription<megamol::MegaMolPlugin::MyModule2>();
            //   ...
            //

            // register calls here:

            //
            // TODO: Register your plugin's calls here
            // like:
            //   this->call_descriptions.RegisterAutoDescription<megamol::MegaMolPlugin::MyCall1>();
            //   this->call_descriptions.RegisterAutoDescription<megamol::MegaMolPlugin::MyCall2>();
            //   ...
            //

        }
        MEGAMOLCORE_PLUGIN200UTIL_IMPLEMENT_plugininstance_connectStatics
    };
}

/*
 * mmplgPluginAPIVersion
 */
MEGAMOLPLUGIN_API int mmplgPluginAPIVersion(void) {
    MEGAMOLCORE_PLUGIN200UTIL_IMPLEMENT_mmplgPluginAPIVersion
}

/*
 * mmplgGetPluginCompatibilityInfo
 */
MEGAMOLPLUGIN_API
::megamol::core::utility::plugins::PluginCompatibilityInfo *
mmplgGetPluginCompatibilityInfo(
        ::megamol::core::utility::plugins::ErrorCallback onError) {
    // compatibility information with core and vislib
    using ::megamol::core::utility::plugins::PluginCompatibilityInfo;
    using ::megamol::core::utility::plugins::LibraryVersionInfo;

    PluginCompatibilityInfo *ci = new PluginCompatibilityInfo;
    ci->libs_cnt = 2;
    ci->libs = new LibraryVersionInfo[2];

    SetLibraryVersionInfo(ci->libs[0], "MegaMolCore",
        MEGAMOL_CORE_MAJOR_VER, MEGAMOL_CORE_MINOR_VER, MEGAMOL_CORE_MAJOR_REV, MEGAMOL_CORE_MINOR_REV, 0
#if defined(DEBUG) || defined(_DEBUG)
        | MEGAMOLCORE_PLUGIN200UTIL_FLAGS_DEBUG_BUILD
#endif
#if defined(MEGAMOL_CORE_DIRTY) && (MEGAMOL_CORE_DIRTY != 0)
        | MEGAMOLCORE_PLUGIN200UTIL_FLAGS_DIRTY_BUILD
#endif
        );

    SetLibraryVersionInfo(ci->libs[1], "vislib",
        VISLIB_VERSION_MAJOR, VISLIB_VERSION_MINOR, VISLIB_VERSION_REVISION, VISLIB_VERSION_BUILD, 0
#if defined(DEBUG) || defined(_DEBUG)
        | MEGAMOLCORE_PLUGIN200UTIL_FLAGS_DEBUG_BUILD
#endif
#if defined(VISLIB_DIRTY_BUILD) && (VISLIB_DIRTY_BUILD != 0)
        | MEGAMOLCORE_PLUGIN200UTIL_FLAGS_DIRTY_BUILD
#endif
        );
    //
    // If you want to test additional compatibilties, add the corresponding versions here
    //

    return ci;
}

/*
 * mmplgReleasePluginCompatibilityInfo
 */
MEGAMOLPLUGIN_API
void mmplgReleasePluginCompatibilityInfo(
        ::megamol::core::utility::plugins::PluginCompatibilityInfo* ci) {
    // release compatiblity data on the correct heap
    MEGAMOLCORE_PLUGIN200UTIL_IMPLEMENT_mmplgReleasePluginCompatibilityInfo(ci)
}

/*
 * mmplgGetPluginInstance
 */
MEGAMOLPLUGIN_API
::megamol::core::utility::plugins::AbstractPluginInstance*
mmplgGetPluginInstance(
        ::megamol::core::utility::plugins::ErrorCallback onError) {
    MEGAMOLCORE_PLUGIN200UTIL_IMPLEMENT_mmplgGetPluginInstance(plugin_instance, onError)
}

/*
 * mmplgReleasePluginInstance
 */
MEGAMOLPLUGIN_API
void mmplgReleasePluginInstance(
        ::megamol::core::utility::plugins::AbstractPluginInstance* pi) {
    MEGAMOLCORE_PLUGIN200UTIL_IMPLEMENT_mmplgReleasePluginInstance(pi)
}
<|endoftext|>


<commit_before>/*******************************************************************************
 * examples/word_count.cpp
 *
 * Part of Project c7a.
 *
 *
 * This file has no license. Only Chuck Norris can compile it.
 ******************************************************************************/

#include <c7a/api/bootstrap.hpp>
#include <c7a/api/dia.hpp>

int word_count(c7a::Context& context);

int main(int argc, char* argv[]) {
    return c7a::Execute(argc, argv, word_count);
}

//! The WordCount user program
int word_count(c7a::Context& ctx) {
    using c7a::Context;
    using WordPair = std::pair<std::string, int>;

    auto line_to_words = [](std::string line, std::function<void(WordPair)> emit) {
                             std::string word;
                             std::istringstream iss(line);
                             while (iss >> word) {
                                 WordPair wp = std::make_pair(word, 1);
                                 emit(wp);
                             }
                         };
    auto key = [](WordPair in) {
                   return in.first;
               };
    auto red_fn = [](WordPair in1, WordPair in2) {
                      WordPair wp = std::make_pair(in1.first, in1.second + in2.second);
                      return wp;
                  };

    std::cout << ctx.get_current_dir() + "/tests/inputs/wordcount.in" << std::endl;
    auto lines = ReadFromFileSystem(
        ctx,
        ctx.get_current_dir() + "/tests/inputs/wordcount.in",
        [](const std::string& line) {
            return line;
        });

    auto word_pairs = lines.FlatMap(line_to_words);

    auto red_words = word_pairs.ReduceBy(key).With(red_fn);

    red_words.WriteToFileSystem(ctx.get_current_dir() + "/tests/outputs/wordcount.out",
                                [](const WordPair& item) {
                                    std::string str;
                                    str += item.first;
                                    str += ": ";
                                    str += item.second;
                                    return str;
                                });
    return 0;
}

/******************************************************************************/
<commit_msg>add missing std::to_string() in wordcount example<commit_after>/*******************************************************************************
 * examples/word_count.cpp
 *
 * Part of Project c7a.
 *
 *
 * This file has no license. Only Chuck Norris can compile it.
 ******************************************************************************/

#include <c7a/api/bootstrap.hpp>
#include <c7a/api/dia.hpp>

int word_count(c7a::Context& context);

int main(int argc, char* argv[]) {
    return c7a::Execute(argc, argv, word_count);
}

//! The WordCount user program
int word_count(c7a::Context& ctx) {
    using c7a::Context;
    using WordPair = std::pair<std::string, int>;

    auto line_to_words = [](std::string line, std::function<void(WordPair)> emit) {
                             std::string word;
                             std::istringstream iss(line);
                             while (iss >> word) {
                                 WordPair wp = std::make_pair(word, 1);
                                 emit(wp);
                             }
                         };
    auto key = [](WordPair in) {
                   return in.first;
               };
    auto red_fn = [](WordPair in1, WordPair in2) {
                      WordPair wp = std::make_pair(in1.first, in1.second + in2.second);
                      return wp;
                  };

    std::cout << ctx.get_current_dir() + "/tests/inputs/wordcount.in" << std::endl;
    auto lines = ReadFromFileSystem(
        ctx,
        ctx.get_current_dir() + "/tests/inputs/wordcount.in",
        [](const std::string& line) {
            return line;
        });

    auto word_pairs = lines.FlatMap(line_to_words);

    auto red_words = word_pairs.ReduceBy(key).With(red_fn);

    red_words.WriteToFileSystem(ctx.get_current_dir() + "/tests/outputs/wordcount.out",
                                [](const WordPair& item) {
                                    std::string str;
                                    str += item.first;
                                    str += ": ";
                                    str += std::to_string(item.second);
                                    std::cout << str << std::endl;
                                    return str;
                                });
    return 0;
}

/******************************************************************************/
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: eventsdocumenthandler.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: hr $ $Date: 2001-10-09 18:28:09 $
 *
 *  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 __FRAMEWORK_CLASSES_EVENTSDOCUMENTHANDLER_HXX_
#define __FRAMEWORK_CLASSES_EVENTSDOCUMENTHANDLER_HXX_

#ifndef __FRAMEWORK_CLASSES_TOOLBOXCONFIGURATION_HXX_
#include <classes/eventsconfiguration.hxx>
#endif

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

#ifndef __COM_SUN_STAR_XML_SAX_XDOCUMENTHANDLER_HPP_
#include <com/sun/star/xml/sax/XDocumentHandler.hpp>
#endif

//_________________________________________________________________________________________________________________
//  other includes
//_________________________________________________________________________________________________________________

#ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_
#include <threadhelp/threadhelpbase.hxx>
#endif

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

#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif

#ifndef __SGI_STL_HASH_MAP
#include <hash_map>
#endif

#ifndef __FRAMEWORK_STDTYPES_H_
#include <stdtypes.h>
#endif

//_________________________________________________________________________________________________________________
//  namespace
//_________________________________________________________________________________________________________________

namespace framework{

//*****************************************************************************************************************
// Hash code function for using in all hash maps of follow implementation.

class OReadEventsDocumentHandler :  public ::com::sun::star::xml::sax::XDocumentHandler,
                                    private ThreadHelpBase, // Struct for right initalization of lock member! Must be first of baseclasses.
                                    public ::cppu::OWeakObject
{
    public:
        enum Events_XML_Entry
        {
            EV_ELEMENT_EVENTS,
            EV_ELEMENT_EVENT,
            EV_ATTRIBUTE_TYPE,
            EV_ATTRIBUTE_NAME,
            XL_ATTRIBUTE_HREF,
            XL_ATTRIBUTE_TYPE,
            EV_ATTRIBUTE_MACRONAME,
            EV_ATTRIBUTE_LIBRARY,
            EV_XML_ENTRY_COUNT
        };

        enum Event_XML_Namespace
        {
            EV_NS_EVENT,
            EV_NS_XLINK,
            EV_XML_NAMESPACES_COUNT
        };

        OReadEventsDocumentHandler( EventsConfig& aItems );
        virtual ~OReadEventsDocumentHandler();

        // XInterface
        virtual void SAL_CALL acquire() throw()
            { OWeakObject::acquire(); }
        virtual void SAL_CALL release() throw()
            { OWeakObject::release(); }
        virtual ::com::sun::star::uno::Any SAL_CALL queryInterface(
            const ::com::sun::star::uno::Type & rType ) throw( ::com::sun::star::uno::RuntimeException );

        // XDocumentHandler
        virtual void SAL_CALL startDocument(void)
        throw ( ::com::sun::star::xml::sax::SAXException,
                ::com::sun::star::uno::RuntimeException );

        virtual void SAL_CALL endDocument(void)
        throw(  ::com::sun::star::xml::sax::SAXException,
                ::com::sun::star::uno::RuntimeException );

        virtual void SAL_CALL startElement(
            const rtl::OUString& aName,
            const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > &xAttribs)
        throw(  ::com::sun::star::xml::sax::SAXException,
                ::com::sun::star::uno::RuntimeException );

        virtual void SAL_CALL endElement(const rtl::OUString& aName)
        throw(  ::com::sun::star::xml::sax::SAXException,
                ::com::sun::star::uno::RuntimeException );

        virtual void SAL_CALL characters(const rtl::OUString& aChars)
        throw(  ::com::sun::star::xml::sax::SAXException,
                ::com::sun::star::uno::RuntimeException );

        virtual void SAL_CALL ignorableWhitespace(const rtl::OUString& aWhitespaces)
        throw(  ::com::sun::star::xml::sax::SAXException,
                ::com::sun::star::uno::RuntimeException );

        virtual void SAL_CALL processingInstruction(const rtl::OUString& aTarget,
                                                    const rtl::OUString& aData)
        throw(  ::com::sun::star::xml::sax::SAXException,
                ::com::sun::star::uno::RuntimeException );

        virtual void SAL_CALL setDocumentLocator(
            const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XLocator > &xLocator)
        throw(  ::com::sun::star::xml::sax::SAXException,
                ::com::sun::star::uno::RuntimeException );

    private:
        ::rtl::OUString getErrorLineString();

        class EventsHashMap : public ::std::hash_map<   ::rtl::OUString                 ,
                                                        Events_XML_Entry                ,
                                                        OUStringHashCode                ,
                                                        ::std::equal_to< ::rtl::OUString >  >
        {
            public:
                inline void free()
                {
                    EventsHashMap().swap( *this );
                }
        };

        sal_Bool                                                                    m_bEventsStartFound;
        sal_Bool                                                                    m_bEventsEndFound;
        sal_Bool                                                                    m_bEventStartFound;
        EventsHashMap                                                               m_aEventsMap;
        EventsConfig&                                                               m_aEventItems;
        ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XLocator >    m_xLocator;
};

class OWriteEventsDocumentHandler : private ThreadHelpBase // Struct for right initalization of lock member! Must be first of baseclasses.
{
    public:
        OWriteEventsDocumentHandler(
            const EventsConfig& aItems,
            ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XDocumentHandler > );
        virtual ~OWriteEventsDocumentHandler();

        void WriteEventsDocument() throw
            ( ::com::sun::star::xml::sax::SAXException,
              ::com::sun::star::uno::RuntimeException );

    protected:
        virtual void WriteEvent(
                const ::rtl::OUString& aEventName,
                const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aPropertyValue ) throw
            ( ::com::sun::star::xml::sax::SAXException,
              ::com::sun::star::uno::RuntimeException );

        const EventsConfig&                                                                 m_aItems;
        ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XDocumentHandler >    m_xWriteDocumentHandler;
        ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >      m_xEmptyList;
        ::rtl::OUString                                                                     m_aXMLEventNS;
        ::rtl::OUString                                                                     m_aXMLXlinkNS;
        ::rtl::OUString                                                                     m_aAttributeType;
        ::rtl::OUString                                                                     m_aAttributeURL;
        ::rtl::OUString                                                                     m_aAttributeLanguage;
        ::rtl::OUString                                                                     m_aAttributeLinkType;
        ::rtl::OUString                                                                     m_aAttributeMacroName;
        ::rtl::OUString                                                                     m_aAttributeLibrary;
        ::rtl::OUString                                                                     m_aAttributeName;
};

} // namespace framework

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

#ifndef __FRAMEWORK_CLASSES_EVENTSDOCUMENTHANDLER_HXX_
#define __FRAMEWORK_CLASSES_EVENTSDOCUMENTHANDLER_HXX_

#ifndef __FRAMEWORK_CLASSES_TOOLBOXCONFIGURATION_HXX_
#include <classes/eventsconfiguration.hxx>
#endif

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

#ifndef __COM_SUN_STAR_XML_SAX_XDOCUMENTHANDLER_HPP_
#include <com/sun/star/xml/sax/XDocumentHandler.hpp>
#endif

//_________________________________________________________________________________________________________________
//  other includes
//_________________________________________________________________________________________________________________

#ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_
#include <threadhelp/threadhelpbase.hxx>
#endif

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

#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif

#ifndef __SGI_STL_HASH_MAP
#include <hash_map>
#endif

#ifndef __FRAMEWORK_STDTYPES_H_
#include <stdtypes.h>
#endif

//_________________________________________________________________________________________________________________
//  namespace
//_________________________________________________________________________________________________________________

namespace framework{

//*****************************************************************************************************************
// Hash code function for using in all hash maps of follow implementation.

class OReadEventsDocumentHandler :  public ::com::sun::star::xml::sax::XDocumentHandler,
                                    private ThreadHelpBase, // Struct for right initalization of lock member! Must be first of baseclasses.
                                    public ::cppu::OWeakObject
{
    public:
        enum Events_XML_Entry
        {
            EV_ELEMENT_EVENTS,
            EV_ELEMENT_EVENT,
            EV_ATTRIBUTE_TYPE,
            EV_ATTRIBUTE_NAME,
            XL_ATTRIBUTE_HREF,
            XL_ATTRIBUTE_TYPE,
            EV_ATTRIBUTE_MACRONAME,
            EV_ATTRIBUTE_LIBRARY,
            EV_XML_ENTRY_COUNT
        };

        enum Event_XML_Namespace
        {
            EV_NS_EVENT,
            EV_NS_XLINK,
            EV_XML_NAMESPACES_COUNT
        };

        OReadEventsDocumentHandler( EventsConfig& aItems );
        virtual ~OReadEventsDocumentHandler();

        // XInterface
        virtual void SAL_CALL acquire() throw()
            { OWeakObject::acquire(); }
        virtual void SAL_CALL release() throw()
            { OWeakObject::release(); }
        virtual ::com::sun::star::uno::Any SAL_CALL queryInterface(
            const ::com::sun::star::uno::Type & rType ) throw( ::com::sun::star::uno::RuntimeException );

        // XDocumentHandler
        virtual void SAL_CALL startDocument(void)
        throw ( ::com::sun::star::xml::sax::SAXException,
                ::com::sun::star::uno::RuntimeException );

        virtual void SAL_CALL endDocument(void)
        throw(  ::com::sun::star::xml::sax::SAXException,
                ::com::sun::star::uno::RuntimeException );

        virtual void SAL_CALL startElement(
            const rtl::OUString& aName,
            const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList > &xAttribs)
        throw(  ::com::sun::star::xml::sax::SAXException,
                ::com::sun::star::uno::RuntimeException );

        virtual void SAL_CALL endElement(const rtl::OUString& aName)
        throw(  ::com::sun::star::xml::sax::SAXException,
                ::com::sun::star::uno::RuntimeException );

        virtual void SAL_CALL characters(const rtl::OUString& aChars)
        throw(  ::com::sun::star::xml::sax::SAXException,
                ::com::sun::star::uno::RuntimeException );

        virtual void SAL_CALL ignorableWhitespace(const rtl::OUString& aWhitespaces)
        throw(  ::com::sun::star::xml::sax::SAXException,
                ::com::sun::star::uno::RuntimeException );

        virtual void SAL_CALL processingInstruction(const rtl::OUString& aTarget,
                                                    const rtl::OUString& aData)
        throw(  ::com::sun::star::xml::sax::SAXException,
                ::com::sun::star::uno::RuntimeException );

        virtual void SAL_CALL setDocumentLocator(
            const ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XLocator > &xLocator)
        throw(  ::com::sun::star::xml::sax::SAXException,
                ::com::sun::star::uno::RuntimeException );

    private:
        ::rtl::OUString getErrorLineString();

        class EventsHashMap : public ::std::hash_map<   ::rtl::OUString                 ,
                                                        Events_XML_Entry                ,
                                                        OUStringHashCode                ,
                                                        ::std::equal_to< ::rtl::OUString >  >
        {
            public:
                inline void free()
                {
                    EventsHashMap().swap( *this );
                }
        };

        sal_Bool                                                                    m_bEventsStartFound;
        sal_Bool                                                                    m_bEventsEndFound;
        sal_Bool                                                                    m_bEventStartFound;
        EventsHashMap                                                               m_aEventsMap;
        EventsConfig&                                                               m_aEventItems;
        ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XLocator >    m_xLocator;
};

class OWriteEventsDocumentHandler : private ThreadHelpBase // Struct for right initalization of lock member! Must be first of baseclasses.
{
    public:
        OWriteEventsDocumentHandler(
            const EventsConfig& aItems,
            ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XDocumentHandler > );
        virtual ~OWriteEventsDocumentHandler();

        void WriteEventsDocument() throw
            ( ::com::sun::star::xml::sax::SAXException,
              ::com::sun::star::uno::RuntimeException );

    protected:
        virtual void WriteEvent(
                const ::rtl::OUString& aEventName,
                const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& aPropertyValue ) throw
            ( ::com::sun::star::xml::sax::SAXException,
              ::com::sun::star::uno::RuntimeException );

        const EventsConfig&                                                                 m_aItems;
        ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XDocumentHandler >    m_xWriteDocumentHandler;
        ::com::sun::star::uno::Reference< ::com::sun::star::xml::sax::XAttributeList >      m_xEmptyList;
        ::rtl::OUString                                                                     m_aXMLEventNS;
        ::rtl::OUString                                                                     m_aXMLXlinkNS;
        ::rtl::OUString                                                                     m_aAttributeType;
        ::rtl::OUString                                                                     m_aAttributeURL;
        ::rtl::OUString                                                                     m_aAttributeLanguage;
        ::rtl::OUString                                                                     m_aAttributeLinkType;
        ::rtl::OUString                                                                     m_aAttributeMacroName;
        ::rtl::OUString                                                                     m_aAttributeLibrary;
        ::rtl::OUString                                                                     m_aAttributeName;
};

} // namespace framework

#endif
<|endoftext|>


<commit_before>#include <memory>
#include <algorithm>
#include <stdexcept>
#include <system_error>
#include <random>

#include <realm/util/features.h>
#include <realm/util/assert.hpp>
#include <realm/util/basic_system_errors.hpp>
#include <realm/impl/simulated_failure.hpp>

#if REALM_PLATFORM_APPLE
#  define USE_PTHREADS_IMPL 1
#else
#  define USE_PTHREADS_IMPL 0
#endif

#if USE_PTHREADS_IMPL
#  include <pthread.h>
#endif

using namespace realm;
using namespace realm::_impl;

#ifdef REALM_ENABLE_SIMULATED_FAILURE

namespace {

const int num_failure_types = SimulatedFailure::_num_failure_types;

struct PrimeMode {
    virtual bool check_trigger() noexcept = 0;
    virtual ~PrimeMode() noexcept {}
};

struct PrimeState {
    std::unique_ptr<PrimeMode> slots[num_failure_types];
};

struct OneShotPrimeMode: PrimeMode {
    bool triggered = false;
    bool check_trigger() noexcept override
    {
        if (triggered)
            return false;
        triggered = true;
        return true;
    }
};

struct RandomPrimeMode: PrimeMode {
    std::mt19937_64 random;
    std::uniform_int_distribution<int> dist;
    int n;
    RandomPrimeMode(int n, int m, uint_fast64_t seed):
        random(seed),
        dist(0, m-1),
        n(n)
    {
        REALM_ASSERT(n >= 0 && m > 0);
    }
    bool check_trigger() noexcept override
    {
        int i = dist(random);
        return i < n;
    }
};

#  if !USE_PTHREADS_IMPL

thread_local PrimeState t_prime_state;

PrimeState& get() noexcept
{
    return t_prime_state;
}

#  else // USE_PTHREADS_IMPL

pthread_key_t key;
pthread_once_t key_once = PTHREAD_ONCE_INIT;

void destroy(void* ptr) noexcept
{
    PrimeState* prime_state = static_cast<PrimeState*>(ptr);
    delete prime_state;
}

void create() noexcept
{
    int ret = pthread_key_create(&key, &destroy);
    if (REALM_UNLIKELY(ret != 0)) {
        std::error_code ec = util::make_basic_system_error_code(errno);
        throw std::system_error(ec); // Termination intended
    }
}

PrimeState& get() noexcept
{
    pthread_once(&key_once, &create);
    void* ptr = pthread_getspecific(key);
    PrimeState* prime_state = static_cast<PrimeState*>(ptr);
    if (!prime_state) {
        prime_state = new PrimeState; // Throws with intended termination
        int ret = pthread_setspecific(key, prime_state);
        if (REALM_UNLIKELY(ret != 0)) {
            std::error_code ec = util::make_basic_system_error_code(errno);
            throw std::system_error(ec); // Termination intended
        }
    }
    return *prime_state;
}

#  endif // USE_PTHREADS_IMPL

} // unnamed namespace

void SimulatedFailure::do_prime_one_shot(FailureType failure_type)
{
    PrimeState& state = get();
    if (state.slots[failure_type])
        throw std::runtime_error("Already primed");
    state.slots[failure_type].reset(new OneShotPrimeMode); // Throws
}

void SimulatedFailure::do_prime_random(FailureType failure_type, int n, int m, uint_fast64_t seed)
{
    PrimeState& state = get();
    if (state.slots[failure_type])
        throw std::runtime_error("Already primed");
    state.slots[failure_type].reset(new RandomPrimeMode(n, m, seed)); // Throws
}

void SimulatedFailure::do_unprime(FailureType failure_type) noexcept
{
    PrimeState& state = get();
    state.slots[failure_type].reset();
}

bool SimulatedFailure::do_check_trigger(FailureType failure_type) noexcept
{
    PrimeState& state = get();
    if (PrimeMode* p = state.slots[failure_type].get())
        return p->check_trigger();
    return false;
}

#endif // REALM_ENABLE_SIMULATED_FAILURE

namespace {

class ErrorCategory: public std::error_category {
public:
    const char* name() const noexcept override;
    std::string message(int) const override;
};

const ErrorCategory g_error_category{};

const char* ErrorCategory::name() const noexcept
{
    return "realm.simulated_failure";
}

std::string ErrorCategory::message(int value) const
{
    switch (SimulatedFailure::FailureType(value)) {
        case SimulatedFailure::generic:
            return "Simulated failure (generic)";
        case SimulatedFailure::slab_alloc__reset_free_space_tracking:
            return "Simulated failure (slab_alloc__reset_free_space_tracking)";
        case SimulatedFailure::slab_alloc__remap:
            return "Simulated failure (slab_alloc__remap)";
        case SimulatedFailure::shared_group__grow_reader_mapping:
            return "Simulated failure (shared_group__grow_reader_mapping)";
        case SimulatedFailure::sync_client__read_head:
            return "Simulated failure (sync_client__read_head)";
        case SimulatedFailure::sync_server__read_head:
            return "Simulated failure (sync_server__read_head)";
        case SimulatedFailure::_num_failure_types:
            break;
    }
    REALM_ASSERT(false);
    return std::string();
}

} // unnamed namespace

namespace realm {
namespace _impl {

std::error_code make_error_code(SimulatedFailure::FailureType failure_type) noexcept
{
    return std::error_code(failure_type, g_error_category);
}

} // namespace _impl
} // namespace realm
<commit_msg>simulated_failure shouldn't use thread_local on Android<commit_after>#include <memory>
#include <algorithm>
#include <stdexcept>
#include <system_error>
#include <random>

#include <realm/util/features.h>
#include <realm/util/assert.hpp>
#include <realm/util/basic_system_errors.hpp>
#include <realm/impl/simulated_failure.hpp>

#if REALM_PLATFORM_APPLE || REALM_ANDROID
#  define USE_PTHREADS_IMPL 1
#else
#  define USE_PTHREADS_IMPL 0
#endif

#if USE_PTHREADS_IMPL
#  include <pthread.h>
#endif

using namespace realm;
using namespace realm::_impl;

#ifdef REALM_ENABLE_SIMULATED_FAILURE

namespace {

const int num_failure_types = SimulatedFailure::_num_failure_types;

struct PrimeMode {
    virtual bool check_trigger() noexcept = 0;
    virtual ~PrimeMode() noexcept {}
};

struct PrimeState {
    std::unique_ptr<PrimeMode> slots[num_failure_types];
};

struct OneShotPrimeMode: PrimeMode {
    bool triggered = false;
    bool check_trigger() noexcept override
    {
        if (triggered)
            return false;
        triggered = true;
        return true;
    }
};

struct RandomPrimeMode: PrimeMode {
    std::mt19937_64 random;
    std::uniform_int_distribution<int> dist;
    int n;
    RandomPrimeMode(int n, int m, uint_fast64_t seed):
        random(seed),
        dist(0, m-1),
        n(n)
    {
        REALM_ASSERT(n >= 0 && m > 0);
    }
    bool check_trigger() noexcept override
    {
        int i = dist(random);
        return i < n;
    }
};

#  if !USE_PTHREADS_IMPL

thread_local PrimeState t_prime_state;

PrimeState& get() noexcept
{
    return t_prime_state;
}

#  else // USE_PTHREADS_IMPL

pthread_key_t key;
pthread_once_t key_once = PTHREAD_ONCE_INIT;

void destroy(void* ptr) noexcept
{
    PrimeState* prime_state = static_cast<PrimeState*>(ptr);
    delete prime_state;
}

void create() noexcept
{
    int ret = pthread_key_create(&key, &destroy);
    if (REALM_UNLIKELY(ret != 0)) {
        std::error_code ec = util::make_basic_system_error_code(errno);
        throw std::system_error(ec); // Termination intended
    }
}

PrimeState& get() noexcept
{
    pthread_once(&key_once, &create);
    void* ptr = pthread_getspecific(key);
    PrimeState* prime_state = static_cast<PrimeState*>(ptr);
    if (!prime_state) {
        prime_state = new PrimeState; // Throws with intended termination
        int ret = pthread_setspecific(key, prime_state);
        if (REALM_UNLIKELY(ret != 0)) {
            std::error_code ec = util::make_basic_system_error_code(errno);
            throw std::system_error(ec); // Termination intended
        }
    }
    return *prime_state;
}

#  endif // USE_PTHREADS_IMPL

} // unnamed namespace

void SimulatedFailure::do_prime_one_shot(FailureType failure_type)
{
    PrimeState& state = get();
    if (state.slots[failure_type])
        throw std::runtime_error("Already primed");
    state.slots[failure_type].reset(new OneShotPrimeMode); // Throws
}

void SimulatedFailure::do_prime_random(FailureType failure_type, int n, int m, uint_fast64_t seed)
{
    PrimeState& state = get();
    if (state.slots[failure_type])
        throw std::runtime_error("Already primed");
    state.slots[failure_type].reset(new RandomPrimeMode(n, m, seed)); // Throws
}

void SimulatedFailure::do_unprime(FailureType failure_type) noexcept
{
    PrimeState& state = get();
    state.slots[failure_type].reset();
}

bool SimulatedFailure::do_check_trigger(FailureType failure_type) noexcept
{
    PrimeState& state = get();
    if (PrimeMode* p = state.slots[failure_type].get())
        return p->check_trigger();
    return false;
}

#endif // REALM_ENABLE_SIMULATED_FAILURE

namespace {

class ErrorCategory: public std::error_category {
public:
    const char* name() const noexcept override;
    std::string message(int) const override;
};

const ErrorCategory g_error_category{};

const char* ErrorCategory::name() const noexcept
{
    return "realm.simulated_failure";
}

std::string ErrorCategory::message(int value) const
{
    switch (SimulatedFailure::FailureType(value)) {
        case SimulatedFailure::generic:
            return "Simulated failure (generic)";
        case SimulatedFailure::slab_alloc__reset_free_space_tracking:
            return "Simulated failure (slab_alloc__reset_free_space_tracking)";
        case SimulatedFailure::slab_alloc__remap:
            return "Simulated failure (slab_alloc__remap)";
        case SimulatedFailure::shared_group__grow_reader_mapping:
            return "Simulated failure (shared_group__grow_reader_mapping)";
        case SimulatedFailure::sync_client__read_head:
            return "Simulated failure (sync_client__read_head)";
        case SimulatedFailure::sync_server__read_head:
            return "Simulated failure (sync_server__read_head)";
        case SimulatedFailure::_num_failure_types:
            break;
    }
    REALM_ASSERT(false);
    return std::string();
}

} // unnamed namespace

namespace realm {
namespace _impl {

std::error_code make_error_code(SimulatedFailure::FailureType failure_type) noexcept
{
    return std::error_code(failure_type, g_error_category);
}

} // namespace _impl
} // namespace realm
<|endoftext|>


<commit_before>/*
 * Author: Brendan Le Foll <brendan.le.foll@intel.com>
 * Copyright (c) 2014 Intel Corporation.
 *
 * 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 <iostream>

//! [Interesting]
#include "lsm303.h"

int
main(int argc, char **argv)
{
    upm::LSM303 *sensor = new upm::LSM303(0);

    sensor->getCoordinates();
    int16_t* coor = sensor->getRawCoorData(); // in XZY order
    std::cout << "coor: rX " << (int)coor[0]
              << " - rY " << (int)coor[2]  // note: index is 2
              << " - rZ " << (int)coor[1]  // note: index is 1
              << std::endl;
    std::cout << "coor: gX " << sensor->getCoorX()
              << " - gY " << sensor->getCoorY()
              << " - gZ " << sensor->getCoorZ()
              << std::endl;

    std::cout << "heading: "
              << sensor->getHeading()
              << std::endl;

    sensor->getAcceleration();
    int16_t* accel = sensor->getRawAccelData();
    std::cout << "acc: rX " << (int)accel[0]
              << " - rY " << (int)accel[1]
              << " - Z " << (int)accel[2]
              << std::endl;
    std::cout << "acc: gX " << sensor->getAccelX()
              << " - gY " << sensor->getAccelY()
              << " - gZ " << sensor->getAccelZ()
              << std::endl;

    return 0;
}
//! [Interesting]
<commit_msg>lsm303: Modifying C++ example<commit_after>/*
 * Author: Brendan Le Foll <brendan.le.foll@intel.com>
 * Copyright (c) 2014 Intel Corporation.
 *
 * 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 <iostream>

//! [Interesting]
#include "lsm303.h"

int
main(int argc, char **argv)
{
	// Instantiate LSM303 compass on I2C
    upm::LSM303 *sensor = new upm::LSM303(0);

    // Get the coordinate data
    sensor->getCoordinates();
    int16_t* coor = sensor->getRawCoorData(); // in XYZ order.
    // The sensor returns XZY, but the driver compensates and makes it XYZ

    // Print out the X, Y, and Z coordinate data using two different methods
    std::cout << "coor: rX " << (int)coor[0]
              << " - rY " << (int)coor[1]
              << " - rZ " << (int)coor[2]
              << std::endl;
    std::cout << "coor: gX " << sensor->getCoorX()
              << " - gY " << sensor->getCoorY()
              << " - gZ " << sensor->getCoorZ()
              << std::endl;

    // Get and print out the heading
    std::cout << "heading: "
              << sensor->getHeading()
              << std::endl;

    // Get the acceleration
    sensor->getAcceleration();
    int16_t* accel = sensor->getRawAccelData();
    // Print out the X, Y, and Z acceleration data using two different methods
    std::cout << "acc: rX " << (int)accel[0]
              << " - rY " << (int)accel[1]
              << " - Z " << (int)accel[2]
              << std::endl;
    std::cout << "acc: gX " << sensor->getAccelX()
              << " - gY " << sensor->getAccelY()
              << " - gZ " << sensor->getAccelZ()
              << std::endl;

    return 0;
}
//! [Interesting]
<|endoftext|>


<commit_before>#include <reactive.hpp>
#include <thread-pool.hpp>
#include <iostream>
#include <chrono>
#include <string>

int main() {
  using namespace std::chrono_literals;
  using namespace reactive;
  ThreadPool Pool(4);

  auto p = pipe(
    repeat(4, [](auto x){ return x; } ),
    forEach( [](auto x){ std::cout << "in: " << x <<std::endl;}),
    scan(0, [](auto x, auto y) { return x+y; }),
    map([](auto x){ return x+1;}),
    filter([](auto x) { return x != 4; }),
    wait(1s),
    asyncify(Pool),
    [](auto x) {
      std::cout<< ("out: " + std::to_string( x )  ) << std::endl;
      return x%7;
    }
  ).create();

  p(1);
  p(2);

  return 0;
}
<commit_msg>minor changes to simple.cpp<commit_after>#include <reactive.hpp>
#include <thread-pool.hpp>
#include <iostream>
#include <chrono>
#include <string>

int main() {
  using namespace std::chrono_literals;
  using namespace reactive;
  ThreadPool Pool(4);

  auto p = pipe(
    repeat(4, [](auto x){ return x; } ),
    forEach( [](auto x){ std::cout << "in: " << x <<std::endl;}),
    scan(0, [](auto x, auto y) { return x+y; }),
    map([](auto x){ return x+1;}),
    filter([](auto x) { return x != 4; }),
    wait(1s),
    asyncify(Pool)
  );

  auto sink = p.pipe([](auto x) {
    std::cout<< ("out: " + std::to_string( x )  ) << std::endl;
  }).create();

  sink(1);
  sink(2);

  return 0;
}
<|endoftext|>


<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "app/gfx/chrome_canvas.h"

#include <pango/pango.h>

#include "app/gfx/chrome_font.h"
#include "base/gfx/rect.h"
#include "base/logging.h"
#include "base/string_util.h"

namespace {

// Returns a new pango font, free with pango_font_description_free().
PangoFontDescription* PangoFontFromChromeFont(const ChromeFont& chrome_font) {
  ChromeFont font = chrome_font;  // Copy so we can call non-const methods.
  PangoFontDescription* pfd = pango_font_description_new();
  pango_font_description_set_family(pfd, WideToUTF8(font.FontName()).c_str());
  pango_font_description_set_size(pfd, font.FontSize() * PANGO_SCALE);

  switch (font.style()) {
    case ChromeFont::NORMAL:
      // Nothing to do, should already be PANGO_STYLE_NORMAL.
      break;
    case ChromeFont::BOLD:
      pango_font_description_set_weight(pfd, PANGO_WEIGHT_BOLD);
      break;
    case ChromeFont::ITALIC:
      pango_font_description_set_style(pfd, PANGO_STYLE_ITALIC);
      break;
    case ChromeFont::UNDERLINED:
      // TODO(deanm): How to do underlined?  Where do we use it?  Probably have
      // to paint it ourselves, see pango_font_metrics_get_underline_position.
      break;
  }

  return pfd;
}

}  // namespace

ChromeCanvas::ChromeCanvas(int width, int height, bool is_opaque)
    : skia::PlatformCanvasLinux(width, height, is_opaque) {
}

ChromeCanvas::ChromeCanvas() : skia::PlatformCanvasLinux() {
}

ChromeCanvas::~ChromeCanvas() {
}

// static
void ChromeCanvas::SizeStringInt(const std::wstring& text,
                                 const ChromeFont& font,
                                 int* width, int* height, int flags) {
  NOTIMPLEMENTED();
}

void ChromeCanvas::ApplySkiaMatrixToCairoContext(cairo_t* cr) {
  const SkMatrix& skia_matrix = getTotalMatrix();
  cairo_matrix_t cairo_matrix;
  cairo_matrix_init(&cairo_matrix,
                    SkScalarToFloat(skia_matrix.getScaleX()),
                    SkScalarToFloat(skia_matrix.getSkewY()),
                    SkScalarToFloat(skia_matrix.getSkewX()),
                    SkScalarToFloat(skia_matrix.getScaleY()),
                    SkScalarToFloat(skia_matrix.getTranslateX()),
                    SkScalarToFloat(skia_matrix.getTranslateY()));
  cairo_set_matrix(cr, &cairo_matrix);
}

void ChromeCanvas::DrawStringInt(const std::wstring& text,
                                 const ChromeFont& font,
                                 const SkColor& color, int x, int y, int w,
                                 int h, int flags) {
  cairo_surface_t* surface = beginPlatformPaint();
  cairo_t* cr = cairo_create(surface);
  // We're going to draw onto the surface directly. This circumvents the matrix
  // installed by Skia. Apply the matrix from skia to cairo so they align and
  // we draw at the right place.
  ApplySkiaMatrixToCairoContext(cr);
  PangoLayout* layout = pango_cairo_create_layout(cr);

  cairo_set_source_rgb(cr,
                       SkColorGetR(color) / 255.0,
                       SkColorGetG(color) / 255.0,
                       SkColorGetB(color) / 255.0);

  // TODO(deanm): Implement the rest of the ChromeCanvas flags.
  if (!(flags & ChromeCanvas::NO_ELLIPSIS))
    pango_layout_set_ellipsize(layout, PANGO_ELLIPSIZE_END);

  pango_layout_set_width(layout, w * PANGO_SCALE);
  pango_layout_set_height(layout, h * PANGO_SCALE);

  if (flags & TEXT_ALIGN_CENTER) {
    pango_layout_set_alignment(layout, PANGO_ALIGN_CENTER);
  } else if (flags & TEXT_ALIGN_RIGHT) {
    pango_layout_set_alignment(layout, PANGO_ALIGN_RIGHT);
  }

  std::string utf8 = WideToUTF8(text);
  pango_layout_set_text(layout, utf8.data(), utf8.size());

  PangoFontDescription* desc = PangoFontFromChromeFont(font);
  pango_layout_set_font_description(layout, desc);
  pango_font_description_free(desc);

  int width, height;
  pango_layout_get_size(layout, &width, &height);

  if (flags & ChromeCanvas::TEXT_VALIGN_TOP) {
    // Cairo should draw from the top left corner already.
  } else if (flags & ChromeCanvas::TEXT_VALIGN_BOTTOM) {
    y = y + (h - (height / PANGO_SCALE));
  } else {
    // Vertically centered.
    y = y + ((h - (height / PANGO_SCALE)) / 2);
  }

  cairo_move_to(cr, x, y);
  pango_cairo_show_layout(cr, layout);

  g_object_unref(layout);
  cairo_destroy(cr);
  // NOTE: beginPlatformPaint returned its surface, we shouldn't destroy it.
}
<commit_msg>Honor MULTI_LINE, CHARACTER_BREAK, and NO_ELLIPSIS in Linux ChromeCanvas.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "app/gfx/chrome_canvas.h"

#include <pango/pango.h>

#include "app/gfx/chrome_font.h"
#include "base/gfx/rect.h"
#include "base/logging.h"
#include "base/string_util.h"

namespace {

// Returns a new pango font, free with pango_font_description_free().
PangoFontDescription* PangoFontFromChromeFont(const ChromeFont& chrome_font) {
  ChromeFont font = chrome_font;  // Copy so we can call non-const methods.
  PangoFontDescription* pfd = pango_font_description_new();
  pango_font_description_set_family(pfd, WideToUTF8(font.FontName()).c_str());
  pango_font_description_set_size(pfd, font.FontSize() * PANGO_SCALE);

  switch (font.style()) {
    case ChromeFont::NORMAL:
      // Nothing to do, should already be PANGO_STYLE_NORMAL.
      break;
    case ChromeFont::BOLD:
      pango_font_description_set_weight(pfd, PANGO_WEIGHT_BOLD);
      break;
    case ChromeFont::ITALIC:
      pango_font_description_set_style(pfd, PANGO_STYLE_ITALIC);
      break;
    case ChromeFont::UNDERLINED:
      // TODO(deanm): How to do underlined?  Where do we use it?  Probably have
      // to paint it ourselves, see pango_font_metrics_get_underline_position.
      break;
  }

  return pfd;
}

}  // namespace

ChromeCanvas::ChromeCanvas(int width, int height, bool is_opaque)
    : skia::PlatformCanvasLinux(width, height, is_opaque) {
}

ChromeCanvas::ChromeCanvas() : skia::PlatformCanvasLinux() {
}

ChromeCanvas::~ChromeCanvas() {
}

// static
void ChromeCanvas::SizeStringInt(const std::wstring& text,
                                 const ChromeFont& font,
                                 int* width, int* height, int flags) {
  NOTIMPLEMENTED();
}

void ChromeCanvas::ApplySkiaMatrixToCairoContext(cairo_t* cr) {
  const SkMatrix& skia_matrix = getTotalMatrix();
  cairo_matrix_t cairo_matrix;
  cairo_matrix_init(&cairo_matrix,
                    SkScalarToFloat(skia_matrix.getScaleX()),
                    SkScalarToFloat(skia_matrix.getSkewY()),
                    SkScalarToFloat(skia_matrix.getSkewX()),
                    SkScalarToFloat(skia_matrix.getScaleY()),
                    SkScalarToFloat(skia_matrix.getTranslateX()),
                    SkScalarToFloat(skia_matrix.getTranslateY()));
  cairo_set_matrix(cr, &cairo_matrix);
}

void ChromeCanvas::DrawStringInt(const std::wstring& text,
                                 const ChromeFont& font,
                                 const SkColor& color, int x, int y, int w,
                                 int h, int flags) {
  cairo_surface_t* surface = beginPlatformPaint();
  cairo_t* cr = cairo_create(surface);
  // We're going to draw onto the surface directly. This circumvents the matrix
  // installed by Skia. Apply the matrix from skia to cairo so they align and
  // we draw at the right place.
  ApplySkiaMatrixToCairoContext(cr);
  PangoLayout* layout = pango_cairo_create_layout(cr);

  cairo_set_source_rgb(cr,
                       SkColorGetR(color) / 255.0,
                       SkColorGetG(color) / 255.0,
                       SkColorGetB(color) / 255.0);

  // TODO(deanm): Implement the rest of the ChromeCanvas flags.
  if (!(flags & ChromeCanvas::NO_ELLIPSIS))
    pango_layout_set_ellipsize(layout, PANGO_ELLIPSIZE_END);

  pango_layout_set_width(layout, w * PANGO_SCALE);
  pango_layout_set_height(layout, h * PANGO_SCALE);

  if (flags & TEXT_ALIGN_CENTER) {
    pango_layout_set_alignment(layout, PANGO_ALIGN_CENTER);
  } else if (flags & TEXT_ALIGN_RIGHT) {
    pango_layout_set_alignment(layout, PANGO_ALIGN_RIGHT);
  }

  if (flags & MULTI_LINE) {
    pango_layout_set_wrap(layout,
        (flags & CHARACTER_BREAK) ? PANGO_WRAP_WORD_CHAR : PANGO_WRAP_WORD);
  }

  if (flags & NO_ELLIPSIS)
    pango_layout_set_ellipsize(layout, PANGO_ELLIPSIZE_NONE);

  std::string utf8 = WideToUTF8(text);
  pango_layout_set_text(layout, utf8.data(), utf8.size());

  PangoFontDescription* desc = PangoFontFromChromeFont(font);
  pango_layout_set_font_description(layout, desc);
  pango_font_description_free(desc);

  int width, height;
  pango_layout_get_size(layout, &width, &height);

  if (flags & ChromeCanvas::TEXT_VALIGN_TOP) {
    // Cairo should draw from the top left corner already.
  } else if (flags & ChromeCanvas::TEXT_VALIGN_BOTTOM) {
    y = y + (h - (height / PANGO_SCALE));
  } else {
    // Vertically centered.
    y = y + ((h - (height / PANGO_SCALE)) / 2);
  }

  cairo_move_to(cr, x, y);
  pango_cairo_show_layout(cr, layout);

  g_object_unref(layout);
  cairo_destroy(cr);
  // NOTE: beginPlatformPaint returned its surface, we shouldn't destroy it.
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2008, Willow Garage, Inc.
 * 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 Willow Garage, Inc. 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.
 */

#include "stl_loader.h"
#include <ros/console.h>

#include <OgreManualObject.h>

namespace ogre_tools
{

STLLoader::STLLoader()
{

}

STLLoader::~STLLoader()
{

}

bool STLLoader::load(const std::string& path)
{
  FILE* input = fopen( path.c_str(), "r" );
  if ( !input )
  {
    ROS_ERROR( "Could not open '%s' for read", path.c_str() );
    return false;
  }

  /* from wikipedia:
   * Because ASCII STL files can become very large, a binary version of STL exists. A binary STL file has an 80 character header
   * (which is generally ignored - but which should never begin with 'solid' because that will lead most software to assume that
   * this is an ASCII STL file). Following the header is a 4 byte unsigned integer indicating the number of triangular facets in
   * the file. Following that is data describing each triangle in turn. The file simply ends after the last triangle.
   *
   * Each triangle is described by twelve 32-bit-floating point numbers: three for the normal and then three for the X/Y/Z coordinate
   * of each vertex - just as with the ASCII version of STL. After the twelve floats there is a two byte unsigned 'short' integer that
   * is the 'attribute byte count' - in the standard format, this should be zero because most software does not understand anything else.
   *
   * Floating point numbers are represented as IEEE floating point numbers and the endianness is assumed to be little endian although this
   * is not stated in documentation.
   */

  // find the file size
  fseek( input, 0, SEEK_END );
  long fileSize = ftell( input );
  rewind( input );

  std::vector<uint8_t> buffer_vec(fileSize);
  uint8_t* buffer = &buffer_vec[0];

  long num_bytes_read = fread( buffer, 1, fileSize, input );
  if ( num_bytes_read != fileSize )
  {
    ROS_ERROR("STLLoader::load( \"%s\" ) only read %ld bytes out of total %ld.",
              path.c_str(), num_bytes_read, fileSize);
    fclose( input );
    return false;
  }
  fclose( input );

  return this->load(buffer, num_bytes_read, path);
}

bool STLLoader::load(uint8_t* buffer, const size_t num_bytes, const std::string& origin)
{
  // check for ascii since we can only load binary types with this class
  std::string buffer_str = std::string(reinterpret_cast<char *>(buffer), num_bytes);

  if (buffer_str.substr(0, 5) == std::string("solid"))
  {
    // file says that it is ascii, but why should we trust it?

    // check for "endsolid" as well
    if (buffer_str.find("endsolid", 5) != std::string::npos)
    {
      ROS_ERROR_STREAM("The STL file '" << origin << "' is malformed. It "
                       "starts with the word 'solid' and also contains the "
                       "word 'endsolid', indicating that it's an ASCII STL "
                       "file, but rviz can only load binary STL files so it "
                       "will not be loaded. Please convert it to a "
                       "binary STL file.");
      return false;
    }

    // chastise the user for malformed files
    ROS_WARN_STREAM("The STL file '" << origin << "' is malformed. It starts"
                    " with the word 'solid', indicating that it's an ASCII "
                    "STL file, but it does not contain the word 'endsolid' so"
                    "it is either a malformed ASCII STL file or it is actually "
                    "a binary STL file. Trying to interpret it as a binary "
                    "STL file instead.");
  }

  // make sure there's enough data for a binary STL header and triangle count
  static const size_t binary_stl_header_len = 84;
  if (num_bytes <= binary_stl_header_len)
  {
    ROS_ERROR_STREAM("The STL file '" << origin <<"' is malformed. It "
                     "appears to be a binary STL file but does not contain "
                     "enough data for the 80 byte header and 16-bit integer "
                     "triangle count.");
    return false;
  }

  // one last check to make sure that the size matches the number of triangles
  unsigned int num_triangles = *(reinterpret_cast<uint32_t *>(buffer + 80));
  static const size_t number_of_bytes_per_triangle = 50;
  size_t expected_size = binary_stl_header_len + num_triangles * number_of_bytes_per_triangle;
  if (num_bytes != expected_size)
  {
    ROS_ERROR_STREAM("The STL file '" << origin << "' is malformed. According "
                     "to the binary STL header it should have '" <<
                     num_triangles << "' triangles, but it has too " <<
                     (num_bytes > expected_size ? "much" : "little") <<
                     " data for that to be the case.");
    return false;
  }

  // load the binary STL data
  return this->load_binary(buffer);
}

bool STLLoader::load_binary(uint8_t* buffer)
{
  uint8_t* pos = buffer;

  pos += 80; // skip the 80 byte header

  unsigned int numTriangles = *(unsigned int*)pos;
  pos += 4;

  for ( unsigned int currentTriangle = 0; currentTriangle < numTriangles; ++currentTriangle )
  {
    Triangle tri;

    tri.normal_.x = *(float*)pos;
    pos += 4;
    tri.normal_.y = *(float*)pos;
    pos += 4;
    tri.normal_.z = *(float*)pos;
    pos += 4;

    tri.vertices_[0].x = *(float*)pos;
    pos += 4;
    tri.vertices_[0].y = *(float*)pos;
    pos += 4;
    tri.vertices_[0].z = *(float*)pos;
    pos += 4;

    tri.vertices_[1].x = *(float*)pos;
    pos += 4;
    tri.vertices_[1].y = *(float*)pos;
    pos += 4;
    tri.vertices_[1].z = *(float*)pos;
    pos += 4;

    tri.vertices_[2].x = *(float*)pos;
    pos += 4;
    tri.vertices_[2].y = *(float*)pos;
    pos += 4;
    tri.vertices_[2].z = *(float*)pos;
    pos += 4;

    // Blender was writing a large number into this short... am I misinterpreting what the attribute byte count is supposed to do?
    //unsigned short attributeByteCount = *(unsigned short*)pos;
    pos += 2;

    //pos += attributeByteCount;

    if (tri.normal_.squaredLength() < 0.001)
    {
      Ogre::Vector3 side1 = tri.vertices_[0] - tri.vertices_[1];
      Ogre::Vector3 side2 = tri.vertices_[1] - tri.vertices_[2];
      tri.normal_ = side1.crossProduct(side2);
    }
    tri.normal_.normalise();

    triangles_.push_back(tri);
  }

  return true;
}

void calculateUV(const Ogre::Vector3& vec, float& u, float& v)
{
  Ogre::Vector3 pos(vec);
  pos.normalise();
  u = acos( pos.y / pos.length() );

  float val = pos.x / ( sin( u ) );
  v = acos( val );

  u /= Ogre::Math::PI;
  v /= Ogre::Math::PI;
}

Ogre::MeshPtr STLLoader::toMesh(const std::string& name)
{
  Ogre::ManualObject* object = new Ogre::ManualObject( "the one and only" );
  object->begin( "BaseWhiteNoLighting", Ogre::RenderOperation::OT_TRIANGLE_LIST );

  unsigned int vertexCount = 0;
  V_Triangle::const_iterator it = triangles_.begin();
  V_Triangle::const_iterator end = triangles_.end();
  for (; it != end; ++it )
  {
    if( vertexCount >= 2004 )
    {
      // Subdivide large meshes into submeshes with at most 2004
      // vertices to prevent problems on some graphics cards.
      object->end();
      object->begin( "BaseWhiteNoLighting", Ogre::RenderOperation::OT_TRIANGLE_LIST );
      vertexCount = 0;
    }

    const STLLoader::Triangle& tri = *it;

    float u, v;
    u = v = 0.0f;
    object->position( tri.vertices_[0] );
    object->normal( tri.normal_);
    calculateUV( tri.vertices_[0], u, v );
    object->textureCoord( u, v );

    object->position( tri.vertices_[1] );
    object->normal( tri.normal_);
    calculateUV( tri.vertices_[1], u, v );
    object->textureCoord( u, v );

    object->position( tri.vertices_[2] );
    object->normal( tri.normal_);
    calculateUV( tri.vertices_[2], u, v );
    object->textureCoord( u, v );

    object->triangle( vertexCount + 0, vertexCount + 1, vertexCount + 2 );

    vertexCount += 3;
  }

  object->end();

  Ogre::MeshPtr mesh = object->convertToMesh( name, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME );
  mesh->buildEdgeList();

  delete object;

  return mesh;
}

}
<commit_msg>Updated warning message to indicate triangle count is a 32bit integer, not 16.<commit_after>/*
 * Copyright (c) 2008, Willow Garage, Inc.
 * 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 Willow Garage, Inc. 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.
 */

#include "stl_loader.h"
#include <ros/console.h>

#include <OgreManualObject.h>

namespace ogre_tools
{

STLLoader::STLLoader()
{

}

STLLoader::~STLLoader()
{

}

bool STLLoader::load(const std::string& path)
{
  FILE* input = fopen( path.c_str(), "r" );
  if ( !input )
  {
    ROS_ERROR( "Could not open '%s' for read", path.c_str() );
    return false;
  }

  /* from wikipedia:
   * Because ASCII STL files can become very large, a binary version of STL exists. A binary STL file has an 80 character header
   * (which is generally ignored - but which should never begin with 'solid' because that will lead most software to assume that
   * this is an ASCII STL file). Following the header is a 4 byte unsigned integer indicating the number of triangular facets in
   * the file. Following that is data describing each triangle in turn. The file simply ends after the last triangle.
   *
   * Each triangle is described by twelve 32-bit-floating point numbers: three for the normal and then three for the X/Y/Z coordinate
   * of each vertex - just as with the ASCII version of STL. After the twelve floats there is a two byte unsigned 'short' integer that
   * is the 'attribute byte count' - in the standard format, this should be zero because most software does not understand anything else.
   *
   * Floating point numbers are represented as IEEE floating point numbers and the endianness is assumed to be little endian although this
   * is not stated in documentation.
   */

  // find the file size
  fseek( input, 0, SEEK_END );
  long fileSize = ftell( input );
  rewind( input );

  std::vector<uint8_t> buffer_vec(fileSize);
  uint8_t* buffer = &buffer_vec[0];

  long num_bytes_read = fread( buffer, 1, fileSize, input );
  if ( num_bytes_read != fileSize )
  {
    ROS_ERROR("STLLoader::load( \"%s\" ) only read %ld bytes out of total %ld.",
              path.c_str(), num_bytes_read, fileSize);
    fclose( input );
    return false;
  }
  fclose( input );

  return this->load(buffer, num_bytes_read, path);
}

bool STLLoader::load(uint8_t* buffer, const size_t num_bytes, const std::string& origin)
{
  // check for ascii since we can only load binary types with this class
  std::string buffer_str = std::string(reinterpret_cast<char *>(buffer), num_bytes);

  if (buffer_str.substr(0, 5) == std::string("solid"))
  {
    // file says that it is ascii, but why should we trust it?

    // check for "endsolid" as well
    if (buffer_str.find("endsolid", 5) != std::string::npos)
    {
      ROS_ERROR_STREAM("The STL file '" << origin << "' is malformed. It "
                       "starts with the word 'solid' and also contains the "
                       "word 'endsolid', indicating that it's an ASCII STL "
                       "file, but rviz can only load binary STL files so it "
                       "will not be loaded. Please convert it to a "
                       "binary STL file.");
      return false;
    }

    // chastise the user for malformed files
    ROS_WARN_STREAM("The STL file '" << origin << "' is malformed. It starts"
                    " with the word 'solid', indicating that it's an ASCII "
                    "STL file, but it does not contain the word 'endsolid' so"
                    "it is either a malformed ASCII STL file or it is actually "
                    "a binary STL file. Trying to interpret it as a binary "
                    "STL file instead.");
  }

  // make sure there's enough data for a binary STL header and triangle count
  static const size_t binary_stl_header_len = 84;
  if (num_bytes <= binary_stl_header_len)
  {
    ROS_ERROR_STREAM("The STL file '" << origin <<"' is malformed. It "
                     "appears to be a binary STL file but does not contain "
                     "enough data for the 80 byte header and 32-bit integer "
                     "triangle count.");
    return false;
  }

  // one last check to make sure that the size matches the number of triangles
  unsigned int num_triangles = *(reinterpret_cast<uint32_t *>(buffer + 80));
  static const size_t number_of_bytes_per_triangle = 50;
  size_t expected_size = binary_stl_header_len + num_triangles * number_of_bytes_per_triangle;
  if (num_bytes != expected_size)
  {
    ROS_ERROR_STREAM("The STL file '" << origin << "' is malformed. According "
                     "to the binary STL header it should have '" <<
                     num_triangles << "' triangles, but it has too " <<
                     (num_bytes > expected_size ? "much" : "little") <<
                     " data for that to be the case.");
    return false;
  }

  // load the binary STL data
  return this->load_binary(buffer);
}

bool STLLoader::load_binary(uint8_t* buffer)
{
  uint8_t* pos = buffer;

  pos += 80; // skip the 80 byte header

  unsigned int numTriangles = *(unsigned int*)pos;
  pos += 4;

  for ( unsigned int currentTriangle = 0; currentTriangle < numTriangles; ++currentTriangle )
  {
    Triangle tri;

    tri.normal_.x = *(float*)pos;
    pos += 4;
    tri.normal_.y = *(float*)pos;
    pos += 4;
    tri.normal_.z = *(float*)pos;
    pos += 4;

    tri.vertices_[0].x = *(float*)pos;
    pos += 4;
    tri.vertices_[0].y = *(float*)pos;
    pos += 4;
    tri.vertices_[0].z = *(float*)pos;
    pos += 4;

    tri.vertices_[1].x = *(float*)pos;
    pos += 4;
    tri.vertices_[1].y = *(float*)pos;
    pos += 4;
    tri.vertices_[1].z = *(float*)pos;
    pos += 4;

    tri.vertices_[2].x = *(float*)pos;
    pos += 4;
    tri.vertices_[2].y = *(float*)pos;
    pos += 4;
    tri.vertices_[2].z = *(float*)pos;
    pos += 4;

    // Blender was writing a large number into this short... am I misinterpreting what the attribute byte count is supposed to do?
    //unsigned short attributeByteCount = *(unsigned short*)pos;
    pos += 2;

    //pos += attributeByteCount;

    if (tri.normal_.squaredLength() < 0.001)
    {
      Ogre::Vector3 side1 = tri.vertices_[0] - tri.vertices_[1];
      Ogre::Vector3 side2 = tri.vertices_[1] - tri.vertices_[2];
      tri.normal_ = side1.crossProduct(side2);
    }
    tri.normal_.normalise();

    triangles_.push_back(tri);
  }

  return true;
}

void calculateUV(const Ogre::Vector3& vec, float& u, float& v)
{
  Ogre::Vector3 pos(vec);
  pos.normalise();
  u = acos( pos.y / pos.length() );

  float val = pos.x / ( sin( u ) );
  v = acos( val );

  u /= Ogre::Math::PI;
  v /= Ogre::Math::PI;
}

Ogre::MeshPtr STLLoader::toMesh(const std::string& name)
{
  Ogre::ManualObject* object = new Ogre::ManualObject( "the one and only" );
  object->begin( "BaseWhiteNoLighting", Ogre::RenderOperation::OT_TRIANGLE_LIST );

  unsigned int vertexCount = 0;
  V_Triangle::const_iterator it = triangles_.begin();
  V_Triangle::const_iterator end = triangles_.end();
  for (; it != end; ++it )
  {
    if( vertexCount >= 2004 )
    {
      // Subdivide large meshes into submeshes with at most 2004
      // vertices to prevent problems on some graphics cards.
      object->end();
      object->begin( "BaseWhiteNoLighting", Ogre::RenderOperation::OT_TRIANGLE_LIST );
      vertexCount = 0;
    }

    const STLLoader::Triangle& tri = *it;

    float u, v;
    u = v = 0.0f;
    object->position( tri.vertices_[0] );
    object->normal( tri.normal_);
    calculateUV( tri.vertices_[0], u, v );
    object->textureCoord( u, v );

    object->position( tri.vertices_[1] );
    object->normal( tri.normal_);
    calculateUV( tri.vertices_[1], u, v );
    object->textureCoord( u, v );

    object->position( tri.vertices_[2] );
    object->normal( tri.normal_);
    calculateUV( tri.vertices_[2], u, v );
    object->textureCoord( u, v );

    object->triangle( vertexCount + 0, vertexCount + 1, vertexCount + 2 );

    vertexCount += 3;
  }

  object->end();

  Ogre::MeshPtr mesh = object->convertToMesh( name, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME );
  mesh->buildEdgeList();

  delete object;

  return mesh;
}

}
<|endoftext|>