<commit_before>/**
 * @file
 *
 * @brief
 *
 * @copyright BSD License (see LICENSE.md or https://www.libelektra.org)
 */

#include "ccode.hpp"

#include <kdblogger.h>

namespace
{

/**
 * @brief Cast a character to an unsigned character.
 *
 * @param character This parameter specifies the character this function casts to an unsigned value.
 *
 * @return A unsigned character corresponding to the given argument
 */
inline constexpr unsigned char operator"" _uc (char character) noexcept
{
	return static_cast<unsigned char> (character);
}

/**
 * @brief This function maps hex characters to integer numbers.
 *
 * @pre The specified character has to be between
 *
 *      - `'0'`–`'9'`,
 *      - `'a'`-`'f'`, or
 *      - `'A'`-`'F'`
 *
 *     .
 *
 * @param character This argument specifies the (hexadecimal) character this function converts.
 *
 * @return An integer number between `0` and `15` if the precondition is valid or `0` otherwise
 */
inline int elektraHexcodeConvFromHex (char character)
{
	if (character >= '0' && character <= '9') return character - '0';
	if (character >= 'a' && character <= 'f') return character - 'a' + 10;
	if (character >= 'A' && character <= 'F') return character - 'A' + 10;

	return 0; /* Unknown escape char */
}

} // end namespace

using namespace ckdb;
extern "C" {

/**
 * @brief This function sets default values for the encoding and decoding character mapping.
 *
 * @param mapping This parameter stores the encoding and decoding table this function fills with default values.
 */
void setDefaultConfig (CCodeData * const mapping)
{
	unsigned char pairs[][2] = { { '\b'_uc, 'b'_uc }, { '\t'_uc, 't'_uc }, { '\n'_uc, 'n'_uc },  { '\v'_uc, 'v'_uc },
				     { '\f'_uc, 'f'_uc }, { '\r'_uc, 'r'_uc }, { '\\'_uc, '\\'_uc }, { '\''_uc, '\''_uc },
				     { '\"'_uc, '"'_uc }, { '\0'_uc, '0'_uc } };

	for (size_t pair = 0; pair < sizeof (pairs) / sizeof (pairs[0]); pair++)
	{
		unsigned char character = pairs[pair][0];
		unsigned char replacement = pairs[pair][1];

		mapping->encode[character] = replacement;
		mapping->decode[replacement] = character;
	}
}

/**
 * @brief This function sets values for the encoding and decoding character mapping.
 *
 * @param mapping This parameter stores the encoding and decoding table this function fills with the values specified in `config`.
 * @param config This key set stores the character mappings this function stores inside `mappings`.
 * @param root This key stores the root key for the character mapping stored in `config`.
 */
void readConfig (CCodeData * const mapping, KeySet * const config, Key const * const root)
{
	Key const * key = 0;
	while ((key = ksNext (config)) != 0)
	{
		/* Ignore keys that are not directly below the config root key or have an incorrect size */
		if (keyRel (root, key) != 1 || keyGetBaseNameSize (key) != 3 || keyGetValueSize (key) != 3) continue;

		int character = elektraHexcodeConvFromHex (keyBaseName (key)[1]);
		character += elektraHexcodeConvFromHex (keyBaseName (key)[0]) * 16;

		int replacement = elektraHexcodeConvFromHex (keyString (key)[1]);
		replacement += elektraHexcodeConvFromHex (keyString (key)[0]) * 16;

		/* Hexencode this character! */
		mapping->encode[character & 255] = replacement;
		mapping->decode[replacement & 255] = character;
	}
}

/**
 * @brief This function replaces escaped character in a key value with unescaped characters.
 *
 * The function stores the unescaped result value both in `mapping->buffer` and the given key.
 *
 * @pre The variable `mapping->buffer` needs to be as large as the key value’s size.
 *
 * @param key This key holds the value this function decodes.
 * @param mapping This variable stores the buffer and the character mapping this function uses to decode the value of the given key.
 */
void elektraCcodeDecode (Key * key, CCodeData * mapping)
{
	const char * value = static_cast<const char *> (keyValue (key));
	if (!value) return;

	size_t const SIZE = keyGetValueSize (key) - 1;
	size_t out = 0;
	for (size_t in = 0; in < SIZE; ++in)
	{
		unsigned char character = value[in];

		if (character == mapping->escape)
		{
			++in; /* Advance twice */
			character = value[in];

			mapping->buffer[out] = mapping->decode[character & 255];
		}
		else
		{
			mapping->buffer[out] = character;
		}
		++out; /* Only one char is written */
	}

	mapping->buffer[out] = 0; // null termination for keyString()

	keySetRaw (key, mapping->buffer, out + 1);
}

/**
 * @brief This function replaces unescaped character in a key value with escaped characters.
 *
 * The function stores the escaped result value both in `mapping->buffer` and the given key.
 *
 * @pre The variable `mapping->buffer` needs to be twice as large as the key value’s size.
 *
 * @param cur This key stores the value this function escapes.
 * @param mapping This variable stores the buffer and the character mapping this function uses to encode the value of the given key.
 */
void elektraCcodeEncode (Key * cur, CCodeData * mapping)
{
	const char * val = static_cast<const char *> (keyValue (cur));
	if (!val) return;

	size_t valsize = keyGetValueSize (cur);
	size_t out = 0;
	for (size_t in = 0; in < valsize - 1; ++in)
	{
		unsigned char character = val[in];

		if (mapping->encode[character])
		{
			mapping->buffer[out + 1] = mapping->encode[character];
			// Escape char
			mapping->buffer[out] = mapping->escape;
			out += 2;
		}
		else
		{
			// just copy one character
			mapping->buffer[out] = val[in];
			// advance out cursor
			out++;
			// go to next char
		}
	}

	mapping->buffer[out] = 0; // null termination for keyString()

	keySetRaw (cur, mapping->buffer, out + 1);
}

// ====================
// = Plugin Interface =
// ====================

int elektraCcodeOpen (Plugin * handle, Key * key ELEKTRA_UNUSED)
{
	CCodeData * mapping = new CCodeData ();

	/* Store for later use...*/
	elektraPluginSetData (handle, mapping);

	KeySet * config = elektraPluginGetConfig (handle);

	Key * escape = ksLookupByName (config, "/escape", 0);
	mapping->escape = '\\';
	if (escape && keyGetBaseNameSize (escape) && keyGetValueSize (escape) == 3)
	{
		int res;
		res = elektraHexcodeConvFromHex (keyString (escape)[1]);
		res += elektraHexcodeConvFromHex (keyString (escape)[0]) * 16;

		mapping->escape = res & 255;
	}
	ELEKTRA_LOG_DEBUG ("Use “%c” as escape character", mapping->escape);

	Key * root = ksLookupByName (config, "/chars", 0);

	if (root)
	{
		readConfig (mapping, config, root);
	}
	else
	{
		setDefaultConfig (mapping);
	}

	return 0;
}

int elektraCcodeClose (Plugin * handle, Key * key ELEKTRA_UNUSED)
{
	CCodeData * mapping = static_cast<CCodeData *> (elektraPluginGetData (handle));

	delete[](mapping->buffer);
	delete (mapping);

	return 0;
}

int elektraCcodeGet (Plugin * handle, KeySet * returned, Key * parentKey)
{
	/* get all keys */

	if (!strcmp (keyName (parentKey), "system/elektra/modules/ccode"))
	{
		KeySet * pluginConfig =
			ksNew (30, keyNew ("system/elektra/modules/ccode", KEY_VALUE, "ccode plugin waits for your orders", KEY_END),
			       keyNew ("system/elektra/modules/ccode/exports", KEY_END),
			       keyNew ("system/elektra/modules/ccode/exports/open", KEY_FUNC, elektraCcodeOpen, KEY_END),
			       keyNew ("system/elektra/modules/ccode/exports/close", KEY_FUNC, elektraCcodeClose, KEY_END),
			       keyNew ("system/elektra/modules/ccode/exports/get", KEY_FUNC, elektraCcodeGet, KEY_END),
			       keyNew ("system/elektra/modules/ccode/exports/set", KEY_FUNC, elektraCcodeSet, KEY_END),
#include "readme_ccode.c"
			       keyNew ("system/elektra/modules/ccode/infos/version", KEY_VALUE, PLUGINVERSION, KEY_END), KS_END);
		ksAppend (returned, pluginConfig);
		ksDel (pluginConfig);
		return 1;
	}

	CCodeData * mapping = static_cast<CCodeData *> (elektraPluginGetData (handle));
	if (!mapping->buffer)
	{
		mapping->bufalloc = 1000;
		mapping->buffer = new unsigned char[mapping->bufalloc];
	}

	Key * cur;
	ksRewind (returned);
	while ((cur = ksNext (returned)) != 0)
	{
		size_t valsize = keyGetValueSize (cur);
		if (valsize > mapping->bufalloc)
		{
			mapping->bufalloc = valsize;
			mapping->buffer = new unsigned char[mapping->bufalloc];
		}

		elektraCcodeDecode (cur, mapping);
	}

	return 1; /* success */
}

int elektraCcodeSet (Plugin * handle, KeySet * returned, Key * parentKey ELEKTRA_UNUSED)
{
	/* set all keys */
	CCodeData * mapping = static_cast<CCodeData *> (elektraPluginGetData (handle));
	if (!mapping->buffer)
	{
		mapping->bufalloc = 1000;
		mapping->buffer = new unsigned char[mapping->bufalloc];
	}

	Key * cur;
	ksRewind (returned);
	while ((cur = ksNext (returned)) != 0)
	{
		size_t valsize = keyGetValueSize (cur);
		if (valsize * 2 > mapping->bufalloc)
		{
			mapping->bufalloc = valsize * 2;
			mapping->buffer = new unsigned char[mapping->bufalloc];
		}

		elektraCcodeEncode (cur, mapping);
	}

	return 1; /* success */
}

Plugin * ELEKTRA_PLUGIN_EXPORT (ccode)
{
	// clang-format off
	return elektraPluginExport("ccode",
		ELEKTRA_PLUGIN_OPEN,	&elektraCcodeOpen,
		ELEKTRA_PLUGIN_CLOSE,	&elektraCcodeClose,
		ELEKTRA_PLUGIN_GET,	&elektraCcodeGet,
		ELEKTRA_PLUGIN_SET,	&elektraCcodeSet,
		ELEKTRA_PLUGIN_END);
}

} // end extern "C"
<commit_msg>CCode: Improve variable name<commit_after>/**
 * @file
 *
 * @brief
 *
 * @copyright BSD License (see LICENSE.md or https://www.libelektra.org)
 */

