<commit_before>/*
Copyright (c) 2013 Daniele Bartolini, Michele Rossi
Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto

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 <stdarg.h>

#include "LuaEnvironment.h"
#include "Assert.h"
#include "StringUtils.h"
#include "LuaStack.h"
#include "Device.h"
#include "LuaResource.h"
#include "ResourceManager.h"

namespace crown
{

extern int vector3_add(lua_State* L);
extern int vector3_subtract(lua_State* L);
extern int vector3_multiply(lua_State* L);
extern int vector3_divide(lua_State* L);
extern int vector3_negate(lua_State* L);
extern int vector3(lua_State* L);

//-----------------------------------------------------------------------------
CE_EXPORT int luaopen_libcrown(lua_State* /*L*/)
{
	LuaEnvironment* env = device()->lua_environment();

	load_int_setting(*env);
	load_float_setting(*env);
	load_string_setting(*env);

	load_vector2(*env);
	load_vector3(*env);
	load_matrix4x4(*env);
	load_quaternion(*env);
	load_math(*env);
	load_window(*env);
	load_mouse(*env);
	load_keyboard(*env);
	load_accelerometer(*env);
	load_device(*env);
	load_resource_package(*env);

	load_unit(*env);
	load_camera(*env);
	load_world(*env);
	load_mesh(*env);
	load_sprite(*env);

	return 1;
}

//-----------------------------------------------------------------------------
static int crown_lua_lightuserdata_add(lua_State* L)
{
	return vector3_add(L);
}

//-----------------------------------------------------------------------------
static int crown_lua_lightuserdata_sub(lua_State* L)
{
	return vector3_subtract(L);
}

//-----------------------------------------------------------------------------
static int crown_lua_lightuserdata_mul(lua_State* L)
{
	return vector3_multiply(L);
}

//-----------------------------------------------------------------------------
static int crown_lua_lightuserdata_div(lua_State* L)
{
	return vector3_divide(L);
}

//-----------------------------------------------------------------------------
static int crown_lua_lightuserdata_unm(lua_State* L)
{
	return vector3_negate(L);
}

//-----------------------------------------------------------------------------
static int crown_lua_require(lua_State* L)
{
	LuaStack stack(L);

	const char* filename = stack.get_string(1);

	const ResourceId lua_res = device()->resource_manager()->load("lua", filename);
	device()->resource_manager()->flush();

	const LuaResource* lr = (LuaResource*) device()->resource_manager()->data(lua_res);
	luaL_loadbuffer(L, (const char*) lr->code(), lr->size(), "");

	device()->resource_manager()->unload(lua_res);

	return 1;
}

//-----------------------------------------------------------------------------
LuaEnvironment::LuaEnvironment()
	: m_state(luaL_newstate())
{
}

//-----------------------------------------------------------------------------
void LuaEnvironment::init()
{
	// Open default libraries
	luaL_openlibs(m_state);
	// Open Crown library
	lua_cpcall(m_state, luaopen_libcrown, NULL);

	// Register custom loader
	lua_getfield(m_state, LUA_GLOBALSINDEX, "package");
	lua_getfield(m_state, -1, "loaders");
	lua_remove(m_state, -2);

	int num_loaders = 0;
	lua_pushnil(m_state);
	while (lua_next(m_state, -2) != 0)
	{
		lua_pop(m_state, 1);
		num_loaders++;
	}

	lua_pushinteger(m_state, num_loaders + 1);
	lua_pushcfunction(m_state, crown_lua_require);
	lua_rawset(m_state, -3);

	lua_pop(m_state, 1);

	// Create metatable for lightuserdata
	lua_pushlightuserdata(m_state, (void*)0x0);
	luaL_newmetatable(m_state, "Crown.lightuserdata.metatable");
	lua_setmetatable(m_state, -2);
	lua_pop(m_state, 1);

	luaL_newmetatable(m_state, "Crown.lightuserdata.metatable");

	lua_pushstring(m_state, "__add");
	lua_pushcfunction(m_state, crown_lua_lightuserdata_add);
	lua_settable(m_state, 1);

	lua_pushstring(m_state, "__sub");
	lua_pushcfunction(m_state, crown_lua_lightuserdata_sub);
	lua_settable(m_state, 1);

	lua_pushstring(m_state, "__mul");
	lua_pushcfunction(m_state, crown_lua_lightuserdata_mul);
	lua_settable(m_state, 1);

	lua_pushstring(m_state, "__div");
	lua_pushcfunction(m_state, crown_lua_lightuserdata_div);
	lua_settable(m_state, 1);

	lua_pushstring(m_state, "__unm");
	lua_pushcfunction(m_state, crown_lua_lightuserdata_unm);
	lua_settable(m_state, 1);
}

//-----------------------------------------------------------------------------
void LuaEnvironment::shutdown()
{
	lua_close(m_state);
}

//-----------------------------------------------------------------------------
bool LuaEnvironment::load_and_execute(const char* res_name)
{
	CE_ASSERT_NOT_NULL(res_name);

	ResourceManager* resman = device()->resource_manager();

	// Load the resource
	ResourceId res_id = resman->load("lua", res_name);
	resman->flush();
	LuaResource* lr = (LuaResource*) resman->data(res_id);

	lua_getglobal(m_state, "debug");
	lua_getfield(m_state, -1, "traceback");
	if (luaL_loadbuffer(m_state, (const char*) lr->code(), lr->size(), res_name) == 0)
	{
		if (lua_pcall(m_state, 0, 0, -2) == 0)
		{
			// Unloading is OK since the script data has been copied to Lua
			resman->unload(res_id);
			lua_pop(m_state, 2); // Pop debug.traceback
			return true;
		}
	}

	error();
	lua_pop(m_state, 2); // Pop debug.traceback
	return false;
}

//-----------------------------------------------------------------------------
bool LuaEnvironment::execute_string(const char* s)
{
	CE_ASSERT_NOT_NULL(s);

	lua_getglobal(m_state, "debug");
	lua_getfield(m_state, -1, "traceback");
	if (luaL_loadstring(m_state, s) == 0)
	{
		if (lua_pcall(m_state, 0, 0, -2) == 0)
		{
			// Unloading is OK since the script data has been copied to Lua
			lua_pop(m_state, 2); // Pop debug.traceback
			return true;
		}
	}

	error();
	lua_pop(m_state, 2); // Pop debug.traceback
	return false;
}

//-----------------------------------------------------------------------------
void LuaEnvironment::load_module_function(const char* module, const char* name, const lua_CFunction func)
{
	luaL_Reg entry[2];

	entry[0].name = name;
	entry[0].func = func;
	entry[1].name = NULL;
	entry[1].func = NULL;

	luaL_register(m_state, module, entry);
}

//-----------------------------------------------------------
void LuaEnvironment::load_module_enum(const char* /*module*/, const char* name, uint32_t value)
{
	lua_pushinteger(m_state, value);
	lua_setfield(m_state, -2, name);
}

//-----------------------------------------------------------------------------
bool LuaEnvironment::call_global(const char* func, uint8_t argc, ...)
{
	CE_ASSERT_NOT_NULL(func);

	LuaStack stack(m_state);

	va_list vl;
	va_start(vl, argc);

	lua_getglobal(m_state, "debug");
	lua_getfield(m_state, -1, "traceback");
	lua_getglobal(m_state, func);

	for (uint8_t i = 0; i < argc; i++)
	{
		const int type = va_arg(vl, int);
		switch (type)
		{
			case ARGUMENT_FLOAT:
			{
				stack.push_float(va_arg(vl, double));
				break;
			}
			default:
			{
				CE_ASSERT(false, "Oops, lua argument unknown");
				break;
			}
		}
	}

	va_end(vl);

	if (lua_pcall(m_state, argc, 0, -argc - 2) != 0)
	{
		error();
		lua_pop(m_state, 2); // Pop debug.traceback
		return false;
	}

	lua_pop(m_state, 2); // Pop debug.traceback

	return true;
}

//-----------------------------------------------------------------------------
void LuaEnvironment::error()
{
	const char* msg = lua_tostring(m_state, -1);
	Log::e(msg);
	lua_pop(m_state, 1);
}

} // namespace crown<commit_msg>Add metatable to Vector2/Vector3/Matrix4x4/Quaternion in order to prevent engine hackers from injuries of any kind. And also to improve Lua code readability<commit_after>/*
Copyright (c) 2013 Daniele Bartolini, Michele Rossi
Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto

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 <stdarg.h>

#include "LuaEnvironment.h"
#include "Assert.h"
#include "StringUtils.h"
#include "LuaStack.h"
#include "Device.h"
#include "LuaResource.h"
#include "ResourceManager.h"

