<commit_before>/*!
	@file
	@author		Albert Semenov
	@date		09/2008
	@module
*/
/*
	This file is part of MyGUI.

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

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

	You should have received a copy of the GNU Lesser General Public License
	along with MyGUI.  If not, see <http://www.gnu.org/licenses/>.
*/
#include "MyGUI_Precompiled.h"
#include "MyGUI_ResourceManager.h"
#include "MyGUI_XmlDocument.h"
#include "MyGUI_IResource.h"
#include "MyGUI_DataManager.h"
#include "MyGUI_FactoryManager.h"

#include "MyGUI_ResourceImageSet.h"

namespace MyGUI
{

	const std::string XML_TYPE("Resource");
	const std::string XML_TYPE_LIST("List");

	MYGUI_INSTANCE_IMPLEMENT(ResourceManager);

	void ResourceManager::initialise()
	{
		MYGUI_ASSERT(false == mIsInitialise, INSTANCE_TYPE_NAME << " initialised twice");
		MYGUI_LOG(Info, "* Initialise: " << INSTANCE_TYPE_NAME);

		registerLoadXmlDelegate(XML_TYPE) = newDelegate(this, &ResourceManager::_load);
		registerLoadXmlDelegate(XML_TYPE_LIST) = newDelegate(this, &ResourceManager::_loadList);

		// регестрируем дефолтные ресурсы
		FactoryManager::getInstance().registryFactory<ResourceImageSet>(XML_TYPE);

		MYGUI_LOG(Info, INSTANCE_TYPE_NAME << " successfully initialized");
		mIsInitialise = true;
	}

	void ResourceManager::shutdown()
	{
		if (false == mIsInitialise) return;
		MYGUI_LOG(Info, "* Shutdown: " << INSTANCE_TYPE_NAME);

		FactoryManager::getInstance().unregistryFactory<ResourceImageSet>(XML_TYPE);

		clear();
		unregisterLoadXmlDelegate(XML_TYPE);
		unregisterLoadXmlDelegate(XML_TYPE_LIST);

		mMapLoadXmlDelegate.clear();

		MYGUI_LOG(Info, INSTANCE_TYPE_NAME << " successfully shutdown");
		mIsInitialise = false;
	}

	bool ResourceManager::load(const std::string& _file)
	{
		return _loadImplement(_file, false, "", INSTANCE_TYPE_NAME);
	}

	void ResourceManager::_load(xml::ElementPtr _node, const std::string& _file, Version _version)
	{
		FactoryManager& factory = FactoryManager::getInstance();

		VectorGuid vector_guid;
		// берем детей и крутимся, основной цикл
		xml::ElementEnumerator root = _node->getElementEnumerator();
		while (root.next(XML_TYPE))
		{
			// парсим атрибуты
			std::string id, type, name;
			root->findAttribute("type", type);
			root->findAttribute("name", name);
			root->findAttribute("id", id);

			Guid guid(id);
			if (!guid.empty())
			{
				MYGUI_ASSERT(mResourcesID.find(guid) == mResourcesID.end(), "dublicate resource id " << guid.print());
			}

			MYGUI_ASSERT(mResources.find(name) == mResources.end(), "dublicate resource name '" << name << "'");

			vector_guid.push_back(guid);

			IObject* object = factory.createObject(XML_TYPE, type);
			if (object == nullptr)
			{
				MYGUI_LOG(Error, "resource type '" << type << "' not found");
				continue;
			}

			IResourcePtr resource = object->castType<IResource>();
			resource->deserialization(root.current(), _version);

			if (!guid.empty()) mResourcesID[guid] = resource;
			if (!name.empty()) mResources[name] = resource;
		}

		if (!vector_guid.empty())
		{
			mListFileGuid[_file] = vector_guid;
		}

	}

	std::string ResourceManager::getFileNameByID(const Guid& _id)
	{
		for (MapVectorString::iterator item=mListFileGuid.begin(); item!=mListFileGuid.end(); ++item)
		{
			for (VectorGuid::iterator item2=item->second.begin(); item2!=item->second.end(); ++item2)
			{
				if (*item2 == _id)
				{
					return item->first;
				}
			}
		}
		return "";
	}

	void ResourceManager::_loadList(xml::ElementPtr _node, const std::string& _file, Version _version)
	{
		// берем детей и крутимся, основной цикл
		xml::ElementEnumerator node = _node->getElementEnumerator();
		while (node.next(XML_TYPE_LIST))
		{
			std::string source;
			if (false == node->findAttribute("file", source)) continue;
			MYGUI_LOG(Info, "Load ini file '" << source << "'");
			_loadImplement(source, false, "", INSTANCE_TYPE_NAME);
		};
	}

	LoadXmlDelegate& ResourceManager::registerLoadXmlDelegate(const std::string& _key)
	{
		MapLoadXmlDelegate::iterator iter = mMapLoadXmlDelegate.find(_key);
		MYGUI_ASSERT(iter == mMapLoadXmlDelegate.end(), "name delegate is exist");
		return (mMapLoadXmlDelegate[_key] = LoadXmlDelegate());
	}

	void ResourceManager::unregisterLoadXmlDelegate(const std::string& _key)
	{
		MapLoadXmlDelegate::iterator iter = mMapLoadXmlDelegate.find(_key);
		if (iter != mMapLoadXmlDelegate.end()) mMapLoadXmlDelegate.erase(iter);
	}

	bool ResourceManager::_loadImplement(const std::string& _file, bool _match, const std::string& _type, const std::string& _instance)
	{
		IDataStream* data = DataManager::getInstance().getData(_file);
		if (data == nullptr)
		{
			MYGUI_LOG(Error, _instance << " : '" << _file << "', not found");
			return false;
		}

		xml::Document doc;
		if (false == doc.open(data))
		{
			MYGUI_LOG(Error, _instance << " : '" << _file << "', " << doc.getLastError());

			// FIXME
			delete data;

			return false;
		}

		// FIXME
		delete data;

		xml::ElementPtr root = doc.getRoot();
		if ( (nullptr == root) || (root->getName() != "MyGUI") )
		{
			MYGUI_LOG(Error, _instance << " : '" << _file << "', tag 'MyGUI' not found");
			return false;
		}

		std::string type;
		if (root->findAttribute("type", type))
		{
			Version version = Version::parse(root->findAttribute("version"));
			MapLoadXmlDelegate::iterator iter = mMapLoadXmlDelegate.find(type);
			if (iter != mMapLoadXmlDelegate.end())
			{
				if ((false == _match) || (type == _type)) (*iter).second(root, _file, version);
				else
				{
					MYGUI_LOG(Error, _instance << " : '" << _file << "', type '" << _type << "' not found");
					return false;
				}
			}
			else
			{
				MYGUI_LOG(Error, _instance << " : '" << _file << "', delegate for type '" << type << "'not found");
				return false;
			}
		}
		// предпологаем что будут вложенные
		else if (false == _match)
		{
			xml::ElementEnumerator node = root->getElementEnumerator();
			while (node.next("MyGUI"))
			{
				if (node->findAttribute("type", type))
				{
					Version version = Version::parse(root->findAttribute("version"));
					MapLoadXmlDelegate::iterator iter = mMapLoadXmlDelegate.find(type);
					if (iter != mMapLoadXmlDelegate.end())
					{
						(*iter).second(node.current(), _file, version);
					}
					else
					{
						MYGUI_LOG(Error, _instance << " : '" << _file << "', delegate for type '" << type << "'not found");
					}
				}
				else
				{
					MYGUI_LOG(Error, _instance << " : '" << _file << "', tag 'type' not found");
				}
			}
		}

		return true;
	}

	IResourcePtr ResourceManager::getByID(const Guid& _id, bool _throw)
	{
		MapResourceID::iterator iter = mResourcesID.find(_id);
		if (iter == mResourcesID.end())
		{
			if (_throw) MYGUI_EXCEPT("resource '" << _id.print() << "' not found");
			MYGUI_LOG(Warning, "resource '" << _id.print() << "' not found");
			return nullptr;
		}
		return iter->second;
	}

	void ResourceManager::addResource(IResourcePtr _item)
	{
		if (!_item->getResourceName().empty())
			mResources[_item->getResourceName()] = _item;
		if (!_item->getResourceID().empty())
			mResourcesID[_item->getResourceID()] = _item;
	}

	void ResourceManager::removeResource(IResourcePtr _item)
	{
		if (_item == nullptr) return;

		if (!_item->getResourceName().empty())
		{
			MapResource::iterator item = mResources.find(_item->getResourceName());
			if (item != mResources.end())
				mResources.erase(item);
		}

		if (!_item->getResourceID().empty())
		{
			MapResourceID::iterator id = mResourcesID.find(_item->getResourceID());
			if (id != mResourcesID.end())
				mResourcesID.erase(id);
		}
	}

} // namespace MyGUI
<commit_msg>update resource manager<commit_after>/*!
	@file
	@author		Albert Semenov
	@date		09/2008
	@module
*/
/*
	This file is part of MyGUI.

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

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

	You should have received a copy of the GNU Lesser General Public License
	along with MyGUI.  If not, see <http://www.gnu.org/licenses/>.
*/
#include "MyGUI_Precompiled.h"
#include "MyGUI_ResourceManager.h"
#include "MyGUI_XmlDocument.h"
#include "MyGUI_IResource.h"
#include "MyGUI_DataManager.h"
#include "MyGUI_FactoryManager.h"

#include "MyGUI_ResourceImageSet.h"

namespace MyGUI
{

	const std::string XML_TYPE("Resource");
	const std::string XML_TYPE_LIST("List");

	MYGUI_INSTANCE_IMPLEMENT(ResourceManager);

	void ResourceManager::initialise()
	{
		MYGUI_ASSERT(false == mIsInitialise, INSTANCE_TYPE_NAME << " initialised twice");
		MYGUI_LOG(Info, "* Initialise: " << INSTANCE_TYPE_NAME);

		registerLoadXmlDelegate(XML_TYPE) = newDelegate(this, &ResourceManager::_load);
		registerLoadXmlDelegate(XML_TYPE_LIST) = newDelegate(this, &ResourceManager::_loadList);

		// регестрируем дефолтные ресурсы
		FactoryManager::getInstance().registryFactory<ResourceImageSet>(XML_TYPE);

		MYGUI_LOG(Info, INSTANCE_TYPE_NAME << " successfully initialized");
		mIsInitialise = true;
	}

	void ResourceManager::shutdown()
	{
		if (false == mIsInitialise) return;
		MYGUI_LOG(Info, "* Shutdown: " << INSTANCE_TYPE_NAME);

		FactoryManager::getInstance().unregistryFactory<ResourceImageSet>(XML_TYPE);

		clear();
		unregisterLoadXmlDelegate(XML_TYPE);
		unregisterLoadXmlDelegate(XML_TYPE_LIST);

		mMapLoadXmlDelegate.clear();

		MYGUI_LOG(Info, INSTANCE_TYPE_NAME << " successfully shutdown");
		mIsInitialise = false;
	}

	bool ResourceManager::load(const std::string& _file)
	{
		return _loadImplement(_file, false, "", INSTANCE_TYPE_NAME);
	}