#include "ccode.hpp"

#include <kdblogger.h>

namespace
{

/**
 * @brief Cast a character to an unsigned character.
 *
 * @param character This parameter specifies the character this function casts to an unsigned value.
 *
 * @return A unsigned character corresponding to the given argument
 */
inline constexpr unsigned char operator"" _uc (char character) noexcept
{
	return static_cast<unsigned char> (character);
}

/**
 * @brief This function maps hex characters to integer numbers.
 *
 * @pre The specified character has to be between
 *
 *      - `'0'`–`'9'`,
 *      - `'a'`-`'f'`, or
 *      - `'A'`-`'F'`
 *
 *     .
 *
 * @param character This argument specifies the (hexadecimal) character this function converts.
 *
 * @return An integer number between `0` and `15` if the precondition is valid or `0` otherwise
 */
inline int elektraHexcodeConvFromHex (char character)
{
	if (character >= '0' && character <= '9') return character - '0';
	if (character >= 'a' && character <= 'f') return character - 'a' + 10;
	if (character >= 'A' && character <= 'F') return character - 'A' + 10;

	return 0; /* Unknown escape char */
}

} // end namespace

using namespace ckdb;
extern "C" {

/**
 * @brief This function sets default values for the encoding and decoding character mapping.
 *
 * @param mapping This parameter stores the encoding and decoding table this function fills with default values.
 */
void setDefaultConfig (CCodeData * const mapping)
{
	unsigned char pairs[][2] = { { '\b'_uc, 'b'_uc }, { '\t'_uc, 't'_uc }, { '\n'_uc, 'n'_uc },  { '\v'_uc, 'v'_uc },
				     { '\f'_uc, 'f'_uc }, { '\r'_uc, 'r'_uc }, { '\\'_uc, '\\'_uc }, { '\''_uc, '\''_uc },
				     { '\"'_uc, '"'_uc }, { '\0'_uc, '0'_uc } };

	for (size_t pair = 0; pair < sizeof (pairs) / sizeof (pairs[0]); pair++)
	{
		unsigned char character = pairs[pair][0];
		unsigned char replacement = pairs[pair][1];

		mapping->encode[character] = replacement;
		mapping->decode[replacement] = character;
	}
}

/**
 * @brief This function sets values for the encoding and decoding character mapping.
 *
 * @param mapping This parameter stores the encoding and decoding table this function fills with the values specified in `config`.
 * @param config This key set stores the character mappings this function stores inside `mappings`.
 * @param root This key stores the root key for the character mapping stored in `config`.
 */
void readConfig (CCodeData * const mapping, KeySet * const config, Key const * const root)
{
	Key const * key = 0;
	while ((key = ksNext (config)) != 0)
	{
		/* Ignore keys that are not directly below the config root key or have an incorrect size */
		if (keyRel (root, key) != 1 || keyGetBaseNameSize (key) != 3 || keyGetValueSize (key) != 3) continue;

		int character = elektraHexcodeConvFromHex (keyBaseName (key)[1]);
		character += elektraHexcodeConvFromHex (keyBaseName (key)[0]) * 16;

		int replacement = elektraHexcodeConvFromHex (keyString (key)[1]);
		replacement += elektraHexcodeConvFromHex (keyString (key)[0]) * 16;

		/* Hexencode this character! */
		mapping->encode[character & 255] = replacement;
		mapping->decode[replacement & 255] = character;
	}
}

/**
 * @brief This function replaces escaped character in a key value with unescaped characters.
 *
 * The function stores the unescaped result value both in `mapping->buffer` and the given key.
 *
 * @pre The variable `mapping->buffer` needs to be as large as the key value’s size.
 *
 * @param key This key holds the value this function decodes.
 * @param mapping This variable stores the buffer and the character mapping this function uses to decode the value of the given key.
 */
void elektraCcodeDecode (Key * key, CCodeData * mapping)
{
	const char * value = static_cast<const char *> (keyValue (key));
	if (!value) return;

	size_t const SIZE = keyGetValueSize (key) - 1;
	size_t out = 0;
	for (size_t in = 0; in < SIZE; ++in)
	{
		unsigned char character = value[in];

		if (character == mapping->escape)
		{
			++in; /* Advance twice */
			character = value[in];

			mapping->buffer[out] = mapping->decode[character & 255];
		}
		else
		{
			mapping->buffer[out] = character;
		}
		++out; /* Only one char is written */
	}

	mapping->buffer[out] = 0; // null termination for keyString()

	keySetRaw (key, mapping->buffer, out + 1);
}

/**
 * @brief This function replaces unescaped character in a key value with escaped characters.
 *
 * The function stores the escaped result value both in `mapping->buffer` and the given key.
 *
 * @pre The variable `mapping->buffer` needs to be twice as large as the key value’s size.
 *
 * @param key This key stores the value this function escapes.
 * @param mapping This variable stores the buffer and the character mapping this function uses to encode the value of the given key.
 */
void elektraCcodeEncode (Key * key, CCodeData * mapping)
{
	const char * value = static_cast<const char *> (keyValue (key));
	if (!value) return;

	size_t size = keyGetValueSize (key);
	size_t out = 0;
	for (size_t in = 0; in < size - 1; ++in)
	{
		unsigned char character = value[in];

		if (mapping->encode[character])
		{
			mapping->buffer[out + 1] = mapping->encode[character];
			// Escape char
			mapping->buffer[out] = mapping->escape;
			out += 2;
		}
		else
		{
			// just copy one character
			mapping->buffer[out] = value[in];
			// advance out cursor
			out++;
			// go to next char
		}
	}

	mapping->buffer[out] = 0; // null termination for keyString()

	keySetRaw (key, mapping->buffer, out + 1);
}

// ====================
// = Plugin Interface =
// ====================

int elektraCcodeOpen (Plugin * handle, Key * key ELEKTRA_UNUSED)
{
	CCodeData * mapping = new CCodeData ();

	/* Store for later use...*/
	elektraPluginSetData (handle, mapping);

	KeySet * config = elektraPluginGetConfig (handle);

	Key * escape = ksLookupByName (config, "/escape", 0);
	mapping->escape = '\\';
	if (escape && keyGetBaseNameSize (escape) && keyGetValueSize (escape) == 3)
	{
		int res;
		res = elektraHexcodeConvFromHex (keyString (escape)[1]);
		res += elektraHexcodeConvFromHex (keyString (escape)[0]) * 16;

		mapping->escape = res & 255;
	}
	ELEKTRA_LOG_DEBUG ("Use “%c” as escape character", mapping->escape);

	Key * root = ksLookupByName (config, "/chars", 0);

	if (root)
	{
		readConfig (mapping, config, root);
	}
	else
	{
		setDefaultConfig (mapping);
	}

	return 0;
}

int elektraCcodeClose (Plugin * handle, Key * key ELEKTRA_UNUSED)
{
	CCodeData * mapping = static_cast<CCodeData *> (elektraPluginGetData (handle));

	delete[](mapping->buffer);
	delete (mapping);

	return 0;
}

int elektraCcodeGet (Plugin * handle, KeySet * returned, Key * parentKey)
{
	/* get all keys */

	if (!strcmp (keyName (parentKey), "system/elektra/modules/ccode"))
	{
		KeySet * pluginConfig =
			ksNew (30, keyNew ("system/elektra/modules/ccode", KEY_VALUE, "ccode plugin waits for your orders", KEY_END),
			       keyNew ("system/elektra/modules/ccode/exports", KEY_END),
			       keyNew ("system/elektra/modules/ccode/exports/open", KEY_FUNC, elektraCcodeOpen, KEY_END),
			       keyNew ("system/elektra/modules/ccode/exports/close", KEY_FUNC, elektraCcodeClose, KEY_END),
			       keyNew ("system/elektra/modules/ccode/exports/get", KEY_FUNC, elektraCcodeGet, KEY_END),
			       keyNew ("system/elektra/modules/ccode/exports/set", KEY_FUNC, elektraCcodeSet, KEY_END),
#include "readme_ccode.c"
			       keyNew ("system/elektra/modules/ccode/infos/version", KEY_VALUE, PLUGINVERSION, KEY_END), KS_END);
		ksAppend (returned, pluginConfig);
		ksDel (pluginConfig);
		return 1;
	}

	CCodeData * mapping = static_cast<CCodeData *> (elektraPluginGetData (handle));
	if (!mapping->buffer)
	{
		mapping->bufalloc = 1000;
		mapping->buffer = new unsigned char[mapping->bufalloc];
	}

	Key * cur;
	ksRewind (returned);
	while ((cur = ksNext (returned)) != 0)
	{
		size_t valsize = keyGetValueSize (cur);
		if (valsize > mapping->bufalloc)
		{
			mapping->bufalloc = valsize;
			mapping->buffer = new unsigned char[mapping->bufalloc];
		}

		elektraCcodeDecode (cur, mapping);
	}

	return 1; /* success */
}

int elektraCcodeSet (Plugin * handle, KeySet * returned, Key * parentKey ELEKTRA_UNUSED)
{
	/* set all keys */
	CCodeData * mapping = static_cast<CCodeData *> (elektraPluginGetData (handle));
	if (!mapping->buffer)
	{
		mapping->bufalloc = 1000;
		mapping->buffer = new unsigned char[mapping->bufalloc];
	}

	Key * cur;
	ksRewind (returned);
	while ((cur = ksNext (returned)) != 0)
	{
		size_t valsize = keyGetValueSize (cur);
		if (valsize * 2 > mapping->bufalloc)
		{
			mapping->bufalloc = valsize * 2;
			mapping->buffer = new unsigned char[mapping->bufalloc];
		}

		elektraCcodeEncode (cur, mapping);
	}

	return 1; /* success */
}

Plugin * ELEKTRA_PLUGIN_EXPORT (ccode)
{
	// clang-format off
	return elektraPluginExport("ccode",
		ELEKTRA_PLUGIN_OPEN,	&elektraCcodeOpen,
		ELEKTRA_PLUGIN_CLOSE,	&elektraCcodeClose,
		ELEKTRA_PLUGIN_GET,	&elektraCcodeGet,
		ELEKTRA_PLUGIN_SET,	&elektraCcodeSet,
		ELEKTRA_PLUGIN_END);
}

} // end extern "C"
<|endoftext|>


<commit_before>
#include <nstd/Debug.h>
#include <nstd/Atomic.h>