namespace crown
{

extern int vector3_add(lua_State* L);
extern int vector3_subtract(lua_State* L);
extern int vector3_multiply(lua_State* L);
extern int vector3_divide(lua_State* L);
extern int vector3_negate(lua_State* L);
extern int vector2(lua_State* L);
extern int vector3(lua_State* L);
extern int matrix4x4(lua_State* L);
extern int quaternion(lua_State* L);

//-----------------------------------------------------------------------------
CE_EXPORT int luaopen_libcrown(lua_State* /*L*/)
{
	LuaEnvironment* env = device()->lua_environment();

	load_int_setting(*env);
	load_float_setting(*env);
	load_string_setting(*env);

	load_vector2(*env);
	load_vector3(*env);
	load_matrix4x4(*env);
	load_quaternion(*env);
	load_math(*env);
	load_window(*env);
	load_mouse(*env);
	load_keyboard(*env);
	load_accelerometer(*env);
	load_device(*env);
	load_resource_package(*env);

	load_unit(*env);
	load_camera(*env);
	load_world(*env);
	load_mesh(*env);
	load_sprite(*env);

	return 1;
}

//-----------------------------------------------------------------------------
static int crown_lua_vector2_call(lua_State* L)
{
	lua_remove(L, 1);
	return vector2(L);
}

//-----------------------------------------------------------------------------
static int crown_lua_vector3_call(lua_State* L)
{
	lua_remove(L, 1);
	return vector3(L);
}

//-----------------------------------------------------------------------------
static int crown_lua_matrix4x4_call(lua_State* L)
{
	lua_remove(L, 1);
	return matrix4x4(L);
}

//-----------------------------------------------------------------------------
static int crown_lua_quaternion_call(lua_State* L)
{
	lua_remove(L, 1);
	return quaternion(L);
}

//-----------------------------------------------------------------------------
static int crown_lua_lightuserdata_add(lua_State* L)
{
	return vector3_add(L);
}

//-----------------------------------------------------------------------------
static int crown_lua_lightuserdata_sub(lua_State* L)
{
	return vector3_subtract(L);
}

//-----------------------------------------------------------------------------
static int crown_lua_lightuserdata_mul(lua_State* L)
{
	return vector3_multiply(L);
}

//-----------------------------------------------------------------------------
static int crown_lua_lightuserdata_div(lua_State* L)
{
	return vector3_divide(L);
}

//-----------------------------------------------------------------------------
static int crown_lua_lightuserdata_unm(lua_State* L)
{
	return vector3_negate(L);
}

//-----------------------------------------------------------------------------
static int crown_lua_require(lua_State* L)
{
	LuaStack stack(L);

	const char* filename = stack.get_string(1);

	const ResourceId lua_res = device()->resource_manager()->load("lua", filename);
	device()->resource_manager()->flush();

	const LuaResource* lr = (LuaResource*) device()->resource_manager()->data(lua_res);
	luaL_loadbuffer(L, (const char*) lr->code(), lr->size(), "");

	device()->resource_manager()->unload(lua_res);

	return 1;
}

//-----------------------------------------------------------------------------
LuaEnvironment::LuaEnvironment()
	: m_state(luaL_newstate())
{
}

//-----------------------------------------------------------------------------
void LuaEnvironment::init()
{
	// Open default libraries
	luaL_openlibs(m_state);
	// Open Crown library
	lua_cpcall(m_state, luaopen_libcrown, NULL);

	// Register custom loader
	lua_getfield(m_state, LUA_GLOBALSINDEX, "package");
	lua_getfield(m_state, -1, "loaders");
	lua_remove(m_state, -2);

	int num_loaders = 0;
	lua_pushnil(m_state);
	while (lua_next(m_state, -2) != 0)
	{
		lua_pop(m_state, 1);
		num_loaders++;
	}

	lua_pushinteger(m_state, num_loaders + 1);
	lua_pushcfunction(m_state, crown_lua_require);
	lua_rawset(m_state, -3);

	lua_pop(m_state, 1);

	// Create metatable for lightuserdata
	lua_pushlightuserdata(m_state, (void*)0x0);
	luaL_newmetatable(m_state, "Lightuserdata_mt");
	lua_setmetatable(m_state, -2);
	lua_pop(m_state, 1);

	luaL_newmetatable(m_state, "Lightuserdata_mt");

	lua_pushstring(m_state, "__add");
	lua_pushcfunction(m_state, crown_lua_lightuserdata_add);
	lua_settable(m_state, 1);

	lua_pushstring(m_state, "__sub");
	lua_pushcfunction(m_state, crown_lua_lightuserdata_sub);
	lua_settable(m_state, 1);

	lua_pushstring(m_state, "__mul");
	lua_pushcfunction(m_state, crown_lua_lightuserdata_mul);
	lua_settable(m_state, 1);

	lua_pushstring(m_state, "__div");
	lua_pushcfunction(m_state, crown_lua_lightuserdata_div);
	lua_settable(m_state, 1);

	lua_pushstring(m_state, "__unm");
	lua_pushcfunction(m_state, crown_lua_lightuserdata_unm);
	lua_settable(m_state, 1);

	// Vector2 metatable
	luaL_newmetatable(m_state, "Vector2_mt");
	lua_pushvalue(m_state, -1);
	lua_setfield(m_state, -2, "__index");
	lua_pushcfunction(m_state, crown_lua_vector2_call);
	lua_setfield(m_state, -2, "__call");

	lua_getglobal(m_state, "Vector2");
	lua_pushvalue(m_state, -2); // Duplicate metatable
	lua_setmetatable(m_state, -2); // setmetatable(Vector2, Vector2_mt)

	// Vector3 metatable
	luaL_newmetatable(m_state, "Vector3_mt");
	lua_pushvalue(m_state, -1);
	lua_setfield(m_state, -2, "__index");
	lua_pushcfunction(m_state, crown_lua_vector3_call);
	lua_setfield(m_state, -2, "__call");

	lua_getglobal(m_state, "Vector3");
	lua_pushvalue(m_state, -2); // Duplicate metatable
	lua_setmetatable(m_state, -2); // setmetatable(Vector3, Vector3_mt)

	// Matrix4x4 metatable
	luaL_newmetatable(m_state, "Matrix4x4_mt");
	lua_pushvalue(m_state, -1);
	lua_setfield(m_state, -2, "__index");
	lua_pushcfunction(m_state, crown_lua_matrix4x4_call);
	lua_setfield(m_state, -2, "__call");

	lua_getglobal(m_state, "Matrix4x4");
	lua_pushvalue(m_state, -2); // Duplicate metatable
	lua_setmetatable(m_state, -2); // setmetatable(Matrix4x4, Matrix4x4_mt)

	// Quaternion metatable
	luaL_newmetatable(m_state, "Quaternion_mt");
	lua_pushvalue(m_state, -1);
	lua_setfield(m_state, -2, "__index");
	lua_pushcfunction(m_state, crown_lua_quaternion_call);
	lua_setfield(m_state, -2, "__call");

	lua_getglobal(m_state, "Quaternion");
	lua_pushvalue(m_state, -2); // Duplicate metatable
	lua_setmetatable(m_state, -2); // setmetatable(Quaternion, Quaternion_mt)
}

//-----------------------------------------------------------------------------
void LuaEnvironment::shutdown()
{
	lua_close(m_state);
}

//-----------------------------------------------------------------------------
bool LuaEnvironment::load_and_execute(const char* res_name)
{
	CE_ASSERT_NOT_NULL(res_name);

	ResourceManager* resman = device()->resource_manager();

	// Load the resource
	ResourceId res_id = resman->load("lua", res_name);
	resman->flush();
	LuaResource* lr = (LuaResource*) resman->data(res_id);

	lua_getglobal(m_state, "debug");
	lua_getfield(m_state, -1, "traceback");
	if (luaL_loadbuffer(m_state, (const char*) lr->code(), lr->size(), res_name) == 0)
	{
		if (lua_pcall(m_state, 0, 0, -2) == 0)
		{
			// Unloading is OK since the script data has been copied to Lua
			resman->unload(res_id);
			lua_pop(m_state, 2); // Pop debug.traceback
			return true;
		}
	}

	error();
	lua_pop(m_state, 2); // Pop debug.traceback
	return false;
}

//-----------------------------------------------------------------------------
bool LuaEnvironment::execute_string(const char* s)
{
	CE_ASSERT_NOT_NULL(s);

	lua_getglobal(m_state, "debug");
	lua_getfield(m_state, -1, "traceback");
	if (luaL_loadstring(m_state, s) == 0)
	{
		if (lua_pcall(m_state, 0, 0, -2) == 0)
		{
			// Unloading is OK since the script data has been copied to Lua
			lua_pop(m_state, 2); // Pop debug.traceback
			return true;
		}
	}

	error();
	lua_pop(m_state, 2); // Pop debug.traceback
	return false;
}

//-----------------------------------------------------------------------------
void LuaEnvironment::load_module_function(const char* module, const char* name, const lua_CFunction func)
{
	luaL_Reg entry[2];

	entry[0].name = name;
	entry[0].func = func;
	entry[1].name = NULL;
	entry[1].func = NULL;

	luaL_register(m_state, module, entry);
}

//-----------------------------------------------------------
void LuaEnvironment::load_module_enum(const char* /*module*/, const char* name, uint32_t value)
{
	lua_pushinteger(m_state, value);
	lua_setfield(m_state, -2, name);
}

//-----------------------------------------------------------------------------
bool LuaEnvironment::call_global(const char* func, uint8_t argc, ...)
{
	CE_ASSERT_NOT_NULL(func);

	LuaStack stack(m_state);

	va_list vl;
	va_start(vl, argc);

	lua_getglobal(m_state, "debug");
	lua_getfield(m_state, -1, "traceback");
	lua_getglobal(m_state, func);

	for (uint8_t i = 0; i < argc; i++)
	{
		const int type = va_arg(vl, int);
		switch (type)
		{
			case ARGUMENT_FLOAT:
			{
				stack.push_float(va_arg(vl, double));
				break;
			}
			default:
			{
				CE_ASSERT(false, "Oops, lua argument unknown");
				break;
			}
		}
	}

	va_end(vl);

	if (lua_pcall(m_state, argc, 0, -argc - 2) != 0)
	{
		error();
		lua_pop(m_state, 2); // Pop debug.traceback
		return false;
	}

	lua_pop(m_state, 2); // Pop debug.traceback

	return true;
}

//-----------------------------------------------------------------------------
void LuaEnvironment::error()
{
	const char* msg = lua_tostring(m_state, -1);
	Log::e(msg);
	lua_pop(m_state, 1);
}

} // namespace crown<|endoftext|>


<commit_before>// Copyright 2012-2013 Samplecount S.L.
//
// 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.

#ifndef METHCLA_MEMORY_HPP_INCLUDED
#define METHCLA_MEMORY_HPP_INCLUDED

#include <boost/assert.hpp>
#include <cstddef>
#include <cstdint>

namespace Methcla { namespace Memory {

class Alignment
{
public:
    Alignment(size_t alignment)
        : m_alignment(std::max(alignment, sizeof(void*)))
    {
        BOOST_ASSERT_MSG( (m_alignment & (m_alignment - 1)) == 0, "Alignment must be a power of two" );
    }
    Alignment(const Alignment&) = default;