	void ResourceManager::_load(xml::ElementPtr _node, const std::string& _file, Version _version)
	{
		FactoryManager& factory = FactoryManager::getInstance();

		VectorGuid vector_guid;
		// берем детей и крутимся, основной цикл
		xml::ElementEnumerator root = _node->getElementEnumerator();
		while (root.next(XML_TYPE))
		{
			// парсим атрибуты
			std::string id, type, name;
			root->findAttribute("type", type);
			root->findAttribute("name", name);
			root->findAttribute("id", id);

			Guid guid(id);
			if (!guid.empty())
			{
				if (mResourcesID.find(guid) != mResourcesID.end())
				{
					MYGUI_LOG(Warning, "dublicate resource id " << guid.print());
				}
			}

			if (mResources.find(name) != mResources.end())
			{
				MYGUI_LOG(Warning, "dublicate resource name '" << name << "'");
			}

			vector_guid.push_back(guid);

			IObject* object = factory.createObject(XML_TYPE, type);
			if (object == nullptr)
			{
				MYGUI_LOG(Error, "resource type '" << type << "' not found");
				continue;
			}

			IResourcePtr resource = object->castType<IResource>();
			resource->deserialization(root.current(), _version);

			if (!guid.empty()) mResourcesID[guid] = resource;
			if (!name.empty()) mResources[name] = resource;
		}

		if (!vector_guid.empty())
		{
			mListFileGuid[_file] = vector_guid;
		}

	}

	std::string ResourceManager::getFileNameByID(const Guid& _id)
	{
		for (MapVectorString::iterator item=mListFileGuid.begin(); item!=mListFileGuid.end(); ++item)
		{
			for (VectorGuid::iterator item2=item->second.begin(); item2!=item->second.end(); ++item2)
			{
				if (*item2 == _id)
				{
					return item->first;
				}
			}
		}
		return "";
	}

	void ResourceManager::_loadList(xml::ElementPtr _node, const std::string& _file, Version _version)
	{
		// берем детей и крутимся, основной цикл
		xml::ElementEnumerator node = _node->getElementEnumerator();
		while (node.next(XML_TYPE_LIST))
		{
			std::string source;
			if (false == node->findAttribute("file", source)) continue;
			MYGUI_LOG(Info, "Load ini file '" << source << "'");
			_loadImplement(source, false, "", INSTANCE_TYPE_NAME);
		};
	}

	LoadXmlDelegate& ResourceManager::registerLoadXmlDelegate(const std::string& _key)
	{
		MapLoadXmlDelegate::iterator iter = mMapLoadXmlDelegate.find(_key);
		MYGUI_ASSERT(iter == mMapLoadXmlDelegate.end(), "name delegate is exist");
		return (mMapLoadXmlDelegate[_key] = LoadXmlDelegate());
	}

	void ResourceManager::unregisterLoadXmlDelegate(const std::string& _key)
	{
		MapLoadXmlDelegate::iterator iter = mMapLoadXmlDelegate.find(_key);
		if (iter != mMapLoadXmlDelegate.end()) mMapLoadXmlDelegate.erase(iter);
	}

	bool ResourceManager::_loadImplement(const std::string& _file, bool _match, const std::string& _type, const std::string& _instance)
	{
		IDataStream* data = DataManager::getInstance().getData(_file);
		if (data == nullptr)
		{
			MYGUI_LOG(Error, _instance << " : '" << _file << "', not found");
			return false;
		}

		xml::Document doc;
		if (false == doc.open(data))
		{
			MYGUI_LOG(Error, _instance << " : '" << _file << "', " << doc.getLastError());

			// FIXME
			delete data;

			return false;
		}

		// FIXME
		delete data;

		xml::ElementPtr root = doc.getRoot();
		if ( (nullptr == root) || (root->getName() != "MyGUI") )
		{
			MYGUI_LOG(Error, _instance << " : '" << _file << "', tag 'MyGUI' not found");
			return false;
		}

		std::string type;
		if (root->findAttribute("type", type))
		{
			Version version = Version::parse(root->findAttribute("version"));
			MapLoadXmlDelegate::iterator iter = mMapLoadXmlDelegate.find(type);
			if (iter != mMapLoadXmlDelegate.end())
			{
				if ((false == _match) || (type == _type)) (*iter).second(root, _file, version);
				else
				{
					MYGUI_LOG(Error, _instance << " : '" << _file << "', type '" << _type << "' not found");
					return false;
				}
			}
			else
			{
				MYGUI_LOG(Error, _instance << " : '" << _file << "', delegate for type '" << type << "'not found");
				return false;
			}
		}
		// предпологаем что будут вложенные
		else if (false == _match)
		{
			xml::ElementEnumerator node = root->getElementEnumerator();
			while (node.next("MyGUI"))
			{
				if (node->findAttribute("type", type))
				{
					Version version = Version::parse(root->findAttribute("version"));
					MapLoadXmlDelegate::iterator iter = mMapLoadXmlDelegate.find(type);
					if (iter != mMapLoadXmlDelegate.end())
					{
						(*iter).second(node.current(), _file, version);
					}
					else
					{
						MYGUI_LOG(Error, _instance << " : '" << _file << "', delegate for type '" << type << "'not found");
					}
				}
				else
				{
					MYGUI_LOG(Error, _instance << " : '" << _file << "', tag 'type' not found");
				}
			}
		}

		return true;
	}

	IResourcePtr ResourceManager::getByID(const Guid& _id, bool _throw)
	{
		MapResourceID::iterator iter = mResourcesID.find(_id);
		if (iter == mResourcesID.end())
		{
			if (_throw) MYGUI_EXCEPT("resource '" << _id.print() << "' not found");
			MYGUI_LOG(Warning, "resource '" << _id.print() << "' not found");
			return nullptr;
		}
		return iter->second;
	}

	void ResourceManager::addResource(IResourcePtr _item)
	{
		if (!_item->getResourceName().empty())
			mResources[_item->getResourceName()] = _item;
		if (!_item->getResourceID().empty())
			mResourcesID[_item->getResourceID()] = _item;
	}

	void ResourceManager::removeResource(IResourcePtr _item)
	{
		if (_item == nullptr) return;

		if (!_item->getResourceName().empty())
		{
			MapResource::iterator item = mResources.find(_item->getResourceName());
			if (item != mResources.end())
				mResources.erase(item);
		}

		if (!_item->getResourceID().empty())
		{
			MapResourceID::iterator id = mResourcesID.find(_item->getResourceID());
			if (id != mResourcesID.end())
				mResourcesID.erase(id);
		}
	}

} // namespace MyGUI
<|endoftext|>


<commit_before>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_SPACE_CONTINUOUS_LAGRANGE_FEM_LOCALFUNCTIONS_HH
#define DUNE_GDT_SPACE_CONTINUOUS_LAGRANGE_FEM_LOCALFUNCTIONS_HH

#ifdef HAVE_CMAKE_CONFIG
#include "cmake_config.h"
#elif defined(HAVE_CONFIG_H)
#include "config.h"
#endif

#include <dune/common/static_assert.hh>
#include <dune/common/exceptions.hh>

#include <dune/localfunctions/lagrange/equidistantpoints.hh>
#include <dune/localfunctions/lagrange.hh>

#include <dune/fem/space/common/allgeomtypes.hh>

#include <dune/fem_localfunctions/localfunctions/transformations.hh>
#include <dune/fem_localfunctions/basefunctions/genericbasefunctionsetstorage.hh>
#include <dune/fem_localfunctions/basefunctionsetmap/basefunctionsetmap.hh>
#include <dune/fem_localfunctions/space/genericdiscretefunctionspace.hh>

#include <dune/stuff/common/color.hh>

#include "../../mapper/fem.hh"
#include "../../basefunctionset/fem-localfunctions.hh"
#include "../constraints.hh"
#include "../interface.hh"