void testAtomic()
{
  volatile usize size = 0;
  ASSERT(Atomic::increment(size) == 1);
  ASSERT(Atomic::increment(size) == 2);
  ASSERT(Atomic::increment(size) == 3);
  ASSERT(Atomic::decrement(size) == 2);
  ASSERT(Atomic::decrement(size) == 1);
  ASSERT(Atomic::decrement(size) == 0);
  volatile int32 int32 = 0;
  ASSERT(Atomic::increment(int32) == 1);
  ASSERT(Atomic::decrement(int32) == 0);
  ASSERT(Atomic::decrement(int32) == -1);
  volatile uint32 uint32 = 0xfffffff0;
  ASSERT(Atomic::increment(uint32) == 0xfffffff1);
  ASSERT(Atomic::decrement(uint32) == 0xfffffff0);
#ifndef _ARM
  volatile int64 int64 = 0;
  ASSERT(Atomic::increment(int64) == 1);
  ASSERT(Atomic::decrement(int64) == 0);
  ASSERT(Atomic::decrement(int64) == -1);
  volatile uint64 uint64 =  (0xffffffffULL << 32) | 0xfffffff0ULL;
  ASSERT(Atomic::increment(uint64) == ((0xffffffffULL << 32) | 0xfffffff1ULL));
  ASSERT(Atomic::decrement(uint64) == ((0xffffffffULL << 32) | 0xfffffff0ULL));
#endif

  void* volatile ptr = 0;
  ASSERT(Atomic::compareAndSwap(ptr, 0, (void*)0xff) == 0);
  ASSERT(Atomic::compareAndSwap(ptr, (void*)0xff, 0) == (void*)0xff);
  ASSERT(Atomic::compareAndSwap(ptr, (void*)23, 0) == 0);

  size = 0;
  ASSERT(Atomic::swap(size, 1) == 0);
  ASSERT(Atomic::swap(size, 2) == 1);
  int32 = 0;
  ASSERT(Atomic::swap(int32, 1) == 0);
  ASSERT(Atomic::swap(int32, -1) == 1);
  ASSERT(Atomic::swap(int32, 2) == -1);
  uint32 = 0;
  ASSERT(Atomic::swap(uint32, 1) == 0);
  ASSERT(Atomic::swap(uint32, 2) == 1);
  uint64 = 0;
  ASSERT(Atomic::swap(uint64, 1) == 0);
  ASSERT(Atomic::swap(uint64, 2) == 1);
  ptr = 0;
  ASSERT(Atomic::swap(ptr, (void*)0xffffffff) == 0);
  ASSERT(Atomic::swap(ptr, (void*)123) == (void*)0xffffffff);
}
<commit_msg>Atomic: Fixed build on ARMv7 Linux<commit_after>
#include <nstd/Debug.h>
#include <nstd/Atomic.h>

void testAtomic()
{
  volatile usize size = 0;
  ASSERT(Atomic::increment(size) == 1);
  ASSERT(Atomic::increment(size) == 2);
  ASSERT(Atomic::increment(size) == 3);
  ASSERT(Atomic::decrement(size) == 2);
  ASSERT(Atomic::decrement(size) == 1);
  ASSERT(Atomic::decrement(size) == 0);
  volatile int32 int32 = 0;
  ASSERT(Atomic::increment(int32) == 1);
  ASSERT(Atomic::decrement(int32) == 0);
  ASSERT(Atomic::decrement(int32) == -1);
  volatile uint32 uint32 = 0xfffffff0;
  ASSERT(Atomic::increment(uint32) == 0xfffffff1);
  ASSERT(Atomic::decrement(uint32) == 0xfffffff0);
  volatile int64 int64 = 0;
#ifndef _ARM
  ASSERT(Atomic::increment(int64) == 1);
  ASSERT(Atomic::decrement(int64) == 0);
  ASSERT(Atomic::decrement(int64) == -1);
#endif
  volatile uint64 uint64 =  (0xffffffffULL << 32) | 0xfffffff0ULL;
#ifndef _ARM
  ASSERT(Atomic::increment(uint64) == ((0xffffffffULL << 32) | 0xfffffff1ULL));
  ASSERT(Atomic::decrement(uint64) == ((0xffffffffULL << 32) | 0xfffffff0ULL));
#endif

  void* volatile ptr = 0;
  ASSERT(Atomic::compareAndSwap(ptr, 0, (void*)0xff) == 0);
  ASSERT(Atomic::compareAndSwap(ptr, (void*)0xff, 0) == (void*)0xff);
  ASSERT(Atomic::compareAndSwap(ptr, (void*)23, 0) == 0);

  size = 0;
  ASSERT(Atomic::swap(size, 1) == 0);
  ASSERT(Atomic::swap(size, 2) == 1);
  int32 = 0;
  ASSERT(Atomic::swap(int32, 1) == 0);
  ASSERT(Atomic::swap(int32, -1) == 1);
  ASSERT(Atomic::swap(int32, 2) == -1);
  int64 = 0;
  ASSERT(Atomic::swap(int64, 1) == 0);
  ASSERT(Atomic::swap(int64, -1) == 1);
  ASSERT(Atomic::swap(int64, 2) == -1);
  uint32 = 0;
  ASSERT(Atomic::swap(uint32, 1) == 0);
  ASSERT(Atomic::swap(uint32, 2) == 1);
  uint64 = 0;
  ASSERT(Atomic::swap(uint64, 1) == 0);
  ASSERT(Atomic::swap(uint64, 2) == 1);
  ptr = 0;
  ASSERT(Atomic::swap(ptr, (void*)0xffffffff) == 0);
  ASSERT(Atomic::swap(ptr, (void*)123) == (void*)0xffffffff);
}
<|endoftext|>


<commit_before>/**
 * @file
 *
 * @brief Source for yanlr plugin
 *
 * @copyright BSD License (see LICENSE.md or https://www.libelektra.org)
 *
 */

#include "yanlr.hpp"
#include "YAMLLexer.h"
#include "YAMLParser.h"
#include "antlr4-runtime.h"

#include <iostream>
#include <kdb.hpp>
using namespace ckdb;
#include <kdberrors.h>
#include <kdbhelper.h>

using namespace antlr;
using namespace antlr4;
using namespace std;

/**
 * @brief This function returns a key set containing the contract of this plugin.
 *
 * @return A contract describing the functionality of this plugin.
 */
static KeySet * contractYanlr (void)
{
	return ksNew (30, keyNew ("system/elektra/modules/yanlr", KEY_VALUE, "yanlr plugin waits for your orders", KEY_END),
		      keyNew ("system/elektra/modules/yanlr/exports", KEY_END),
		      keyNew ("system/elektra/modules/yanlr/exports/get", KEY_FUNC, elektraYanlrGet, KEY_END),
		      keyNew ("system/elektra/modules/yanlr/exports/set", KEY_FUNC, elektraYanlrSet, KEY_END),
#include ELEKTRA_README (yanlr)
		      keyNew ("system/elektra/modules/yanlr/infos/version", KEY_VALUE, PLUGINVERSION, KEY_END), KS_END);
}

extern "C" {
// ====================
// = Plugin Interface =
// ====================

/** @see elektraDocGet */
int elektraYanlrGet (Plugin * handle ELEKTRA_UNUSED, KeySet * returned, Key * parentKey)
{
	kdb::Key parent = kdb::Key (parentKey);

	if (parent.getName () == "system/elektra/modules/yanlr")
	{
		KeySet * contract = contractYanlr ();
		ksAppend (returned, contract);
		ksDel (contract);
		parent.release ();

		return ELEKTRA_PLUGIN_STATUS_SUCCESS;
	}

	ifstream file (parent.getString ());
	if (!file.is_open ())
	{
		ELEKTRA_SET_ERRORF (ELEKTRA_ERROR_COULD_NOT_OPEN, parent.getKey (), "Unable to open file “%s”",
				    parent.getString ().c_str ());
	}

	ANTLRInputStream input (file);
	YAMLLexer lexer (&input);
	CommonTokenStream tokens (&lexer);
	YAMLParser parser (&tokens); //! OCLint

	parent.release ();
	return ELEKTRA_PLUGIN_STATUS_NO_UPDATE;
}

/** @see elektraDocSet */
int elektraYanlrSet (Plugin * handle ELEKTRA_UNUSED, KeySet * returned ELEKTRA_UNUSED, Key * parentKey ELEKTRA_UNUSED)
{
	return ELEKTRA_PLUGIN_STATUS_NO_UPDATE;
}

Plugin * ELEKTRA_PLUGIN_EXPORT (yanlr)
{
	return elektraPluginExport ("yanlr", ELEKTRA_PLUGIN_GET, &elektraYanlrGet, ELEKTRA_PLUGIN_SET, &elektraYanlrSet,
				    ELEKTRA_PLUGIN_END);
}

} // end extern "C"
<commit_msg>Yan LR: Explicitly list imported symbols<commit_after>/**
 * @file
 *
 * @brief Source for yanlr plugin
 *
 * @copyright BSD License (see LICENSE.md or https://www.libelektra.org)
 *
 */

#include "yanlr.hpp"
#include "YAMLLexer.h"
#include "YAMLParser.h"
#include "antlr4-runtime.h"

#include <iostream>
#include <kdb.hpp>
using namespace ckdb;
#include <kdberrors.h>
#include <kdbhelper.h>

using antlr::YAMLLexer;
using antlr::YAMLParser;
using antlr4::ANTLRInputStream;
using antlr4::CommonTokenStream;
using std::ifstream;

/**
 * @brief This function returns a key set containing the contract of this plugin.
 *
 * @return A contract describing the functionality of this plugin.
 */
static KeySet * contractYanlr (void)
{
	return ksNew (30, keyNew ("system/elektra/modules/yanlr", KEY_VALUE, "yanlr plugin waits for your orders", KEY_END),
		      keyNew ("system/elektra/modules/yanlr/exports", KEY_END),
		      keyNew ("system/elektra/modules/yanlr/exports/get", KEY_FUNC, elektraYanlrGet, KEY_END),
		      keyNew ("system/elektra/modules/yanlr/exports/set", KEY_FUNC, elektraYanlrSet, KEY_END),
#include ELEKTRA_README (yanlr)
		      keyNew ("system/elektra/modules/yanlr/infos/version", KEY_VALUE, PLUGINVERSION, KEY_END), KS_END);
}