    operator size_t () const
    {
        return m_alignment;
    }

    template <typename T> bool isAligned(T size) const
    {
        return isAligned(m_alignment, size);
    }

    template <typename T> T align(T size) const
    {
        return align(m_alignment, size);
    }

    template <typename T> size_t padding(T size) const
    {
        return padding(m_alignment, size);
    }

    // Aligning pointers
    template <typename T> bool isAligned(T* ptr) const
    {
        return isAligned(reinterpret_cast<uintptr_t>(ptr));
    }

    template <typename T> T* align(T* ptr) const
    {
        return reinterpret_cast<T*>(align(reinterpret_cast<uintptr_t>(ptr)));
    }

    template <typename T> size_t padding(T* ptr) const
    {
        return padding(reinterpret_cast<uintptr_t>(ptr));
    }

    // Static alignment functions
    template <typename T> static bool isAligned(size_t alignment, T n)
    {
        return (n & ~(alignment-1)) == n;
    }

    template <typename T> static T align(size_t alignment, T n)
    {
        return (n + alignment) & ~(alignment-1);
    }

    template <typename T> static size_t padding(size_t alignment, T n)
    {
        return align(alignment, n) - n;
    }

private:
    size_t m_alignment;
};

//* Default alignment.
static const Alignment kDefaultAlignment(
#if defined(__ANDROID__)
    alignof(max_align_t)
#else
    alignof(std::max_align_t)
#endif
    );

//* Alignment needed for data accessed by SIMD instructions.
static const Alignment kSIMDAlignment(16);

//* Allocate memory of `size` bytes.
//
// @throw std::invalid_argument
// @throw std::bad_alloc
void* alloc(size_t size);

//* Allocate aligned memory of `size` bytes.
//
// @throw std::invalid_argument
// @throw std::bad_alloc
void* allocAligned(Alignment align, size_t size);

//* Free memory allocated by this allocator.
void free(void* ptr) noexcept;

//* Allocate memory for `n` elements of type `T`.
//
// @throw std::invalid_argument
// @throw std::bad_alloc
template <typename T> T* allocOf(size_t n=1)
{
    return static_cast<T*>(alloc(n * sizeof(T)));
}

//* Allocate aligned memory for `n` elements of type `T`.
//
// @throw std::invalid_argument
// @throw std::bad_alloc
template <typename T> T* allocAlignedOf(Alignment align, size_t n=1)
{
    return static_cast<T*>(allocAligned(align, n * sizeof(T)));
}

} }

#endif // METHCLA_MEMORY_HPP_INCLUDED
<commit_msg>Add missing include<commit_after>// Copyright 2012-2013 Samplecount S.L.
//
// 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.

#ifndef METHCLA_MEMORY_HPP_INCLUDED
#define METHCLA_MEMORY_HPP_INCLUDED

#include <algorithm>
#include <boost/assert.hpp>
#include <cstddef>
#include <cstdint>

namespace Methcla { namespace Memory {

class Alignment
{
public:
    Alignment(size_t alignment)
        : m_alignment(std::max(alignment, sizeof(void*)))
    {
        BOOST_ASSERT_MSG( (m_alignment & (m_alignment - 1)) == 0, "Alignment must be a power of two" );
    }
    Alignment(const Alignment&) = default;

    operator size_t () const
    {
        return m_alignment;
    }

    template <typename T> bool isAligned(T size) const
    {
        return isAligned(m_alignment, size);
    }

    template <typename T> T align(T size) const
    {
        return align(m_alignment, size);
    }

    template <typename T> size_t padding(T size) const
    {
        return padding(m_alignment, size);
    }

    // Aligning pointers
    template <typename T> bool isAligned(T* ptr) const
    {
        return isAligned(reinterpret_cast<uintptr_t>(ptr));
    }

    template <typename T> T* align(T* ptr) const
    {
        return reinterpret_cast<T*>(align(reinterpret_cast<uintptr_t>(ptr)));
    }

    template <typename T> size_t padding(T* ptr) const
    {
        return padding(reinterpret_cast<uintptr_t>(ptr));
    }

    // Static alignment functions
    template <typename T> static bool isAligned(size_t alignment, T n)
    {
        return (n & ~(alignment-1)) == n;
    }

    template <typename T> static T align(size_t alignment, T n)
    {
        return (n + alignment) & ~(alignment-1);
    }

    template <typename T> static size_t padding(size_t alignment, T n)
    {
        return align(alignment, n) - n;
    }

private:
    size_t m_alignment;
};

//* Default alignment.
static const Alignment kDefaultAlignment(
#if defined(__ANDROID__)
    alignof(max_align_t)
#else
    alignof(std::max_align_t)
#endif
    );

//* Alignment needed for data accessed by SIMD instructions.
static const Alignment kSIMDAlignment(16);

//* Allocate memory of `size` bytes.
//
// @throw std::invalid_argument
// @throw std::bad_alloc
void* alloc(size_t size);

//* Allocate aligned memory of `size` bytes.
//
// @throw std::invalid_argument
// @throw std::bad_alloc
void* allocAligned(Alignment align, size_t size);

//* Free memory allocated by this allocator.
void free(void* ptr) noexcept;

//* Allocate memory for `n` elements of type `T`.
//
// @throw std::invalid_argument
// @throw std::bad_alloc
template <typename T> T* allocOf(size_t n=1)
{
    return static_cast<T*>(alloc(n * sizeof(T)));
}

//* Allocate aligned memory for `n` elements of type `T`.
//
// @throw std::invalid_argument
// @throw std::bad_alloc
template <typename T> T* allocAlignedOf(Alignment align, size_t n=1)
{
    return static_cast<T*>(allocAligned(align, n * sizeof(T)));
}

} }

#endif // METHCLA_MEMORY_HPP_INCLUDED
<|endoftext|>


<commit_before>#include "physics/discrete_trajectory_segment_iterator.hpp"

namespace principia {
namespace physics {
namespace internal_discrete_trajectory_segment_iterator {

template<typename Frame>
DiscreteTrajectorySegmentIterator<Frame>&
DiscreteTrajectorySegmentIterator<Frame>::operator++() {
  ++iterator_;
  return *this;
}

template<typename Frame>
DiscreteTrajectorySegmentIterator<Frame>&
DiscreteTrajectorySegmentIterator<Frame>::operator--() {
  --iterator_;
  return *this;
}

template<typename Frame>
DiscreteTrajectorySegmentIterator<Frame>
DiscreteTrajectorySegmentIterator<Frame>::operator++(int) {
  return DiscreteTrajectorySegmentIterator(segments_, iterator_++);
}

template<typename Frame>
DiscreteTrajectorySegmentIterator<Frame>
DiscreteTrajectorySegmentIterator<Frame>::operator--(int) {
  return DiscreteTrajectorySegmentIterator(segments_, iterator_--);
}

template<typename Frame>
internal_discrete_trajectory_segment::DiscreteTrajectorySegment<Frame> const&
DiscreteTrajectorySegmentIterator<Frame>::operator*() const {
  return **iterator_;
}

template<typename Frame>
internal_discrete_trajectory_segment::DiscreteTrajectorySegment<Frame> const*
DiscreteTrajectorySegmentIterator<Frame>::operator->() const {
  return iterator_->get();
}

template<typename Frame>
bool DiscreteTrajectorySegmentIterator<Frame>::operator==(
    DiscreteTrajectorySegmentIterator const& other) const {
  return segments_ == other.segments_ && iterator_ == other.iterator_;
}

template<typename Frame>
bool DiscreteTrajectorySegmentIterator<Frame>::operator!=(
    DiscreteTrajectorySegmentIterator const& other) const {
  return !operator==(other);
}

template<typename Frame>
DiscreteTrajectorySegmentIterator<Frame>::DiscreteTrajectorySegmentIterator(
    not_null<Segments const*> const segments,
    typename Segments::const_iterator iterator)
    : segments_(segments),
      iterator_(iterator) {}

template<typename Frame>
DiscreteTrajectorySegmentIterator<Frame>
DiscreteTrajectorySegmentIterator<Frame>::begin() const {
  return DiscreteTrajectorySegmentIterator(segments_, segments_->begin());
}

template<typename Frame>
DiscreteTrajectorySegmentIterator<Frame>
DiscreteTrajectorySegmentIterator<Frame>::end() const {
  return DiscreteTrajectorySegmentIterator(segments_, segments_->end());
}

}  // namespace internal_discrete_trajectory_segment_iterator
}  // namespace physics
}  // namespace principia
<commit_msg>C++ is stupid.  So is the linter.<commit_after>#include "physics/discrete_trajectory_segment_iterator.hpp"