namespace Dune {
namespace GDT {
namespace ContinuousLagrangeSpace {

// forward, to be used in the traits and to allow for specialization
template <class GridPartImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1>
class FemLocalfunctionsWrapper;

// forward, to allow for specialization
template <class GridPartImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1>
class FemLocalfunctionsWrapperTraits;

/**
 *  \brief Traits class for ContinuousLagrangeSpace for dimRange 1x1.
 */
template <class GridPartImp, int polynomialOrder, class RangeFieldImp>
class FemLocalfunctionsWrapperTraits<GridPartImp, polynomialOrder, RangeFieldImp, 1, 1>
{
public:
  typedef GridPartImp GridPartType;
  static const int polOrder = polynomialOrder;
  dune_static_assert((polOrder >= 1), "ERROR: wrong polOrder given!");

private:
  typedef typename GridPartType::ctype DomainFieldType;
  static const unsigned int dimDomain = GridPartType::dimension;

public:
  typedef RangeFieldImp RangeFieldType;
  static const unsigned int dimRange     = 1;
  static const unsigned int dimRangeCols = 1;
  typedef FemLocalfunctionsWrapper<GridPartType, polOrder, RangeFieldType, dimRange, dimRangeCols> derived_type;

private:
  typedef FemLocalfunctionsWrapperTraits<GridPartType, polOrder, RangeFieldType, dimRange, dimRangeCols> ThisType;
  typedef Dune::LagrangeLocalFiniteElement<Dune::EquidistantPointSet, dimDomain, DomainFieldType, RangeFieldType>
      FiniteElementType;
  typedef Dune::FemLocalFunctions::BaseFunctionSetMap<GridPartType, FiniteElementType,
                                                      Dune::FemLocalFunctions::NoTransformation,
                                                      Dune::FemLocalFunctions::SimpleStorage, polOrder,
                                                      polOrder> BaseFunctionSetMapType;

public:
  typedef Dune::FemLocalFunctions::DiscreteFunctionSpace<BaseFunctionSetMapType> BackendType;
  typedef Mapper::FemDofWrapper<typename BackendType::MapperType> MapperType;
  typedef BaseFunctionSet::FemLocalfunctionsWrapper<BaseFunctionSetMapType, DomainFieldType, dimDomain, RangeFieldType,
                                                    dimRange, dimRangeCols> BaseFunctionSetType;
  typedef typename BaseFunctionSetType::EntityType EntityType;

private:
  template <class G, int p, class R, int r, int rC>
  friend class FemLocalfunctionsWrapper;
}; // class FemLocalfunctionsWrapperTraits< ..., 1, 1 >

template <class GridPartImp, int polynomialOrder, class RangeFieldImp>
class FemLocalfunctionsWrapper<GridPartImp, polynomialOrder, RangeFieldImp, 1, 1>
    : public SpaceInterface<FemLocalfunctionsWrapperTraits<GridPartImp, polynomialOrder, RangeFieldImp, 1, 1>>
{
  typedef SpaceInterface<FemLocalfunctionsWrapperTraits<GridPartImp, polynomialOrder, RangeFieldImp, 1, 1>> BaseType;

public:
  typedef FemLocalfunctionsWrapperTraits<GridPartImp, polynomialOrder, RangeFieldImp, 1, 1> Traits;

  typedef typename Traits::GridPartType GridPartType;
  typedef typename GridPartType::ctype DomainFieldType;
  static const int polOrder           = Traits::polOrder;
  static const unsigned int dimDomain = GridPartType::dimension;
  typedef typename Traits::RangeFieldType RangeFieldType;
  static const unsigned int dimRange     = Traits::dimRange;
  static const unsigned int dimRangeCols = Traits::dimRangeCols;

  typedef typename Traits::BackendType BackendType;
  typedef typename Traits::MapperType MapperType;
  typedef typename Traits::BaseFunctionSetType BaseFunctionSetType;
  typedef typename Traits::EntityType EntityType;

  typedef Dune::Stuff::LA::SparsityPatternDefault PatternType;

private:
  typedef typename Traits::BaseFunctionSetMapType BaseFunctionSetMapType;

public:
  FemLocalfunctionsWrapper(const GridPartType& gridP)
    : gridPart_(assertGridPart(gridP))
    , baseFunctionSetMap_(gridPart_)
    , backend_(const_cast<GridPartType&>(gridPart_), baseFunctionSetMap_)
    , mapper_(backend_.mapper())
  {
  }

  const GridPartType& gridPart() const
  {
    return gridPart_;
  }

  const BackendType& backend() const
  {
    return backend_;
  }

  bool continuous() const
  {
    return true;
  }

  const MapperType& mapper() const
  {
    return mapper_;
  }

  BaseFunctionSetType baseFunctionSet(const EntityType& entity) const
  {
    return BaseFunctionSetType(baseFunctionSetMap_, entity);
  }

  template <class R>
  void localConstraints(const EntityType& /*entity*/, Constraints::LocalDefault<R>& /*ret*/) const
  {
    dune_static_assert(Dune::AlwaysFalse<R>::value, "ERROR: not implemented for arbitrary constraints!");
  }

  using BaseType::computePattern;

  template <class LocalGridPartType, class OtherSpaceType>
  PatternType* computePattern(const LocalGridPartType& localGridPart, const OtherSpaceType& otherSpace) const
  {
    return BaseType::computeVolumePattern(localGridPart, otherSpace);
  }

private:
  static const GridPartType& assertGridPart(const GridPartType& gP)
  {
    // check
    typedef typename Dune::Fem::AllGeomTypes<typename GridPartType::IndexSetType, typename GridPartType::GridType>
        AllGeometryTypes;
    const AllGeometryTypes allGeometryTypes(gP.indexSet());
    const std::vector<Dune::GeometryType>& geometryTypes = allGeometryTypes.geomTypes(0);
    if (!(geometryTypes.size() == 1 && geometryTypes[0].isSimplex()))
      DUNE_THROW(Dune::NotImplemented,
                 "\n" << Dune::Stuff::Common::colorStringRed("ERROR:")
                      << " this space is only implemented for simplicial grids!");
    return gP;
  } // ... assertGridPart(...)

  const GridPartType& gridPart_;
  BaseFunctionSetMapType baseFunctionSetMap_;
  const BackendType backend_;
  const MapperType mapper_;
}; // class FemLocalfunctionsWrapper< ..., 1, 1 >

} // namespace ContinuousLagrangeSpace
} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_SPACE_CONTINUOUS_LAGRANGE_FEM_LOCALFUNCTIONS_HH
<commit_msg>[space.continuouslagrange.fem-localfunctions] added dirichlet constraints<commit_after>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_SPACE_CONTINUOUS_LAGRANGE_FEM_LOCALFUNCTIONS_HH
#define DUNE_GDT_SPACE_CONTINUOUS_LAGRANGE_FEM_LOCALFUNCTIONS_HH

#ifdef HAVE_CMAKE_CONFIG
#include "cmake_config.h"
#elif defined(HAVE_CONFIG_H)
#include "config.h"
#endif

#include <dune/common/static_assert.hh>
#include <dune/common/exceptions.hh>

#include <dune/localfunctions/lagrange/equidistantpoints.hh>
#include <dune/localfunctions/lagrange.hh>

#include <dune/fem/space/common/allgeomtypes.hh>

#include <dune/fem_localfunctions/localfunctions/transformations.hh>
#include <dune/fem_localfunctions/basefunctions/genericbasefunctionsetstorage.hh>
#include <dune/fem_localfunctions/basefunctionsetmap/basefunctionsetmap.hh>
#include <dune/fem_localfunctions/space/genericdiscretefunctionspace.hh>

#include <dune/stuff/common/color.hh>
#include <dune/stuff/common/float_cmp.hh>

#include "../../mapper/fem.hh"
#include "../../basefunctionset/fem-localfunctions.hh"
#include "../constraints.hh"
#include "../interface.hh"

namespace Dune {
namespace GDT {
namespace ContinuousLagrangeSpace {

// forward, to be used in the traits and to allow for specialization
template <class GridPartImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1>
class FemLocalfunctionsWrapper;

// forward, to allow for specialization
template <class GridPartImp, int polynomialOrder, class RangeFieldImp, int rangeDim, int rangeDimCols = 1>
class FemLocalfunctionsWrapperTraits;

/**
 *  \brief Traits class for ContinuousLagrangeSpace for dimRange 1x1.
 */
template <class GridPartImp, int polynomialOrder, class RangeFieldImp>
class FemLocalfunctionsWrapperTraits<GridPartImp, polynomialOrder, RangeFieldImp, 1, 1>
{
public:
  typedef GridPartImp GridPartType;
  static const int polOrder = polynomialOrder;
  dune_static_assert((polOrder >= 1), "ERROR: wrong polOrder given!");

private:
  typedef typename GridPartType::ctype DomainFieldType;
  static const unsigned int dimDomain = GridPartType::dimension;

public:
  typedef RangeFieldImp RangeFieldType;
  static const unsigned int dimRange     = 1;
  static const unsigned int dimRangeCols = 1;
  typedef FemLocalfunctionsWrapper<GridPartType, polOrder, RangeFieldType, dimRange, dimRangeCols> derived_type;

private:
  typedef FemLocalfunctionsWrapperTraits<GridPartType, polOrder, RangeFieldType, dimRange, dimRangeCols> ThisType;

public:
  typedef Dune::LagrangeLocalFiniteElement<Dune::EquidistantPointSet, dimDomain, DomainFieldType, RangeFieldType>
      FiniteElementType;

private:
  typedef Dune::FemLocalFunctions::BaseFunctionSetMap<GridPartType, FiniteElementType,
                                                      Dune::FemLocalFunctions::NoTransformation,
                                                      Dune::FemLocalFunctions::SimpleStorage, polOrder,
                                                      polOrder> BaseFunctionSetMapType;

public:
  typedef Dune::FemLocalFunctions::DiscreteFunctionSpace<BaseFunctionSetMapType> BackendType;
  typedef Mapper::FemDofWrapper<typename BackendType::MapperType> MapperType;
  typedef BaseFunctionSet::FemLocalfunctionsWrapper<BaseFunctionSetMapType, DomainFieldType, dimDomain, RangeFieldType,
                                                    dimRange, dimRangeCols> BaseFunctionSetType;
  typedef typename BaseFunctionSetType::EntityType EntityType;

private:
  template <class G, int p, class R, int r, int rC>
  friend class FemLocalfunctionsWrapper;
}; // class FemLocalfunctionsWrapperTraits< ..., 1, 1 >

template <class GridPartImp, int polynomialOrder, class RangeFieldImp>
class FemLocalfunctionsWrapper<GridPartImp, polynomialOrder, RangeFieldImp, 1, 1>
    : public SpaceInterface<FemLocalfunctionsWrapperTraits<GridPartImp, polynomialOrder, RangeFieldImp, 1, 1>>
{
  typedef SpaceInterface<FemLocalfunctionsWrapperTraits<GridPartImp, polynomialOrder, RangeFieldImp, 1, 1>> BaseType;

public:
  typedef FemLocalfunctionsWrapperTraits<GridPartImp, polynomialOrder, RangeFieldImp, 1, 1> Traits;

  typedef typename Traits::GridPartType GridPartType;
  typedef typename GridPartType::ctype DomainFieldType;
  static const int polOrder           = Traits::polOrder;
  static const unsigned int dimDomain = GridPartType::dimension;
  typedef typename Traits::RangeFieldType RangeFieldType;
  static const unsigned int dimRange     = Traits::dimRange;
  static const unsigned int dimRangeCols = Traits::dimRangeCols;

  typedef typename Traits::BackendType BackendType;
  typedef typename Traits::MapperType MapperType;
  typedef typename Traits::BaseFunctionSetType BaseFunctionSetType;
  typedef typename Traits::EntityType EntityType;

  typedef Dune::Stuff::LA::SparsityPatternDefault PatternType;

private:
  typedef typename Traits::BaseFunctionSetMapType BaseFunctionSetMapType;

public:
  FemLocalfunctionsWrapper(const GridPartType& gridP)
    : gridPart_(assertGridPart(gridP))
    , baseFunctionSetMap_(gridPart_)
    , backend_(const_cast<GridPartType&>(gridPart_), baseFunctionSetMap_)
    , mapper_(backend_.mapper())
    , tmp_global_indices_(mapper_.maxNumDofs())
  {
  }

  const GridPartType& gridPart() const
  {
    return gridPart_;
  }

  const BackendType& backend() const
  {
    return backend_;
  }

  bool continuous() const
  {
    return true;
  }

  const MapperType& mapper() const
  {
    return mapper_;
  }

  BaseFunctionSetType baseFunctionSet(const EntityType& entity) const
  {
    return BaseFunctionSetType(baseFunctionSetMap_, entity);
  }

  template <class R>
  void localConstraints(const EntityType& /*entity*/, Constraints::LocalDefault<R>& /*ret*/) const
  {
    dune_static_assert(Dune::AlwaysFalse<R>::value, "ERROR: not implemented for arbitrary constraints!");
  }

  void
  localConstraints(const EntityType& entity,
                   Constraints::Dirichlet<typename GridPartType::IntersectionType, RangeFieldType, true>& ret) const
  {
    static_assert(dimDomain == 2, "This does not work for other dimensions!");
    static_assert(polOrder == 1, "Not tested for higher polynomial orders!");
    // only work if we are at the boundary
    if (entity.hasBoundaryIntersections()) {
      // get local finite elements
      // * we are a CG space
      const auto cg_finite_element      = backend_.finiteElement(entity);
      const auto& cg_local_coefficients = cg_finite_element.localCoefficients();
      // * but we also need a local DG finite element
      typedef Dune::DGLocalFiniteElement<typename Traits::FiniteElementType> DgFiniteElementType;
      const DgFiniteElementType dg_finite_element(entity.type(), polOrder);
      const auto& dg_local_coefficients = dg_finite_element.localCoefficients();
      assert(dg_local_coefficients.size() == cg_local_coefficients.size() && "Wrong finite element given!");

      // first we loop over all vertices of the entity
      typedef FieldVector<DomainFieldType, dimDomain> DomainType;
      std::vector<DomainType> global_vertices(entity.template count<dimDomain>(), DomainType(0));
      std::vector<size_t> local_DoF_ids(global_vertices.size(), 0);
      for (size_t local_vertex_id = 0; local_vertex_id < global_vertices.size(); ++local_vertex_id) {
        // get the vertex
        const auto vertexPtr             = entity.template subEntity<dimDomain>(local_vertex_id);
        const auto& vertex               = *vertexPtr;
        global_vertices[local_vertex_id] = vertex.geometry().center();
        // find the global DoF id to this vertex, therefore
        // loop over all local DoFs
        for (size_t ii = 0; ii < dg_local_coefficients.size(); ++ii) {
          const auto& entity_cg_local_key = cg_local_coefficients.localKey(ii);
          if (entity_cg_local_key.subEntity() == local_vertex_id) {
            // get the local DoF to this vertex
            const auto& entity_dg_local_key = dg_local_coefficients.localKey(ii);
            assert(entity_cg_local_key.codim() == dimDomain && "Wrong finite element given!");
            local_DoF_ids[local_vertex_id] = entity_dg_local_key.index();
            // there must be one and only one for a polorder 1 lagrange basis
            break;
          }
        } // loop over all local DoFs
      } // loop over all vertices of the entity

      // then we walk the intersections
      std::set<size_t> local_dirichlet_DoF_ids;
      const auto intersection_it_end = gridPart_.iend(entity);
      for (auto intersection_it = gridPart_.ibegin(entity); intersection_it != intersection_it_end; ++intersection_it) {
        const auto& intersection = *intersection_it;
        if (ret.gridBoundary().dirichlet(intersection)) {
          const auto& intersection_geometry = intersection.geometry();
          // and walk its corners (i.e. the vertices in 2d)
          for (size_t local_intersection_corner_id = 0;
               int(local_intersection_corner_id) < intersection_geometry.corners();
               ++local_intersection_corner_id) {
            const auto global_intersection_corner = intersection_geometry.corner(local_intersection_corner_id);
            // to check which vertex this corner is
            // loop over all vertices of the entity again
            for (size_t local_vertex_id = 0; local_vertex_id < global_vertices.size(); ++local_vertex_id) {
              // and check for equality
              if (Stuff::Common::FloatCmp::eq(global_intersection_corner, global_vertices[local_vertex_id])) {
                // this vertex is on the dirichlet boundary, so we add the local DoF id this vertex corresponds to
                local_dirichlet_DoF_ids.insert(local_DoF_ids[local_vertex_id]);
              }
            } // loop over all vertices of the entity
          } // walk its corners
        }
      } // walk the intersections

      // finally we compute the local constraints
      const size_t num_rows = local_dirichlet_DoF_ids.size();
      if (num_rows > 0) {
        const size_t num_cols = baseFunctionSet(entity).size();
        mapper_.globalIndices(entity, tmp_global_indices_);
        ret.setSize(num_rows, num_cols);
        size_t local_row = 0;
        const RangeFieldType zero(0);
        const RangeFieldType one(1);
        for (const size_t& local_dirichlet_DoF_id : local_dirichlet_DoF_ids) {
          ret.globalRow(local_row) = tmp_global_indices_[local_dirichlet_DoF_id];
          for (size_t jj = 0; jj < ret.cols(); ++jj) {
            ret.globalCol(jj) = tmp_global_indices_[jj];
            if (tmp_global_indices_[jj] == tmp_global_indices_[local_dirichlet_DoF_id])
              ret.value(local_row, jj) = one;
            else
              ret.value(local_row, jj) = zero;
          }
          ++local_row;
        }
      } else {
        ret.setSize(0, 0);
      }
    }
  } // ... localConstraints(...)

  void
  localConstraints(const EntityType& entity,
                   Constraints::Dirichlet<typename GridPartType::IntersectionType, RangeFieldType, false>& ret) const
  {
    static_assert(dimDomain == 2, "This does not work for other dimensions!");
    static_assert(polOrder == 1, "Not tested for higher polynomial orders!");
    // only work if we are at the boundary
    if (entity.hasBoundaryIntersections()) {
      // get local finite elements
      // * we are a CG space
      const auto cg_finite_element      = backend_.finiteElement(entity);
      const auto& cg_local_coefficients = cg_finite_element.localCoefficients();
      // * but we also need a local DG finite element
      typedef Dune::DGLocalFiniteElement<typename Traits::FiniteElementType> DgFiniteElementType;
      const DgFiniteElementType dg_finite_element(entity.type(), polOrder);
      const auto& dg_local_coefficients = dg_finite_element.localCoefficients();
      assert(dg_local_coefficients.size() == cg_local_coefficients.size() && "Wrong finite element given!");

      // first we loop over all vertices of the entity
      typedef FieldVector<DomainFieldType, dimDomain> DomainType;
      std::vector<DomainType> global_vertices(entity.template count<dimDomain>(), DomainType(0));
      std::vector<size_t> local_DoF_ids(global_vertices.size(), 0);
      for (size_t local_vertex_id = 0; local_vertex_id < global_vertices.size(); ++local_vertex_id) {
        // get the vertex
        const auto vertexPtr             = entity.template subEntity<dimDomain>(local_vertex_id);
        const auto& vertex               = *vertexPtr;
        global_vertices[local_vertex_id] = vertex.geometry().center();
        // find the global DoF id to this vertex, therefore
        // loop over all local DoFs
        for (size_t ii = 0; ii < dg_local_coefficients.size(); ++ii) {
          const auto& entity_cg_local_key = cg_local_coefficients.localKey(ii);
          if (entity_cg_local_key.subEntity() == local_vertex_id) {
            // get the local DoF to this vertex
            const auto& entity_dg_local_key = dg_local_coefficients.localKey(ii);
            assert(entity_cg_local_key.codim() == dimDomain && "Wrong finite element given!");
            local_DoF_ids[local_vertex_id] = entity_dg_local_key.index();
            // there must be one and only one for a polorder 1 lagrange basis
            break;
          }
        } // loop over all local DoFs
      } // loop over all vertices of the entity

      // then we walk the intersections
      std::set<size_t> local_dirichlet_DoF_ids;
      const auto intersection_it_end = gridPart_.iend(entity);
      for (auto intersection_it = gridPart_.ibegin(entity); intersection_it != intersection_it_end; ++intersection_it) {
        const auto& intersection = *intersection_it;
        if (ret.gridBoundary().dirichlet(intersection)) {
          const auto& intersection_geometry = intersection.geometry();
          // and walk its corners (i.e. the vertices in 2d)
          for (size_t local_intersection_corner_id = 0;
               int(local_intersection_corner_id) < intersection_geometry.corners();
               ++local_intersection_corner_id) {
            const auto global_intersection_corner = intersection_geometry.corner(local_intersection_corner_id);
            // to check which vertex this corner is
            // loop over all vertices of the entity again
            for (size_t local_vertex_id = 0; local_vertex_id < global_vertices.size(); ++local_vertex_id) {
              // and check for equality
              if (Stuff::Common::FloatCmp::eq(global_intersection_corner, global_vertices[local_vertex_id])) {
                // this vertex is on the dirichlet boundary, so we add the local DoF id this vertex corresponds to
                local_dirichlet_DoF_ids.insert(local_DoF_ids[local_vertex_id]);
              }
            } // loop over all vertices of the entity
          } // walk its corners
        }
      } // walk the intersections

      // finally we compute the local constraints
      const size_t num_rows = local_dirichlet_DoF_ids.size();
      if (num_rows > 0) {
        const size_t num_cols = baseFunctionSet(entity).size();
        mapper_.globalIndices(entity, tmp_global_indices_);
        ret.setSize(num_rows, num_cols);
        size_t local_row = 0;
        const RangeFieldType zero(0);
        for (const size_t& local_dirichlet_DoF_id : local_dirichlet_DoF_ids) {
          ret.globalRow(local_row) = tmp_global_indices_[local_dirichlet_DoF_id];
          for (size_t jj = 0; jj < ret.cols(); ++jj) {
            ret.globalCol(jj) = tmp_global_indices_[jj];
            ret.value(local_row, jj) = zero;
          }
          ++local_row;
        }
      } else {
        ret.setSize(0, 0);
      }
    }
  } // ... localConstraints(...)

  using BaseType::computePattern;

  template <class LocalGridPartType, class OtherSpaceType>
  PatternType* computePattern(const LocalGridPartType& localGridPart, const OtherSpaceType& otherSpace) const
  {
    return BaseType::computeVolumePattern(localGridPart, otherSpace);
  }

private:
  static const GridPartType& assertGridPart(const GridPartType& gP)
  {
    // check
    typedef typename Dune::Fem::AllGeomTypes<typename GridPartType::IndexSetType, typename GridPartType::GridType>
        AllGeometryTypes;
    const AllGeometryTypes allGeometryTypes(gP.indexSet());
    const std::vector<Dune::GeometryType>& geometryTypes = allGeometryTypes.geomTypes(0);
    if (!(geometryTypes.size() == 1 && geometryTypes[0].isSimplex()))
      DUNE_THROW(Dune::NotImplemented,
                 "\n" << Dune::Stuff::Common::colorStringRed("ERROR:")
                      << " this space is only implemented for simplicial grids!");
    return gP;
  } // ... assertGridPart(...)

  const GridPartType& gridPart_;
  BaseFunctionSetMapType baseFunctionSetMap_;
  const BackendType backend_;
  const MapperType mapper_;
  mutable Dune::DynamicVector<size_t> tmp_global_indices_;
}; // class FemLocalfunctionsWrapper< ..., 1, 1 >

} // namespace ContinuousLagrangeSpace
} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_SPACE_CONTINUOUS_LAGRANGE_FEM_LOCALFUNCTIONS_HH
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 *  Effective License of whole file:
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 *  Parts "Copyright by Sun Microsystems, Inc" prior to August 2011:
 *
 *    The Contents of this file are made available subject to the terms of
 *    the GNU Lesser General Public License Version 2.1
 *
 *    Copyright: 2000 by Sun Microsystems, Inc.
 *
 *    Contributor(s): Joerg Budischewski
 *
 *  All parts contributed on or after August 2011:
 *
 *    This Source Code Form is subject to the terms of the Mozilla Public
 *    License, v. 2.0. If a copy of the MPL was not distributed with this
 *    file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 ************************************************************************/

#ifndef INCLUDED_CONNECTIVITY_SOURCE_DRIVERS_POSTGRESQL_PQ_CONNECTION_HXX
#define INCLUDED_CONNECTIVITY_SOURCE_DRIVERS_POSTGRESQL_PQ_CONNECTION_HXX

#include <config_lgpl.h>
#include <com/sun/star/uno/XComponentContext.hpp>
#include <com/sun/star/lang/XInitialization.hpp>
#include <com/sun/star/script/XTypeConverter.hpp>
#include <com/sun/star/sdbc/XWarningsSupplier.hpp>
#include <com/sun/star/sdbcx/XTablesSupplier.hpp>
#include <com/sun/star/sdbcx/XUsersSupplier.hpp>
#include <com/sun/star/sdbcx/XViewsSupplier.hpp>
#include <com/sun/star/sdbc/XConnection.hpp>

#include <com/sun/star/container/XNameAccess.hpp>

#include <rtl/ref.hxx>
#include <rtl/byteseq.hxx>

#include <salhelper/simplereferenceobject.hxx>

#include <cppuhelper/weakref.hxx>
#include <cppuhelper/compbase6.hxx>
#include <boost/functional/hash.hpp>

#include <libpq-fe.h>
#include <unordered_map>

namespace pq_sdbc_driver
{
#ifdef POSTGRE_TRACE
#define POSTGRE_TRACE( x ) printf( "%s\n" , x )
#else
#define POSTGRE_TRACE(x) ((void)0)
#endif

class RefCountedMutex : public salhelper::SimpleReferenceObject
{
public:
    osl::Mutex mutex;
};

struct ConnectionSettings;

// Logging API

namespace LogLevel
{
// when you add a loglevel, extend the log function !
static const sal_Int32 NONE = 0;
static const sal_Int32 ERROR = 1;
static const sal_Int32 SQL = 2;
static const sal_Int32 INFO = 3;
static const sal_Int32 DATA = 4;
}
bool isLog( ConnectionSettings *settings, int loglevel );
void log( ConnectionSettings *settings, sal_Int32 level, const OUString &logString );
void log( ConnectionSettings *settings, sal_Int32 level, const char *str );

class Tables;
class Views;
struct ConnectionSettings
{
    ConnectionSettings() :
        encoding( RTL_TEXTENCODING_UTF8),
        pConnection(0),
        maxNameLen(0),
        maxIndexKeys(0),
        pTablesImpl(0),
        pViewsImpl(0),
        showSystemColumns( false ),
        logFile( 0 ),
        loglevel( LogLevel::INFO )
    {}
    rtl_TextEncoding encoding;
    PGconn *pConnection;
    sal_Int32 maxNameLen;
    sal_Int32 maxIndexKeys;
    ::com::sun::star::uno::Reference< com::sun::star::script::XTypeConverter > tc;
    ::com::sun::star::uno::Reference< com::sun::star::container::XNameAccess > tables;
    ::com::sun::star::uno::Reference< com::sun::star::container::XNameAccess > users;
    ::com::sun::star::uno::Reference< com::sun::star::container::XNameAccess > views;
    Tables *pTablesImpl;  // needed to implement renaming of tables / views
    Views *pViewsImpl;   // needed to implement renaming of tables / views
    OUString user;
    OUString catalog;
    bool showSystemColumns;
    FILE *logFile;
    sal_Int32 loglevel;
};

typedef cppu::WeakComponentImplHelper6<
    com::sun::star::sdbc::XConnection,
    com::sun::star::sdbc::XWarningsSupplier,
    com::sun::star::lang::XInitialization,
    com::sun::star::sdbcx::XTablesSupplier,
    com::sun::star::sdbcx::XViewsSupplier,
    com::sun::star::sdbcx::XUsersSupplier > ConnectionBase;

// some types
struct HashByteSequence
{
    sal_Int32 operator () ( const ::rtl::ByteSequence & seq ) const
    {
        return *(sal_Int32*) seq.getConstArray();
    }
};

typedef std::unordered_map<
    ::rtl::ByteSequence,
    ::com::sun::star::uno::WeakReference< com::sun::star::sdbc::XCloseable >,
    HashByteSequence,
    ::std::equal_to< ::rtl::ByteSequence >
> WeakHashMap;
typedef ::std::vector< OString > OStringVector;

typedef std::unordered_map
<
    const sal_Int32,
    OUString,
    ::boost::hash< sal_Int32 >,
    ::std::equal_to< sal_Int32 >
> Int2StringMap;

class Connection : public ConnectionBase
{
    ::com::sun::star::uno::Reference< com::sun::star::uno::XComponentContext > m_ctx;
    ::com::sun::star::uno::Reference< com::sun::star::container::XNameAccess > m_typeMap;
    ConnectionSettings m_settings;
    ::rtl::Reference< RefCountedMutex > m_refMutex;
    ::com::sun::star::uno::Reference< com::sun::star::sdbc::XDatabaseMetaData > m_meta;
    WeakHashMap m_myStatements;

private:
    void checkClosed()
        throw ( com::sun::star::sdbc::SQLException, com::sun::star::uno::RuntimeException );

public:
    Connection(
        const rtl::Reference< RefCountedMutex > &refMutex,
        const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > & ctx );