extern "C" {
// ====================
// = Plugin Interface =
// ====================

/** @see elektraDocGet */
int elektraYanlrGet (Plugin * handle ELEKTRA_UNUSED, KeySet * returned, Key * parentKey)
{
	kdb::Key parent = kdb::Key (parentKey);

	if (parent.getName () == "system/elektra/modules/yanlr")
	{
		KeySet * contract = contractYanlr ();
		ksAppend (returned, contract);
		ksDel (contract);
		parent.release ();

		return ELEKTRA_PLUGIN_STATUS_SUCCESS;
	}

	ifstream file (parent.getString ());
	if (!file.is_open ())
	{
		ELEKTRA_SET_ERRORF (ELEKTRA_ERROR_COULD_NOT_OPEN, parent.getKey (), "Unable to open file “%s”",
				    parent.getString ().c_str ());
	}

	ANTLRInputStream input (file);
	YAMLLexer lexer (&input);
	CommonTokenStream tokens (&lexer);
	YAMLParser parser (&tokens); //! OCLint

	parent.release ();
	return ELEKTRA_PLUGIN_STATUS_NO_UPDATE;
}

/** @see elektraDocSet */
int elektraYanlrSet (Plugin * handle ELEKTRA_UNUSED, KeySet * returned ELEKTRA_UNUSED, Key * parentKey ELEKTRA_UNUSED)
{
	return ELEKTRA_PLUGIN_STATUS_NO_UPDATE;
}

Plugin * ELEKTRA_PLUGIN_EXPORT (yanlr)
{
	return elektraPluginExport ("yanlr", ELEKTRA_PLUGIN_GET, &elektraYanlrGet, ELEKTRA_PLUGIN_SET, &elektraYanlrSet,
				    ELEKTRA_PLUGIN_END);
}

} // end extern "C"
<|endoftext|>


<commit_before>/* -*- mode: C; c-basic-offset: 4; indent-tabs-mode: nil; -*- */
/*
 * Copyright (c) 2008  litl, LLC
 *
 * 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 <config.h>
#include <string.h>
#include <stdlib.h>
#include <locale.h>

#include <gjs/gjs.h>

#include "coverage.h"

static char **include_path = NULL;
static char **coverage_prefixes = NULL;
static char *coverage_output_path = NULL;
static char *command = NULL;
static gboolean print_version = false;

static const char *GJS_COVERAGE_CACHE_FILE_NAME = ".internal-gjs-coverage-cache";

static GOptionEntry entries[] = {
    { "version", 0, 0, G_OPTION_ARG_NONE, &print_version, "Print GJS version and exit" },
    { "command", 'c', 0, G_OPTION_ARG_STRING, &command, "Program passed in as a string", "COMMAND" },
    { "coverage-prefix", 'C', 0, G_OPTION_ARG_STRING_ARRAY, &coverage_prefixes, "Add the prefix PREFIX to the list of files to generate coverage info for", "PREFIX" },
    { "coverage-output", 0, 0, G_OPTION_ARG_STRING, &coverage_output_path, "Write coverage output to a directory DIR. This option is mandatory when using --coverage-path", "DIR", },
    { "include-path", 'I', 0, G_OPTION_ARG_STRING_ARRAY, &include_path, "Add the directory DIR to the list of directories to search for js files.", "DIR" },
    { NULL }
};

static char **
strndupv(int           n,
         char * const *strv)
{
    int ix;
    if (n == 0)
        return NULL;
    char **retval = g_new(char *, n + 1);
    for (ix = 0; ix < n; ix++)
        retval[ix] = g_strdup(strv[ix]);
    retval[n] = NULL;
    return retval;
}

static char **
strcatv(char **strv1,
        char **strv2)
{
    if (strv1 == NULL && strv2 == NULL)
        return NULL;
    if (strv1 == NULL)
        return g_strdupv(strv2);
    if (strv2 == NULL)
        return g_strdupv(strv1);

    unsigned len1 = g_strv_length(strv1);
    unsigned len2 = g_strv_length(strv2);
    char **retval = g_new(char *, len1 + len2 + 1);
    unsigned ix;

    for (ix = 0; ix < len1; ix++)
        retval[ix] = g_strdup(strv1[ix]);
    for (ix = 0; ix < len2; ix++)
        retval[len1 + ix] = g_strdup(strv2[ix]);
    retval[len1 + len2] = NULL;

    return retval;
}

static void
check_script_args_for_stray_gjs_args(int           argc,
                                     char * const *argv)
{
    GError *error = NULL;
    char **new_coverage_prefixes = NULL;
    char *new_coverage_output_path = NULL;
    char **new_include_paths = NULL;
    static GOptionEntry script_check_entries[] = {
        { "coverage-prefix", 'C', 0, G_OPTION_ARG_STRING_ARRAY, &new_coverage_prefixes },
        { "coverage-output", 0, 0, G_OPTION_ARG_STRING, &new_coverage_output_path },
        { "include-path", 'I', 0, G_OPTION_ARG_STRING_ARRAY, &new_include_paths },
        { NULL }
    };
    char **argv_copy = g_new(char *, argc + 2);
    int ix, argc_copy = argc + 1;

    argv_copy[0] = g_strdup("dummy"); /* Fake argv[0] for GOptionContext */
    for (ix = 0; ix < argc; ix++)
        argv_copy[ix + 1] = g_strdup(argv[ix]);
    argv_copy[argc + 1] = NULL;

    GOptionContext *script_options = g_option_context_new(NULL);
    g_option_context_set_ignore_unknown_options(script_options, true);
    g_option_context_set_help_enabled(script_options, false);
    g_option_context_add_main_entries(script_options, script_check_entries, NULL);
    if (!g_option_context_parse(script_options, &argc_copy, &argv_copy, &error)) {
        g_warning("Scanning script arguments failed: %s", error->message);
        g_error_free(error);
        return;
    }

    if (new_coverage_prefixes != NULL) {
        g_warning("You used the --coverage-prefix option after the script on "
                  "the GJS command line. Support for this will be removed in a "
                  "future version. Place the option before the script or use "
                  "the GJS_COVERAGE_PREFIXES environment variable.");
        char **old_coverage_prefixes = coverage_prefixes;
        coverage_prefixes = strcatv(old_coverage_prefixes, new_coverage_prefixes);
        g_strfreev(old_coverage_prefixes);
    }
    if (new_include_paths != NULL) {
        g_warning("You used the --include-path option after the script on the "
                  "GJS command line. Support for this will be removed in a "
                  "future version. Place the option before the script or use "
                  "the GJS_PATH environment variable.");
        char **old_include_paths = include_path;
        include_path = strcatv(old_include_paths, new_include_paths);
        g_strfreev(old_include_paths);
    }
    if (new_coverage_output_path != NULL) {
        g_warning("You used the --coverage-output option after the script on "
                  "the GJS command line. Support for this will be removed in a "
                  "future version. Place the option before the script or use "
                  "the GJS_COVERAGE_OUTPUT environment variable.");
        g_free(coverage_output_path);
        coverage_output_path = new_coverage_output_path;
    }

    g_option_context_free(script_options);
    g_strfreev(argv_copy);
}