namespace principia {
namespace physics {
namespace internal_discrete_trajectory_segment_iterator {

template<typename Frame>
DiscreteTrajectorySegmentIterator<Frame>&
DiscreteTrajectorySegmentIterator<Frame>::operator++() {
  ++iterator_;
  return *this;
}

template<typename Frame>
DiscreteTrajectorySegmentIterator<Frame>&
DiscreteTrajectorySegmentIterator<Frame>::operator--() {
  --iterator_;
  return *this;
}

template<typename Frame>
DiscreteTrajectorySegmentIterator<Frame>
DiscreteTrajectorySegmentIterator<Frame>::operator++(int) {  // NOLINT
  return DiscreteTrajectorySegmentIterator(segments_, iterator_++);
}

template<typename Frame>
DiscreteTrajectorySegmentIterator<Frame>
DiscreteTrajectorySegmentIterator<Frame>::operator--(int) {  // NOLINT
  return DiscreteTrajectorySegmentIterator(segments_, iterator_--);
}

template<typename Frame>
internal_discrete_trajectory_segment::DiscreteTrajectorySegment<Frame> const&
DiscreteTrajectorySegmentIterator<Frame>::operator*() const {
  return **iterator_;
}

template<typename Frame>
internal_discrete_trajectory_segment::DiscreteTrajectorySegment<Frame> const*
DiscreteTrajectorySegmentIterator<Frame>::operator->() const {
  return iterator_->get();
}

template<typename Frame>
bool DiscreteTrajectorySegmentIterator<Frame>::operator==(
    DiscreteTrajectorySegmentIterator const& other) const {
  return segments_ == other.segments_ && iterator_ == other.iterator_;
}

template<typename Frame>
bool DiscreteTrajectorySegmentIterator<Frame>::operator!=(
    DiscreteTrajectorySegmentIterator const& other) const {
  return !operator==(other);
}

template<typename Frame>
DiscreteTrajectorySegmentIterator<Frame>::DiscreteTrajectorySegmentIterator(
    not_null<Segments const*> const segments,
    typename Segments::const_iterator iterator)
    : segments_(segments),
      iterator_(iterator) {}

template<typename Frame>
DiscreteTrajectorySegmentIterator<Frame>
DiscreteTrajectorySegmentIterator<Frame>::begin() const {
  return DiscreteTrajectorySegmentIterator(segments_, segments_->begin());
}

template<typename Frame>
DiscreteTrajectorySegmentIterator<Frame>
DiscreteTrajectorySegmentIterator<Frame>::end() const {
  return DiscreteTrajectorySegmentIterator(segments_, segments_->end());
}

}  // namespace internal_discrete_trajectory_segment_iterator
}  // namespace physics
}  // namespace principia
<|endoftext|>


<commit_before>#include <iostream>
#include <sstream>
#include <string>

using namespace std;
int main()
{
stringstream ss;
int start(0);
int end(0);
string tmp;
	while(std::getline(std::cin,tmp))
	{
		ss.str(tmp);
		ss>>start>>end;
		if(start > end)
		{
			int tmp(0);
			tmp= start;
			start= end;
			end= tmp;
		}
		int max(0);
		for(int i=start;i<=end;i++)
		{
			int count(1);
			int val= i;
			while(val!=1)
			{
				count++;
				if(val%2==1) val= val * 3 +1;
				else	val/=2;
			}
			if(count>max) max= count;
		}
		std::cout<<start<<" "<<end<<" "<<max<<'\n';
		ss.clear();
	}
return -1;
}
<commit_msg>Update 3n+1.cpp<commit_after>#include <iostream>
#include <sstream>
#include <string>

using namespace std;
int main()
{
stringstream ss;
int start(0);
int end(0);
string tmp;
	while(std::getline(std::cin,tmp))
	{
		ss.str(tmp);
		ss>>start>>end;
		if(start > end)
		{
			int tmp(0);
			tmp= start;
			start= end;
			end= tmp;
		}
		int max(0);
		for(int i=start;i<=end;i++)
		{
			int count(1);
			int val= i;
			while(val!=1)
			{
				count++;
				if(val%2==1) val= val * 3 +1;
				else	val/=2;
			}
			if(count>max) max= count;
		}
		std::cout<<start<<" "<<end<<" "<<max<<'\n';
		ss.clear();
	}
return 0;
}
<|endoftext|>


<commit_before>#include "MQTTClient.h"

void messageArrived(MQTT::MessageData& messageData) {
  MQTT::Message &message = messageData.message;

  // null terminate topic to create String object
  int len = messageData.topicName.lenstring.len;
  char topic[len+1];
  memcpy(topic, messageData.topicName.lenstring.data, (size_t)len);
  topic[len] = '\0';

  // null terminate payload
  char * payload = (char *)message.payload;
  payload[message.payloadlen] = '\0';
  messageReceived(String(topic), String(payload), (char*)message.payload, (unsigned int)message.payloadlen);
}

MQTTClient::MQTTClient() {}

boolean MQTTClient::begin(const char * hostname, Client& client) {
  return this->begin(hostname, 1883, client);
}

boolean MQTTClient::begin(const char * _hostname, int _port, Client& _client) {
  this->client = new MQTT::Client<Network, Timer, MQTT_BUFFER_SIZE, 0>(this->network);
  this->network.setClient(&_client);
  this->client->setDefaultMessageHandler(messageArrived);
  this->hostname = _hostname;
  this->port = _port;
  this->options = MQTTPacket_connectData_initializer;

  return true;
}

void MQTTClient::setWill(const char * topic) {
  this->setWill(topic, "");
}

void MQTTClient::setWill(const char * topic, const char * payload) {
  this->options.willFlag = 0x1;
  this->options.will.topicName.cstring = (char*)topic;
  this->options.will.message.cstring = (char*)payload;
}

boolean MQTTClient::connect(const char * clientId) {
  return this->connect(clientId, "", "");
}

boolean MQTTClient::connect(const char * clientId, const char * username, const char * password) {
  if(!this->network.connect((char*)this->hostname, this->port)) {
    return false;
  }

  this->options.clientID.cstring = (char*)clientId;
  if(username && password) {
    this->options.username.cstring = (char*)username;
    this->options.password.cstring = (char*)password;
  }

  return this->client->connect(this->options) == 0;
}

void MQTTClient::publish(String topic) {
  this->publish(topic.c_str(), "");
}

void MQTTClient::publish(String topic, String payload) {
  this->publish(topic.c_str(), payload.c_str());
}

void MQTTClient::publish(const char * topic, String payload) {
  this->publish(topic, payload.c_str());
}

void MQTTClient::publish(const char * topic, const char * payload) {
  this->publish(topic, (char*)payload, (unsigned int)strlen(payload));
}

void MQTTClient::publish(const char * topic, char * payload, unsigned int length) {
  MQTT::Message message;
  message.qos = MQTT::QOS0;
  message.retained = false;
  message.dup = false;
  message.payload = payload;
  message.payloadlen = length;
  client->publish(topic, message);
}

void MQTTClient::subscribe(String topic) {
  this->subscribe(topic.c_str());
}

void MQTTClient::subscribe(const char * topic) {
  client->subscribe(topic, MQTT::QOS0, NULL);
}

void MQTTClient::unsubscribe(String topic) {
  this->unsubscribe(topic.c_str());
}

void MQTTClient::unsubscribe(const char * topic) {
  client->unsubscribe(topic);
}

void MQTTClient::loop() {
  this->client->yield();
}

boolean MQTTClient::connected() {
  return this->client->isConnected();
}

void MQTTClient::disconnect() {
  this->client->disconnect();
}
<commit_msg>use NULLs rather than empty strings<commit_after>#include "MQTTClient.h"

void messageArrived(MQTT::MessageData& messageData) {
  MQTT::Message &message = messageData.message;

  // null terminate topic to create String object
  int len = messageData.topicName.lenstring.len;
  char topic[len+1];
  memcpy(topic, messageData.topicName.lenstring.data, (size_t)len);
  topic[len] = '\0';

  // null terminate payload
  char * payload = (char *)message.payload;
  payload[message.payloadlen] = '\0';
  messageReceived(String(topic), String(payload), (char*)message.payload, (unsigned int)message.payloadlen);
}

MQTTClient::MQTTClient() {}

boolean MQTTClient::begin(const char * hostname, Client& client) {
  return this->begin(hostname, 1883, client);
}

boolean MQTTClient::begin(const char * _hostname, int _port, Client& _client) {
  this->client = new MQTT::Client<Network, Timer, MQTT_BUFFER_SIZE, 0>(this->network);
  this->network.setClient(&_client);
  this->client->setDefaultMessageHandler(messageArrived);
  this->hostname = _hostname;
  this->port = _port;
  this->options = MQTTPacket_connectData_initializer;

  return true;
}

void MQTTClient::setWill(const char * topic) {
  this->setWill(topic, "");
}

void MQTTClient::setWill(const char * topic, const char * payload) {
  this->options.willFlag = 0x1;
  this->options.will.topicName.cstring = (char*)topic;
  this->options.will.message.cstring = (char*)payload;
}

boolean MQTTClient::connect(const char * clientId) {
  return this->connect(clientId, NULL, NULL);
}

boolean MQTTClient::connect(const char * clientId, const char * username, const char * password) {
  if(!this->network.connect((char*)this->hostname, this->port)) {
    return false;
  }

  this->options.clientID.cstring = (char*)clientId;
  if(username && password) {
    this->options.username.cstring = (char*)username;
    this->options.password.cstring = (char*)password;
  }

  return this->client->connect(this->options) == 0;
}

void MQTTClient::publish(String topic) {
  this->publish(topic.c_str(), "");
}

void MQTTClient::publish(String topic, String payload) {
  this->publish(topic.c_str(), payload.c_str());
}

void MQTTClient::publish(const char * topic, String payload) {
  this->publish(topic, payload.c_str());
}

void MQTTClient::publish(const char * topic, const char * payload) {
  this->publish(topic, (char*)payload, (unsigned int)strlen(payload));
}

void MQTTClient::publish(const char * topic, char * payload, unsigned int length) {
  MQTT::Message message;
  message.qos = MQTT::QOS0;
  message.retained = false;
  message.dup = false;
  message.payload = payload;
  message.payloadlen = length;
  client->publish(topic, message);
}

void MQTTClient::subscribe(String topic) {
  this->subscribe(topic.c_str());
}

void MQTTClient::subscribe(const char * topic) {
  client->subscribe(topic, MQTT::QOS0, NULL);
}

void MQTTClient::unsubscribe(String topic) {
  this->unsubscribe(topic.c_str());
}

void MQTTClient::unsubscribe(const char * topic) {
  client->unsubscribe(topic);
}

void MQTTClient::loop() {
  this->client->yield();
}

boolean MQTTClient::connected() {
  return this->client->isConnected();
}