    virtual ~Connection( );

public: // XCloseable
    virtual void SAL_CALL close()
        throw ( ::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException, std::exception ) SAL_OVERRIDE;

public: // XConnection

    virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XStatement > SAL_CALL createStatement(  )
        throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE ;
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > SAL_CALL prepareStatement(
        const OUString& sql )
        throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > SAL_CALL prepareCall(
        const OUString& sql )
        throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;
    virtual OUString SAL_CALL nativeSQL( const OUString& sql )
        throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;
    virtual void SAL_CALL setAutoCommit( sal_Bool autoCommit )
        throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;
    virtual sal_Bool SAL_CALL getAutoCommit(  )
        throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;
    virtual void SAL_CALL commit(  )
        throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;
    virtual void SAL_CALL rollback(  )
        throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;
    virtual sal_Bool SAL_CALL isClosed(  )
        throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;
    virtual ::com::sun::star::uno::Reference< com::sun::star::sdbc::XDatabaseMetaData > SAL_CALL getMetaData(  )
        throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;
    virtual void SAL_CALL setReadOnly( sal_Bool readOnly )
        throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;
    virtual sal_Bool SAL_CALL isReadOnly(  )
        throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;
    virtual void SAL_CALL setCatalog( const OUString& catalog )
        throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;
    virtual OUString SAL_CALL getCatalog(  )
        throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;
    virtual void SAL_CALL setTransactionIsolation( sal_Int32 level )
        throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;
    virtual sal_Int32 SAL_CALL getTransactionIsolation(  )
        throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;
    virtual ::com::sun::star::uno::Reference< com::sun::star::container::XNameAccess > SAL_CALL getTypeMap(  )
        throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;
    virtual void SAL_CALL setTypeMap(
        const ::com::sun::star::uno::Reference< com::sun::star::container::XNameAccess >& typeMap )
        throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;

public: // XWarningsSupplier
    virtual ::com::sun::star::uno::Any SAL_CALL getWarnings(  )
        throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;
    virtual void SAL_CALL clearWarnings(  )
        throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;

public: // XInitialization
    virtual void SAL_CALL initialize(
        const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments )
        throw (com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;

public: // XTablesSupplier
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > SAL_CALL getTables(  ) throw (::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;

public: // XUsersSupplier
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > SAL_CALL getUsers(  ) throw (::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;

public: // XViewsSupplier
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > SAL_CALL getViews(  ) throw (::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;

public:
    virtual void SAL_CALL disposing() SAL_OVERRIDE;

public: // helper function
    void removeFromWeakMap( const ::rtl::ByteSequence & seq );
};

}
#endif

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>connectivity: fix gcc-4.8 build<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 *  Effective License of whole file:
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 *  Parts "Copyright by Sun Microsystems, Inc" prior to August 2011:
 *
 *    The Contents of this file are made available subject to the terms of
 *    the GNU Lesser General Public License Version 2.1
 *
 *    Copyright: 2000 by Sun Microsystems, Inc.
 *
 *    Contributor(s): Joerg Budischewski
 *
 *  All parts contributed on or after August 2011:
 *
 *    This Source Code Form is subject to the terms of the Mozilla Public
 *    License, v. 2.0. If a copy of the MPL was not distributed with this
 *    file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 ************************************************************************/

#ifndef INCLUDED_CONNECTIVITY_SOURCE_DRIVERS_POSTGRESQL_PQ_CONNECTION_HXX
#define INCLUDED_CONNECTIVITY_SOURCE_DRIVERS_POSTGRESQL_PQ_CONNECTION_HXX

#include <config_lgpl.h>
#include <com/sun/star/uno/XComponentContext.hpp>
#include <com/sun/star/lang/XInitialization.hpp>
#include <com/sun/star/script/XTypeConverter.hpp>
#include <com/sun/star/sdbc/XWarningsSupplier.hpp>
#include <com/sun/star/sdbcx/XTablesSupplier.hpp>
#include <com/sun/star/sdbcx/XUsersSupplier.hpp>
#include <com/sun/star/sdbcx/XViewsSupplier.hpp>
#include <com/sun/star/sdbc/XConnection.hpp>

#include <com/sun/star/container/XNameAccess.hpp>

#include <rtl/ref.hxx>
#include <rtl/byteseq.hxx>

#include <salhelper/simplereferenceobject.hxx>

#include <cppuhelper/weakref.hxx>
#include <cppuhelper/compbase6.hxx>
#include <boost/functional/hash.hpp>

#include <libpq-fe.h>
#include <unordered_map>

namespace pq_sdbc_driver
{
#ifdef POSTGRE_TRACE
#define POSTGRE_TRACE( x ) printf( "%s\n" , x )
#else
#define POSTGRE_TRACE(x) ((void)0)
#endif

class RefCountedMutex : public salhelper::SimpleReferenceObject
{
public:
    osl::Mutex mutex;
};

struct ConnectionSettings;

// Logging API

namespace LogLevel
{
// when you add a loglevel, extend the log function !
static const sal_Int32 NONE = 0;
static const sal_Int32 ERROR = 1;
static const sal_Int32 SQL = 2;
static const sal_Int32 INFO = 3;
static const sal_Int32 DATA = 4;
}
bool isLog( ConnectionSettings *settings, int loglevel );
void log( ConnectionSettings *settings, sal_Int32 level, const OUString &logString );
void log( ConnectionSettings *settings, sal_Int32 level, const char *str );

class Tables;
class Views;
struct ConnectionSettings
{
    ConnectionSettings() :
        encoding( RTL_TEXTENCODING_UTF8),
        pConnection(0),
        maxNameLen(0),
        maxIndexKeys(0),
        pTablesImpl(0),
        pViewsImpl(0),
        showSystemColumns( false ),
        logFile( 0 ),
        loglevel( LogLevel::INFO )
    {}
    rtl_TextEncoding encoding;
    PGconn *pConnection;
    sal_Int32 maxNameLen;
    sal_Int32 maxIndexKeys;
    ::com::sun::star::uno::Reference< com::sun::star::script::XTypeConverter > tc;
    ::com::sun::star::uno::Reference< com::sun::star::container::XNameAccess > tables;
    ::com::sun::star::uno::Reference< com::sun::star::container::XNameAccess > users;
    ::com::sun::star::uno::Reference< com::sun::star::container::XNameAccess > views;
    Tables *pTablesImpl;  // needed to implement renaming of tables / views
    Views *pViewsImpl;   // needed to implement renaming of tables / views
    OUString user;
    OUString catalog;
    bool showSystemColumns;
    FILE *logFile;
    sal_Int32 loglevel;
};

typedef cppu::WeakComponentImplHelper6<
    com::sun::star::sdbc::XConnection,
    com::sun::star::sdbc::XWarningsSupplier,
    com::sun::star::lang::XInitialization,
    com::sun::star::sdbcx::XTablesSupplier,
    com::sun::star::sdbcx::XViewsSupplier,
    com::sun::star::sdbcx::XUsersSupplier > ConnectionBase;

// some types
struct HashByteSequence
{
    sal_Int32 operator () ( const ::rtl::ByteSequence & seq ) const
    {
        return *(sal_Int32*) seq.getConstArray();
    }
};

typedef std::unordered_map<
    ::rtl::ByteSequence,
    ::com::sun::star::uno::WeakReference< com::sun::star::sdbc::XCloseable >,
    HashByteSequence,
    ::std::equal_to< ::rtl::ByteSequence >
> WeakHashMap;
typedef ::std::vector< OString > OStringVector;

typedef std::unordered_map
<
    sal_Int32,
    OUString,
    ::boost::hash< sal_Int32 >,
    ::std::equal_to< sal_Int32 >
> Int2StringMap;

class Connection : public ConnectionBase
{
    ::com::sun::star::uno::Reference< com::sun::star::uno::XComponentContext > m_ctx;
    ::com::sun::star::uno::Reference< com::sun::star::container::XNameAccess > m_typeMap;
    ConnectionSettings m_settings;
    ::rtl::Reference< RefCountedMutex > m_refMutex;
    ::com::sun::star::uno::Reference< com::sun::star::sdbc::XDatabaseMetaData > m_meta;
    WeakHashMap m_myStatements;

private:
    void checkClosed()
        throw ( com::sun::star::sdbc::SQLException, com::sun::star::uno::RuntimeException );

public:
    Connection(
        const rtl::Reference< RefCountedMutex > &refMutex,
        const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > & ctx );

    virtual ~Connection( );

public: // XCloseable
    virtual void SAL_CALL close()
        throw ( ::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException, std::exception ) SAL_OVERRIDE;

public: // XConnection

    virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XStatement > SAL_CALL createStatement(  )
        throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE ;
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > SAL_CALL prepareStatement(
        const OUString& sql )
        throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > SAL_CALL prepareCall(
        const OUString& sql )
        throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;
    virtual OUString SAL_CALL nativeSQL( const OUString& sql )
        throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;
    virtual void SAL_CALL setAutoCommit( sal_Bool autoCommit )
        throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;
    virtual sal_Bool SAL_CALL getAutoCommit(  )
        throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;
    virtual void SAL_CALL commit(  )
        throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;
    virtual void SAL_CALL rollback(  )
        throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;
    virtual sal_Bool SAL_CALL isClosed(  )
        throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;
    virtual ::com::sun::star::uno::Reference< com::sun::star::sdbc::XDatabaseMetaData > SAL_CALL getMetaData(  )
        throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;
    virtual void SAL_CALL setReadOnly( sal_Bool readOnly )
        throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;
    virtual sal_Bool SAL_CALL isReadOnly(  )
        throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;
    virtual void SAL_CALL setCatalog( const OUString& catalog )
        throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;
    virtual OUString SAL_CALL getCatalog(  )
        throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;
    virtual void SAL_CALL setTransactionIsolation( sal_Int32 level )
        throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;
    virtual sal_Int32 SAL_CALL getTransactionIsolation(  )
        throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;
    virtual ::com::sun::star::uno::Reference< com::sun::star::container::XNameAccess > SAL_CALL getTypeMap(  )
        throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;
    virtual void SAL_CALL setTypeMap(
        const ::com::sun::star::uno::Reference< com::sun::star::container::XNameAccess >& typeMap )
        throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;

public: // XWarningsSupplier
    virtual ::com::sun::star::uno::Any SAL_CALL getWarnings(  )
        throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;
    virtual void SAL_CALL clearWarnings(  )
        throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;

public: // XInitialization
    virtual void SAL_CALL initialize(
        const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments )
        throw (com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;

public: // XTablesSupplier
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > SAL_CALL getTables(  ) throw (::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;

public: // XUsersSupplier
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > SAL_CALL getUsers(  ) throw (::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;

public: // XViewsSupplier
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > SAL_CALL getViews(  ) throw (::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;

public:
    virtual void SAL_CALL disposing() SAL_OVERRIDE;

public: // helper function
    void removeFromWeakMap( const ::rtl::ByteSequence & seq );
};

}
#endif

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>/*
*soundplayer.cpp
By 2MB Solutions: https//2mb.solutions
Released under the terms of the unlicense: http://unlicense.org
Billy: https://stormdragon.tk/
Michael: https://michaeltaboada.me
*/
//#define ALLEGRO_STATICLINK 1
#include <allegro5/allegro.h>
#include "dynamic_menu.h"
#include <keyboard.h>
#include <sound.h>
#include <string>
#include <misc.h>

#include "soundplayer.h"

int power_bar(string soundstring, int p, int min, int max, float wait)
{
sound s;
if(!s.load(soundstring)) {
log("Could not load power bar sound.\n");
return -100;
}
s.set_pitch(min);
s.set_loop(true);
if(!s.play()) {
log("Could not play power bar sound.\n");
return -100;
}
if(p > min-1) {
for(int x = min; x <= p; x++) {
al_rest(wait);
s.set_pitch(s.get_pitch()+1);
}
}
else {
keyboard kb;
int dir = 1;
while(!kb.key_pressed(ALLEGRO_KEY_SPACE)) {
if(kb.key_pressed(ALLEGRO_KEY_ESCAPE) || ((kb.key_down(ALLEGRO_KEY_ALT) || kb.key_down(ALLEGRO_KEY_ALTGR)) && kb.key_pressed(ALLEGRO_KEY_F4))) {
return -100;
}
al_rest(wait);
s.set_pitch(s.get_pitch()+dir);
if(s.get_pitch() >= max) {
dir = -1;
}
else if(s.get_pitch() <= min) {
dir = 1;
}
}
}
s.stop();
return s.get_pitch();
}

int direction_bar(string soundstring, int d, int min, int max, float wait)
{
sound s;
if(!s.load(soundstring)) {
log("Could not load direction bar sound.\n");
return -100;
}
s.set_pan(min);
s.set_loop(true);
if(!s.play()) {
log("Could not play direction bar sound.\n");
return -100;
}
if(d >= min && d <= max) {
for (int x = min; x <= d; x++) {
al_rest(wait);
s.set_pan(x);
}
}
else {
keyboard kb;
int dir = 1;
while(!kb.key_pressed(ALLEGRO_KEY_SPACE)) {
if(kb.key_pressed(ALLEGRO_KEY_ESCAPE) || ((kb.key_down(ALLEGRO_KEY_ALT) || kb.key_down(ALLEGRO_KEY_ALTGR)) && kb.key_pressed(ALLEGRO_KEY_F4))) {
return -100;
}
al_rest(wait);
s.set_pan(s.get_pan()+dir);
if(s.get_pan() >= max) {
dir = -1;
}
else if(s.get_pan() <= min) {
dir = 1;
}
}
}
s.stop();
return s.get_pan();
}

void fade(sound* s, int start, int end, float time) {
if(!s) {
return;
}
s->set_gain(start);
for(int x = 0; x < time/0.005; x++) {
al_rest(0.005);
s->set_gain(s->get_gain()+((end-start)/(time/0.005)+start));
}
s->stop();
}

bool play_sound_wait(sound* s) {
if(!s->play()) {
log("Could not play sound file.\n");
return false;
}
while(s->is_playing()) {
al_rest(0.005);
}
return true;
}

bool play_sound_wait(string s) {
sound so;
if(!so.load(s)) {
log(((string)("Could not load sound ")+s+".\n").c_str());
return false;
}
else {
return play_sound_wait(&so);
}
}

<commit_msg>Ability to go back with direction bar<commit_after>/*
*soundplayer.cpp
By 2MB Solutions: https//2mb.solutions
Released under the terms of the unlicense: http://unlicense.org
Billy: https://stormdragon.tk/
Michael: https://michaeltaboada.me
*/
//#define ALLEGRO_STATICLINK 1
#include <allegro5/allegro.h>
#include "dynamic_menu.h"
#include <keyboard.h>
#include <sound.h>
#include <string>
#include <misc.h>

#include "soundplayer.h"

int power_bar(string soundstring, int p, int min, int max, float wait)
{
sound s;
if(!s.load(soundstring)) {
log("Could not load power bar sound.\n");
return -100;
}
s.set_pitch(min);
s.set_loop(true);
if(!s.play()) {
log("Could not play power bar sound.\n");
return -100;
}
if(p > min-1) {
for(int x = min; x <= p; x++) {
al_rest(wait);
s.set_pitch(s.get_pitch()+1);
}
}
else {
keyboard kb;
int dir = 1;
while(!kb.key_pressed(ALLEGRO_KEY_SPACE)) {
if(kb.key_pressed(ALLEGRO_KEY_ESCAPE) || ((kb.key_down(ALLEGRO_KEY_ALT) || kb.key_down(ALLEGRO_KEY_ALTGR)) && kb.key_pressed(ALLEGRO_KEY_F4))) {
return -100;
}
al_rest(wait);
s.set_pitch(s.get_pitch()+dir);
if(s.get_pitch() >= max) {
dir = -1;
}
else if(s.get_pitch() <= min) {
dir = 1;
}
}
}
s.stop();
return s.get_pitch();
}

int direction_bar(string soundstring, int d, int min, int max, float wait)
{
sound s;
if(!s.load(soundstring)) {
log("Could not load direction bar sound.\n");
return -100;
}
s.set_pan(min);
s.set_loop(true);
if(!s.play()) {
log("Could not play direction bar sound.\n");
return -100;
}
if(d >= min && d <= max) {
for (int x = min; x <= d; x++) {
al_rest(wait);
s.set_pan(x);
}
}
else {
keyboard kb;
int dir = 1;
while(!kb.key_pressed(ALLEGRO_KEY_SPACE)) {
if(kb.key_pressed(ALLEGRO_KEY_ESCAPE) || ((kb.key_down(ALLEGRO_KEY_ALT) || kb.key_down(ALLEGRO_KEY_ALTGR)) && kb.key_pressed(ALLEGRO_KEY_F4))) {
return -100;
}
if(kb.key_pressed(ALLEGRO_KEY_BACKSPACE)) {
return -101;
}
al_rest(wait);
s.set_pan(s.get_pan()+dir);
if(s.get_pan() >= max) {
dir = -1;
}
else if(s.get_pan() <= min) {
dir = 1;
}
}
}
s.stop();
return s.get_pan();
}

void fade(sound* s, int start, int end, float time) {
if(!s) {
return;
}
s->set_gain(start);
for(int x = 0; x < time/0.005; x++) {
al_rest(0.005);
s->set_gain(s->get_gain()+((end-start)/(time/0.005)+start));
}
s->stop();
}

bool play_sound_wait(sound* s) {
if(!s->play()) {
log("Could not play sound file.\n");
return false;
}
while(s->is_playing()) {
al_rest(0.005);
}
return true;
}

bool play_sound_wait(string s) {
sound so;
if(!so.load(s)) {
log(((string)("Could not load sound ")+s+".\n").c_str());
return false;
}
else {
return play_sound_wait(&so);
}
}

<|endoftext|>


<commit_before>/* Aramis' Bitmap Lib - Copyright (c) 2017 Aramis Hornung Moraes */

#define AHMBMP_VERSION "0.9.6"

#include <stdio.h>
#include "ahmbmp.h"
#include "ahmycbcr.h"
#include "ahmlux.h"
#include "ahmskin.h"
#include "ahmfilters.h"
#include "string.h"
#include "math.h"

/* debug stuff for MSVC */
#ifdef WIN32
#ifdef _MSC_VER
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#endif
#endif
#ifdef WIN32
#include "windows.h"
#endif

/* int x = pixel x position
   int y = pixel y position
   int K = amoeba maximumlayere size
   int L = amoeba maximum variance threshold*/
void amoeba_process_pixel(ahm_bitmap *img, ahm_bitmap *trgt_img, int x, int y, int K, int L)
{
	const unsigned int maxWidth = img->Width;
	const unsigned int maxHeight = img->Height;
	ahm_bitmap *amoeba_mask = create_ahmBitmap(img->Width, img->Height);
	int i, j; i = j = 0;

	// media adjacente ao pixel alvo (M1)
	/*
	int M1 = 0;

	for(j = (y-1 < 0? 0 : y-1); (j <= y+1 && j <= maxHeight); ++j)
	{
		for(i = (x-1 < 0? 0 : x-1); (i <= x+1 && i <= maxWidth); ++i) // iterate the row from left to right
		{
			if(!(i == x && j == y)) // sum everything except the very target pixel
			{
				M1 += get_pixel(img, i, j).r_;
				set_pixel(amoeba_mask, i, j, 255, 255, 255); // the core is always marked
			}
		}
	}
	M1 = M1/8;
	*/

	set_pixel(amoeba_mask, x, y, 255, 255, 255); // the core is always marked

	// drarw the amoeba mask
	for(int k = 1; k < K; ++k) // iterate amoeba layers
	{
		// for each line in the window
		for(j = (y-k<0?0:y-k); j <= (y+k>maxHeight?maxHeight:y+k); ++j)
		{

			// if its the window cap or botton, process the entire row,
			if(j == 0 || j == y-k || j == y+k || j == maxHeight)
			{
				for(i = (x-k<0?0:x-k); i <= (x+k>maxWidth?maxWidth:x+k); ++i) // iterate the row from left to right
				{

					if(j == 0 || j == y-k) // if its cap, analyze adjacent bottom pixels
					{
						int x1;
						x1 = i;
						if(i == (x-k)) // far left in top, read inner corn of the structure
							x1 = i+1;
						else if (i == (x+k)) // far right in top, read inner corn of the structure
							x1 = i-1;

						//ABS(Pd[n]-Pd[n-1])<=ABS(M1-L)
						int Pdn = get_pixel(img, i, j).r_;
						//int Pdn1 = get_pixel(img, x1, j+1).r_;
						int Pdn1 = get_pixel(img, x, y).r_;
						int r_val =  get_pixel(amoeba_mask, x1, j+1).r_;

						if(r_val == 255 &&
						abs(Pdn-Pdn1)<=abs(L)) {
							set_pixel(amoeba_mask, i, j, 255, 255, 255); // mark it
						}
					}
					if(j == maxHeight|| j == y+k) // if its bottom, analyze adjacent upper pixels
					{
						int x1;
						x1 = i;
						if(i == (x-k)) // far left in bottom, read inner corn of the structure
							x1 = i+1;
						else if (i == (x+k)) // far right in bottom, read inner corn of the structure
							x1 = i-1;

						int Pdn = get_pixel(img, i, j).r_;
						//int Pdn1 = get_pixel(img, x1, j-1).r_;
						int Pdn1 = get_pixel(img, x, y).r_;
						int r_val =  get_pixel(amoeba_mask, x1, j-1).r_;

						if(r_val == 255 &&
						abs(Pdn-Pdn1)<=abs(L)) {
							set_pixel(amoeba_mask, i, j, 255, 255, 255); // mark it
						}
					}
				}
			}
			else // otherwise, only its far left and far right side pixels
			{
				// left
				{
					i = (x-k<0?0:x-k); // far left pixel in the layer-window

					//ABS(Pd[n]-Pd[n-1])<=ABS(M1-L)
					int Pdn = get_pixel(img, i, j).r_;
					//int Pdn1 = get_pixel(img, i+1, j).r_;
					int Pdn1 = get_pixel(img, x, y).r_;
					int r_val =  get_pixel(amoeba_mask, i+1, j).r_;

					if(r_val == 255 &&
					abs(Pdn-Pdn1)<=abs(L)) {
						set_pixel(amoeba_mask, i, j, 255, 255, 255); // mark it
					}

				}
				//right
				{
					i = (x+k>maxWidth?maxWidth:x+k); // far left pixel in the layer-window

					//ABS(Pd[n]-Pd[n-1])<=ABS(M1-L)
					int Pdn = get_pixel(img, i, j).r_;
					//int Pdn1 = get_pixel(img, i-1, j).r_;
					int Pdn1 = get_pixel(img, x, y).r_;
					int r_val =  get_pixel(amoeba_mask, i-1, j).r_;

					if(r_val == 255 &&
					abs(Pdn-Pdn1)<=abs(L)) {
						set_pixel(amoeba_mask, i, j, 255, 255, 255); // mark it
					}
				}
			} // top/bottom right/left layer sides
		} // window lines
	} // k layers

	// debug amoeba view
	ahm_bitmap *debug_img = create_ahmBitmap(amoeba_mask->Width,amoeba_mask->Height);
	for(i = 0; i < maxWidth; ++i)
	{
		for(j = 0; j < maxHeight; ++j)
		{
			if(get_pixel(amoeba_mask, i, j).r_ == 255)
			{
				set_pixel(debug_img, i, j,
					255,
					190,
					get_pixel(img,i,j).r_/3
					);
			}
			else
			{
				set_pixel(debug_img, i, j,
					get_pixel(img,i,j).r_,
					get_pixel(img,i,j).r_,
					get_pixel(img,i,j).r_);
			}
		}
	}
	save_bmp(debug_img, "amoeba_test.bmp"); // debbuging the amoeba image for the pixel x,y
	Sleep(1100);
	destroy_ahmBitmap(debug_img);

	// by now, we have our amoeba mask, a bitmap wehre with the exact same
	// size of the original image where the white pixels represent the amoeba
	// for the pixel P<x, y>,
	// we can either calculate mean or median and apply the filter only
	// considering those white pixels (amoeba)
	unsigned int pixel_count = 0;
	unsigned int mean_color = 0;
	for(i = 0; i < maxWidth; ++i)
	{
		for(j = 0; j < maxHeight; ++j)
		{
			if(get_pixel(amoeba_mask,i,j).r_ == 255)
			{
				++pixel_count;
				mean_color += (unsigned int)get_pixel(img, i, j).r_;
			}
		}
	}
	if(pixel_count)
		mean_color = mean_color/pixel_count;

	set_pixel(trgt_img, x, y, mean_color, mean_color, mean_color);

	destroy_ahmBitmap(amoeba_mask);
}

void main_process_image(char *file_path)
{
	ahm_bitmap *myBmp;
	ahm_bitmap *ycbcr;
	ahm_bitmap *ycbcr_y;
	ahm_bitmap *ycbcr_cb;
	ahm_bitmap *ycbcr_cr;
	ahm_bitmap *trgt_img;
	char file_output_name[4096];

	/* iterators */
	unsigned int i = 0;
	unsigned int j = 0;

    myBmp = create_bmp_from_file(file_path);
    if(myBmp == 0)
    {
        destroy_ahmBitmap(myBmp);
		printf("Error: File is not supported. Only 24bit bitmaps can be processed.\n");
		return;
    }
	trgt_img=create_ahmBitmap(myBmp->Width,myBmp->Height);
	/* allocate image structures */
	ycbcr=create_ahmBitmap(myBmp->Width,myBmp->Height);
	ycbcr_y = create_ahmBitmap(myBmp->Width, myBmp->Height);
	ycbcr_cb = create_ahmBitmap(myBmp->Width, myBmp->Height);
	ycbcr_cr = create_ahmBitmap(myBmp->Width, myBmp->Height);

	/* start processing */
	create_ycbcr(myBmp, ycbcr);
	create_ycbcr_channels(myBmp, ycbcr_y, ycbcr_cb, ycbcr_cr);
	//ycbcr_to_rgb(ycbcr,myBmp); // testing

	for(i = 0; i < ycbcr_y->Width; ++i)
	{
		for(j = 0; j < ycbcr_y->Height; ++j)
		{
			system("cls");
			//printf("%f%%\n", (float)((float)i/(float)ycbcr->Width)*100.0f);
			//printf("%f%%", (float)((float)j/(float)ycbcr->Height)*100.0f);
			amoeba_process_pixel(ycbcr_y, trgt_img, i, j, 45, 16);
		}
	}

	save_bmp(trgt_img, "amoeba_test.bmp"); // after all, restore the processed image to colors

	destroy_ahmBitmap(ycbcr);
	destroy_ahmBitmap(ycbcr_y);
	destroy_ahmBitmap(ycbcr_cb);
	destroy_ahmBitmap(ycbcr_cr);
	destroy_ahmBitmap(myBmp);
}

int main(int argc, char *argv[])
{
#ifdef _MSC_VER
#ifdef WIN32
	_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
#endif

#endif

	if(argc > 1)
        main_process_image(argv[1]);
	else
	{
		printf("Usage: parameter 1 = 24bits Bitmap file\n");
		fflush(stdin);
		getchar();
	}

#ifdef _MSC_VER
#ifdef WIN32
	_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_DEBUG);
#endif
#endif
	return 0;
}
/*
#if defined(_WIN32)
int APIENTRY _WinMain(HINSTANCE hInstance, HINSTANCE hPevInstance, LPSTR lpCmdLine, int nCmdShow)
{
	return main( __argc, __argv);
}
#endif*/
<commit_msg>Delete main.cpp<commit_after><|endoftext|>


<commit_before>// main.cpp

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "metasorter.h"

#include <boost/foreach.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/info_parser.hpp>

using namespace std;

int main(int argc, char* argv[])
{
	int err = 0;
	int ok_to_run = 0;
	int required_flags = 0;
	char config_file[255];
	boost::property_tree::ptree pt;

	if (argc > 2)
	{
		for (int i = 1; i < argc; i++)
		{
			if (i + 1 != argc)
			{
                if (strcmp(argv[i], "-c") == 0)
				{
                    strcpy(config_file, argv[i + 1]);
					required_flags++;
                }
			}
		}
		if(required_flags == 1)
		{
			ok_to_run = 1;
		}
	}

	if(ok_to_run)
	{
		boost::property_tree::info_parser::read_info(config_file, pt);

		// check for folders entry
		optional<const boost::property_tree::ptree&> pt_check_existence;
		pt_check_existence = pt.get_child_optional("folders");
		if(pt_check_existence)
		{
			BOOST_FOREACH(boost::property_tree::ptree::value_type &v, pt.get_child("folders"))
			{
				int recurse = 0;
				std::cout << std::endl << "Searching Root Folder: " << v.first.data() << std::endl;
				if(strcmp(v.second.data().c_str(), "R") == 0)
				{
					recurse = 1;
				}
				metasorter sorter((char*)v.first.data(), pt);
				//sorter.parse_directory(recurse);
				sorter.traverse_directory(recurse);
			}
		}
		else
		{
			cout << "No folders defined in config file - aborting" << endl;
			exit(0);
		}
	}
	else
	{
		std::cout << "Usage:  metasort -c <config file>" << std::endl;
	}
	return err;
}
<commit_msg>Accepts multiple config files.<commit_after>// main.cpp

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "metasorter.h"

#include <boost/foreach.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/info_parser.hpp>

using namespace std;

int main(int argc, char* argv[])
{
	int err = 0;
	int ok_to_run = 0;
	int required_flags = 0;
	int config_num = 0;
	char config_file[255][255];
	boost::property_tree::ptree pt[255];

	if (argc > 2)
	{
		for (int i = 1; i < argc; i++)
		{
			if (i + 1 != argc)
			{
                if (strcmp(argv[i], "-c") == 0)
				{
                    strcpy(config_file[config_num], argv[i + 1]);
					config_num++;
					required_flags++;
                }
			}
		}
		if(required_flags > 0)
		{
			ok_to_run = 1;
		}
	}

	if(ok_to_run)
	{
		for(int q = 0; q < config_num; q++)
		{
			boost::property_tree::info_parser::read_info(config_file[q], pt[q]);

			// check for folders entry
			optional<const boost::property_tree::ptree&> pt_check_existence;
			pt_check_existence = pt[q].get_child_optional("folders");
			if(pt_check_existence)
			{
				BOOST_FOREACH(boost::property_tree::ptree::value_type &v, pt[q].get_child("folders"))
				{
					int recurse = 0;
					std::cout << std::endl << "Searching Root Folder: " << v.first.data() << std::endl;
					if(strcmp(v.second.data().c_str(), "R") == 0)
					{
						recurse = 1;
					}
					metasorter sorter((char*)v.first.data(), pt[q]);
					sorter.traverse_directory(recurse);
				}
			}
			else
			{
				cout << "No folders defined in config file - aborting" << endl;
				exit(0);
			}
		}
	}
	else
	{
		std::cout << "Usage:  metasort -c <config file>" << std::endl;
	}
	return err;
}
<|endoftext|>


<commit_before>/****************************************************************************
 *
 *   Copyright (c) 2020 PX4 Development Team. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name PX4 nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ****************************************************************************/

#include "worker_thread.hpp"
#include "accelerometer_calibration.h"
#include "airspeed_calibration.h"
#include "calibration_routines.h"
#include "esc_calibration.h"
#include "gyro_calibration.h"
#include "level_calibration.h"
#include "mag_calibration.h"
#include "rc_calibration.h"

#include <px4_platform_common/log.h>
#include <parameters/param.h>

WorkerThread::~WorkerThread()
{
	if (_state.load() == (int)State::Running) {
		/* wait for thread to complete */
		int ret = pthread_join(_thread_handle, nullptr);

		if (ret) {
			PX4_ERR("join failed: %d", ret);
		}
	}
}

void WorkerThread::startTask(Request request)
{
	if (isBusy()) {
		return;
	}

	_request = request;

	/* initialize low priority thread */
	pthread_attr_t low_prio_attr;
	pthread_attr_init(&low_prio_attr);
	pthread_attr_setstacksize(&low_prio_attr, PX4_STACK_ADJUSTED(3304));

#ifndef __PX4_QURT
	// This is not supported by QURT (yet).
	struct sched_param param;
	pthread_attr_getschedparam(&low_prio_attr, &param);

	/* low priority */
	param.sched_priority = SCHED_PRIORITY_DEFAULT - 50;
	pthread_attr_setschedparam(&low_prio_attr, &param);
#endif
	int ret = pthread_create(&_thread_handle, &low_prio_attr, &threadEntryTrampoline, this);
	pthread_attr_destroy(&low_prio_attr);

	if (ret == 0) {
		_state.store((int)State::Running);

	} else {
		PX4_ERR("Failed to start thread (%i)", ret);
		_state.store((int)State::Finished);
		_ret_value = ret;
	}
}

void *WorkerThread::threadEntryTrampoline(void *arg)
{
	WorkerThread *worker_thread = (WorkerThread *)arg;
	worker_thread->threadEntry();
	return nullptr;
}

void WorkerThread::threadEntry()
{
	px4_prctl(PR_SET_NAME, "commander_low_prio", px4_getpid());

	switch (_request) {
	case Request::GyroCalibration:
		_ret_value = do_gyro_calibration(&_mavlink_log_pub);
		break;

	case Request::MagCalibration:
		_ret_value = do_mag_calibration(&_mavlink_log_pub);
		break;

	case Request::RCTrimCalibration:
		_ret_value = do_trim_calibration(&_mavlink_log_pub);
		break;

	case Request::AccelCalibration:
		_ret_value = do_accel_calibration(&_mavlink_log_pub);
		break;

	case Request::LevelCalibration:
		_ret_value = do_level_calibration(&_mavlink_log_pub);
		break;

	case Request::AccelCalibrationQuick:
		_ret_value = do_accel_calibration_quick(&_mavlink_log_pub);
		break;

	case Request::AirspeedCalibration:
		_ret_value = do_airspeed_calibration(&_mavlink_log_pub);
		break;

	case Request::ESCCalibration:
		_ret_value = do_esc_calibration(&_mavlink_log_pub);
		break;

	case Request::MagCalibrationQuick:
		_ret_value = do_mag_calibration_quick(&_mavlink_log_pub, _heading_radians, _latitude, _longitude);
		break;

	case Request::ParamLoadDefault:
		_ret_value = param_load_default();

		if (_ret_value != 0) {
			mavlink_log_critical(&_mavlink_log_pub, "Error loading settings");
		}

		break;

	case Request::ParamSaveDefault:
		_ret_value = param_save_default();

		if (_ret_value != 0) {
			mavlink_log_critical(&_mavlink_log_pub, "Error saving settings");
		}

		break;

	case Request::ParamResetAll:
		param_reset_all();
		_ret_value = 0;
		break;
	}

	_state.store((int)State::Finished); // set this last to signal the main thread we're done
}

void WorkerThread::setMagQuickData(float heading_rad, float lat, float lon)
{
	_heading_radians = heading_rad;
	_latitude = lat;
	_longitude = lon;
}
<commit_msg>BUGFIX Hardfault Commander Calibration<commit_after>/****************************************************************************
 *
 *   Copyright (c) 2020 PX4 Development Team. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name PX4 nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ****************************************************************************/

#include "worker_thread.hpp"
#include "accelerometer_calibration.h"
#include "airspeed_calibration.h"
#include "calibration_routines.h"
#include "esc_calibration.h"
#include "gyro_calibration.h"
#include "level_calibration.h"
#include "mag_calibration.h"
#include "rc_calibration.h"

#include <px4_platform_common/log.h>
#include <parameters/param.h>

WorkerThread::~WorkerThread()
{
	if (_state.load() == (int)State::Running) {
		/* wait for thread to complete */
		int ret = pthread_join(_thread_handle, nullptr);

		if (ret) {
			PX4_ERR("join failed: %d", ret);
		}
	}
}

void WorkerThread::startTask(Request request)
{
	if (isBusy()) {
		return;
	}

	_request = request;

	/* initialize low priority thread */
	pthread_attr_t low_prio_attr;
	pthread_attr_init(&low_prio_attr);
	pthread_attr_setstacksize(&low_prio_attr, PX4_STACK_ADJUSTED(3804));

#ifndef __PX4_QURT
	// This is not supported by QURT (yet).
	struct sched_param param;
	pthread_attr_getschedparam(&low_prio_attr, &param);

	/* low priority */
	param.sched_priority = SCHED_PRIORITY_DEFAULT - 50;
	pthread_attr_setschedparam(&low_prio_attr, &param);
#endif
	int ret = pthread_create(&_thread_handle, &low_prio_attr, &threadEntryTrampoline, this);
	pthread_attr_destroy(&low_prio_attr);

	if (ret == 0) {
		_state.store((int)State::Running);

	} else {
		PX4_ERR("Failed to start thread (%i)", ret);
		_state.store((int)State::Finished);
		_ret_value = ret;
	}
}

void *WorkerThread::threadEntryTrampoline(void *arg)
{
	WorkerThread *worker_thread = (WorkerThread *)arg;
	worker_thread->threadEntry();
	return nullptr;
}

void WorkerThread::threadEntry()
{
	px4_prctl(PR_SET_NAME, "commander_low_prio", px4_getpid());

	switch (_request) {
	case Request::GyroCalibration:
		_ret_value = do_gyro_calibration(&_mavlink_log_pub);
		break;

	case Request::MagCalibration:
		_ret_value = do_mag_calibration(&_mavlink_log_pub);
		break;

	case Request::RCTrimCalibration:
		_ret_value = do_trim_calibration(&_mavlink_log_pub);
		break;

	case Request::AccelCalibration:
		_ret_value = do_accel_calibration(&_mavlink_log_pub);
		break;

	case Request::LevelCalibration:
		_ret_value = do_level_calibration(&_mavlink_log_pub);
		break;

	case Request::AccelCalibrationQuick:
		_ret_value = do_accel_calibration_quick(&_mavlink_log_pub);
		break;

	case Request::AirspeedCalibration:
		_ret_value = do_airspeed_calibration(&_mavlink_log_pub);
		break;

	case Request::ESCCalibration:
		_ret_value = do_esc_calibration(&_mavlink_log_pub);
		break;

	case Request::MagCalibrationQuick:
		_ret_value = do_mag_calibration_quick(&_mavlink_log_pub, _heading_radians, _latitude, _longitude);
		break;

	case Request::ParamLoadDefault:
		_ret_value = param_load_default();

		if (_ret_value != 0) {
			mavlink_log_critical(&_mavlink_log_pub, "Error loading settings");
		}

		break;

	case Request::ParamSaveDefault:
		_ret_value = param_save_default();

		if (_ret_value != 0) {
			mavlink_log_critical(&_mavlink_log_pub, "Error saving settings");
		}

		break;

	case Request::ParamResetAll:
		param_reset_all();
		_ret_value = 0;
		break;
	}

	_state.store((int)State::Finished); // set this last to signal the main thread we're done
}

void WorkerThread::setMagQuickData(float heading_rad, float lat, float lon)
{
	_heading_radians = heading_rad;
	_latitude = lat;
	_longitude = lon;
}
<|endoftext|>


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

#include "content/renderer/pepper/pepper_platform_image_2d_impl.h"

#include "build/build_config.h"
#include "content/common/view_messages.h"
#include "content/renderer/render_thread_impl.h"
#include "ui/surface/transport_dib.h"

namespace content {

PepperPlatformImage2DImpl::PepperPlatformImage2DImpl(int width,
                                                     int height,
                                                     TransportDIB* dib)
    : width_(width),
      height_(height),
      dib_(dib) {
}

// On Mac, we have to tell the browser to free the transport DIB.
PepperPlatformImage2DImpl::~PepperPlatformImage2DImpl() {
#if defined(OS_MACOSX)
  if (dib_.get()) {
    RenderThreadImpl::current()->Send(
        new ViewHostMsg_FreeTransportDIB(dib_->id()));
  }
#endif
}

// static
PepperPlatformImage2DImpl* PepperPlatformImage2DImpl::Create(int width,
                                                             int height) {
  uint32 buffer_size = width * height * 4;

  // Allocate the transport DIB and the PlatformCanvas pointing to it.
#if defined(OS_MACOSX)
  // On the Mac, shared memory has to be created in the browser in order to
  // work in the sandbox.  Do this by sending a message to the browser
  // requesting a TransportDIB (see also
  // chrome/renderer/webplugin_delegate_proxy.cc, method
  // WebPluginDelegateProxy::CreateBitmap() for similar code). The TransportDIB
  // is cached in the browser, and is freed (in typical cases) by the
  // PepperPlatformImage2DImpl's destructor.
  TransportDIB::Handle dib_handle;
  IPC::Message* msg = new ViewHostMsg_AllocTransportDIB(buffer_size,
                                                        true,
                                                        &dib_handle);
  if (!RenderThreadImpl::current()->Send(msg))
    return NULL;
  if (!TransportDIB::is_valid_handle(dib_handle))
    return NULL;

  TransportDIB* dib = TransportDIB::Map(dib_handle);
#else
  static int next_dib_id = 0;
  TransportDIB* dib = TransportDIB::Create(buffer_size, next_dib_id++);
  if (!dib)
    return NULL;
#endif

  return new PepperPlatformImage2DImpl(width, height, dib);
}

skia::PlatformCanvas* PepperPlatformImage2DImpl::Map() {
  return dib_->GetPlatformCanvas(width_, height_);
}

intptr_t PepperPlatformImage2DImpl::GetSharedMemoryHandle(
    uint32* byte_count) const {
  *byte_count = dib_->size();
#if defined(OS_WIN)
  return reinterpret_cast<intptr_t>(dib_->handle());
#elif defined(OS_MACOSX) || defined(OS_ANDROID)
  return static_cast<intptr_t>(dib_->handle().fd);
#elif defined(OS_POSIX)
  return static_cast<intptr_t>(dib_->handle());
#endif
}

TransportDIB* PepperPlatformImage2DImpl::GetTransportDIB() const {
  return dib_.get();
}

}  // namespace content
<commit_msg>[OSX/Pepper] Don't have browser cache shmem ref behind ImageData.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/renderer/pepper/pepper_platform_image_2d_impl.h"

#include "build/build_config.h"

#include "base/metrics/histogram.h"
#include "content/common/view_messages.h"
#include "content/renderer/render_thread_impl.h"
#include "ui/surface/transport_dib.h"

namespace content {

PepperPlatformImage2DImpl::PepperPlatformImage2DImpl(int width,
                                                     int height,
                                                     TransportDIB* dib)
    : width_(width),
      height_(height),
      dib_(dib) {
}

PepperPlatformImage2DImpl::~PepperPlatformImage2DImpl() {
}

// static
PepperPlatformImage2DImpl* PepperPlatformImage2DImpl::Create(int width,
                                                             int height) {
  uint32 buffer_size = width * height * 4;
  UMA_HISTOGRAM_COUNTS("Plugin.PepperImage2DSize", buffer_size);

  // Allocate the transport DIB and the PlatformCanvas pointing to it.
#if defined(OS_MACOSX)
  // On the Mac, shared memory has to be created in the browser in order to
  // work in the sandbox.  Do this by sending a message to the browser
  // requesting a TransportDIB (see also
  // chrome/renderer/webplugin_delegate_proxy.cc, method
  // WebPluginDelegateProxy::CreateBitmap() for similar code).
  TransportDIB::Handle dib_handle;
  IPC::Message* msg = new ViewHostMsg_AllocTransportDIB(buffer_size,
                                                        false,
                                                        &dib_handle);
  if (!RenderThreadImpl::current()->Send(msg))
    return NULL;
  if (!TransportDIB::is_valid_handle(dib_handle))
    return NULL;

  TransportDIB* dib = TransportDIB::Map(dib_handle);
#else
  static int next_dib_id = 0;
  TransportDIB* dib = TransportDIB::Create(buffer_size, next_dib_id++);
  if (!dib)
    return NULL;
#endif

  return new PepperPlatformImage2DImpl(width, height, dib);
}

skia::PlatformCanvas* PepperPlatformImage2DImpl::Map() {
  return dib_->GetPlatformCanvas(width_, height_);
}

intptr_t PepperPlatformImage2DImpl::GetSharedMemoryHandle(
    uint32* byte_count) const {
  *byte_count = dib_->size();
#if defined(OS_WIN)
  return reinterpret_cast<intptr_t>(dib_->handle());
#elif defined(OS_MACOSX) || defined(OS_ANDROID)
  return static_cast<intptr_t>(dib_->handle().fd);
#elif defined(OS_POSIX)
  return static_cast<intptr_t>(dib_->handle());
#endif
}

TransportDIB* PepperPlatformImage2DImpl::GetTransportDIB() const {
  return dib_.get();
}

}  // namespace content
<|endoftext|>