int
main(int argc, char **argv)
{
    GOptionContext *context;
    GError *error = NULL;
    GjsContext *js_context;
    GjsCoverage *coverage = NULL;
    char *script;
    const char *filename;
    const char *program_name;
    gsize len;
    int code, argc_copy = argc, gjs_argc = argc, script_argc, ix;
    char **argv_copy = g_strdupv(argv), **argv_copy_addr = argv_copy;
    char **gjs_argv, **gjs_argv_addr;
    char * const *script_argv;
    const char *env_coverage_output_path;
    const char *env_coverage_prefixes;

    setlocale(LC_ALL, "");

    context = g_option_context_new(NULL);

    g_option_context_set_ignore_unknown_options(context, true);
    g_option_context_set_help_enabled(context, false);

    g_option_context_add_main_entries(context, entries, NULL);
    if (!g_option_context_parse(context, &argc_copy, &argv_copy, &error))
        g_error("option parsing failed: %s", error->message);

    /* Split options so we pass unknown ones through to the JS script */
    for (ix = 1; ix < argc; ix++) {
        /* Check if a file was given and split after it */
        if (argc_copy >= 2 && strcmp(argv[ix], argv_copy[1]) == 0) {
            /* Filename given; split after this argument */
            gjs_argc = ix + 1;
            break;
        }

        /* Check if -c or --command was given and split after following arg */
        if (command != NULL &&
            (strcmp(argv[ix], "-c") == 0 || strcmp(argv[ix], "--command") == 0)) {
            gjs_argc = ix + 2;
            break;
        }
    }
    gjs_argv_addr = gjs_argv = strndupv(gjs_argc, argv);
    script_argc = argc - gjs_argc;
    script_argv = argv + gjs_argc;
    g_strfreev(argv_copy_addr);

    /* Parse again, only the GJS options this time */
    include_path = NULL;
    coverage_prefixes = NULL;
    coverage_output_path = NULL;
    command = NULL;
    print_version = false;
    g_option_context_set_ignore_unknown_options(context, false);
    g_option_context_set_help_enabled(context, true);
    if (!g_option_context_parse(context, &gjs_argc, &gjs_argv, &error))
        g_error("option parsing failed: %s", error->message);

    g_option_context_free (context);

    if (print_version) {
        g_print("%s\n", PACKAGE_STRING);
        exit(0);
    }

    if (command != NULL) {
        script = command;
        len = strlen(script);
        filename = "<command line>";
        program_name = gjs_argv[0];
    } else if (gjs_argc == 1) {
        script = g_strdup("const Console = imports.console; Console.interact();");
        len = strlen(script);
        filename = "<stdin>";
        program_name = gjs_argv[0];
    } else {
        /* All unprocessed options should be in script_argv */
        g_assert(gjs_argc == 2);
        error = NULL;
        if (!g_file_get_contents(gjs_argv[1], &script, &len, &error)) {
            g_printerr("%s\n", error->message);
            exit(1);
        }
        filename = gjs_argv[1];
        program_name = gjs_argv[1];
    }

    /* This should be removed after a suitable time has passed */
    check_script_args_for_stray_gjs_args(script_argc, script_argv);

    js_context = (GjsContext*) g_object_new(GJS_TYPE_CONTEXT,
                                            "search-path", include_path,
                                            "program-name", program_name,
                                            NULL);

    env_coverage_output_path = g_getenv("GJS_COVERAGE_OUTPUT");
    if (env_coverage_output_path != NULL) {
        g_free(coverage_output_path);
        coverage_output_path = g_strdup(env_coverage_output_path);
    }

    env_coverage_prefixes = g_getenv("GJS_COVERAGE_PREFIXES");
    if (env_coverage_prefixes != NULL) {
        if (coverage_prefixes == NULL) {
            coverage_prefixes = g_strdupv((char **) env_coverage_prefixes);
        } else {
            char **env_prefixes = g_strsplit(env_coverage_prefixes, ":", -1);
            g_strfreev(coverage_prefixes);
            coverage_prefixes = env_prefixes;
        }
    }

    if (coverage_prefixes) {
        if (!coverage_output_path)
            g_error("--coverage-output is required when taking coverage statistics");

        char *path_to_cache_file = g_build_filename(coverage_output_path,
                                                    GJS_COVERAGE_CACHE_FILE_NAME,
                                                    NULL);
        coverage = gjs_coverage_new_from_cache((const gchar **) coverage_prefixes,
                                               js_context,
                                               path_to_cache_file);
        g_free(path_to_cache_file);
    }

    /* prepare command line arguments */
    if (!gjs_context_define_string_array(js_context, "ARGV",
                                         script_argc, (const char **) script_argv,
                                         &error)) {
        code = 1;
        g_printerr("Failed to defined ARGV: %s", error->message);
        g_clear_error(&error);
        goto out;
    }

    /* evaluate the script */
    if (!gjs_context_eval(js_context, script, len,
                          filename, &code, &error)) {
        code = 1;
        g_printerr("%s\n", error->message);
        g_clear_error(&error);
        goto out;
    }

 out:
    g_strfreev(gjs_argv_addr);

    /* Probably doesn't make sense to write statistics on failure */
    if (coverage && code == 0)
        gjs_coverage_write_statistics(coverage,
                                      coverage_output_path);

    g_free(coverage_output_path);
    g_strfreev(coverage_prefixes);
    g_object_unref(js_context);
    g_free(script);
    exit(code);
}
<commit_msg>console: Fix wrong cast in coverage prefixes<commit_after>/* -*- mode: C; c-basic-offset: 4; indent-tabs-mode: nil; -*- */
/*
 * Copyright (c) 2008  litl, LLC
 *
 * 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 <config.h>
#include <string.h>
#include <stdlib.h>
#include <locale.h>

#include <gjs/gjs.h>

#include "coverage.h"

static char **include_path = NULL;
static char **coverage_prefixes = NULL;
static char *coverage_output_path = NULL;
static char *command = NULL;
static gboolean print_version = false;

static const char *GJS_COVERAGE_CACHE_FILE_NAME = ".internal-gjs-coverage-cache";

static GOptionEntry entries[] = {
    { "version", 0, 0, G_OPTION_ARG_NONE, &print_version, "Print GJS version and exit" },
    { "command", 'c', 0, G_OPTION_ARG_STRING, &command, "Program passed in as a string", "COMMAND" },
    { "coverage-prefix", 'C', 0, G_OPTION_ARG_STRING_ARRAY, &coverage_prefixes, "Add the prefix PREFIX to the list of files to generate coverage info for", "PREFIX" },
    { "coverage-output", 0, 0, G_OPTION_ARG_STRING, &coverage_output_path, "Write coverage output to a directory DIR. This option is mandatory when using --coverage-path", "DIR", },
    { "include-path", 'I', 0, G_OPTION_ARG_STRING_ARRAY, &include_path, "Add the directory DIR to the list of directories to search for js files.", "DIR" },
    { NULL }
};

static char **
strndupv(int           n,
         char * const *strv)
{
    int ix;
    if (n == 0)
        return NULL;
    char **retval = g_new(char *, n + 1);
    for (ix = 0; ix < n; ix++)
        retval[ix] = g_strdup(strv[ix]);
    retval[n] = NULL;
    return retval;
}

static char **
strcatv(char **strv1,
        char **strv2)
{
    if (strv1 == NULL && strv2 == NULL)
        return NULL;
    if (strv1 == NULL)
        return g_strdupv(strv2);
    if (strv2 == NULL)
        return g_strdupv(strv1);

    unsigned len1 = g_strv_length(strv1);
    unsigned len2 = g_strv_length(strv2);
    char **retval = g_new(char *, len1 + len2 + 1);
    unsigned ix;

    for (ix = 0; ix < len1; ix++)
        retval[ix] = g_strdup(strv1[ix]);
    for (ix = 0; ix < len2; ix++)
        retval[len1 + ix] = g_strdup(strv2[ix]);
    retval[len1 + len2] = NULL;

    return retval;
}

static void
check_script_args_for_stray_gjs_args(int           argc,
                                     char * const *argv)
{
    GError *error = NULL;
    char **new_coverage_prefixes = NULL;
    char *new_coverage_output_path = NULL;
    char **new_include_paths = NULL;
    static GOptionEntry script_check_entries[] = {
        { "coverage-prefix", 'C', 0, G_OPTION_ARG_STRING_ARRAY, &new_coverage_prefixes },
        { "coverage-output", 0, 0, G_OPTION_ARG_STRING, &new_coverage_output_path },
        { "include-path", 'I', 0, G_OPTION_ARG_STRING_ARRAY, &new_include_paths },
        { NULL }
    };
    char **argv_copy = g_new(char *, argc + 2);
    int ix, argc_copy = argc + 1;

    argv_copy[0] = g_strdup("dummy"); /* Fake argv[0] for GOptionContext */
    for (ix = 0; ix < argc; ix++)
        argv_copy[ix + 1] = g_strdup(argv[ix]);
    argv_copy[argc + 1] = NULL;

    GOptionContext *script_options = g_option_context_new(NULL);
    g_option_context_set_ignore_unknown_options(script_options, true);
    g_option_context_set_help_enabled(script_options, false);
    g_option_context_add_main_entries(script_options, script_check_entries, NULL);
    if (!g_option_context_parse(script_options, &argc_copy, &argv_copy, &error)) {
        g_warning("Scanning script arguments failed: %s", error->message);
        g_error_free(error);
        return;
    }

    if (new_coverage_prefixes != NULL) {
        g_warning("You used the --coverage-prefix option after the script on "
                  "the GJS command line. Support for this will be removed in a "
                  "future version. Place the option before the script or use "
                  "the GJS_COVERAGE_PREFIXES environment variable.");
        char **old_coverage_prefixes = coverage_prefixes;
        coverage_prefixes = strcatv(old_coverage_prefixes, new_coverage_prefixes);
        g_strfreev(old_coverage_prefixes);
    }
    if (new_include_paths != NULL) {
        g_warning("You used the --include-path option after the script on the "
                  "GJS command line. Support for this will be removed in a "
                  "future version. Place the option before the script or use "
                  "the GJS_PATH environment variable.");
        char **old_include_paths = include_path;
        include_path = strcatv(old_include_paths, new_include_paths);
        g_strfreev(old_include_paths);
    }
    if (new_coverage_output_path != NULL) {
        g_warning("You used the --coverage-output option after the script on "
                  "the GJS command line. Support for this will be removed in a "
                  "future version. Place the option before the script or use "
                  "the GJS_COVERAGE_OUTPUT environment variable.");
        g_free(coverage_output_path);
        coverage_output_path = new_coverage_output_path;
    }

    g_option_context_free(script_options);
    g_strfreev(argv_copy);
}

int
main(int argc, char **argv)
{
    GOptionContext *context;
    GError *error = NULL;
    GjsContext *js_context;
    GjsCoverage *coverage = NULL;
    char *script;
    const char *filename;
    const char *program_name;
    gsize len;
    int code, argc_copy = argc, gjs_argc = argc, script_argc, ix;
    char **argv_copy = g_strdupv(argv), **argv_copy_addr = argv_copy;
    char **gjs_argv, **gjs_argv_addr;
    char * const *script_argv;
    const char *env_coverage_output_path;
    const char *env_coverage_prefixes;

    setlocale(LC_ALL, "");

    context = g_option_context_new(NULL);

    g_option_context_set_ignore_unknown_options(context, true);
    g_option_context_set_help_enabled(context, false);

    g_option_context_add_main_entries(context, entries, NULL);
    if (!g_option_context_parse(context, &argc_copy, &argv_copy, &error))
        g_error("option parsing failed: %s", error->message);

    /* Split options so we pass unknown ones through to the JS script */
    for (ix = 1; ix < argc; ix++) {
        /* Check if a file was given and split after it */
        if (argc_copy >= 2 && strcmp(argv[ix], argv_copy[1]) == 0) {
            /* Filename given; split after this argument */
            gjs_argc = ix + 1;
            break;
        }

        /* Check if -c or --command was given and split after following arg */
        if (command != NULL &&
            (strcmp(argv[ix], "-c") == 0 || strcmp(argv[ix], "--command") == 0)) {
            gjs_argc = ix + 2;
            break;
        }
    }
    gjs_argv_addr = gjs_argv = strndupv(gjs_argc, argv);
    script_argc = argc - gjs_argc;
    script_argv = argv + gjs_argc;
    g_strfreev(argv_copy_addr);

    /* Parse again, only the GJS options this time */
    include_path = NULL;
    coverage_prefixes = NULL;
    coverage_output_path = NULL;
    command = NULL;
    print_version = false;
    g_option_context_set_ignore_unknown_options(context, false);
    g_option_context_set_help_enabled(context, true);
    if (!g_option_context_parse(context, &gjs_argc, &gjs_argv, &error))
        g_error("option parsing failed: %s", error->message);

    g_option_context_free (context);

    if (print_version) {
        g_print("%s\n", PACKAGE_STRING);
        exit(0);
    }

    if (command != NULL) {
        script = command;
        len = strlen(script);
        filename = "<command line>";
        program_name = gjs_argv[0];
    } else if (gjs_argc == 1) {
        script = g_strdup("const Console = imports.console; Console.interact();");
        len = strlen(script);
        filename = "<stdin>";
        program_name = gjs_argv[0];
    } else {
        /* All unprocessed options should be in script_argv */
        g_assert(gjs_argc == 2);
        error = NULL;
        if (!g_file_get_contents(gjs_argv[1], &script, &len, &error)) {
            g_printerr("%s\n", error->message);
            exit(1);
        }
        filename = gjs_argv[1];
        program_name = gjs_argv[1];
    }

    /* This should be removed after a suitable time has passed */
    check_script_args_for_stray_gjs_args(script_argc, script_argv);

    js_context = (GjsContext*) g_object_new(GJS_TYPE_CONTEXT,
                                            "search-path", include_path,
                                            "program-name", program_name,
                                            NULL);

    env_coverage_output_path = g_getenv("GJS_COVERAGE_OUTPUT");
    if (env_coverage_output_path != NULL) {
        g_free(coverage_output_path);
        coverage_output_path = g_strdup(env_coverage_output_path);
    }

    env_coverage_prefixes = g_getenv("GJS_COVERAGE_PREFIXES");
    if (env_coverage_prefixes != NULL) {
        if (coverage_prefixes != NULL)
            g_strfreev(coverage_prefixes);
        coverage_prefixes = g_strsplit(env_coverage_prefixes, ":", -1);
    }

    if (coverage_prefixes) {
        if (!coverage_output_path)
            g_error("--coverage-output is required when taking coverage statistics");

        char *path_to_cache_file = g_build_filename(coverage_output_path,
                                                    GJS_COVERAGE_CACHE_FILE_NAME,
                                                    NULL);
        coverage = gjs_coverage_new_from_cache((const gchar **) coverage_prefixes,
                                               js_context,
                                               path_to_cache_file);
        g_free(path_to_cache_file);
    }

    /* prepare command line arguments */
    if (!gjs_context_define_string_array(js_context, "ARGV",
                                         script_argc, (const char **) script_argv,
                                         &error)) {
        code = 1;
        g_printerr("Failed to defined ARGV: %s", error->message);
        g_clear_error(&error);
        goto out;
    }

    /* evaluate the script */
    if (!gjs_context_eval(js_context, script, len,
                          filename, &code, &error)) {
        code = 1;
        g_printerr("%s\n", error->message);
        g_clear_error(&error);
        goto out;
    }

 out:
    g_strfreev(gjs_argv_addr);

    /* Probably doesn't make sense to write statistics on failure */
    if (coverage && code == 0)
        gjs_coverage_write_statistics(coverage,
                                      coverage_output_path);

    g_free(coverage_output_path);
    g_strfreev(coverage_prefixes);
    g_object_unref(js_context);
    g_free(script);
    exit(code);
}
<|endoftext|>