void MQTTClient::disconnect() {
  this->client->disconnect();
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2009 David Verhasselt <david@crowdway.com>
 * Licensed under The MIT License - http://gmailcc.crowdway.com/license.txt
 */

#include "MailRecord.h"

#include <boost/filesystem.hpp>
namespace bf = boost::filesystem;

#include "LogSink.h"
#include "MailLink.h"
#include "MailBox.h"

int MailRecord::number_of_deliveries = 0;

MailRecord::MailRecord()
{
	marked = false;

	flag_draft = false;
	flag_flagged = false;
	flag_passed = false;
	flag_replied = false;
	flag_seen = false;
	flag_trashed = false;
}

MailRecord::~MailRecord()
{
	for (vector<MailLink*>::iterator iter = this->links.begin(); iter < links.end(); iter++)
	{
		delete(*iter);
	}
}

void MailRecord::mark()
{
	marked = true;
}

bool MailRecord::get_flag_draft()
{
	return flag_draft;
}

void MailRecord::set_flag_draft(bool flag_draft)
{
	if (this->flag_draft == flag_draft)
		return;

	this->flag_draft = flag_draft;
}

bool MailRecord::get_flag_flagged()
{
	return flag_flagged;
}

void MailRecord::set_flag_flagged(bool flag_flagged)
{
	if (this->flag_flagged == flag_flagged)
		return;

	this->flag_flagged = flag_flagged;
}

bool MailRecord::get_flag_passed()
{
	return flag_passed;
}

void MailRecord::set_flag_passed(bool flag_passed)
{
	if (this->flag_passed == flag_passed)
		return;

	this->flag_passed = flag_passed;
}

bool MailRecord::get_flag_replied()
{
	return flag_replied;
}

void MailRecord::set_flag_replied(bool flag_replied)
{
	if (this->flag_replied == flag_replied)
		return;

	this->flag_replied = flag_replied;
}

bool MailRecord::get_flag_seen()
{
	return flag_seen;
}

void MailRecord::set_flag_seen(bool flag_seen)
{
	if (this->flag_seen == flag_seen)
		return;
	Log::info << "Seen";
	this->flag_seen = flag_seen;
}

bool MailRecord::get_flag_trashed()
{
	return flag_trashed;
}

void MailRecord::set_flag_trashed(bool flag_trashed)
{
	if (this->flag_trashed == flag_trashed)
		return;

	this->flag_trashed = flag_trashed;
}

void MailRecord::save_content(string body)
{
	ofstream mfile;

	mfile.open(mainlink->get_path().c_str());

	if (mfile.is_open())
	{
		mfile << body;
		mfile.close();
	}
	else Log::error << "Unable to open file " << mainlink->get_path() << Log::endl;
}

MailLink* MailRecord::add_to_mailbox(MailBox* mailbox, unsigned long uid, string path)
{
	MailLink* maillink = find_link(mailbox);

	if (maillink != NULL)			// Existing mail: just update UID
	{
		maillink->uid = uid;

		if (!path.empty())
		{
			if (!rename(maillink->get_path().c_str(), path.c_str()))
				perror("MailRecord::add_to_mailbox: unable to move link");
			else
				maillink->set_path(path);
		}
	}
	else
	{
		maillink = new MailLink;

		if (mailbox->primary)
			mainlink = maillink;

		bool exists = false;
		if (path.empty())
			path = mailbox->get_path() + "cur/" + generate_md_filename() + get_md_info();
		else
			exists = true;

		maillink->mailrecord = this;
		maillink->mailbox = mailbox;
		maillink->set_path(path);
		maillink->uid = uid;

		this->links.push_back(maillink);
		mailbox->mails.push_back(maillink);

		if (!exists)
		{
			if (this->links.size() > 1)	// Create a link to the original
			{
				string sourcepath = this->mainlink->get_path().c_str();
				//sourcepath.insert(0, "../");

				bf::create_hard_link(sourcepath, path);
				//	perror("MailRecord::add_to_mailbox: creating symlink failed");
			}
			else			// "Touch" file
			{
				ofstream mfile;
				mfile.open(path.c_str());
				mfile << "";
				mfile.close();
			}
		}
		else
		{
			load_md_info();
		}
	}

	return maillink;
}

void MailRecord::remove_from_mailbox(MailBox* mailbox)
{
	vector<MailLink*>::iterator iter = find_ilink(mailbox);

	if (iter < this->links.end())
	{
		remove_from_mailbox(iter);
		return;
	}
	else
	{
		cout << "Whoops, something went wrong here" << endl;
	}
}

vector<MailLink*>::iterator MailRecord::remove_from_mailbox(vector<MailLink*>::iterator iter)
{
	if (unlink((*iter)->get_path().c_str()) != 0)
			perror("MailRecord::remove_from_mailbox: unable to unlink file");

	(*iter)->mailbox->dirty();
	(*iter)->stale();

	return this->links.erase(iter);
}

void MailRecord::remove()
{
	for (vector<MailLink*>::iterator iter = this->links.begin(); iter < this->links.end(); )
	{
		iter = this->remove_from_mailbox(iter);
	}
}

MailLink* MailRecord::find_link(MailBox* mailbox)
{
	vector<MailLink*>::iterator result = find_ilink(mailbox);

	if (result == this->links.end())
		return NULL;
	else
		return *result;
}

vector<MailLink*>::iterator MailRecord::find_ilink(MailBox* mailbox)
{
	for (vector<MailLink*>::iterator iter = this->links.begin(); iter < this->links.end(); iter++)
	{
		if ((*iter)->mailbox == mailbox)
		{
			return iter;
		}
	}

	return this->links.end();
}

/**
 * Regenerates the paths of every mail, moves the files
 * of the mails, also of every link. This is useful if one of the
 * files has a different info part because another client changed
 * the flags.
 */
void MailRecord::sync_flags()
{
	for (vector<MailLink*>::iterator iter = this->links.begin(); iter < links.end(); iter++)
	{
		string new_path = (*iter)->get_base_path();

		new_path.insert(new_path.size(), this->get_md_info());

		if (new_path.compare((*iter)->get_path()) != 0)
		{
			if (rename((*iter)->get_path().c_str(), new_path.c_str()) != 0)
				perror("MailRecord::flags_changed: Unable to rename file");
			else
				(*iter)->set_path(new_path);
		}
	}
}

string MailRecord::generate_md_filename()
{
	char seconds[20];	sprintf(seconds, "%lu", (unsigned long) time(NULL));

	char hostname[99] = "hostnamex";
	string shostname;
	pid_t pid = getpid();

	if (pid < 0)
		perror("MailRecord::generate_md_filename: unable to get pid");

	char spid[20];	sprintf(spid, "%d", pid);

	if (gethostname(hostname, 99) != 0)
	{
		perror("MailRecord::generate_md_filename: unable to gethostname()");
		perror(hostname);
	}

 	shostname = hostname;

	// Replace "/" with "\057"
	size_t index;
	while((index = shostname.find("/")) != string::npos)
	{
			shostname.replace(index, 1, "\057");
	}

	// Replace ":" with "\072"
	while((index = shostname.find(":")) != string::npos)
	{
			shostname.replace(index, 1, "\072");
	}

	char delnum[20];	sprintf(delnum, "%d", MailRecord::number_of_deliveries++);

	string result;

	result += seconds;
	result += ".";
	result += "P";
	result += spid;
	result += "Q";
	result += delnum;
	result += ".";
	result += shostname;

	return result;
}

/**
 * Generate the "info" part of the maildir specification
 * see: http://cr.yp.to/proto/maildir.html
 */
string MailRecord::get_md_info()
{
	string result = MD_TAIL;

	if (this->flag_draft) result += "D";
	if (this->flag_flagged) result += "F";
	if (this->flag_passed) result += "P";
	if (this->flag_replied) result += "R";
	if (this->flag_seen) result += "S";
	if (this->flag_trashed) result += "T";

	return result;
}

/**
 * Extract the "info" part from the path and update lfags
 */
void MailRecord::load_md_info()
{
	this->flag_draft = false;
	this->flag_flagged = false;
	this->flag_passed = false;
	this->flag_replied = false;
	this->flag_seen = false;
	this->flag_trashed = false;

	string path = mainlink->get_path();
	for(size_t index = path.rfind(MD_TAIL) + strlen(MD_TAIL); index < path.size(); index++)
	{
				switch(path[index])
				{
					case 'D':
						this->flag_draft = true; break;
					case 'F':
						this->flag_flagged = true; break;
					case 'P':
						this->flag_passed = true; break;
					case 'R':
						this->flag_replied = true; break;
					case 'S':
						this->flag_seen = true; break;
					case 'T':
						this->flag_trashed = true; break;
				}
	}
}<commit_msg>Removed a stray debug-message.<commit_after>/*
 * Copyright (c) 2009 David Verhasselt <david@crowdway.com>
 * Licensed under The MIT License - http://gmailcc.crowdway.com/license.txt
 */

#include "MailRecord.h"

#include <boost/filesystem.hpp>
namespace bf = boost::filesystem;

#include "LogSink.h"
#include "MailLink.h"
#include "MailBox.h"

int MailRecord::number_of_deliveries = 0;

MailRecord::MailRecord()
{
	marked = false;

	flag_draft = false;
	flag_flagged = false;
	flag_passed = false;
	flag_replied = false;
	flag_seen = false;
	flag_trashed = false;
}

MailRecord::~MailRecord()
{
	for (vector<MailLink*>::iterator iter = this->links.begin(); iter < links.end(); iter++)
	{
		delete(*iter);
	}
}

void MailRecord::mark()
{
	marked = true;
}

bool MailRecord::get_flag_draft()
{
	return flag_draft;
}

void MailRecord::set_flag_draft(bool flag_draft)
{
	if (this->flag_draft == flag_draft)
		return;

	this->flag_draft = flag_draft;
}

bool MailRecord::get_flag_flagged()
{
	return flag_flagged;
}

void MailRecord::set_flag_flagged(bool flag_flagged)
{
	if (this->flag_flagged == flag_flagged)
		return;

	this->flag_flagged = flag_flagged;
}

bool MailRecord::get_flag_passed()
{
	return flag_passed;
}

void MailRecord::set_flag_passed(bool flag_passed)
{
	if (this->flag_passed == flag_passed)
		return;

	this->flag_passed = flag_passed;
}

bool MailRecord::get_flag_replied()
{
	return flag_replied;
}

void MailRecord::set_flag_replied(bool flag_replied)
{
	if (this->flag_replied == flag_replied)
		return;

	this->flag_replied = flag_replied;
}

bool MailRecord::get_flag_seen()
{
	return flag_seen;
}

void MailRecord::set_flag_seen(bool flag_seen)
{
	if (this->flag_seen == flag_seen)
		return;

	this->flag_seen = flag_seen;
}

bool MailRecord::get_flag_trashed()
{
	return flag_trashed;
}

void MailRecord::set_flag_trashed(bool flag_trashed)
{
	if (this->flag_trashed == flag_trashed)
		return;

	this->flag_trashed = flag_trashed;
}

void MailRecord::save_content(string body)
{
	ofstream mfile;

	mfile.open(mainlink->get_path().c_str());

	if (mfile.is_open())
	{
		mfile << body;
		mfile.close();
	}
	else Log::error << "Unable to open file " << mainlink->get_path() << Log::endl;
}

MailLink* MailRecord::add_to_mailbox(MailBox* mailbox, unsigned long uid, string path)
{
	MailLink* maillink = find_link(mailbox);

	if (maillink != NULL)			// Existing mail: just update UID
	{
		maillink->uid = uid;

		if (!path.empty())
		{
			if (!rename(maillink->get_path().c_str(), path.c_str()))
				perror("MailRecord::add_to_mailbox: unable to move link");
			else
				maillink->set_path(path);
		}
	}
	else
	{
		maillink = new MailLink;

		if (mailbox->primary)
			mainlink = maillink;

		bool exists = false;
		if (path.empty())
			path = mailbox->get_path() + "cur/" + generate_md_filename() + get_md_info();
		else
			exists = true;

		maillink->mailrecord = this;
		maillink->mailbox = mailbox;
		maillink->set_path(path);
		maillink->uid = uid;

		this->links.push_back(maillink);
		mailbox->mails.push_back(maillink);

		if (!exists)
		{
			if (this->links.size() > 1)	// Create a link to the original
			{
				string sourcepath = this->mainlink->get_path().c_str();
				//sourcepath.insert(0, "../");

				bf::create_hard_link(sourcepath, path);
				//	perror("MailRecord::add_to_mailbox: creating symlink failed");
			}
			else			// "Touch" file
			{
				ofstream mfile;
				mfile.open(path.c_str());
				mfile << "";
				mfile.close();
			}
		}
		else
		{
			load_md_info();
		}
	}

	return maillink;
}

void MailRecord::remove_from_mailbox(MailBox* mailbox)
{
	vector<MailLink*>::iterator iter = find_ilink(mailbox);

	if (iter < this->links.end())
	{
		remove_from_mailbox(iter);
		return;
	}
	else
	{
		cout << "Whoops, something went wrong here" << endl;
	}
}

vector<MailLink*>::iterator MailRecord::remove_from_mailbox(vector<MailLink*>::iterator iter)
{
	if (unlink((*iter)->get_path().c_str()) != 0)
			perror("MailRecord::remove_from_mailbox: unable to unlink file");

	(*iter)->mailbox->dirty();
	(*iter)->stale();

	return this->links.erase(iter);
}

void MailRecord::remove()
{
	for (vector<MailLink*>::iterator iter = this->links.begin(); iter < this->links.end(); )
	{
		iter = this->remove_from_mailbox(iter);
	}
}

MailLink* MailRecord::find_link(MailBox* mailbox)
{
	vector<MailLink*>::iterator result = find_ilink(mailbox);

	if (result == this->links.end())
		return NULL;
	else
		return *result;
}

vector<MailLink*>::iterator MailRecord::find_ilink(MailBox* mailbox)
{
	for (vector<MailLink*>::iterator iter = this->links.begin(); iter < this->links.end(); iter++)
	{
		if ((*iter)->mailbox == mailbox)
		{
			return iter;
		}
	}

	return this->links.end();
}

/**
 * Regenerates the paths of every mail, moves the files
 * of the mails, also of every link. This is useful if one of the
 * files has a different info part because another client changed
 * the flags.
 */
void MailRecord::sync_flags()
{
	for (vector<MailLink*>::iterator iter = this->links.begin(); iter < links.end(); iter++)
	{
		string new_path = (*iter)->get_base_path();

		new_path.insert(new_path.size(), this->get_md_info());

		if (new_path.compare((*iter)->get_path()) != 0)
		{
			if (rename((*iter)->get_path().c_str(), new_path.c_str()) != 0)
				perror("MailRecord::flags_changed: Unable to rename file");
			else
				(*iter)->set_path(new_path);
		}
	}
}

string MailRecord::generate_md_filename()
{
	char seconds[20];	sprintf(seconds, "%lu", (unsigned long) time(NULL));

	char hostname[99] = "hostnamex";
	string shostname;
	pid_t pid = getpid();

	if (pid < 0)
		perror("MailRecord::generate_md_filename: unable to get pid");

	char spid[20];	sprintf(spid, "%d", pid);

	if (gethostname(hostname, 99) != 0)
	{
		perror("MailRecord::generate_md_filename: unable to gethostname()");
		perror(hostname);
	}

 	shostname = hostname;

	// Replace "/" with "\057"
	size_t index;
	while((index = shostname.find("/")) != string::npos)
	{
			shostname.replace(index, 1, "\057");
	}

	// Replace ":" with "\072"
	while((index = shostname.find(":")) != string::npos)
	{
			shostname.replace(index, 1, "\072");
	}

	char delnum[20];	sprintf(delnum, "%d", MailRecord::number_of_deliveries++);

	string result;

	result += seconds;
	result += ".";
	result += "P";
	result += spid;
	result += "Q";
	result += delnum;
	result += ".";
	result += shostname;

	return result;
}

/**
 * Generate the "info" part of the maildir specification
 * see: http://cr.yp.to/proto/maildir.html
 */
string MailRecord::get_md_info()
{
	string result = MD_TAIL;

	if (this->flag_draft) result += "D";
	if (this->flag_flagged) result += "F";
	if (this->flag_passed) result += "P";
	if (this->flag_replied) result += "R";
	if (this->flag_seen) result += "S";
	if (this->flag_trashed) result += "T";

	return result;
}

/**
 * Extract the "info" part from the path and update lfags
 */
void MailRecord::load_md_info()
{
	this->flag_draft = false;
	this->flag_flagged = false;
	this->flag_passed = false;
	this->flag_replied = false;
	this->flag_seen = false;
	this->flag_trashed = false;

	string path = mainlink->get_path();
	for(size_t index = path.rfind(MD_TAIL) + strlen(MD_TAIL); index < path.size(); index++)
	{
				switch(path[index])
				{
					case 'D':
						this->flag_draft = true; break;
					case 'F':
						this->flag_flagged = true; break;
					case 'P':
						this->flag_passed = true; break;
					case 'R':
						this->flag_replied = true; break;
					case 'S':
						this->flag_seen = true; break;
					case 'T':
						this->flag_trashed = true; break;
				}
	}
}<|endoftext|>


<commit_before>/**
 * @file MainWindow.h
 * @brief Main window for the Clusterer GUI
 */

// standard headers
#include <limits>

// Own headers
#include "../include/MainWindow.h"
#include "../include/SettingsDialog.h"
#include "../include/PopulationMember.hpp"
#include "../include/IntegerVectorEncoding.hpp"

// External headers
#include <QMessageBox>
#include <QFileDialog>

// Generated headers
#include "ui_MainWindow.h"
#include "../include/GlobalBackendController.hpp"
#include "../include/GlobalFileLogger.hpp"

#define MSEC_60_HZ 16

namespace clusterer
{

namespace frontend
{

MainWindow::MainWindow(QWidget* parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    connect(&timer, SIGNAL(timeout()), this, SLOT(updateFrontend()));

    setStateAlgoOff();
    // No graph loaded - cannot start
    ui->pushButton->setEnabled(false);
    ui->pushButton_3->setEnabled(false);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::setStateAlgoOn()
{
    ui->pushButton->setEnabled(false);
    ui->pushButton_4->setEnabled(true);
    ui->pushButton_2->setEnabled(true);
    ui->pushButton_3->setEnabled(false);
    ui->actionZachary_format->setEnabled(false);
    ui->actionMovielens_format->setEnabled(false);
    ui->actionLoad_Population->setEnabled(false);
    ui->actionSave_Population->setEnabled(false);
}

void MainWindow::setStateAlgoOff()
{
    ui->pushButton->setEnabled(true);
    ui->pushButton_4->setEnabled(false);
    ui->pushButton_2->setEnabled(false);
    ui->pushButton_3->setEnabled(false);
    ui->actionZachary_format->setEnabled(true);
    ui->actionMovielens_format->setEnabled(true);
    ui->actionLoad_Population->setEnabled(true);
    ui->actionSave_Population->setEnabled(true);
}

void MainWindow::updateFrontend()
{
    std::pair<clb::PopulationMember<clb::IntegerVectorEncoding, double>, uint64_t> output;
    std::vector<std::pair<clb::PopulationMember<clb::IntegerVectorEncoding, double>, uint64_t>> vector;
    while (clb::GlobalBackendController::instance()->getOutQueue()->popNonWaiting(output))
    {
        vector.push_back(output);
    }

    if (!vector.empty())
    {
        bool exitFlag = false;
        std::vector<std::pair<uint64_t, double>> fitnessVec;
        fitnessVec.reserve(vector.size());
        for (auto& e : vector)
        {
            if (std::numeric_limits<uint64_t>::max() - std::numeric_limits<uint64_t>::epsilon() <= e.second)
            {
                // algo stopped
                setAlgorithmRunning(false);
                setStateAlgoOff();
                exitFlag = true;
                continue;
            }
            fitnessVec.push_back(std::make_pair(e.second, e.first.fitnessValue));
        }
        ui->fitnessPlotter->replotFitness(fitnessVec);

        if (exitFlag == true && vector.size() > 1)
        {
            ui->nodePlotter->replotSolution(vector[vector.size() - 2].first.populationEncoding);
        }
        else
        {
            ui->nodePlotter->replotSolution(vector[vector.size() - 1].first.populationEncoding);
        }
    }
}

void MainWindow::setAlgorithmRunning(bool val)
{
    algorithmRunning = val;
}

bool MainWindow::isAlgorithmRunning()
{
    return algorithmRunning;
}

void MainWindow::showAlert(const QString& title, const QString& text)
{
    QMessageBox::information(this, title, text);
}

void MainWindow::on_pushButton_clicked()
{
    //Start button
    // @todo put check condition function into controller and call it here and check
    if (clb::GlobalBackendController::instance()->runAlgorithm(true))
    {
        clb::GlobalBackendController::instance()->runAlgorithm(true);
        timer.start(MSEC_60_HZ);
        this->showAlert("Info", "Started the algorithm");
        setStateAlgoOn();
        setAlgorithmRunning(true);
    }
    else
    {
        clc::GlobalFileLogger::instance()->log(clc::SeverityType::ERROR, "Could not start the algorithm as you need to load a Graph first.");
        QMessageBox::critical(this, "Error", "Could not start the algorithm as you need to load a Graph first.");
    }
}

void MainWindow::on_pushButton_4_clicked()
{
    //Stop button
    clb::GlobalBackendController::instance()->stopAlgorithm();
    setStateAlgoOff();
    setAlgorithmRunning(true);
    this->showAlert("Alert", "Stopped the algorithm");
}

void MainWindow::on_pushButton_2_clicked()
{
    clb::GlobalBackendController::instance()->stopAlgorithm();
    setStateAlgoOff();
    setAlgorithmRunning(false);
    this->showAlert("Alert", "Paused algorithm");
    ui->pushButton_3->setEnabled(true);
    ui->pushButton->setEnabled(true);
}

void MainWindow::on_pushButton_3_clicked()
{
    clb::GlobalBackendController::instance()->runAlgorithm(false);
    this->showAlert("Alert", "Resumed execution of the algorithm");
    setStateAlgoOn();
    setAlgorithmRunning(true);
}

void MainWindow::on_actionSave_Settings_2_triggered()
{
    // Save settings
    QString path = QFileDialog::getSaveFileName(this,
                   tr("Save Settings"),
                   tr("."),
                   tr("Text Files (*.txt)"));
    if (!path.isNull() && !path.isEmpty())
    {
        bool result = clb::GlobalBackendController::instance()->saveConfiguration(path.toLocal8Bit().constData());
        if (result == true)
        {
            showAlert("Save Settings Success", "Successfully saved settings");
        }
        else
        {
            clc::GlobalFileLogger::instance()->log(clc::SeverityType::ERROR, "Save Settings failed. Failed saving settings.");
            QMessageBox::critical(this, "Save Settings failed", "Failed saving settings.");
        }
    }
}

void MainWindow::on_actionLoad_Settings_2_triggered()
{
    QString path = QFileDialog::getOpenFileName(this,
                   tr("Open Settings File"),
                   ".",
                   tr("Text Files (*.txt)"));
    if (!path.isNull() && !path.isEmpty())
    {
        bool result = clb::GlobalBackendController::instance()->loadConfiguration(path.toLocal8Bit().constData());
        if (result == true)
        {
            showAlert("Load Settings Success", "Successfully loaded settings");
        }
        else
        {
            clc::GlobalFileLogger::instance()->log(clc::SeverityType::ERROR, "Load Settings failed. The file you selected is not a valid configuration file");
            QMessageBox::critical(this, "Load Settings failed", "The file you selected is not a valid configuration file");
        }
    }
}

void MainWindow::on_actionSave_Graph_triggered()
{
    QString path = QFileDialog::getSaveFileName(this,
                   tr("Save Graph"),
                   tr("."),
                   tr("Text Files (*.txt)"));
    if (!path.isNull() && !path.isEmpty())
    {
        bool result = clb::GlobalBackendController::instance()->saveGraphToFile(path.toLocal8Bit().constData());
        if (result == true)
        {
            showAlert("Save Graph Success", "Successfully saved graph to file.");
        }
        else
        {
            clc::GlobalFileLogger::instance()->log(clc::SeverityType::ERROR, "Save Graph failed. Unable to save graph");
            QMessageBox::critical(this, "Save Graph failed", "Unable to save graph");
        }
    }
}

void MainWindow::on_actionZachary_format_triggered()
{
    // Load Zachary Format
    QString path = QFileDialog::getOpenFileName(this,
                   tr("Open Zachary Karate Club Graph"),
                   ".",
                   tr("All Files (*)"));
    if (!path.isNull() && !path.isEmpty())
    {
        bool result = clb::GlobalBackendController::instance()->loadGraphTypeVertexPairWeight(path.toLocal8Bit().constData());
        if (result == true)
        {
            showAlert("Load Graph Success", "Successfully loaded a vertex-pair-weight type graph.");
            ui->nodePlotter->initGraph();
            ui->pushButton->setEnabled(true);
        }
        else
        {
            clc::GlobalFileLogger::instance()->log(clc::SeverityType::ERROR, "Load Graph failed. Unable to load a vertex-pair-weight graph");
            QMessageBox::critical(this, "Load Graph failed", "Unable to load a vertex-pair-weight graph");
        }
    }
}

void MainWindow::on_actionMovielens_format_triggered()
{
    // Load Movielens Format
    QString path = QFileDialog::getOpenFileName(this,
                   tr("Open Movielens Graph"),
                   ".",
                   tr("All Files (*)"));
    if (!path.isNull() && !path.isEmpty())
    {
        bool result = clb::GlobalBackendController::instance()->loadGraphTypeMovieLens(path.toLocal8Bit().constData());
        if (result == true)
        {
            showAlert("Load Graph Success", "Successfully loaded a Movielens type graph.");
            ui->nodePlotter->initGraph();
            ui->pushButton->setEnabled(true);
        }
        else
        {
            clc::GlobalFileLogger::instance()->log(clc::SeverityType::ERROR, "Load Graph failed. Unable to load a Movielens graph");
            QMessageBox::critical(this, "Load Graph failed", "Unable to load a Movielens graph");
        }
    }
}

void MainWindow::on_actionSave_Population_triggered()
{
    // Save population
    QString path = QFileDialog::getSaveFileName(this,
                   tr("Save Population"),
                   tr("."),
                   tr("Text Files (*.txt)"));
    if (!path.isNull() && !path.isEmpty())
    {
        bool result = clb::GlobalBackendController::instance()->savePopulation(path.toLocal8Bit().constData());
        if (result == true)
        {
            showAlert("Save Population Success", "Successfully saved population to file.");
        }
        else
        {
            clc::GlobalFileLogger::instance()->log(clc::SeverityType::ERROR, "Save Population failed. Unable to save population");
            QMessageBox::critical(this, "Save Population failed", "Unable to save population");
        }
    }
}

void MainWindow::on_actionLoad_Population_triggered()
{
    // Load population
    QString path = QFileDialog::getOpenFileName(this,
                   tr("Load Population"),
                   ".",
                   tr("Text Files (*.txt)"));
    if (!path.isNull() && !path.isEmpty())
    {
        bool result = clb::GlobalBackendController::instance()->loadPopulation(path.toLocal8Bit().constData());
        if (result == true)
        {
            showAlert("Load Population Success", "Successfully loaded a population.");
        }
        else
        {
            clc::GlobalFileLogger::instance()->log(clc::SeverityType::ERROR, "Load Population failed. Unable to load a population out of this file.");
            QMessageBox::critical(this, "Load Population failed", "Unable to load a population out of this file.");
        }
    }
}

void MainWindow::on_actionAbout_2_triggered()
{
    QString info = "Clustering Social Networks by using Genetic Algorithms\n\n"
                   "Software Project for the Course Software Engineering Lab 2015 at Jacobs University Bremen.\n\n"
                   "Authors: Denis Rochau, Dinesh Kannan, Annu Thapa, Valentin Vasiliu, Radu Homorozan, Kiril Kafadarov";
    QMessageBox::about(this, "About this project", info);
}

void MainWindow::on_actionEdit_Settings_triggered()
{
    SettingsDialog dialog(this);
    dialog.exec();
}

}
}
<commit_msg>Fixed merging conflicts, added some more button logic<commit_after>/**
 * @file MainWindow.h
 * @brief Main window for the Clusterer GUI
 */

// standard headers
#include <limits>

// Own headers
#include "../include/MainWindow.h"
#include "../include/SettingsDialog.h"
#include "../include/PopulationMember.hpp"
#include "../include/IntegerVectorEncoding.hpp"

// External headers
#include <QMessageBox>
#include <QFileDialog>

// Generated headers
#include "ui_MainWindow.h"
#include "../include/GlobalBackendController.hpp"
#include "../include/GlobalFileLogger.hpp"

#define MSEC_60_HZ 16

namespace clusterer
{

namespace frontend
{

MainWindow::MainWindow(QWidget* parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    connect(&timer, SIGNAL(timeout()), this, SLOT(updateFrontend()));

    setStateAlgoOff();
    // No graph loaded - cannot start
    ui->pushButton->setEnabled(false);
    ui->pushButton_3->setEnabled(false);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::setStateAlgoOn()
{
    ui->pushButton->setEnabled(false);
    ui->pushButton_4->setEnabled(true);
    ui->pushButton_2->setEnabled(true);
    ui->pushButton_3->setEnabled(false);
    ui->actionZachary_format->setEnabled(false);
    ui->actionMovielens_format->setEnabled(false);
    ui->actionLoad_Population->setEnabled(false);
    ui->actionSave_Population->setEnabled(false);
}

void MainWindow::setStateAlgoOff()
{
    ui->pushButton->setEnabled(true);
    ui->pushButton_4->setEnabled(false);
    ui->pushButton_2->setEnabled(false);
    ui->pushButton_3->setEnabled(false);
    ui->actionZachary_format->setEnabled(true);
    ui->actionMovielens_format->setEnabled(true);
    ui->actionLoad_Population->setEnabled(true);
    ui->actionSave_Population->setEnabled(true);
}

void MainWindow::updateFrontend()
{
    std::pair<clb::PopulationMember<clb::IntegerVectorEncoding, double>, uint64_t> output;
    std::vector<std::pair<clb::PopulationMember<clb::IntegerVectorEncoding, double>, uint64_t>> vector;
    while (clb::GlobalBackendController::instance()->getOutQueue()->popNonWaiting(output))
    {
        vector.push_back(output);
    }

    if (!vector.empty())
    {
        bool exitFlag = false;
        std::vector<std::pair<uint64_t, double>> fitnessVec;
        fitnessVec.reserve(vector.size());
        for (auto& e : vector)
        {
            if (std::numeric_limits<uint64_t>::max() - std::numeric_limits<uint64_t>::epsilon() <= e.second)
            {
                // algo stopped
                setAlgorithmRunning(false);
                setStateAlgoOff();
                timer.stop();
                exitFlag = true;
                continue;
            }
            fitnessVec.push_back(std::make_pair(e.second, e.first.fitnessValue));
        }
        ui->fitnessPlotter->replotFitness(fitnessVec);

        if (exitFlag == true && vector.size() > 1)
        {
            ui->nodePlotter->replotSolution(vector[vector.size() - 2].first.populationEncoding);
        }
        else
        {
            ui->nodePlotter->replotSolution(vector[vector.size() - 1].first.populationEncoding);
        }
    }
}

void MainWindow::setAlgorithmRunning(bool val)
{
    algorithmRunning = val;
}

bool MainWindow::isAlgorithmRunning()
{
    return algorithmRunning;
}

void MainWindow::showAlert(const QString& title, const QString& text)
{
    QMessageBox::information(this, title, text);
}

void MainWindow::on_pushButton_clicked()
{
    //Start button
    // @todo put check condition function into controller and call it here and check
    if (clb::GlobalBackendController::instance()->runAlgorithm(true))
    {
        clb::GlobalBackendController::instance()->runAlgorithm(true);
        timer.start(MSEC_60_HZ);
        this->showAlert("Info", "Started the algorithm");
        setStateAlgoOn();
        setAlgorithmRunning(true);
    }
    else
    {
        clc::GlobalFileLogger::instance()->log(clc::SeverityType::ERROR, "Could not start the algorithm as you need to load a Graph first.");
        QMessageBox::critical(this, "Error", "Could not start the algorithm as you need to load a Graph first.");
    }
}

void MainWindow::on_pushButton_4_clicked()
{
    //Stop button
    clb::GlobalBackendController::instance()->stopAlgorithm();
    this->showAlert("Alert", "Stopped the algorithm");
    setStateAlgoOff();
    setAlgorithmRunning(true);
    timer.stop();
}

void MainWindow::on_pushButton_2_clicked()
{
    clb::GlobalBackendController::instance()->stopAlgorithm();
    setStateAlgoOff();
    setAlgorithmRunning(false);
    this->showAlert("Alert", "Paused algorithm");
    timer.stop();
    ui->pushButton_3->setEnabled(true);
    ui->pushButton->setEnabled(true);
}

void MainWindow::on_pushButton_3_clicked()
{
    clb::GlobalBackendController::instance()->runAlgorithm(false);
    this->showAlert("Alert", "Resumed execution of the algorithm");
    timer.start(MSEC_60_HZ);
    setStateAlgoOn();
    setAlgorithmRunning(true);
}

void MainWindow::on_actionSave_Settings_2_triggered()
{
    // Save settings
    QString path = QFileDialog::getSaveFileName(this,
                   tr("Save Settings"),
                   tr("."),
                   tr("Text Files (*.txt)"));
    if (!path.isNull() && !path.isEmpty())
    {
        bool result = clb::GlobalBackendController::instance()->saveConfiguration(path.toLocal8Bit().constData());
        if (result == true)
        {
            showAlert("Save Settings Success", "Successfully saved settings");
        }
        else
        {
            clc::GlobalFileLogger::instance()->log(clc::SeverityType::ERROR, "Save Settings failed. Failed saving settings.");
            QMessageBox::critical(this, "Save Settings failed", "Failed saving settings.");
        }
    }
}

void MainWindow::on_actionLoad_Settings_2_triggered()
{
    QString path = QFileDialog::getOpenFileName(this,
                   tr("Open Settings File"),
                   ".",
                   tr("Text Files (*.txt)"));
    if (!path.isNull() && !path.isEmpty())
    {
        bool result = clb::GlobalBackendController::instance()->loadConfiguration(path.toLocal8Bit().constData());
        if (result == true)
        {
            showAlert("Load Settings Success", "Successfully loaded settings");
        }
        else
        {
            clc::GlobalFileLogger::instance()->log(clc::SeverityType::ERROR, "Load Settings failed. The file you selected is not a valid configuration file");
            QMessageBox::critical(this, "Load Settings failed", "The file you selected is not a valid configuration file");
        }
    }
}

void MainWindow::on_actionSave_Graph_triggered()
{
    QString path = QFileDialog::getSaveFileName(this,
                   tr("Save Graph"),
                   tr("."),
                   tr("Text Files (*.txt)"));
    if (!path.isNull() && !path.isEmpty())
    {
        bool result = clb::GlobalBackendController::instance()->saveGraphToFile(path.toLocal8Bit().constData());
        if (result == true)
        {
            showAlert("Save Graph Success", "Successfully saved graph to file.");
        }
        else
        {
            clc::GlobalFileLogger::instance()->log(clc::SeverityType::ERROR, "Save Graph failed. Unable to save graph");
            QMessageBox::critical(this, "Save Graph failed", "Unable to save graph");
        }
    }
}

void MainWindow::on_actionZachary_format_triggered()
{
    // Load Zachary Format
    QString path = QFileDialog::getOpenFileName(this,
                   tr("Open Zachary Karate Club Graph"),
                   ".",
                   tr("All Files (*)"));
    if (!path.isNull() && !path.isEmpty())
    {
        bool result = clb::GlobalBackendController::instance()->loadGraphTypeVertexPairWeight(path.toLocal8Bit().constData());
        if (result == true)
        {
            showAlert("Load Graph Success", "Successfully loaded a vertex-pair-weight type graph.");
            ui->nodePlotter->initGraph();
            ui->pushButton->setEnabled(true);
        }
        else
        {
            clc::GlobalFileLogger::instance()->log(clc::SeverityType::ERROR, "Load Graph failed. Unable to load a vertex-pair-weight graph");
            QMessageBox::critical(this, "Load Graph failed", "Unable to load a vertex-pair-weight graph");
        }
    }
}

void MainWindow::on_actionMovielens_format_triggered()
{
    // Load Movielens Format
    QString path = QFileDialog::getOpenFileName(this,
                   tr("Open Movielens Graph"),
                   ".",
                   tr("All Files (*)"));
    if (!path.isNull() && !path.isEmpty())
    {
        bool result = clb::GlobalBackendController::instance()->loadGraphTypeMovieLens(path.toLocal8Bit().constData());
        if (result == true)
        {
            showAlert("Load Graph Success", "Successfully loaded a Movielens type graph.");
            ui->nodePlotter->initGraph();
            ui->pushButton->setEnabled(true);
        }
        else
        {
            clc::GlobalFileLogger::instance()->log(clc::SeverityType::ERROR, "Load Graph failed. Unable to load a Movielens graph");
            QMessageBox::critical(this, "Load Graph failed", "Unable to load a Movielens graph");
        }
    }
}

void MainWindow::on_actionSave_Population_triggered()
{
    // Save population
    QString path = QFileDialog::getSaveFileName(this,
                   tr("Save Population"),
                   tr("."),
                   tr("Text Files (*.txt)"));
    if (!path.isNull() && !path.isEmpty())
    {
        bool result = clb::GlobalBackendController::instance()->savePopulation(path.toLocal8Bit().constData());
        if (result == true)
        {
            showAlert("Save Population Success", "Successfully saved population to file.");
        }
        else
        {
            clc::GlobalFileLogger::instance()->log(clc::SeverityType::ERROR, "Save Population failed. Unable to save population");
            QMessageBox::critical(this, "Save Population failed", "Unable to save population");
        }
    }
}

void MainWindow::on_actionLoad_Population_triggered()
{
    // Load population
    QString path = QFileDialog::getOpenFileName(this,
                   tr("Load Population"),
                   ".",
                   tr("Text Files (*.txt)"));
    if (!path.isNull() && !path.isEmpty())
    {
        bool result = clb::GlobalBackendController::instance()->loadPopulation(path.toLocal8Bit().constData());
        if (result == true)
        {
            showAlert("Load Population Success", "Successfully loaded a population.");
        }
        else
        {
            clc::GlobalFileLogger::instance()->log(clc::SeverityType::ERROR, "Load Population failed. Unable to load a population out of this file.");
            QMessageBox::critical(this, "Load Population failed", "Unable to load a population out of this file.");
        }
    }
}

void MainWindow::on_actionAbout_2_triggered()
{
    QString info = "Clustering Social Networks by using Genetic Algorithms\n\n"
                   "Software Project for the Course Software Engineering Lab 2015 at Jacobs University Bremen.\n\n"
                   "Authors: Denis Rochau, Dinesh Kannan, Annu Thapa, Valentin Vasiliu, Radu Homorozan, Kiril Kafadarov";
    QMessageBox::about(this, "About this project", info);
}

void MainWindow::on_actionEdit_Settings_triggered()
{
    SettingsDialog dialog(this);
    dialog.exec();
}

}
}
<|endoftext|>