<commit_before>#include "glwidget.h"

#include <QtOpenGL>

#ifdef __APPLE__
    #include <GLUT/glut.h>
#else
    #include <glut.h>
#endif

#include <QDebug>

#include "db/database.h"
#include "algorithms/pathalgorithms.h"
#include "../stable.h"

GLWidget::GLWidget(QWidget *parent) :
    QGLWidget(parent)
{
    canvasWidth = 0;
    canvasHeight = 0;
    timer = new QTimer(this);
    camera = new GLCamera();

    isStop = true;

    startPoint = 0;
    endPoint = 0;

}

void GLWidget::initializeGL()
{
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA);
    glClearColor(0, 0, 0, 1.0);
    glColor3f(1.0, 1.0, 1.0);

    glEnable(GL_DEPTH_TEST);
    glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
    glHint(GL_POINT_SMOOTH_HINT, GL_NICEST);

    glEnable(GL_POINT_SMOOTH);

//    glEnable( GL_POINT_SPRITE );
//    glEnable( GL_BLEND );

    connect(timer, SIGNAL(timeout()), this, SLOT(updateLC()));
    this->setFocus();
}

void GLWidget::updateLC()
{
    // Do my update stuff

    //map->update();

    updateGL();
}

void GLWidget::paintGL()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glLoadIdentity();

    gluLookAt(camera->x, camera->y, camera->z,
              camera->look_x, camera->look_y, camera->look_z,
              0.0, 1.0, 0.0);

    glPushMatrix();

    glColor3f(1.0f, 1.0f, 1.0f);

    glLineWidth(1.0f);

//    map<unsigned long int,Way*>* allWays = db->getAllWays();
    if(allWays == NULL)
        return;
    map<unsigned long int, Way*>::iterator wayIt;
    for(wayIt = allWays->begin(); wayIt != allWays->end(); ++wayIt)
    {
        glBegin(GL_LINE_STRIP);
        //((Way*)(*wayIt).second)->getNodesBegin()
        for (vector<Node*>::iterator nodeIt = ((Way*)(*wayIt).second)->getNodesBegin(); nodeIt != ((Way*)(*wayIt).second)->getNodesEnd(); nodeIt++){
            //cout<<(*nodeIt)->getId()<<endl;
            boost_xy_point& nodeGeoPos = (*nodeIt)->getGeoPosition();
            //qDebug() << "Node Pos: " << nodeGeoPos.x() << " " << nodeGeoPos.y();
            //glVertex2f(nodeGeoPos.x() * 1000000, nodeGeoPos.y() * 1000000);
            //glVertex2f(nodeGeoPos.x() * 100, nodeGeoPos.y() * 100);
            glVertex3f(nodeGeoPos.x() * 100, nodeGeoPos.y() * 100, 0.0f);
            //qDebug() << "Node Pos: " << nodeGeoPos.x() * 100<< " " << nodeGeoPos.y() * 100;
            //glVertex2d(nodeGeoPos.x(), nodeGeoPos.y());
            // lat="46.7918039" lon="4.4277047"
        }
        glEnd();
    }

////        vector<WaySegment*> segments_in_area;
////        //d->searchWaySegmentsInArea(boost_xy_point(46.78,4.402), boost_xy_point(46.79,4.403),segments_in_area);
////        d->searchWaySegmentsInArea(boost_xy_point(4.400,46.76), boost_xy_point(4.403,46.79),segments_in_area);

////        //qDebug() << "Size of the segment: " << segments_in_area.size();

////        glColor3f(1.0f, 0.0f, 0.0f);

////        for(int i = 0; i < segments_in_area.size(); i++)
////        {
////            WaySegment* waySegment = segments_in_area[i];
////            boost_xy_point& nodeGeoPosA = waySegment->getPointA()->getGeoPosition();
////            boost_xy_point& nodeGeoPosB = waySegment->getPointB()->getGeoPosition();
////            glBegin(GL_LINES);
////                glVertex3f(nodeGeoPosA.x() * 100, nodeGeoPosA.y() * 100, 1.0f);
////                glVertex3f(nodeGeoPosB.x() * 100, nodeGeoPosB.y() * 100, 1.0f);
////            glEnd();
////        }

//    glColor3f(1.0f, 0.0f, 0.0f);
//    glLineWidth(5.0f);

//    vector<WaySegment*> path;
//    float cost,time;
//    boost_xy_point start_point(4.4097667,46.7901184);
//    boost_xy_point end_point(4.4249021,46.7990036);
//    ns_permisions::transport_type tt = ns_permisions::foot;

//    bool found = PathAlgorithms::findShortestPath(d, start_point, end_point, tt, path, cost, time);
//    //bool found = PathAlgorithms::findShortestPath(&d, &start_point, &end_point, tt, path, cost, time);

//    if(found)
//    {
//        for(int i = 0; i < path.size(); i++)
//        {
//            WaySegment* waySegment = path[i];
//            boost_xy_point& nodeGeoPosA = waySegment->getPointA()->getGeoPosition();
//            boost_xy_point& nodeGeoPosB = waySegment->getPointB()->getGeoPosition();
//            glBegin(GL_LINES);
//            //qDebug() << "A: " <<nodeGeoPosA.x() << "-" << nodeGeoPosA.y();
//            //qDebug() << "B: " <<nodeGeoPosB.x() << "-" << nodeGeoPosB.y();
//            glVertex3f(nodeGeoPosA.x() * 100, nodeGeoPosA.y() * 100, 1.0f);
//            glVertex3f(nodeGeoPosB.x() * 100, nodeGeoPosB.y() * 100, 1.0f);
//            glEnd();
//        }
//    }

    glBegin(GL_LINES);
    if(startPoint != NULL)
    {
        glColor3f(0.0f, 0.0f, 1.0f);
        glVertex3f(startPoint->x() * 100.0f, startPoint->y() * 100.0f, 0.1f);
    }
    glColor3f(1.0f, 0.0f, 0.0f);
    for(int i = 0; i < path.size(); i++)
    {
        WaySegment* waySegment = path[i];
        boost_xy_point& nodeGeoPosA = waySegment->getPointA()->getGeoPosition();
        boost_xy_point& nodeGeoPosB = waySegment->getPointB()->getGeoPosition();
        //glBegin(GL_LINES);
        //qDebug() << "A: " <<nodeGeoPosA.x() << "-" << nodeGeoPosA.y();
        //qDebug() << "B: " <<nodeGeoPosB.x() << "-" << nodeGeoPosB.y();
        glVertex3f(nodeGeoPosA.x() * 100.0f, nodeGeoPosA.y() * 100.0f, 0.1f);
        glVertex3f(nodeGeoPosB.x() * 100.0f, nodeGeoPosB.y() * 100.0f, 0.1f);
        //glEnd();
    }
    if(endPoint != NULL)
    {
        glColor3f(0.0f, 0.0f, 1.0f);
        glVertex3f(endPoint->x() * 100.0f, endPoint->y() * 100.0f, 0.1f);
    }
    glEnd();

    if(startPoint != NULL)
    {
        glColor3f(0.0f, 1.0f, 0.0f);
        glPointSize(7.0f);
        glBegin(GL_POINTS);
        glVertex3f(startPoint->x() * 100.0f, startPoint->y() * 100.0f, 0.2f);
        glEnd();
    }

    if(endPoint != NULL)
    {
        glColor3f(1.0f, 0.0f, 0.0f);
        glPointSize(7.0f);
        glBegin(GL_POINTS);
        glVertex3f(endPoint->x() * 100.0f, endPoint->y() * 100.0f, 0.2f);
        glEnd();
    }

    glPopMatrix();
}

void GLWidget::resizeGL(int w, int h)
{
    glViewport(0, 0, w, h);

    camera->canvasWidth = w;
    camera->canvasHeight = h;

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    float ratio = float(w) / float(h);

    glOrtho(camera->planeLeft,
            camera->planeRight,
            camera->planeBottom,
            camera->planeTop,
            camera->planeNear,
            camera->planeFar);

    //gluPerspective(60.0, ratio, 1.0, 100.0);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
}

void GLWidget::keyPressEvent(QKeyEvent *event)
{
    switch (event->key())
    {
    case Qt::Key_W:
        camera->up();
        break;
    case Qt::Key_A:
        camera->left();
        break;
    case Qt::Key_S:
        camera->down();
        break;
    case Qt::Key_D:
        camera->right();
        break;
    case Qt::Key_Q:
        camera->zoomIn();
        break;
    case Qt::Key_E:
        camera->zoomOut();
        break;
    case Qt::Key_Up:
        camera->up();
        break;
    case Qt::Key_Down:
        camera->down();
        break;
    case Qt::Key_Left:
        camera->left();
        break;
    case Qt::Key_Right:
        camera->right();
        break;
    case Qt::Key_Plus:
        camera->zoomIn();
        break;
    case Qt::Key_Minus:
        camera->zoomOut();
        break;
    case Qt::Key_Escape:
        this->parentWidget()->parentWidget()->close();
        break;
    default:
        break;
    }

    event->accept();
}

void GLWidget::wheelEvent(QWheelEvent *event)
{
    if(event->orientation() == Qt::Vertical)
    {
        if(event->delta() > 0)
            camera->zoomIn();
        else
            camera->zoomOut();
    }
    else
    {
        if(event->delta() > 0)
            camera->right();
        else
            camera->left();
    }

    event->accept();
}

void GLWidget::mousePressEvent(QMouseEvent *event)
{
    lastPos = event->pos();
    event->accept();
}

void GLWidget::mouseMoveEvent(QMouseEvent *event)
{
    //qDebug() << "mouseMoveEvent"<<endl;
    int dx = event->x() - lastPos.x();
    int dy = event->y() - lastPos.y();

//    qDebug() << "lastPos.x: "<< lastPos.x() << " lastPost.y: " << lastPos.y() <<endl;
//    qDebug() << "event->x: "<< event->x() << " event->y: " << event->y() << endl;
//    qDebug() << "dx: "<< dx << " dy: " << dy << endl;
//    qDebug() << "===========================================" << endl;

    if (event->buttons() & Qt::LeftButton) {
        camera->move(dx, dy);
        //setXRotation(xRot + 8 * dy);
        //setYRotation(yRot + 8 * dx);
    } else if (event->buttons() & Qt::RightButton) {
        //setXRotation(xRot + 8 * dy);
        //setZRotation(zRot + 8 * dx);
    }

    lastPos = event->pos();
}

void GLWidget::startGL()
{
    isStop = false;
    timer->start(10);
}

void GLWidget::stopGL()
{
    isStop = true;
    timer->stop();
}

QPointF GLWidget::getGeoPosition(QPoint point)
{
    GLint viewport[4];
    GLdouble modelview[16];
    GLdouble projection[16];
    GLfloat winX, winY, winZ;
    GLdouble posX, posY, posZ;

    glGetDoublev(GL_MODELVIEW_MATRIX, modelview);
    glGetDoublev(GL_PROJECTION_MATRIX, projection);
    glGetIntegerv(GL_VIEWPORT, viewport);

    winX = (float)point.x();
    winY = (float)viewport[3] - (float)point.y();
    glReadPixels(point.x(), int(winY), 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &winZ);

    gluUnProject(winX, winY, winZ, modelview, projection, viewport, &posX, &posY, &posZ);

    return QPointF(posX / 100.0, posY / 100.0);
}

void GLWidget::centerMap()
{

}

void GLWidget::setMap(map<unsigned long int,Way*>* ways)
{
    allWays = ways;
}

void GLWidget::setPath(vector<WaySegment*> waySegments)
{
    path = waySegments;
}

void GLWidget::drawStartPoint(QPointF *startp)
{
    startPoint = startp;
}

void GLWidget::drawEndPoint(QPointF *endp)
{
    endPoint = endp;
}

void GLWidget::deleteStartPoint()
{
    delete startPoint;
    startPoint = 0;
}

void GLWidget::deleteEndPoint()
{
    delete endPoint;
    endPoint = 0;
}

void GLWidget::deletePath()
{
    path.clear();
}
<commit_msg>Start and End Drawing<commit_after>#include "glwidget.h"

#include <QtOpenGL>

#ifdef __APPLE__
    #include <GLUT/glut.h>
#else
    #include <glut.h>
#endif

#include <QDebug>

#include "db/database.h"
#include "algorithms/pathalgorithms.h"
#include "../stable.h"

GLWidget::GLWidget(QWidget *parent) :
    QGLWidget(parent)
{
    canvasWidth = 0;
    canvasHeight = 0;
    timer = new QTimer(this);
    camera = new GLCamera();

    isStop = true;

    startPoint = 0;
    endPoint = 0;

}

void GLWidget::initializeGL()
{
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA);
    glClearColor(0, 0, 0, 1.0);
    glColor3f(1.0, 1.0, 1.0);

    glEnable(GL_DEPTH_TEST);
    glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
    glHint(GL_POINT_SMOOTH_HINT, GL_NICEST);

    glEnable(GL_POINT_SMOOTH);

//    glEnable( GL_POINT_SPRITE );
//    glEnable( GL_BLEND );

    connect(timer, SIGNAL(timeout()), this, SLOT(updateLC()));
    this->setFocus();
}

void GLWidget::updateLC()
{
    // Do my update stuff

    //map->update();

    updateGL();
}

void GLWidget::paintGL()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glLoadIdentity();

    gluLookAt(camera->x, camera->y, camera->z,
              camera->look_x, camera->look_y, camera->look_z,
              0.0, 1.0, 0.0);

    glPushMatrix();

    glColor3f(1.0f, 1.0f, 1.0f);

    glLineWidth(1.0f);

//    map<unsigned long int,Way*>* allWays = db->getAllWays();
    if(allWays == NULL)
        return;
    map<unsigned long int, Way*>::iterator wayIt;
    for(wayIt = allWays->begin(); wayIt != allWays->end(); ++wayIt)
    {
        glBegin(GL_LINE_STRIP);
        //((Way*)(*wayIt).second)->getNodesBegin()
        for (vector<Node*>::iterator nodeIt = ((Way*)(*wayIt).second)->getNodesBegin(); nodeIt != ((Way*)(*wayIt).second)->getNodesEnd(); nodeIt++){
            //cout<<(*nodeIt)->getId()<<endl;
            boost_xy_point& nodeGeoPos = (*nodeIt)->getGeoPosition();
            //qDebug() << "Node Pos: " << nodeGeoPos.x() << " " << nodeGeoPos.y();
            //glVertex2f(nodeGeoPos.x() * 1000000, nodeGeoPos.y() * 1000000);
            //glVertex2f(nodeGeoPos.x() * 100, nodeGeoPos.y() * 100);
            glVertex3f(nodeGeoPos.x() * 100, nodeGeoPos.y() * 100, 0.0f);
            //qDebug() << "Node Pos: " << nodeGeoPos.x() * 100<< " " << nodeGeoPos.y() * 100;
            //glVertex2d(nodeGeoPos.x(), nodeGeoPos.y());
            // lat="46.7918039" lon="4.4277047"
        }
        glEnd();
    }

////        vector<WaySegment*> segments_in_area;
////        //d->searchWaySegmentsInArea(boost_xy_point(46.78,4.402), boost_xy_point(46.79,4.403),segments_in_area);
////        d->searchWaySegmentsInArea(boost_xy_point(4.400,46.76), boost_xy_point(4.403,46.79),segments_in_area);

////        //qDebug() << "Size of the segment: " << segments_in_area.size();

////        glColor3f(1.0f, 0.0f, 0.0f);

////        for(int i = 0; i < segments_in_area.size(); i++)
////        {
////            WaySegment* waySegment = segments_in_area[i];
////            boost_xy_point& nodeGeoPosA = waySegment->getPointA()->getGeoPosition();
////            boost_xy_point& nodeGeoPosB = waySegment->getPointB()->getGeoPosition();
////            glBegin(GL_LINES);
////                glVertex3f(nodeGeoPosA.x() * 100, nodeGeoPosA.y() * 100, 1.0f);
////                glVertex3f(nodeGeoPosB.x() * 100, nodeGeoPosB.y() * 100, 1.0f);
////            glEnd();
////        }

//    glColor3f(1.0f, 0.0f, 0.0f);
//    glLineWidth(5.0f);

//    vector<WaySegment*> path;
//    float cost,time;
//    boost_xy_point start_point(4.4097667,46.7901184);
//    boost_xy_point end_point(4.4249021,46.7990036);
//    ns_permisions::transport_type tt = ns_permisions::foot;

//    bool found = PathAlgorithms::findShortestPath(d, start_point, end_point, tt, path, cost, time);
//    //bool found = PathAlgorithms::findShortestPath(&d, &start_point, &end_point, tt, path, cost, time);

//    if(found)
//    {
//        for(int i = 0; i < path.size(); i++)
//        {
//            WaySegment* waySegment = path[i];
//            boost_xy_point& nodeGeoPosA = waySegment->getPointA()->getGeoPosition();
//            boost_xy_point& nodeGeoPosB = waySegment->getPointB()->getGeoPosition();
//            glBegin(GL_LINES);
//            //qDebug() << "A: " <<nodeGeoPosA.x() << "-" << nodeGeoPosA.y();
//            //qDebug() << "B: " <<nodeGeoPosB.x() << "-" << nodeGeoPosB.y();
//            glVertex3f(nodeGeoPosA.x() * 100, nodeGeoPosA.y() * 100, 1.0f);
//            glVertex3f(nodeGeoPosB.x() * 100, nodeGeoPosB.y() * 100, 1.0f);
//            glEnd();
//        }
//    }

    glColor3f(1.0f, 0.0f, 0.0f);
        glBegin(GL_LINES);
        if(startPoint != NULL && !path.empty())
        {
            glColor3f(0.0f, 0.0f, 1.0f);
            glVertex3f(startPoint->x() * 100.0f, startPoint->y() * 100.0f, 0.1f);
            WaySegment* waySegment = path[0];
            boost_xy_point& nodeGeoPosA = waySegment->getPointA()->getGeoPosition();
            boost_xy_point& nodeGeoPosB = waySegment->getPointB()->getGeoPosition();
            glVertex3f(nodeGeoPosA.x() * 100.0f, nodeGeoPosA.y() * 100.0f, 0.1f);
        }
        glColor3f(1.0f, 0.0f, 0.0f);
        int i;
        for(i = 0; i < path.size(); i++)
        {
            WaySegment* waySegment = path[i];
            boost_xy_point& nodeGeoPosA = waySegment->getPointA()->getGeoPosition();
            boost_xy_point& nodeGeoPosB = waySegment->getPointB()->getGeoPosition();
            //glBegin(GL_LINES);
            //qDebug() << "A: " <<nodeGeoPosA.x() << "-" << nodeGeoPosA.y();
            //qDebug() << "B: " <<nodeGeoPosB.x() << "-" << nodeGeoPosB.y();
            glVertex3f(nodeGeoPosA.x() * 100.0f, nodeGeoPosA.y() * 100.0f, 0.1f);
            glVertex3f(nodeGeoPosB.x() * 100.0f, nodeGeoPosB.y() * 100.0f, 0.1f);
            //glEnd();
        }
        if(endPoint != NULL && !path.empty())
        {
            glColor3f(0.0f, 0.0f, 1.0f);
            WaySegment* waySegment = path[i-1];
            boost_xy_point& nodeGeoPosA = waySegment->getPointA()->getGeoPosition();
            boost_xy_point& nodeGeoPosB = waySegment->getPointB()->getGeoPosition();
            glVertex3f(nodeGeoPosB.x() * 100.0f, nodeGeoPosB.y() * 100.0f, 0.1f);
            glVertex3f(endPoint->x() * 100.0f, endPoint->y() * 100.0f, 0.1f);
        }
        glEnd();

    if(startPoint != NULL)
    {
        glColor3f(0.0f, 1.0f, 0.0f);
        glPointSize(7.0f);
        glBegin(GL_POINTS);
        glVertex3f(startPoint->x() * 100.0f, startPoint->y() * 100.0f, 0.2f);
        glEnd();
    }

    if(endPoint != NULL)
    {
        glColor3f(1.0f, 0.0f, 0.0f);
        glPointSize(7.0f);
        glBegin(GL_POINTS);
        glVertex3f(endPoint->x() * 100.0f, endPoint->y() * 100.0f, 0.2f);
        glEnd();
    }

    glPopMatrix();
}

void GLWidget::resizeGL(int w, int h)
{
    glViewport(0, 0, w, h);

    camera->canvasWidth = w;
    camera->canvasHeight = h;

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    float ratio = float(w) / float(h);

    glOrtho(camera->planeLeft,
            camera->planeRight,
            camera->planeBottom,
            camera->planeTop,
            camera->planeNear,
            camera->planeFar);

    //gluPerspective(60.0, ratio, 1.0, 100.0);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
}

void GLWidget::keyPressEvent(QKeyEvent *event)
{
    switch (event->key())
    {
    case Qt::Key_W:
        camera->up();
        break;
    case Qt::Key_A:
        camera->left();
        break;
    case Qt::Key_S:
        camera->down();
        break;
    case Qt::Key_D:
        camera->right();
        break;
    case Qt::Key_Q:
        camera->zoomIn();
        break;
    case Qt::Key_E:
        camera->zoomOut();
        break;
    case Qt::Key_Up:
        camera->up();
        break;
    case Qt::Key_Down:
        camera->down();
        break;
    case Qt::Key_Left:
        camera->left();
        break;
    case Qt::Key_Right:
        camera->right();
        break;
    case Qt::Key_Plus:
        camera->zoomIn();
        break;
    case Qt::Key_Minus:
        camera->zoomOut();
        break;
    case Qt::Key_Escape:
        this->parentWidget()->parentWidget()->close();
        break;
    default:
        break;
    }

    event->accept();
}

void GLWidget::wheelEvent(QWheelEvent *event)
{
    if(event->orientation() == Qt::Vertical)
    {
        if(event->delta() > 0)
            camera->zoomIn();
        else
            camera->zoomOut();
    }
    else
    {
        if(event->delta() > 0)
            camera->right();
        else
            camera->left();
    }

    event->accept();
}

void GLWidget::mousePressEvent(QMouseEvent *event)
{
    lastPos = event->pos();
    event->accept();
}

void GLWidget::mouseMoveEvent(QMouseEvent *event)
{
    //qDebug() << "mouseMoveEvent"<<endl;
    int dx = event->x() - lastPos.x();
    int dy = event->y() - lastPos.y();

//    qDebug() << "lastPos.x: "<< lastPos.x() << " lastPost.y: " << lastPos.y() <<endl;
//    qDebug() << "event->x: "<< event->x() << " event->y: " << event->y() << endl;
//    qDebug() << "dx: "<< dx << " dy: " << dy << endl;
//    qDebug() << "===========================================" << endl;

    if (event->buttons() & Qt::LeftButton) {
        camera->move(dx, dy);
        //setXRotation(xRot + 8 * dy);
        //setYRotation(yRot + 8 * dx);
    } else if (event->buttons() & Qt::RightButton) {
        //setXRotation(xRot + 8 * dy);
        //setZRotation(zRot + 8 * dx);
    }

    lastPos = event->pos();
}

void GLWidget::startGL()
{
    isStop = false;
    timer->start(10);
}

void GLWidget::stopGL()
{
    isStop = true;
    timer->stop();
}

QPointF GLWidget::getGeoPosition(QPoint point)
{
    GLint viewport[4];
    GLdouble modelview[16];
    GLdouble projection[16];
    GLfloat winX, winY, winZ;
    GLdouble posX, posY, posZ;

    glGetDoublev(GL_MODELVIEW_MATRIX, modelview);
    glGetDoublev(GL_PROJECTION_MATRIX, projection);
    glGetIntegerv(GL_VIEWPORT, viewport);

    winX = (float)point.x();
    winY = (float)viewport[3] - (float)point.y();
    glReadPixels(point.x(), int(winY), 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &winZ);

    gluUnProject(winX, winY, winZ, modelview, projection, viewport, &posX, &posY, &posZ);

    return QPointF(posX / 100.0, posY / 100.0);
}

void GLWidget::centerMap()
{

}

void GLWidget::setMap(map<unsigned long int,Way*>* ways)
{
    allWays = ways;
}

void GLWidget::setPath(vector<WaySegment*> waySegments)
{
    path = waySegments;
}

void GLWidget::drawStartPoint(QPointF *startp)
{
    startPoint = startp;
}

void GLWidget::drawEndPoint(QPointF *endp)
{
    endPoint = endp;
}

void GLWidget::deleteStartPoint()
{
    delete startPoint;
    startPoint = 0;
}

void GLWidget::deleteEndPoint()
{
    delete endPoint;
    endPoint = 0;
}

void GLWidget::deletePath()
{
    path.clear();
}
<|endoftext|>


<commit_before>
#include <cmath>
#include <string>

using namespace std;

namespace euler
{
    namespace problems
    {
        class Problem003 : public IProblem
        {
        public:
            bool IsProblemSolved()
            {
                return _isProblemSolved;
            }

            uint32_t GetProblemNumber()
            {
                return 3;
            }

            string GetProblemDescription()
            {
                return
                    "Project Euler #3 - Largest Prime Factor"
                    "\n\n"
                    "The prime factors of 13195 are 5, 7, 13 and 29."
                    "\n\n"
                    "What is the largest prime factor of the number "
                    "600851475143?";
            }

            void SolveProblem()
            {
                const uint64_t composite = 600851475143;
                uint64_t squareRoot = sqrt((double)composite);

                uint64_t prime = 2;
                uint64_t largestPrime;

                uint64_t quotient = composite;

                while (prime <= squareRoot)
                {
                    if (quotient % prime == 0)
                    {
                        quotient /= prime;

                        if (isPrime(quotient))
                        {
                            largestPrime = quotient;
                            break;
                        }
                    }
                    else
                        prime = getNextPrime(prime);
                }

                _computedAnswer = largestPrime;
                _isProblemSolved = true;
            }

            string GetComputedAnswer()
            {
                return to_string(_computedAnswer);
            }

            string GetCorrectAnswer()
            {
                return to_string(_correctAnswer);
            }

        private:
            bool _isProblemSolved = false;
            uint64_t _computedAnswer;
            uint64_t _correctAnswer = 6857;

            uint64_t getNextPrime(uint64_t num)
            {
                uint64_t origNum = num;

                if (num % 2 == 0 || num == 1)
                {
                    num += 1;

                    if (!isPrime(num))
                        num = getNextPrime(num);
                }
                else
                {
                    while (num == origNum || !isPrime(num))
                    {
                        num += 2;
                    }
                }

                return num;
            }

            bool isPrime(uint64_t num)
            {
                // 1 is an exceptional case - it is an odd number that is only divisible by
                // one and itself that is not prime.
                if (num == 1)
                    return false;
                // 2 is an exceptional case - it is an even number divided by 1 and itself,
                // so it is a prime number.
                if (num == 2)
                    return true;

                bool prime = true;
                uint64_t i = 2;

                if (num % 2 != 0)
                {
                    while (i <= sqrt((double)num))
                    {
                        if (num % i == 0)
                            prime = false;

                        if (i == 2)
                            i++;
                        else
                            i += 2;
                    }
                }
                else
                    prime = false;

                return prime;
            }
        };
    }
}
<commit_msg>Correct uninitialzed variable in problem 3.<commit_after>
#include <cmath>
#include <string>

using namespace std;

namespace euler
{
    namespace problems
    {
        class Problem003 : public IProblem
        {
        public:
            bool IsProblemSolved()
            {
                return _isProblemSolved;
            }

            uint32_t GetProblemNumber()
            {
                return 3;
            }

            string GetProblemDescription()
            {
                return
                    "Project Euler #3 - Largest Prime Factor"
                    "\n\n"
                    "The prime factors of 13195 are 5, 7, 13 and 29."
                    "\n\n"
                    "What is the largest prime factor of the number "
                    "600851475143?";
            }

            void SolveProblem()
            {
                const uint64_t composite = 600851475143;
                uint64_t squareRoot = sqrt((double)composite);

                uint64_t prime = 2;
                uint64_t largestPrime = 0;

                uint64_t quotient = composite;

                while (prime <= squareRoot)
                {
                    if (quotient % prime == 0)
                    {
                        quotient /= prime;

                        if (isPrime(quotient))
                        {
                            largestPrime = quotient;
                            break;
                        }
                    }
                    else
                        prime = getNextPrime(prime);
                }

                _computedAnswer = largestPrime;
                _isProblemSolved = true;
            }

            string GetComputedAnswer()
            {
                return to_string(_computedAnswer);
            }

            string GetCorrectAnswer()
            {
                return to_string(_correctAnswer);
            }

        private:
            bool _isProblemSolved = false;
            uint64_t _computedAnswer;
            uint64_t _correctAnswer = 6857;

            uint64_t getNextPrime(uint64_t num)
            {
                uint64_t origNum = num;

                if (num % 2 == 0 || num == 1)
                {
                    num += 1;

                    if (!isPrime(num))
                        num = getNextPrime(num);
                }
                else
                {
                    while (num == origNum || !isPrime(num))
                    {
                        num += 2;
                    }
                }

                return num;
            }

            bool isPrime(uint64_t num)
            {
                // 1 is an exceptional case - it is an odd number that is only divisible by
                // one and itself that is not prime.
                if (num == 1)
                    return false;
                // 2 is an exceptional case - it is an even number divided by 1 and itself,
                // so it is a prime number.
                if (num == 2)
                    return true;

                bool prime = true;
                uint64_t i = 2;

                if (num % 2 != 0)
                {
                    while (i <= sqrt((double)num))
                    {
                        if (num % i == 0)
                            prime = false;

                        if (i == 2)
                            i++;
                        else
                            i += 2;
                    }
                }
                else
                    prime = false;

                return prime;
            }
        };
    }
}
<|endoftext|>