<commit_before>/*!
  \copyright (c) RDO-Team, 2012
  \file      function_type.h
  \author    Урусов Андрей (rdo@rk9.bmstu.ru)
  \date      04.12.2012
  \brief     Тип функции
  \indent    4T
*/

// ---------------------------------------------------------------------------- PCH
#include "simulator/compiler/parser/pch.h"
// ----------------------------------------------------------------------- INCLUDES
#include <boost/foreach.hpp>
// ----------------------------------------------------------------------- SYNOPSIS
#include "simulator/compiler/parser/type/function_type.h"
#include "simulator/compiler/parser/rdo_value.h"
#include "simulator/compiler/parser/rdoparser.h"
// --------------------------------------------------------------------------------

OPEN_RDO_PARSER_NAMESPACE

// --------------------------------------------------------------------------------
// -------------------- FunctionParamType
// --------------------------------------------------------------------------------
FunctionParamType::FunctionParamType(CREF(ParamList) paramList, CREF(RDOParserSrcInfo) srcInfo)
	: RDOParserSrcInfo(srcInfo  )
	, m_paramList     (paramList)
{
	if (m_paramList.empty())
	{
		LPTypeInfo pType = rdo::Factory<TypeInfo>::delegate<RDOType__void>(srcInfo);
		ASSERT(pType);
		m_paramList.push_back(pType);
	}
}

FunctionParamType::~FunctionParamType()
{}

CREF(FunctionParamType::ParamList) FunctionParamType::paramList() const
{
	return m_paramList;
}

CREF(rdo::runtime::LPRDOType) FunctionParamType::type() const
{
	NEVER_REACH_HERE;
	static rdo::runtime::LPRDOType s_Type;
	return s_Type;
}

rdo::runtime::RDOType::TypeID FunctionParamType::typeID() const
{
	NEVER_REACH_HERE;
	return rdo::runtime::RDOType::t_unknow;
}

tstring FunctionParamType::name() const
{
	return src_text();
}

LPRDOType FunctionParamType::type_cast(CREF(LPRDOType) pFrom, CREF(RDOParserSrcInfo) from_src_info, CREF(RDOParserSrcInfo) to_src_info, CREF(RDOParserSrcInfo) src_info) const
{
	LPFunctionParamType pFromParamType = pFrom.object_dynamic_cast<FunctionParamType>();
	if (!pFromParamType)
	{
		parser::g_error().push_only(src_info,    rdo::format("Ожидаеются параметры вызова, найдено: %s", from_src_info.src_text().c_str()));
		parser::g_error().push_only(to_src_info, rdo::format("См. тип: %s", to_src_info.src_text().c_str()));
		parser::g_error().push_done();
	}

	if (paramList().size() != pFromParamType->paramList().size())
	{
		RDOParser::s_parser()->error().error(
			src_info,
			rdo::format("Неверное количество параметров: %s", from_src_info.src_text().c_str())
		);
	}

	ParamList::const_iterator paramFromIt = pFromParamType->paramList().begin();
	BOOST_FOREACH(const LPTypeInfo& pParamType, paramList())
	{
		pParamType->type_cast(*paramFromIt, src_info);
		++paramFromIt;
	}

	return const_cast<PTR(FunctionParamType)>(this);
}

LPRDOValue FunctionParamType::value_cast(CREF(LPRDOValue) pFrom, CREF(RDOParserSrcInfo) to_src_info, CREF(RDOParserSrcInfo) src_info) const
{
	NEVER_REACH_HERE;
	return LPRDOValue();
}

rdo::runtime::LPRDOCalc FunctionParamType::calc_cast(CREF(rdo::runtime::LPRDOCalc) pCalc, CREF(LPRDOType) pType) const
{
	NEVER_REACH_HERE;
	return rdo::runtime::LPRDOCalc();
}

rdo::runtime::RDOValue FunctionParamType::get_default() const
{
	NEVER_REACH_HERE;
	return rdo::runtime::RDOValue();
}

void FunctionParamType::writeModelStructure(std::ostream& stream) const
{
	stream << "F " << std::endl;
	NEVER_REACH_HERE;
}

// --------------------------------------------------------------------------------
// -------------------- FunctionType
// --------------------------------------------------------------------------------
FunctionType::FunctionType(CREF(LPTypeInfo) pReturnType, CREF(LPFunctionParamType) pParamType, CREF(RDOParserSrcInfo) srcInfo)
	: RDOParserSrcInfo(srcInfo    )
	, m_pReturnType   (pReturnType)
	, m_pParamType    (pParamType )
{
	ASSERT(m_pReturnType);
	ASSERT(m_pParamType );
}

FunctionType::~FunctionType()
{}

CREF(rdo::runtime::LPRDOType) FunctionType::type() const
{
	return m_pReturnType->type()->type();
}

rdo::runtime::RDOType::TypeID FunctionType::typeID() const
{
	return m_pReturnType->type()->typeID();
}

CREF(LPTypeInfo) FunctionType::returnType() const
{
	return m_pReturnType;
}

CREF(LPFunctionParamType) FunctionType::paramType() const
{
	return m_pParamType;
}

tstring FunctionType::name() const
{
	return src_text();
}

LPRDOType FunctionType::type_cast(CREF(LPRDOType) pFrom, CREF(RDOParserSrcInfo) from_src_info, CREF(RDOParserSrcInfo) to_src_info, CREF(RDOParserSrcInfo) src_info) const
{
	NEVER_REACH_HERE;
	return LPRDOType();
}

LPRDOValue FunctionType::value_cast(CREF(LPRDOValue) pFrom, CREF(RDOParserSrcInfo) to_src_info, CREF(RDOParserSrcInfo) src_info) const
{
	NEVER_REACH_HERE;
	return LPRDOValue();
}

rdo::runtime::LPRDOCalc FunctionType::calc_cast(CREF(rdo::runtime::LPRDOCalc) pCalc, CREF(LPRDOType) pType) const
{
	NEVER_REACH_HERE;
	return rdo::runtime::LPRDOCalc();
}

rdo::runtime::RDOValue FunctionType::get_default() const
{
	NEVER_REACH_HERE;
	return rdo::runtime::RDOValue();
}

void FunctionType::writeModelStructure(std::ostream& stream) const
{
	stream << "F " << std::endl;
	NEVER_REACH_HERE;
}

CLOSE_RDO_PARSER_NAMESPACE
<commit_msg> - подавлен ворнинг<commit_after>/*!
  \copyright (c) RDO-Team, 2012
  \file      function_type.h
  \author    Урусов Андрей (rdo@rk9.bmstu.ru)
  \date      04.12.2012
  \brief     Тип функции
  \indent    4T
*/

// ---------------------------------------------------------------------------- PCH
#include "simulator/compiler/parser/pch.h"
// ----------------------------------------------------------------------- INCLUDES
#include <boost/foreach.hpp>
// ----------------------------------------------------------------------- SYNOPSIS
#include "simulator/compiler/parser/type/function_type.h"
#include "simulator/compiler/parser/rdo_value.h"
#include "simulator/compiler/parser/rdoparser.h"
// --------------------------------------------------------------------------------

OPEN_RDO_PARSER_NAMESPACE

// --------------------------------------------------------------------------------
// -------------------- FunctionParamType
// --------------------------------------------------------------------------------
FunctionParamType::FunctionParamType(CREF(ParamList) paramList, CREF(RDOParserSrcInfo) srcInfo)
	: RDOParserSrcInfo(srcInfo  )
	, m_paramList     (paramList)
{
	if (m_paramList.empty())
	{
		LPTypeInfo pType = rdo::Factory<TypeInfo>::delegate<RDOType__void>(srcInfo);
		ASSERT(pType);
		m_paramList.push_back(pType);
	}
}

FunctionParamType::~FunctionParamType()
{}

CREF(FunctionParamType::ParamList) FunctionParamType::paramList() const
{
	return m_paramList;
}

CREF(rdo::runtime::LPRDOType) FunctionParamType::type() const
{
	NEVER_REACH_HERE;
	static rdo::runtime::LPRDOType s_Type;
	return s_Type;
}

rdo::runtime::RDOType::TypeID FunctionParamType::typeID() const
{
	NEVER_REACH_HERE;
	return rdo::runtime::RDOType::t_unknow;
}

tstring FunctionParamType::name() const
{
	return src_text();
}

LPRDOType FunctionParamType::type_cast(CREF(LPRDOType) pFrom, CREF(RDOParserSrcInfo) from_src_info, CREF(RDOParserSrcInfo) to_src_info, CREF(RDOParserSrcInfo) src_info) const
{
	LPFunctionParamType pFromParamType = pFrom.object_dynamic_cast<FunctionParamType>();
	if (!pFromParamType)
	{
		parser::g_error().push_only(src_info,    rdo::format("Ожидаеются параметры вызова, найдено: %s", from_src_info.src_text().c_str()));
		parser::g_error().push_only(to_src_info, rdo::format("См. тип: %s", to_src_info.src_text().c_str()));
		parser::g_error().push_done();
	}

	if (paramList().size() != pFromParamType->paramList().size())
	{
		RDOParser::s_parser()->error().error(
			src_info,
			rdo::format("Неверное количество параметров: %s", from_src_info.src_text().c_str())
		);
	}

	ParamList::const_iterator paramFromIt = pFromParamType->paramList().begin();
	BOOST_FOREACH(const LPTypeInfo& pParamType, paramList())
	{
		pParamType->type_cast(*paramFromIt, src_info);
		++paramFromIt;
	}

	return const_cast<PTR(FunctionParamType)>(this);
}

LPRDOValue FunctionParamType::value_cast(CREF(LPRDOValue) /*pFrom*/, CREF(RDOParserSrcInfo) /*to_src_info*/, CREF(RDOParserSrcInfo) /*src_info*/) const
{
	NEVER_REACH_HERE;
	return LPRDOValue();
}

rdo::runtime::LPRDOCalc FunctionParamType::calc_cast(CREF(rdo::runtime::LPRDOCalc) /*pCalc*/, CREF(LPRDOType) /*pType*/) const
{
	NEVER_REACH_HERE;
	return rdo::runtime::LPRDOCalc();
}

rdo::runtime::RDOValue FunctionParamType::get_default() const
{
	NEVER_REACH_HERE;
	return rdo::runtime::RDOValue();
}

void FunctionParamType::writeModelStructure(std::ostream& stream) const
{
	stream << "F " << std::endl;
	NEVER_REACH_HERE;
}

// --------------------------------------------------------------------------------
// -------------------- FunctionType
// --------------------------------------------------------------------------------
FunctionType::FunctionType(CREF(LPTypeInfo) pReturnType, CREF(LPFunctionParamType) pParamType, CREF(RDOParserSrcInfo) srcInfo)
	: RDOParserSrcInfo(srcInfo    )
	, m_pReturnType   (pReturnType)
	, m_pParamType    (pParamType )
{
	ASSERT(m_pReturnType);
	ASSERT(m_pParamType );
}

FunctionType::~FunctionType()
{}

CREF(rdo::runtime::LPRDOType) FunctionType::type() const
{
	return m_pReturnType->type()->type();
}

rdo::runtime::RDOType::TypeID FunctionType::typeID() const
{
	return m_pReturnType->type()->typeID();
}

CREF(LPTypeInfo) FunctionType::returnType() const
{
	return m_pReturnType;
}

CREF(LPFunctionParamType) FunctionType::paramType() const
{
	return m_pParamType;
}

tstring FunctionType::name() const
{
	return src_text();
}

LPRDOType FunctionType::type_cast(CREF(LPRDOType) /*pFrom*/, CREF(RDOParserSrcInfo) /*from_src_info*/, CREF(RDOParserSrcInfo) /*to_src_info*/, CREF(RDOParserSrcInfo) /*src_info*/) const
{
	NEVER_REACH_HERE;
	return LPRDOType();
}

LPRDOValue FunctionType::value_cast(CREF(LPRDOValue) /*pFrom*/, CREF(RDOParserSrcInfo) /*to_src_info*/, CREF(RDOParserSrcInfo) /*src_info*/) const
{
	NEVER_REACH_HERE;
	return LPRDOValue();
}

rdo::runtime::LPRDOCalc FunctionType::calc_cast(CREF(rdo::runtime::LPRDOCalc) /*pCalc*/, CREF(LPRDOType) /*pType*/) const
{
	NEVER_REACH_HERE;
	return rdo::runtime::LPRDOCalc();
}

rdo::runtime::RDOValue FunctionType::get_default() const
{
	NEVER_REACH_HERE;
	return rdo::runtime::RDOValue();
}

void FunctionType::writeModelStructure(std::ostream& stream) const
{
	stream << "F " << std::endl;
	NEVER_REACH_HERE;
}

CLOSE_RDO_PARSER_NAMESPACE
<|endoftext|>


<commit_before>//-----------------------------------------------
//
//	This file is part of the Siv3D Engine.
//
//	Copyright (c) 2008-2021 Ryo Suzuki
//	Copyright (c) 2016-2021 OpenSiv3D Project
//
//	Licensed under the MIT License.
//
//-----------------------------------------------

# include "DirectoryWatcherDetail.hpp"
# include <Siv3D/FileSystem.hpp>
# include <Siv3D/EngineLog.hpp>

namespace s3d
{
	namespace detail
	{
		constexpr uint32 NotificationFilter = (FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_CREATION);

		[[nodiscard]]
		inline constexpr FileAction ToFileAction(DWORD action) noexcept
		{
			switch (action)
			{
			case FILE_ACTION_ADDED:
			case FILE_ACTION_RENAMED_NEW_NAME:
				return FileAction::Added;
			case FILE_ACTION_MODIFIED:
				return FileAction::Modified;
			case FILE_ACTION_REMOVED:
			case FILE_ACTION_RENAMED_OLD_NAME:
				return FileAction::Removed;
			default:
				return FileAction::Unknown;
			}
		}
	}

	DirectoryWatcher::DirectoryWatcherDetail::DirectoryWatcherDetail(const FilePath& directory)
	{
		if (directory.isEmpty()
			|| (not FileSystem::IsDirectory(directory)))
		{
			LOG_FAIL(U"❌ DirectoryWatcher: `{}` is not a directory"_fmt(directory));
			return;
		}

		m_targetDirectory = FileSystem::FullPath(directory);

		m_thread = std::jthread{ DirectoryWatcherDetail::Update, this };

		while (not m_initCalled)
		{
			::Sleep(1);
		}

		m_isActive = (m_directoryHandle != INVALID_HANDLE_VALUE);
	}

	DirectoryWatcher::DirectoryWatcherDetail::~DirectoryWatcherDetail()
	{
		if (m_thread.joinable())
		{
			m_thread.request_stop();

			m_thread.join();
		}

		if (m_directoryHandle == INVALID_HANDLE_VALUE)
		{
			return;
		}

		::CancelIoEx(m_directoryHandle, &m_overlapped);
		HANDLE tempDirectoryHandle = std::exchange(m_directoryHandle, INVALID_HANDLE_VALUE);
		::WaitForSingleObjectEx(tempDirectoryHandle, 1000, true);
		::CloseHandle(tempDirectoryHandle);

		LOG_INFO(U"ℹ DirectoryWatcher: Monitoring `{}` is deactivated"_fmt(m_targetDirectory));
	}

	bool DirectoryWatcher::DirectoryWatcherDetail::isActive() const
	{
		return m_isActive;
	}

	void DirectoryWatcher::DirectoryWatcherDetail::retrieveChanges(Array<FileChange>& fileChanges)
	{
		std::lock_guard lock(m_changesMutex);

		fileChanges.assign(m_fileChanges.begin(), m_fileChanges.end());

		m_fileChanges.clear();
	}

	void DirectoryWatcher::DirectoryWatcherDetail::clearChanges()
	{
		std::lock_guard lock(m_changesMutex);

		m_fileChanges.clear();
	}

	const FilePath& DirectoryWatcher::DirectoryWatcherDetail::directory() const noexcept
	{
		return m_targetDirectory;
	}

	bool DirectoryWatcher::DirectoryWatcherDetail::init()
	{
		m_overlapped.hEvent = this;
		m_buffer.resize(BufferSize);
		m_backBuffer.resize(BufferSize);

		m_directoryHandle = ::CreateFileW(
			m_targetDirectory.toWstr().c_str(),
			FILE_LIST_DIRECTORY,
			(FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE),
			nullptr,
			OPEN_EXISTING,
			(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED),
			nullptr
		);

		if (m_directoryHandle == INVALID_HANDLE_VALUE)
		{
			LOG_FAIL(U"❌ DirectoryWatcher: Failed to create a directory handle `{}`"_fmt(m_targetDirectory));
			return false;
		}

		LOG_INFO(U"ℹ DirectoryWatcher: A directory handle `{}` created"_fmt(m_targetDirectory));

		const bool result = !!::ReadDirectoryChangesW(
			m_directoryHandle,
			m_buffer.data(),
			static_cast<DWORD>(m_buffer.size()),
			WatchSubtree,
			detail::NotificationFilter,
			nullptr,
			&m_overlapped,
			&DirectoryWatcherDetail::OnChangeNotification);

		if (not result)
		{
			LOG_FAIL(U"❌ DirectoryWatcher: ReadDirectoryChangesW() failed. `{}`"_fmt(m_targetDirectory));
			::CloseHandle(m_directoryHandle);
			m_directoryHandle = INVALID_HANDLE_VALUE;
			return false;
		}

		LOG_INFO(U"ℹ DirectoryWatcher: Monitoring `{}` is activated"_fmt(m_targetDirectory));

		return true;
	}

	void DirectoryWatcher::DirectoryWatcherDetail::processChange(const DWORD errorCode, const DWORD numBytes)
	{
		if ((errorCode == ERROR_OPERATION_ABORTED)
			|| (numBytes == 0))
		{
			return;
		}

		const bool isValid = (errorCode != ERROR_IO_INCOMPLETE);

		if (isValid)
		{
			m_backBuffer.swap(m_buffer);
		}

		const bool result = !!::ReadDirectoryChangesW(
			m_directoryHandle,
			m_buffer.data(),
			static_cast<DWORD>(m_buffer.size()),
			WatchSubtree,
			detail::NotificationFilter,
			nullptr,
			&m_overlapped,
			&DirectoryWatcherDetail::OnChangeNotification);

		if (not result)
		{
			LOG_FAIL(U"❌ DirectoryWatcher: ReadDirectoryChangesW() failed. `{}`"_fmt(m_targetDirectory));
			::CloseHandle(m_directoryHandle);
			m_directoryHandle = INVALID_HANDLE_VALUE;
			return;
		}

		if (not isValid)
		{
			return;
		}

		std::lock_guard lock(m_changesMutex);

		for (const uint8* pInfo = m_backBuffer.data();;)
		{
			const FILE_NOTIFY_INFORMATION* notifyInfo = reinterpret_cast<const FILE_NOTIFY_INFORMATION*>(pInfo);
			const std::wstring_view view(notifyInfo->FileName, (notifyInfo->FileNameLength / sizeof(WCHAR)));
			const String localPath = Unicode::FromWstring(view).replace(L'\\', L'/');
			const FileAction action = detail::ToFileAction(notifyInfo->Action);

			m_fileChanges.emplace_back((m_targetDirectory + localPath), action);

			if (notifyInfo->NextEntryOffset == 0)
			{
				break;
			}

			pInfo += notifyInfo->NextEntryOffset;
		}
	}

	void DirectoryWatcher::DirectoryWatcherDetail::Update(std::stop_token stop_token, DirectoryWatcherDetail* watcher)
	{
		if (not watcher->init())
		{
			m_initCalled = true;
			return;
		}

		m_initCalled = true;

		while (not stop_token.stop_requested())
		{
			::SleepEx(15, true);
		}
	}

	void CALLBACK DirectoryWatcher::DirectoryWatcherDetail::OnChangeNotification(const DWORD dwErrorCode, const DWORD dwNumberOfBytesTransfered, const LPOVERLAPPED lpOverlapped)
	{
		DirectoryWatcherDetail* directoryWatcher = static_cast<DirectoryWatcherDetail*>(lpOverlapped->hEvent);

		directoryWatcher->processChange(dwErrorCode, dwNumberOfBytesTransfered);
	}
}
<commit_msg>[Windows] fix<commit_after>//-----------------------------------------------
//
//	This file is part of the Siv3D Engine.
//
//	Copyright (c) 2008-2021 Ryo Suzuki
//	Copyright (c) 2016-2021 OpenSiv3D Project
//
//	Licensed under the MIT License.
//
//-----------------------------------------------

# include "DirectoryWatcherDetail.hpp"
# include <Siv3D/FileSystem.hpp>
# include <Siv3D/EngineLog.hpp>

namespace s3d
{
	namespace detail
	{
		constexpr uint32 NotificationFilter = (FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_CREATION);

		[[nodiscard]]
		inline constexpr FileAction ToFileAction(DWORD action) noexcept
		{
			switch (action)
			{
			case FILE_ACTION_ADDED:
			case FILE_ACTION_RENAMED_NEW_NAME:
				return FileAction::Added;
			case FILE_ACTION_MODIFIED:
				return FileAction::Modified;
			case FILE_ACTION_REMOVED:
			case FILE_ACTION_RENAMED_OLD_NAME:
				return FileAction::Removed;
			default:
				return FileAction::Unknown;
			}
		}
	}

	DirectoryWatcher::DirectoryWatcherDetail::DirectoryWatcherDetail(const FilePath& directory)
	{
		if (directory.isEmpty()
			|| (not FileSystem::IsDirectory(directory)))
		{
			LOG_FAIL(U"❌ DirectoryWatcher: `{}` is not a directory"_fmt(directory));
			return;
		}

		m_targetDirectory = FileSystem::FullPath(directory);

		m_thread = std::jthread{ DirectoryWatcherDetail::Update, this };

		while (not m_initCalled)
		{
			::Sleep(1);
		}

		m_isActive = (m_directoryHandle != INVALID_HANDLE_VALUE);
	}

	DirectoryWatcher::DirectoryWatcherDetail::~DirectoryWatcherDetail()
	{
		if (m_thread.joinable())
		{
			m_thread.request_stop();

			m_thread.join();
		}

		if (m_directoryHandle == INVALID_HANDLE_VALUE)
		{
			return;
		}

		::CancelIoEx(m_directoryHandle, &m_overlapped);
		HANDLE tempDirectoryHandle = std::exchange(m_directoryHandle, INVALID_HANDLE_VALUE);
		::WaitForSingleObjectEx(tempDirectoryHandle, 1000, true);
		::CloseHandle(tempDirectoryHandle);

		LOG_INFO(U"ℹ DirectoryWatcher: Monitoring `{}` is deactivated"_fmt(m_targetDirectory));
	}

	bool DirectoryWatcher::DirectoryWatcherDetail::isActive() const
	{
		return m_isActive;
	}

	void DirectoryWatcher::DirectoryWatcherDetail::retrieveChanges(Array<FileChange>& fileChanges)
	{
		std::lock_guard lock(m_changesMutex);

		fileChanges.assign(m_fileChanges.begin(), m_fileChanges.end());

		m_fileChanges.clear();
	}

	void DirectoryWatcher::DirectoryWatcherDetail::clearChanges()
	{
		std::lock_guard lock(m_changesMutex);

		m_fileChanges.clear();
	}

	const FilePath& DirectoryWatcher::DirectoryWatcherDetail::directory() const noexcept
	{
		return m_targetDirectory;
	}

	bool DirectoryWatcher::DirectoryWatcherDetail::init()
	{
		m_overlapped.hEvent = this;
		m_buffer.resize(BufferSize);
		m_backBuffer.resize(BufferSize);

		m_directoryHandle = ::CreateFileW(
			m_targetDirectory.toWstr().c_str(),
			FILE_LIST_DIRECTORY,
			(FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE),
			nullptr,
			OPEN_EXISTING,
			(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED),
			nullptr
		);

		if (m_directoryHandle == INVALID_HANDLE_VALUE)
		{
			LOG_FAIL(U"❌ DirectoryWatcher: Failed to create a directory handle `{}`"_fmt(m_targetDirectory));
			return false;
		}

		LOG_INFO(U"ℹ DirectoryWatcher: A directory handle `{}` created"_fmt(m_targetDirectory));

		const bool result = !!::ReadDirectoryChangesW(
			m_directoryHandle,
			m_buffer.data(),
			static_cast<DWORD>(m_buffer.size()),
			WatchSubtree,
			detail::NotificationFilter,
			nullptr,
			&m_overlapped,
			&DirectoryWatcherDetail::OnChangeNotification);

		if (not result)
		{
			LOG_FAIL(U"❌ DirectoryWatcher: ReadDirectoryChangesW() failed. `{}`"_fmt(m_targetDirectory));
			::CloseHandle(m_directoryHandle);
			m_directoryHandle = INVALID_HANDLE_VALUE;
			return false;
		}

		LOG_INFO(U"ℹ DirectoryWatcher: Monitoring `{}` is activated"_fmt(m_targetDirectory));

		return true;
	}

	void DirectoryWatcher::DirectoryWatcherDetail::processChange(const DWORD errorCode, const DWORD numBytes)
	{
		if ((errorCode == ERROR_OPERATION_ABORTED)
			|| (numBytes == 0))
		{
			return;
		}

		const bool isValid = (errorCode != ERROR_IO_INCOMPLETE);

		if (isValid)
		{
			m_backBuffer.swap(m_buffer);
		}

		const bool result = !!::ReadDirectoryChangesW(
			m_directoryHandle,
			m_buffer.data(),
			static_cast<DWORD>(m_buffer.size()),
			WatchSubtree,
			detail::NotificationFilter,
			nullptr,
			&m_overlapped,
			&DirectoryWatcherDetail::OnChangeNotification);

		if (not result)
		{
			LOG_FAIL(U"❌ DirectoryWatcher: ReadDirectoryChangesW() failed. `{}`"_fmt(m_targetDirectory));
			::CloseHandle(m_directoryHandle);
			m_directoryHandle = INVALID_HANDLE_VALUE;
			return;
		}

		if (not isValid)
		{
			return;
		}

		std::lock_guard lock(m_changesMutex);

		for (const uint8* pInfo = m_backBuffer.data();;)
		{
			const FILE_NOTIFY_INFORMATION* notifyInfo = reinterpret_cast<const FILE_NOTIFY_INFORMATION*>(pInfo);
			const std::wstring_view view(notifyInfo->FileName, (notifyInfo->FileNameLength / sizeof(WCHAR)));
			const String localPath = Unicode::FromWstring(view).replace(L'\\', L'/');
			const FileAction action = detail::ToFileAction(notifyInfo->Action);

			m_fileChanges.emplace_back((m_targetDirectory + localPath), action);

			if (notifyInfo->NextEntryOffset == 0)
			{
				break;
			}

			pInfo += notifyInfo->NextEntryOffset;
		}
	}

	void DirectoryWatcher::DirectoryWatcherDetail::Update(std::stop_token stop_token, DirectoryWatcherDetail* watcher)
	{
		if (not watcher->init())
		{
			watcher->m_initCalled = true;
			return;
		}

		watcher->m_initCalled = true;

		while (not stop_token.stop_requested())
		{
			::SleepEx(15, true);
		}
	}

	void CALLBACK DirectoryWatcher::DirectoryWatcherDetail::OnChangeNotification(const DWORD dwErrorCode, const DWORD dwNumberOfBytesTransfered, const LPOVERLAPPED lpOverlapped)
	{
		DirectoryWatcherDetail* directoryWatcher = static_cast<DirectoryWatcherDetail*>(lpOverlapped->hEvent);

		directoryWatcher->processChange(dwErrorCode, dwNumberOfBytesTransfered);
	}
}
<|endoftext|>


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

#define DISABLE_BOUNDS_CHECKS 1

#include <string>
#include <benchmark/benchmark.h>
#include <thread>
#include <atomic>

#include "concurrent/Atomic64.h"
#include "concurrent/BusySpinIdleStrategy.h"

extern "C"
{
#include "concurrent/aeron_spsc_concurrent_array_queue.h"
#include "util/aeron_error.h"
}

using namespace aeron::concurrent;

int SENTINEL = 1000;

static void BM_C_SpscQueueLatency(benchmark::State &state)
{
    const auto burstLength = static_cast<std::size_t>(state.range(0));
    aeron_spsc_concurrent_array_queue_t q_in;
    aeron_spsc_concurrent_array_queue_t q_out;

    if (aeron_spsc_concurrent_array_queue_init(&q_in, 64 * 1024) < 0)
    {
        throw std::runtime_error("could not init q_in: " + std::string(aeron_errmsg()));
    }

    if (aeron_spsc_concurrent_array_queue_init(&q_out, 128) < 0)
    {
        throw std::runtime_error("could not init q_out: " + std::string(aeron_errmsg()));
    }

    auto *values = new std::int32_t[burstLength];
    auto burstLengthValue = static_cast<std::int32_t>(burstLength);
    for (std::int32_t i = 0; i < burstLengthValue; i++)
    {
        values[static_cast<std::size_t>(i)] = -(burstLengthValue - i);
    }

    values[burstLength - 1] = 0;

    std::atomic<bool> start{ false };
    std::atomic<bool> running{ true };

    std::thread t(
        [&]()
        {
            BusySpinIdleStrategy idle;
            start.store(true);

            while (running)
            {
                int *p = (int *)aeron_spsc_concurrent_array_queue_poll(&q_in);
                if (p != nullptr)
                {
                    if (*p >= 0)
                    {
                        while (aeron_spsc_concurrent_array_queue_offer(&q_out, &SENTINEL) != AERON_OFFER_SUCCESS)
                        {
                            idle.idle();
                        }
                    }
                }
                else
                {
                    idle.idle();
                }
            }
        });

    while (!start)
    {
        std::this_thread::yield();
    }

    BusySpinIdleStrategy burstIdle;

    while (state.KeepRunning())
    {
        for (std::size_t i = 0; i < burstLength; i++)
        {
            while (aeron_spsc_concurrent_array_queue_offer(&q_in, &values[i]) != AERON_OFFER_SUCCESS)
            {
                burstIdle.idle();
            }
        }

        while (aeron_spsc_concurrent_array_queue_poll(&q_out) == nullptr)
        {
            burstIdle.idle();
        }
    }

    state.SetItemsProcessed(state.iterations());
    state.SetBytesProcessed(state.iterations() * sizeof(int));

    running.store(false);

    t.join();

    delete [] values;

    aeron_spsc_concurrent_array_queue_close(&q_in);
    aeron_spsc_concurrent_array_queue_close(&q_out);
}

BENCHMARK(BM_C_SpscQueueLatency)
    ->Arg(1)
    ->Arg(100)
    ->UseRealTime();

static void BM_C_SpscQueueThroughput(benchmark::State &state)
{
    int *i = new int{ 42 };
    aeron_spsc_concurrent_array_queue_t q;

    if (aeron_spsc_concurrent_array_queue_init(&q, static_cast<std::size_t>(state.range(0))) < 0)
    {
        throw std::runtime_error("could not init q: " + std::string(aeron_errmsg()));
    }

    std::atomic<bool> start{ false };
    std::atomic<bool> running{ true };
    std::int64_t totalMsgs = 0;

    std::thread t(
        [&]()
        {
            start.store(true);

            while (running)
            {
                if (nullptr == aeron_spsc_concurrent_array_queue_poll(&q))
                {
                    aeron::concurrent::atomic::cpu_pause();
                }
            }
        });

    while (!start)
    {
        std::this_thread::yield();
    }

    while (state.KeepRunning())
    {
        while (aeron_spsc_concurrent_array_queue_offer(&q, i) != AERON_OFFER_SUCCESS)
        {
            aeron::concurrent::atomic::cpu_pause();
        }

        totalMsgs++;
    }

    state.SetItemsProcessed(totalMsgs);
    state.SetBytesProcessed(totalMsgs * sizeof(int));

    running.store(false);

    t.join();
}

BENCHMARK(BM_C_SpscQueueThroughput)
    ->Arg(1024)
    ->Arg(64 * 1024)
    ->Arg(128 * 1024)
    ->Arg(256 * 1024)
    ->UseRealTime();

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

#define DISABLE_BOUNDS_CHECKS 1

#include <string>
#include <benchmark/benchmark.h>
#include <thread>
#include <atomic>

#include "concurrent/Atomic64.h"
#include "concurrent/BusySpinIdleStrategy.h"

extern "C"
{
#include "concurrent/aeron_spsc_concurrent_array_queue.h"
#include "util/aeron_error.h"
}

using namespace aeron::concurrent;

int SENTINEL = 1000;

static void BM_C_SpscQueueLatency(benchmark::State &state)
{
    const auto burstLength = static_cast<std::size_t>(state.range(0));
    aeron_spsc_concurrent_array_queue_t q_in;
    aeron_spsc_concurrent_array_queue_t q_out;

    if (aeron_spsc_concurrent_array_queue_init(&q_in, 64 * 1024) < 0)
    {
        throw std::runtime_error("could not init q_in: " + std::string(aeron_errmsg()));
    }

    if (aeron_spsc_concurrent_array_queue_init(&q_out, 128) < 0)
    {
        throw std::runtime_error("could not init q_out: " + std::string(aeron_errmsg()));
    }

    auto *values = new std::int32_t[burstLength];
    auto burstLengthValue = static_cast<std::int32_t>(burstLength);
    for (std::int32_t i = 0; i < burstLengthValue; i++)
    {
        values[static_cast<std::size_t>(i)] = -(burstLengthValue - i);
    }

    values[burstLength - 1] = 0;

    std::atomic<bool> start(false);
    std::atomic<bool> running(true);

    std::thread t(
        [&]()
        {
            BusySpinIdleStrategy idle;
            start.store(true);

            while (running)
            {
                int *p = (int *)aeron_spsc_concurrent_array_queue_poll(&q_in);
                if (p != nullptr)
                {
                    if (*p >= 0)
                    {
                        while (aeron_spsc_concurrent_array_queue_offer(&q_out, &SENTINEL) != AERON_OFFER_SUCCESS)
                        {
                            idle.idle();
                        }
                    }
                }
                else
                {
                    idle.idle();
                }
            }
        });

    while (!start)
    {
        std::this_thread::yield();
    }

    BusySpinIdleStrategy burstIdle;

    while (state.KeepRunning())
    {
        for (std::size_t i = 0; i < burstLength; i++)
        {
            while (aeron_spsc_concurrent_array_queue_offer(&q_in, &values[i]) != AERON_OFFER_SUCCESS)
            {
                burstIdle.idle();
            }
        }

        while (aeron_spsc_concurrent_array_queue_poll(&q_out) == nullptr)
        {
            burstIdle.idle();
        }
    }

    state.SetItemsProcessed(state.iterations());
    state.SetBytesProcessed(state.iterations() * sizeof(int));

    running.store(false);

    t.join();

    delete [] values;

    aeron_spsc_concurrent_array_queue_close(&q_in);
    aeron_spsc_concurrent_array_queue_close(&q_out);
}

BENCHMARK(BM_C_SpscQueueLatency)
    ->Arg(1)
    ->Arg(100)
    ->UseRealTime();

static void BM_C_SpscQueueThroughput(benchmark::State &state)
{
    int *i = new int{ 42 };
    aeron_spsc_concurrent_array_queue_t q;

    if (aeron_spsc_concurrent_array_queue_init(&q, static_cast<std::size_t>(state.range(0))) < 0)
    {
        throw std::runtime_error("could not init q: " + std::string(aeron_errmsg()));
    }

    std::atomic<bool> start{ false };
    std::atomic<bool> running{ true };
    std::int64_t totalMsgs = 0;

    std::thread t(
        [&]()
        {
            start.store(true);

            while (running)
            {
                if (nullptr == aeron_spsc_concurrent_array_queue_poll(&q))
                {
                    aeron::concurrent::atomic::cpu_pause();
                }
            }
        });

    while (!start)
    {
        std::this_thread::yield();
    }

    while (state.KeepRunning())
    {
        while (aeron_spsc_concurrent_array_queue_offer(&q, i) != AERON_OFFER_SUCCESS)
        {
            aeron::concurrent::atomic::cpu_pause();
        }

        totalMsgs++;
    }

    state.SetItemsProcessed(totalMsgs);
    state.SetBytesProcessed(totalMsgs * sizeof(int));

    running.store(false);

    t.join();
}

BENCHMARK(BM_C_SpscQueueThroughput)
    ->Arg(1024)
    ->Arg(64 * 1024)
    ->Arg(128 * 1024)
    ->Arg(256 * 1024)
    ->UseRealTime();

BENCHMARK_MAIN();
<|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 "ash/system/power/power_status_view.h"

#include "ash/shell.h"
#include "ash/shell_delegate.h"
#include "ash/system/power/tray_power.h"
#include "ash/system/tray/tray_constants.h"
#include "ash/system/tray/tray_views.h"
#include "base/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "grit/ash_strings.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/views/controls/image_view.h"
#include "ui/views/controls/label.h"
#include "ui/views/layout/box_layout.h"
#include "ui/views/layout/grid_layout.h"

namespace ash {
namespace internal {

namespace {

// Top/bottom padding of the text items.
const int kPaddingVertical = 10;
// Specify min width of status label for layout.
const int kLabelMinWidth = 120;
// Padding between battery status text and battery icon on default view.
const int kPaddingBetweenBatteryStatusAndIcon = 3;
}  // namespace

PowerStatusView::PowerStatusView(ViewType view_type,
                                 bool default_view_right_align)
    : default_view_right_align_(default_view_right_align),
      status_label_(NULL),
      time_label_(NULL),
      time_status_label_(NULL),
      icon_(NULL),
      icon_image_index_(-1),
      view_type_(view_type) {
  if (view_type == VIEW_DEFAULT) {
    time_status_label_ = new views::Label;
    LayoutDefaultView();
  } else {
    status_label_ = new views::Label;
    time_label_ = new views::Label;
    LayoutNotificationView();
  }
  Update();
}

void PowerStatusView::UpdatePowerStatus(const PowerSupplyStatus& status) {
  supply_status_ = status;
  // Sanitize.
  if (supply_status_.battery_is_full)
    supply_status_.battery_percentage = 100.0;

  Update();
}

void PowerStatusView::LayoutDefaultView() {
  if (default_view_right_align_) {
    views::BoxLayout* layout =
        new views::BoxLayout(views::BoxLayout::kHorizontal, 0, 0,
                             kPaddingBetweenBatteryStatusAndIcon);
    SetLayoutManager(layout);

    AddChildView(time_status_label_);

    icon_ = new views::ImageView;
    AddChildView(icon_);
  } else {
    // PowerStatusView is left aligned on the system tray pop up item.
    views::BoxLayout* layout =
        new views::BoxLayout(views::BoxLayout::kHorizontal, 0, 0,
                             kTrayPopupPaddingBetweenItems);
    SetLayoutManager(layout);

    icon_ =
        new ash::internal::FixedSizedImageView(0, ash::kTrayPopupItemHeight);
    AddChildView(icon_);

    AddChildView(time_status_label_);
  }
}

void PowerStatusView::LayoutNotificationView() {
  SetLayoutManager(
      new views::BoxLayout(views::BoxLayout::kVertical, 0, 0, 1));
  status_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
  AddChildView(status_label_);

  time_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
  AddChildView(time_label_);
}

void PowerStatusView::UpdateText() {
  view_type_ == VIEW_DEFAULT ?
      UpdateTextForDefaultView() : UpdateTextForNotificationView();
}

void PowerStatusView::UpdateTextForDefaultView() {
  int hour = 0;
  int min = 0;
  if (!supply_status_.is_calculating_battery_time) {
    // TODO(jennyz): Due to crosbug.com/31633, averaged_battery_time_to_empty
    // from PowerSupplyStatus object can contain garbage data for the first
    // call in a crOS session. Until this bug is fixed, use
    // supply_status_.battery_seconds_to_empty to render battery time.
    // Change back to use averaged_battery_time_to_empty to display in UI
    // once crosbug.com/31633 is fixed.
    base::TimeDelta time = base::TimeDelta::FromSeconds(
        supply_status_.averaged_battery_time_to_empty);
    hour = time.InHours();
    min = (time - base::TimeDelta::FromHours(hour)).InMinutes();
  }

  if (supply_status_.line_power_on && supply_status_.battery_is_full) {
    time_status_label_->SetText(
        ui::ResourceBundle::GetSharedInstance().GetLocalizedString(
            IDS_ASH_STATUS_TRAY_BATTERY_FULL));
  } else {
    string16 battery_percentage = l10n_util::GetStringFUTF16(
        IDS_ASH_STATUS_TRAY_BATTERY_PERCENT_ONLY,
        base::IntToString16(
            static_cast<int>(supply_status_.battery_percentage)));
    string16 battery_time = string16();
    if (supply_status_.is_calculating_battery_time) {
      battery_time =
          ui::ResourceBundle::GetSharedInstance().GetLocalizedString(
              IDS_ASH_STATUS_TRAY_BATTERY_CALCULATING);
    } else if (hour || min){
      string16 minute = min < 10 ?
          ASCIIToUTF16("0") + base::IntToString16(min) :
          base::IntToString16(min);
      battery_time =
          l10n_util::GetStringFUTF16(
              IDS_ASH_STATUS_TRAY_BATTERY_TIME_ONLY,
              base::IntToString16(hour),
              minute);
    }
    string16 battery_status = battery_time.empty() ?
        battery_percentage :
        battery_percentage + ASCIIToUTF16(" - ") + battery_time;
    time_status_label_->SetText(battery_status);
  }
}

void PowerStatusView::UpdateTextForNotificationView() {
  int hour = 0;
  int min = 0;
  if (!supply_status_.is_calculating_battery_time) {
    base::TimeDelta time = base::TimeDelta::FromSeconds(
        supply_status_.line_power_on ?
        supply_status_.averaged_battery_time_to_full :
        supply_status_.averaged_battery_time_to_empty);
    hour = time.InHours();
    min = (time - base::TimeDelta::FromHours(hour)).InMinutes();
  }

  if (supply_status_.line_power_on && supply_status_.battery_is_full) {
    status_label_->SetText(
        ui::ResourceBundle::GetSharedInstance().GetLocalizedString(
            IDS_ASH_STATUS_TRAY_BATTERY_FULL));
  } else {
    status_label_->SetText(
        l10n_util::GetStringFUTF16(
            IDS_ASH_STATUS_TRAY_BATTERY_PERCENT,
            base::IntToString16(
                static_cast<int>(supply_status_.battery_percentage))));
  }

  if (supply_status_.is_calculating_battery_time) {
    time_label_->SetText(
        ui::ResourceBundle::GetSharedInstance().GetLocalizedString(
            IDS_ASH_STATUS_TRAY_BATTERY_CALCULATING));
  } else if (hour || min) {
    if (supply_status_.line_power_on) {
      time_label_->SetText(
          l10n_util::GetStringFUTF16(
              IDS_ASH_STATUS_TRAY_BATTERY_TIME_UNTIL_FULL,
              base::IntToString16(hour),
              base::IntToString16(min)));
    } else {
      // This is a low battery warning, which prompts user when battery
      // time left is not much (ie in minutes).
      min = hour * 60 + min;
      ShellDelegate* delegate = Shell::GetInstance()->delegate();
      if (delegate) {
        time_label_->SetText(delegate->GetTimeRemainingString(
            base::TimeDelta::FromMinutes(min)));
      } else {
        time_label_->SetText(string16());
      }
    }
  } else {
    time_label_->SetText(string16());
  }
}

void PowerStatusView::UpdateIcon() {
  if (icon_) {
    int index = TrayPower::GetBatteryImageIndex(supply_status_);
    if (icon_image_index_ != index) {
      icon_image_index_ = index;
      if (icon_image_index_ != -1) {
        icon_->SetImage(
            TrayPower::GetBatteryImage(icon_image_index_, ICON_DARK));
      }
    }
    icon_->SetVisible(true);
  }
}

void PowerStatusView::Update() {
  UpdateText();
  UpdateIcon();
}

void PowerStatusView::ChildPreferredSizeChanged(views::View* child) {
  PreferredSizeChanged();
}

gfx::Size PowerStatusView::GetPreferredSize() {
  gfx::Size size = views::View::GetPreferredSize();
  return gfx::Size(size.width(), kTrayPopupItemHeight);
}

}  // namespace internal
}  // namespace ash
<commit_msg>Fix the battery percentage "-1" issue.<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 "ash/system/power/power_status_view.h"

#include "ash/shell.h"
#include "ash/shell_delegate.h"
#include "ash/system/power/tray_power.h"
#include "ash/system/tray/tray_constants.h"
#include "ash/system/tray/tray_views.h"
#include "base/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "grit/ash_strings.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/views/controls/image_view.h"
#include "ui/views/controls/label.h"
#include "ui/views/layout/box_layout.h"
#include "ui/views/layout/grid_layout.h"

namespace ash {
namespace internal {

namespace {

// Top/bottom padding of the text items.
const int kPaddingVertical = 10;
// Specify min width of status label for layout.
const int kLabelMinWidth = 120;
// Padding between battery status text and battery icon on default view.
const int kPaddingBetweenBatteryStatusAndIcon = 3;
}  // namespace

PowerStatusView::PowerStatusView(ViewType view_type,
                                 bool default_view_right_align)
    : default_view_right_align_(default_view_right_align),
      status_label_(NULL),
      time_label_(NULL),
      time_status_label_(NULL),
      icon_(NULL),
      icon_image_index_(-1),
      view_type_(view_type) {
  if (view_type == VIEW_DEFAULT) {
    time_status_label_ = new views::Label;
    LayoutDefaultView();
  } else {
    status_label_ = new views::Label;
    time_label_ = new views::Label;
    LayoutNotificationView();
  }
  Update();
}

void PowerStatusView::UpdatePowerStatus(const PowerSupplyStatus& status) {
  supply_status_ = status;
  // Sanitize.
  if (supply_status_.battery_is_full)
    supply_status_.battery_percentage = 100.0;

  Update();
}

void PowerStatusView::LayoutDefaultView() {
  if (default_view_right_align_) {
    views::BoxLayout* layout =
        new views::BoxLayout(views::BoxLayout::kHorizontal, 0, 0,
                             kPaddingBetweenBatteryStatusAndIcon);
    SetLayoutManager(layout);

    AddChildView(time_status_label_);

    icon_ = new views::ImageView;
    AddChildView(icon_);
  } else {
    // PowerStatusView is left aligned on the system tray pop up item.
    views::BoxLayout* layout =
        new views::BoxLayout(views::BoxLayout::kHorizontal, 0, 0,
                             kTrayPopupPaddingBetweenItems);
    SetLayoutManager(layout);

    icon_ =
        new ash::internal::FixedSizedImageView(0, ash::kTrayPopupItemHeight);
    AddChildView(icon_);

    AddChildView(time_status_label_);
  }
}

void PowerStatusView::LayoutNotificationView() {
  SetLayoutManager(
      new views::BoxLayout(views::BoxLayout::kVertical, 0, 0, 1));
  status_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
  AddChildView(status_label_);

  time_label_->SetHorizontalAlignment(views::Label::ALIGN_LEFT);
  AddChildView(time_label_);
}

void PowerStatusView::UpdateText() {
  view_type_ == VIEW_DEFAULT ?
      UpdateTextForDefaultView() : UpdateTextForNotificationView();
}

void PowerStatusView::UpdateTextForDefaultView() {
  if (supply_status_.line_power_on && supply_status_.battery_is_full) {
    time_status_label_->SetText(
        ui::ResourceBundle::GetSharedInstance().GetLocalizedString(
            IDS_ASH_STATUS_TRAY_BATTERY_FULL));
  } else if (supply_status_.is_calculating_battery_time ||
             supply_status_.battery_percentage < 0.0f) {
    time_status_label_->SetText(
        ui::ResourceBundle::GetSharedInstance().GetLocalizedString(
            IDS_ASH_STATUS_TRAY_BATTERY_CALCULATING));
  } else {
    string16 battery_percentage = l10n_util::GetStringFUTF16(
        IDS_ASH_STATUS_TRAY_BATTERY_PERCENT_ONLY,
        base::IntToString16(
            static_cast<int>(supply_status_.battery_percentage)));
    string16 battery_time = string16();
    int hour = 0;
    int min = 0;
    base::TimeDelta time = base::TimeDelta::FromSeconds(
        supply_status_.averaged_battery_time_to_empty);
    hour = time.InHours();
    min = (time - base::TimeDelta::FromHours(hour)).InMinutes();
    if (hour || min) {
      string16 minute = min < 10 ?
          ASCIIToUTF16("0") + base::IntToString16(min) :
          base::IntToString16(min);
      battery_time =
          l10n_util::GetStringFUTF16(
              IDS_ASH_STATUS_TRAY_BATTERY_TIME_ONLY,
              base::IntToString16(hour),
              minute);
    }
    string16 battery_status = battery_time.empty() ?
        battery_percentage :
        battery_percentage + ASCIIToUTF16(" - ") + battery_time;
    time_status_label_->SetText(battery_status);
  }
}

void PowerStatusView::UpdateTextForNotificationView() {
  int hour = 0;
  int min = 0;
  if (!supply_status_.is_calculating_battery_time) {
    base::TimeDelta time = base::TimeDelta::FromSeconds(
        supply_status_.line_power_on ?
        supply_status_.averaged_battery_time_to_full :
        supply_status_.averaged_battery_time_to_empty);
    hour = time.InHours();
    min = (time - base::TimeDelta::FromHours(hour)).InMinutes();
  }

  if (supply_status_.line_power_on && supply_status_.battery_is_full) {
    status_label_->SetText(
        ui::ResourceBundle::GetSharedInstance().GetLocalizedString(
            IDS_ASH_STATUS_TRAY_BATTERY_FULL));
  } else {
    if (supply_status_.battery_percentage < 0.0f) {
        status_label_->SetText(
            ui::ResourceBundle::GetSharedInstance().GetLocalizedString(
                IDS_ASH_STATUS_TRAY_BATTERY_CALCULATING));
    } else {
      status_label_->SetText(
          l10n_util::GetStringFUTF16(
              IDS_ASH_STATUS_TRAY_BATTERY_PERCENT,
              base::IntToString16(
                  static_cast<int>(supply_status_.battery_percentage))));
    }
  }

  if (supply_status_.is_calculating_battery_time) {
    time_label_->SetText(
        ui::ResourceBundle::GetSharedInstance().GetLocalizedString(
            IDS_ASH_STATUS_TRAY_BATTERY_CALCULATING));
  } else if (hour || min) {
    if (supply_status_.line_power_on) {
      time_label_->SetText(
          l10n_util::GetStringFUTF16(
              IDS_ASH_STATUS_TRAY_BATTERY_TIME_UNTIL_FULL,
              base::IntToString16(hour),
              base::IntToString16(min)));
    } else {
      // This is a low battery warning, which prompts user when battery
      // time left is not much (ie in minutes).
      min = hour * 60 + min;
      ShellDelegate* delegate = Shell::GetInstance()->delegate();
      if (delegate) {
        time_label_->SetText(delegate->GetTimeRemainingString(
            base::TimeDelta::FromMinutes(min)));
      } else {
        time_label_->SetText(string16());
      }
    }
  } else {
    time_label_->SetText(string16());
  }
}

void PowerStatusView::UpdateIcon() {
  if (icon_) {
    int index = TrayPower::GetBatteryImageIndex(supply_status_);
    if (icon_image_index_ != index) {
      icon_image_index_ = index;
      if (icon_image_index_ != -1) {
        icon_->SetImage(
            TrayPower::GetBatteryImage(icon_image_index_, ICON_DARK));
      }
    }
    icon_->SetVisible(true);
  }
}

void PowerStatusView::Update() {
  UpdateText();
  UpdateIcon();
}

void PowerStatusView::ChildPreferredSizeChanged(views::View* child) {
  PreferredSizeChanged();
}

gfx::Size PowerStatusView::GetPreferredSize() {
  gfx::Size size = views::View::GetPreferredSize();
  return gfx::Size(size.width(), kTrayPopupItemHeight);
}

}  // namespace internal
}  // namespace ash
<|endoftext|>


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

#include <sys/sysctl.h>
#include "cc/check.h"

namespace minigo {

int GetNumLogicalCpus() {
 int nproc = 0;
 size_t len;
 MG_CHECK(sysctlbyname("hw.logicalcpu", &nproc, &len, nullptr, 0) == 0);
 MG_CHECK(len == sizeof(nproc));
 return nproc;

}

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

#include <sys/sysctl.h>
#include "cc/check.h"

namespace minigo {

int GetNumLogicalCpus() {
  int nproc = 0;
  size_t len;
  MG_CHECK(sysctlbyname("hw.logicalcpu", &nproc, &len, nullptr, 0) == 0);
  MG_CHECK(len == sizeof(nproc));
  return nproc;
}

}  // namespace minigo
<|endoftext|>


<commit_before>#include "ImageGradient.hpp"
#include "DeviceManager.hpp"

namespace fast {

void ImageGradient::setInput(ImageData::pointer input) {
    setInputData(0, input);
}

ImageData::pointer ImageGradient::getOutput() {
    return getOutputData<Image, DynamicImage>(0);
}

ImageGradient::ImageGradient() {
    setOutputDataDynamicDependsOnInputData(0, 0);
}

void ImageGradient::execute() {
    Image::pointer input = getStaticInputData<Image>(0);
    Image::pointer output = getStaticOutputData<Image>(0);

    // Initialize output image
    if(input->getDimensions() == 2) {
        output->create2DImage(
                input->getWidth(),
                input->getHeight(),
                TYPE_FLOAT,
                2,
                getMainDevice()
                );
    } else {
        throw Exception("Not implemented yet.");
         output->create3DImage(
                input->getWidth(),
                input->getHeight(),
                input->getDepth(),
                TYPE_FLOAT,
                3,
                getMainDevice()
                );
    }

    if(getMainDevice()->isHost()) {
        throw Exception("Not implemented yet.");
    } else {
        OpenCLDevice::pointer device = OpenCLDevice::pointer(getMainDevice());
        std::string buildOptions = "";
        if(input->getDataType() == TYPE_FLOAT) {
            buildOptions = "-DTYPE_FLOAT";
        } else if(input->getDataType() == TYPE_INT8 || input->getDataType() == TYPE_INT16) {
            buildOptions = "-DTYPE_INT";
        } else {
            buildOptions = "-DTYPE_UINT";
        }
        int programNr = device->createProgramFromSource(std::string(FAST_SOURCE_DIR) + "Algorithms/ImageGradient/ImageGradient.cl", buildOptions);
        cl::Program program = device->getProgram(programNr);
        cl::Kernel kernel;
        if(input->getDimensions() == 2) {
            kernel = cl::Kernel(program, "gradient2D");
            OpenCLImageAccess2D inputAccess = input->getOpenCLImageAccess2D(ACCESS_READ, device);
            OpenCLImageAccess2D outputAccess = output->getOpenCLImageAccess2D(ACCESS_READ_WRITE, device);
            kernel.setArg(0, *inputAccess.get());
            kernel.setArg(1, *outputAccess.get());
        } else {
            kernel = cl::Kernel(program, "gradient3D");
            OpenCLImageAccess3D inputAccess = input->getOpenCLImageAccess3D(ACCESS_READ, device);
            OpenCLImageAccess3D outputAccess = output->getOpenCLImageAccess3D(ACCESS_READ_WRITE, device);
            kernel.setArg(0, *inputAccess.get());
            kernel.setArg(1, *outputAccess.get());
        }

        device->getCommandQueue().enqueueNDRangeKernel(
                kernel,
                cl::NullRange,
                cl::NDRange(input->getWidth(), input->getHeight(), input->getDepth()),
                cl::NullRange
        );
    }
}

}

<commit_msg>enabled 3D image gradient calculation<commit_after>#include "ImageGradient.hpp"
#include "DeviceManager.hpp"

namespace fast {

void ImageGradient::setInput(ImageData::pointer input) {
    setInputData(0, input);
}

ImageData::pointer ImageGradient::getOutput() {
    return getOutputData<Image, DynamicImage>(0);
}

ImageGradient::ImageGradient() {
    setOutputDataDynamicDependsOnInputData(0, 0);
}

void ImageGradient::execute() {
    Image::pointer input = getStaticInputData<Image>(0);
    Image::pointer output = getStaticOutputData<Image>(0);

    // Initialize output image
    if(input->getDimensions() == 2) {
        output->create2DImage(
                input->getWidth(),
                input->getHeight(),
                TYPE_FLOAT,
                2,
                getMainDevice()
                );
    } else {
         output->create3DImage(
                input->getWidth(),
                input->getHeight(),
                input->getDepth(),
                TYPE_FLOAT,
                3,
                getMainDevice()
                );
    }

    if(getMainDevice()->isHost()) {
        throw Exception("Not implemented yet.");
    } else {
        OpenCLDevice::pointer device = OpenCLDevice::pointer(getMainDevice());
        std::string buildOptions = "";
        if(input->getDataType() == TYPE_FLOAT) {
            buildOptions = "-DTYPE_FLOAT";
        } else if(input->getDataType() == TYPE_INT8 || input->getDataType() == TYPE_INT16) {
            buildOptions = "-DTYPE_INT";
        } else {
            buildOptions = "-DTYPE_UINT";
        }
        int programNr = device->createProgramFromSource(std::string(FAST_SOURCE_DIR) + "Algorithms/ImageGradient/ImageGradient.cl", buildOptions);
        cl::Program program = device->getProgram(programNr);
        cl::Kernel kernel;
        if(input->getDimensions() == 2) {
            kernel = cl::Kernel(program, "gradient2D");
            OpenCLImageAccess2D inputAccess = input->getOpenCLImageAccess2D(ACCESS_READ, device);
            OpenCLImageAccess2D outputAccess = output->getOpenCLImageAccess2D(ACCESS_READ_WRITE, device);
            kernel.setArg(0, *inputAccess.get());
            kernel.setArg(1, *outputAccess.get());
        } else {
            kernel = cl::Kernel(program, "gradient3D");
            OpenCLImageAccess3D inputAccess = input->getOpenCLImageAccess3D(ACCESS_READ, device);
            kernel.setArg(0, *inputAccess.get());

            const bool writingTo3DTextures = device->getDevice().getInfo<CL_DEVICE_EXTENSIONS>().find("cl_khr_3d_image_writes") != std::string::npos;
            if(writingTo3DTextures) {
                OpenCLImageAccess3D outputAccess = output->getOpenCLImageAccess3D(ACCESS_READ_WRITE, device);
                kernel.setArg(1, *outputAccess.get());
            } else {
                // If device does not support writing to 3D textures, use a buffer instead
                OpenCLBufferAccess outputAccess = output->getOpenCLBufferAccess(ACCESS_READ_WRITE, device);
                kernel.setArg(1, *outputAccess.get());
            }
        }

        device->getCommandQueue().enqueueNDRangeKernel(
                kernel,
                cl::NullRange,
                cl::NDRange(input->getWidth(), input->getHeight(), input->getDepth()),
                cl::NullRange
        );
    }
}

}

<|endoftext|>


<commit_before>//===-- SystemInitializerCommon.cpp -----------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "lldb/Initialization/SystemInitializerCommon.h"

#include "lldb/Host/Host.h"
#include "lldb/Host/HostInfo.h"
#include "lldb/Core/Log.h"
#include "lldb/Core/Timer.h"
#include "lldb/Symbol/GoASTContext.h"
#include "lldb/Symbol/ClangASTContext.h"
#include "Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderMacOSXDYLD.h"
#include "Plugins/DynamicLoader/POSIX-DYLD/DynamicLoaderPOSIXDYLD.h"
#include "Plugins/DynamicLoader/Windows-DYLD/DynamicLoaderWindowsDYLD.h"
#include "Plugins/Instruction/ARM/EmulateInstructionARM.h"
#include "Plugins/Instruction/MIPS/EmulateInstructionMIPS.h"
#include "Plugins/Instruction/MIPS64/EmulateInstructionMIPS64.h"
#include "Plugins/ObjectContainer/BSD-Archive/ObjectContainerBSDArchive.h"
#include "Plugins/ObjectContainer/Universal-Mach-O/ObjectContainerUniversalMachO.h"
#include "Plugins/ObjectFile/ELF/ObjectFileELF.h"
#include "Plugins/ObjectFile/PECOFF/ObjectFilePECOFF.h"
#include "Plugins/OperatingSystem/Python/OperatingSystemPython.h"
#include "Plugins/OperatingSystem/Go/OperatingSystemGo.h"
#include "Plugins/Platform/Android/PlatformAndroid.h"
#include "Plugins/Platform/FreeBSD/PlatformFreeBSD.h"
#include "Plugins/Platform/Kalimba/PlatformKalimba.h"
#include "Plugins/Platform/Linux/PlatformLinux.h"
#include "Plugins/Platform/MacOSX/PlatformMacOSX.h"
#include "Plugins/Platform/MacOSX/PlatformRemoteiOS.h"
#include "Plugins/Platform/NetBSD/PlatformNetBSD.h"
#include "Plugins/Platform/Windows/PlatformWindows.h"
#include "Plugins/Process/gdb-remote/ProcessGDBRemoteLog.h"

#if defined(__APPLE__)
#include "Plugins/Platform/MacOSX/PlatformiOSSimulator.h"
#include "Plugins/DynamicLoader/Darwin-Kernel/DynamicLoaderDarwinKernel.h"
#include "Plugins/ObjectFile/Mach-O/ObjectFileMachO.h"
#include "Plugins/Platform/MacOSX/PlatformDarwinKernel.h"
#endif

#if defined(__linux__)
#include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
#endif

#if defined(_MSC_VER)
#include "lldb/Host/windows/windows.h"
#include "Plugins/Process/Windows/Common/ProcessWindowsLog.h"
#endif

#include "llvm/Support/TargetSelect.h"

#include <string>

using namespace lldb_private;

static void
fatal_error_handler(void *user_data, const std::string &reason, bool gen_crash_diag)
{
    Host::SetCrashDescription(reason.c_str());
    ::abort();
}

SystemInitializerCommon::SystemInitializerCommon()
{
}

SystemInitializerCommon::~SystemInitializerCommon()
{
}

void
SystemInitializerCommon::Initialize()
{
#if defined(_MSC_VER)
    const char *disable_crash_dialog_var = getenv("LLDB_DISABLE_CRASH_DIALOG");
    if (disable_crash_dialog_var && llvm::StringRef(disable_crash_dialog_var).equals_lower("true"))
    {
        // This will prevent Windows from displaying a dialog box requiring user interaction when
        // LLDB crashes.  This is mostly useful when automating LLDB, for example via the test
        // suite, so that a crash in LLDB does not prevent completion of the test suite.
        ::SetErrorMode(GetErrorMode() | SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);

        _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
        _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
        _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
        _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
        _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
        _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);
    }
#endif

    Log::Initialize();
    HostInfo::Initialize();
    Timer::Initialize();
    Timer scoped_timer(__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);

    llvm::install_fatal_error_handler(fatal_error_handler, 0);

    process_gdb_remote::ProcessGDBRemoteLog::Initialize();

    // Initialize plug-ins
    ClangASTContext::Initialize();
    GoASTContext::Initialize();

    ObjectContainerBSDArchive::Initialize();
    ObjectFileELF::Initialize();
    ObjectFilePECOFF::Initialize();
    DynamicLoaderPOSIXDYLD::Initialize();
    DynamicLoaderWindowsDYLD::Initialize();
    platform_freebsd::PlatformFreeBSD::Initialize();
    platform_linux::PlatformLinux::Initialize();
    platform_netbsd::PlatformNetBSD::Initialize();
    PlatformWindows::Initialize();
    PlatformKalimba::Initialize();
    platform_android::PlatformAndroid::Initialize();

    EmulateInstructionARM::Initialize();
    EmulateInstructionMIPS::Initialize();
    EmulateInstructionMIPS64::Initialize();

    //----------------------------------------------------------------------
    // Apple/Darwin hosted plugins
    //----------------------------------------------------------------------
    DynamicLoaderMacOSXDYLD::Initialize();
    ObjectContainerUniversalMachO::Initialize();

    PlatformRemoteiOS::Initialize();
    PlatformMacOSX::Initialize();

#if defined(__APPLE__)
    PlatformiOSSimulator::Initialize();
    DynamicLoaderDarwinKernel::Initialize();
    PlatformDarwinKernel::Initialize();
    ObjectFileMachO::Initialize();
#endif
#if defined(__linux__)
    static ConstString g_linux_log_name("linux");
    ProcessPOSIXLog::Initialize(g_linux_log_name);
#endif
#if defined(_MSC_VER)
    ProcessWindowsLog::Initialize();
#endif
#ifndef LLDB_DISABLE_PYTHON
    OperatingSystemPython::Initialize();
#endif
    OperatingSystemGo::Initialize();
}

void
SystemInitializerCommon::Terminate()
{
    Timer scoped_timer(__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
    ObjectContainerBSDArchive::Terminate();
    ObjectFileELF::Terminate();
    ObjectFilePECOFF::Terminate();
    DynamicLoaderPOSIXDYLD::Terminate();
    DynamicLoaderWindowsDYLD::Terminate();
    platform_freebsd::PlatformFreeBSD::Terminate();
    platform_linux::PlatformLinux::Terminate();
    platform_netbsd::PlatformNetBSD::Terminate();
    PlatformWindows::Terminate();
    PlatformKalimba::Terminate();
    platform_android::PlatformAndroid::Terminate();
    DynamicLoaderMacOSXDYLD::Terminate();
    ObjectContainerUniversalMachO::Terminate();
    PlatformMacOSX::Terminate();
    PlatformRemoteiOS::Terminate();

    ClangASTContext::Terminate();
    GoASTContext::Terminate();

    EmulateInstructionARM::Terminate();
    EmulateInstructionMIPS::Terminate();
    EmulateInstructionMIPS64::Terminate();

#if defined(__APPLE__)
    PlatformiOSSimulator::Terminate();
    DynamicLoaderDarwinKernel::Terminate();
    ObjectFileMachO::Terminate();
    PlatformDarwinKernel::Terminate();
#endif

#if defined(_MSC_VER)
    ProcessWindowsLog::Terminate();
#endif

#ifndef LLDB_DISABLE_PYTHON
    OperatingSystemPython::Terminate();
#endif
    OperatingSystemGo::Terminate();

    Log::Terminate();
}
<commit_msg>Revert "Plug-in PlatformNetBSD initializer and terminator"<commit_after>//===-- SystemInitializerCommon.cpp -----------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "lldb/Initialization/SystemInitializerCommon.h"

#include "lldb/Host/Host.h"
#include "lldb/Host/HostInfo.h"
#include "lldb/Core/Log.h"
#include "lldb/Core/Timer.h"
#include "lldb/Symbol/GoASTContext.h"
#include "lldb/Symbol/ClangASTContext.h"
#include "Plugins/DynamicLoader/MacOSX-DYLD/DynamicLoaderMacOSXDYLD.h"
#include "Plugins/DynamicLoader/POSIX-DYLD/DynamicLoaderPOSIXDYLD.h"
#include "Plugins/DynamicLoader/Windows-DYLD/DynamicLoaderWindowsDYLD.h"
#include "Plugins/Instruction/ARM/EmulateInstructionARM.h"
#include "Plugins/Instruction/MIPS/EmulateInstructionMIPS.h"
#include "Plugins/Instruction/MIPS64/EmulateInstructionMIPS64.h"
#include "Plugins/ObjectContainer/BSD-Archive/ObjectContainerBSDArchive.h"
#include "Plugins/ObjectContainer/Universal-Mach-O/ObjectContainerUniversalMachO.h"
#include "Plugins/ObjectFile/ELF/ObjectFileELF.h"
#include "Plugins/ObjectFile/PECOFF/ObjectFilePECOFF.h"
#include "Plugins/OperatingSystem/Python/OperatingSystemPython.h"
#include "Plugins/OperatingSystem/Go/OperatingSystemGo.h"
#include "Plugins/Platform/Android/PlatformAndroid.h"
#include "Plugins/Platform/FreeBSD/PlatformFreeBSD.h"
#include "Plugins/Platform/Kalimba/PlatformKalimba.h"
#include "Plugins/Platform/Linux/PlatformLinux.h"
#include "Plugins/Platform/MacOSX/PlatformMacOSX.h"
#include "Plugins/Platform/MacOSX/PlatformRemoteiOS.h"
#include "Plugins/Platform/NetBSD/PlatformNetBSD.h"
#include "Plugins/Platform/Windows/PlatformWindows.h"
#include "Plugins/Process/gdb-remote/ProcessGDBRemoteLog.h"

#if defined(__APPLE__)
#include "Plugins/Platform/MacOSX/PlatformiOSSimulator.h"
#include "Plugins/DynamicLoader/Darwin-Kernel/DynamicLoaderDarwinKernel.h"
#include "Plugins/ObjectFile/Mach-O/ObjectFileMachO.h"
#include "Plugins/Platform/MacOSX/PlatformDarwinKernel.h"
#endif

#if defined(__linux__)
#include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
#endif

#if defined(_MSC_VER)
#include "lldb/Host/windows/windows.h"
#include "Plugins/Process/Windows/Common/ProcessWindowsLog.h"
#endif

#include "llvm/Support/TargetSelect.h"

#include <string>

using namespace lldb_private;

static void
fatal_error_handler(void *user_data, const std::string &reason, bool gen_crash_diag)
{
    Host::SetCrashDescription(reason.c_str());
    ::abort();
}

SystemInitializerCommon::SystemInitializerCommon()
{
}

SystemInitializerCommon::~SystemInitializerCommon()
{
}

void
SystemInitializerCommon::Initialize()
{
#if defined(_MSC_VER)
    const char *disable_crash_dialog_var = getenv("LLDB_DISABLE_CRASH_DIALOG");
    if (disable_crash_dialog_var && llvm::StringRef(disable_crash_dialog_var).equals_lower("true"))
    {
        // This will prevent Windows from displaying a dialog box requiring user interaction when
        // LLDB crashes.  This is mostly useful when automating LLDB, for example via the test
        // suite, so that a crash in LLDB does not prevent completion of the test suite.
        ::SetErrorMode(GetErrorMode() | SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);

        _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
        _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
        _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
        _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
        _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
        _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);
    }
#endif

    Log::Initialize();
    HostInfo::Initialize();
    Timer::Initialize();
    Timer scoped_timer(__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);

    llvm::install_fatal_error_handler(fatal_error_handler, 0);

    process_gdb_remote::ProcessGDBRemoteLog::Initialize();

    // Initialize plug-ins
    ClangASTContext::Initialize();
    GoASTContext::Initialize();

    ObjectContainerBSDArchive::Initialize();
    ObjectFileELF::Initialize();
    ObjectFilePECOFF::Initialize();
    DynamicLoaderPOSIXDYLD::Initialize();
    DynamicLoaderWindowsDYLD::Initialize();
    platform_freebsd::PlatformFreeBSD::Initialize();
    platform_linux::PlatformLinux::Initialize();
    PlatformWindows::Initialize();
    PlatformKalimba::Initialize();
    platform_android::PlatformAndroid::Initialize();

    EmulateInstructionARM::Initialize();
    EmulateInstructionMIPS::Initialize();
    EmulateInstructionMIPS64::Initialize();

    //----------------------------------------------------------------------
    // Apple/Darwin hosted plugins
    //----------------------------------------------------------------------
    DynamicLoaderMacOSXDYLD::Initialize();
    ObjectContainerUniversalMachO::Initialize();

    PlatformRemoteiOS::Initialize();
    PlatformMacOSX::Initialize();

#if defined(__APPLE__)
    PlatformiOSSimulator::Initialize();
    DynamicLoaderDarwinKernel::Initialize();
    PlatformDarwinKernel::Initialize();
    ObjectFileMachO::Initialize();
#endif
#if defined(__linux__)
    static ConstString g_linux_log_name("linux");
    ProcessPOSIXLog::Initialize(g_linux_log_name);
#endif
#if defined(_MSC_VER)
    ProcessWindowsLog::Initialize();
#endif
#ifndef LLDB_DISABLE_PYTHON
    OperatingSystemPython::Initialize();
#endif
    OperatingSystemGo::Initialize();
}

void
SystemInitializerCommon::Terminate()
{
    Timer scoped_timer(__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
    ObjectContainerBSDArchive::Terminate();
    ObjectFileELF::Terminate();
    ObjectFilePECOFF::Terminate();
    DynamicLoaderPOSIXDYLD::Terminate();
    DynamicLoaderWindowsDYLD::Terminate();
    platform_freebsd::PlatformFreeBSD::Terminate();
    platform_linux::PlatformLinux::Terminate();
    PlatformWindows::Terminate();
    PlatformKalimba::Terminate();
    platform_android::PlatformAndroid::Terminate();
    DynamicLoaderMacOSXDYLD::Terminate();
    ObjectContainerUniversalMachO::Terminate();
    PlatformMacOSX::Terminate();
    PlatformRemoteiOS::Terminate();

    ClangASTContext::Terminate();
    GoASTContext::Terminate();

    EmulateInstructionARM::Terminate();
    EmulateInstructionMIPS::Terminate();
    EmulateInstructionMIPS64::Terminate();

#if defined(__APPLE__)
    PlatformiOSSimulator::Terminate();
    DynamicLoaderDarwinKernel::Terminate();
    ObjectFileMachO::Terminate();
    PlatformDarwinKernel::Terminate();
#endif

#if defined(_MSC_VER)
    ProcessWindowsLog::Terminate();
#endif

#ifndef LLDB_DISABLE_PYTHON
    OperatingSystemPython::Terminate();
#endif
    OperatingSystemGo::Terminate();

    Log::Terminate();
}
<|endoftext|>


<commit_before>//
// This file is part of the Marble Desktop Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2009      Eckhart Wörner <ewoerner@kde.org>
//

#include "GpsdPositionProviderPlugin.h"

#include <QtCore/QDebug>

using namespace Marble;

QString GpsdPositionProviderPlugin::name() const
{
    return tr( "Gpsd position provider Plugin" );
}

QString GpsdPositionProviderPlugin::nameId() const
{
    return QString::fromLatin1( "Gpsd" );
}

QString GpsdPositionProviderPlugin::guiString() const
{
    return tr( "Gpsd position provider plugin" );
}

QString GpsdPositionProviderPlugin::description() const
{
    return tr( "Reports the the position of a GPS device." );
}

QIcon GpsdPositionProviderPlugin::icon() const
{
    return QIcon();
}

void GpsdPositionProviderPlugin::initialize()
{
    m_gpsd = new gpsmm;
    m_gpsdData = m_gpsd->open();
    m_timer = new QTimer;
    connect( m_timer, SIGNAL( timeout() ), this, SLOT( update() ) );
    m_timer->start( 5000 );
    m_initialized = true;
}

void GpsdPositionProviderPlugin::update() {
    m_gpsdData = m_gpsd->query( "o" );
    PositionProviderStatus oldStatus = m_status;
    GeoDataCoordinates oldPosition = m_position;
    if (m_gpsdData->status == STATUS_NO_FIX)
        m_status = PositionProviderStatusUnavailable;
    else {
        m_status = PositionProviderStatusAvailable;
        m_position.set( m_gpsdData->fix.longitude, m_gpsdData->fix.latitude,
        m_gpsdData->fix.altitude, GeoDataCoordinates::Degree );
        m_accuracy.level = GeoDataAccuracy::Detailed;
        // FIXME: Add real values here
        m_accuracy.horizontal = 5;
        m_accuracy.vertical = 5;
    }
    if (m_status != oldStatus)
        emit statusChanged( m_status );
    // FIXME: Check whether position has changed first
    if (m_status == PositionProviderStatusAvailable)
        emit positionChanged( m_position, m_accuracy );
}

bool GpsdPositionProviderPlugin::isInitialized() const
{
    return m_initialized;
}

PositionProviderPlugin* GpsdPositionProviderPlugin::newInstance() const
{
    return new GpsdPositionProviderPlugin;
}

PositionProviderStatus GpsdPositionProviderPlugin::status() const {
    return m_status;
}

GeoDataCoordinates GpsdPositionProviderPlugin::position() const {
    return m_position;
}

GeoDataAccuracy GpsdPositionProviderPlugin::accuracy() const {
    return m_accuracy;
}

GpsdPositionProviderPlugin::GpsdPositionProviderPlugin() : m_initialized(false) {}

GpsdPositionProviderPlugin::~GpsdPositionProviderPlugin()
{
    if (m_initialized) {
        delete m_timer;
        delete m_gpsd;
    }
}

Q_EXPORT_PLUGIN2( GpsdPositionProviderPlugin, Marble::GpsdPositionProviderPlugin )

#include "GpsdPositionProviderPlugin.moc"
<commit_msg>fix segfault for gpsd when building with libgpsd and gpsd is not running<commit_after>//
// This file is part of the Marble Desktop Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2009      Eckhart Wörner <ewoerner@kde.org>
//

#include "GpsdPositionProviderPlugin.h"

#include <QtCore/QDebug>

using namespace Marble;

QString GpsdPositionProviderPlugin::name() const
{
    return tr( "Gpsd position provider Plugin" );
}

QString GpsdPositionProviderPlugin::nameId() const
{
    return QString::fromLatin1( "Gpsd" );
}

QString GpsdPositionProviderPlugin::guiString() const
{
    return tr( "Gpsd position provider plugin" );
}

QString GpsdPositionProviderPlugin::description() const
{
    return tr( "Reports the the position of a GPS device." );
}

QIcon GpsdPositionProviderPlugin::icon() const
{
    return QIcon();
}

void GpsdPositionProviderPlugin::initialize()
{
    m_gpsd = new gpsmm;
    m_gpsdData = m_gpsd->open();
    m_timer = new QTimer;
    connect( m_timer, SIGNAL( timeout() ), this, SLOT( update() ) );
    m_timer->start( 5000 );
    m_initialized = true;
}

void GpsdPositionProviderPlugin::update() {
    //Check that m_gpsd->open() has successfully completed
    if ( m_gpsdData != 0 ) {
        m_gpsdData = m_gpsd->query( "o" );
        PositionProviderStatus oldStatus = m_status;
        GeoDataCoordinates oldPosition = m_position;
        if (m_gpsdData->status == STATUS_NO_FIX)
            m_status = PositionProviderStatusUnavailable;
        else {
            m_status = PositionProviderStatusAvailable;
            m_position.set( m_gpsdData->fix.longitude, m_gpsdData->fix.latitude,
            m_gpsdData->fix.altitude, GeoDataCoordinates::Degree );
            m_accuracy.level = GeoDataAccuracy::Detailed;
            // FIXME: Add real values here
            m_accuracy.horizontal = 5;
            m_accuracy.vertical = 5;
        }
        if (m_status != oldStatus)
            emit statusChanged( m_status );
        // FIXME: Check whether position has changed first
        if (m_status == PositionProviderStatusAvailable)
            emit positionChanged( m_position, m_accuracy );
    }
}

bool GpsdPositionProviderPlugin::isInitialized() const
{
    return m_initialized;
}

PositionProviderPlugin* GpsdPositionProviderPlugin::newInstance() const
{
    return new GpsdPositionProviderPlugin;
}

PositionProviderStatus GpsdPositionProviderPlugin::status() const {
    return m_status;
}

GeoDataCoordinates GpsdPositionProviderPlugin::position() const {
    return m_position;
}

GeoDataAccuracy GpsdPositionProviderPlugin::accuracy() const {
    return m_accuracy;
}

GpsdPositionProviderPlugin::GpsdPositionProviderPlugin() : m_initialized(false) {}

GpsdPositionProviderPlugin::~GpsdPositionProviderPlugin()
{
    if (m_initialized) {
        delete m_timer;
        delete m_gpsd;
    }
}

Q_EXPORT_PLUGIN2( GpsdPositionProviderPlugin, Marble::GpsdPositionProviderPlugin )

#include "GpsdPositionProviderPlugin.moc"
<|endoftext|>


<commit_before>#include <iostream>
#include <boost/bind.hpp>
#include "..//util/util.h"
#include "async_client.h"

namespace twitpp {
namespace net {

namespace asio = boost::asio;

async_client::async_client(const net::method& method, const std::string& url, const std::string& header, const std::string& data)
    : io_service_(std::make_shared<boost::asio::io_service>()), context_(boost::asio::ssl::context_base::tlsv12),
      resolver_(*io_service_), request_stream_(&request_), response_(std::make_shared<net::response>()) {
  auto parsed_url = util::url_parser(url);

  if (!parsed_url) {
    throw std::invalid_argument("failed to parse the url");
  }

  context_.set_verify_mode(boost::asio::ssl::verify_none);
  socket_ = std::make_shared<boost::asio::ssl::stream<boost::asio::ip::tcp::socket>>(*io_service_, context_);

  query_ = std::make_shared<boost::asio::ip::tcp::resolver::query>(std::get<1>(*parsed_url), std::get<0>(*parsed_url));

  switch (method) {
    case net::method::GET:
      request_stream_ << "GET " << std::get<2>(*parsed_url);

      if (!data.empty()) {
        request_stream_ << "?" << data;
      }

      request_stream_ << " HTTP/1.1\r\n";
      break;
    case net::method::POST:
      request_stream_ << "POST " << std::get<2>(*parsed_url) << std::get<3>(*parsed_url) << " HTTP/1.1\r\n";
      break;
  }

  request_stream_ << "Host: " << std::get<1>(*parsed_url) << "\r\n";
  request_stream_ << "Accept: */*\r\n";

  if (!header.empty()) {
    request_stream_ << header << "\r\n";
  }

  if (method == net::method::POST && !data.empty()) {
    request_stream_ << "Content-Length: " << data.length() << "\r\n";
    request_stream_ << "Content-Type: application/x-www-form-urlencoded\r\n";
    request_stream_ << "Connection: close\r\n\r\n";
    request_stream_ << data << "\r\n";
  } else {
    request_stream_ << "Connection: close\r\n\r\n";
  }
}

void async_client::run(const response_handler& handler) {
  handler_ = handler;

  // name resolving
  resolver_.async_resolve(
      *query_, boost::bind(&async_client::handle_resolve, this, asio::placeholders::error, asio::placeholders::iterator));

  io_service_->run();
}

void async_client::handle_resolve(const boost::system::error_code& error, asio::ip::tcp::resolver::iterator endpoint_iterator) {
  if (!error) {
    asio::async_connect(socket_->lowest_layer(), endpoint_iterator,
                        boost::bind(&async_client::handle_connect, this, asio::placeholders::error));
  } else {
    std::cerr << "twitpp::net::async_client: " << "resolve failed: " << error.value() << std::endl;
  }
}

void async_client::handle_connect(const boost::system::error_code& error) {
  if (!error) {
    socket_->async_handshake(asio::ssl::stream_base::client,
                            boost::bind(&async_client::handle_handshake, this, asio::placeholders::error));
  } else {
    std::cerr << "twitpp::net::async_client: " << "connect failed: " << error.value() << std::endl;
  }
}

void async_client::handle_handshake(const boost::system::error_code& error) {
  if (!error) {
    asio::async_write(*socket_, request_, boost::bind(&async_client::handle_write, this, asio::placeholders::error));
  } else {
    std::cerr << "twitpp::net::async_client: " << "handshake failed: " << error.value() << std::endl;
  }
}

void async_client::handle_write(const boost::system::error_code& error) {
  if (!error) {
    asio::async_read_until(*socket_, response_buffer_, "\r\n",
                           boost::bind(&async_client::handle_read_status, this, asio::placeholders::error));
  } else {
    std::cerr << "twitpp::net::async_client: " << "write failed: " << error.value() << std::endl;
  }
}

void async_client::handle_read_status(const boost::system::error_code& error) {
  if (!error) {
    // check response
    std::istream response_stream(&response_buffer_);
    response_stream >> response_->http_version >> response_->status_code >> std::ws;
    std::getline(response_stream, response_->status_message);

    if (!response_stream || response_->http_version.substr(0, 5) != "HTTP/") {
      std::cerr << "twitpp::net::async_client: " << "invalid response" << std::endl;
      return;
    }

    // read response header
    asio::async_read_until(*socket_, response_buffer_, "\r\n\r\n",
                           boost::bind(&async_client::handle_read_header, this, asio::placeholders::error));
  } else {
    std::cerr << "twitpp::net::async_client: " << "read status failed: " << error.value() << std::endl;
  }
}

void async_client::handle_read_header(const boost::system::error_code& error) {
  if (!error) {
    // read response header
    std::istream response_stream(&response_buffer_);
    for (std::string s; std::getline(response_stream, s, ':') && s[0] != '\r';) {
      response_stream >> std::ws;
      std::getline(response_stream, response_->header[s], '\r');
      response_stream >> std::ws;
    }

    if (response_->header["transfer-encoding"] == "chunked") {
      // chuncked transfer
      asio::async_read_until(*socket_, response_buffer_, "\r\n",
                             boost::bind(&async_client::handle_read_chunk_size, this, asio::placeholders::error));
    } else if (response_->header.count("Content-Length") != 0) {
      // use content length
      std::size_t content_length = std::stoi(response_->header["Content-Length"]);

      asio::async_read(*socket_, response_buffer_,
                       asio::transfer_at_least(content_length - asio::buffer_size(response_buffer_.data())),
                       boost::bind(&async_client::handle_read_content, this, content_length, asio::placeholders::error));
    } else if (response_->header.count("content-length") != 0) {
      std::size_t content_length = std::stoi(response_->header["content-length"]);

      asio::async_read(*socket_, response_buffer_,
                       asio::transfer_at_least(content_length - asio::buffer_size(response_buffer_.data())),
                       boost::bind(&async_client::handle_read_content, this, content_length, asio::placeholders::error));
    } else {
      // other (not working now
      asio::async_read(*socket_, response_buffer_, asio::transfer_all(),
                       boost::bind(&async_client::handle_read_content_all, this, asio::placeholders::error));
    }

  } else {
    std::cerr << "twitpp::net::async_client: " << "read header failed: " << error.value() << std::endl;
  }
}

void async_client::handle_read_chunk_size(const boost::system::error_code& error) {
  if (!error) {
    if (response_buffer_.size() == 0) {
      return;
    } else if (response_buffer_.size() <= 2) {
      response_buffer_.consume(response_buffer_.size());
      asio::async_read_until(*socket_, response_buffer_, "\r\n",
                             boost::bind(&async_client::handle_read_chunk_size, this, asio::placeholders::error));
    } else {
      // read chunk size
      std::size_t chunk_size = std::strtoul(asio::buffer_cast<const char*>(response_buffer_.data()), nullptr, 16);
      response_buffer_.consume(chunk_size);

      if (chunk_size > 0) {
        // read chunk
        asio::async_read(*socket_, response_buffer_,
                         asio::transfer_at_least(chunk_size - asio::buffer_size(response_buffer_.data())),
                         boost::bind(&async_client::handle_read_chunk_body, this, chunk_size, asio::placeholders::error));
      } else {
        // end
        return;
      }
    }
  } else if (error != asio::error::eof) {
    std::cerr << "twitpp::net::async_client: " << "read chunksize failed: " << error.value() << std::endl;
  }
}

void async_client::handle_read_chunk_body(std::size_t content_length, const boost::system::error_code& error) {
  if (!error) {
    boost::system::error_code ec;
    asio::read(*socket_, response_buffer_,
               asio::transfer_at_least((content_length + 2) - asio::buffer_size(response_buffer_.data())), ec);

    response_->body.append(boost::asio::buffer_cast<const char*>(response_buffer_.data()), content_length);
    response_buffer_.consume(content_length + 2);
    handler_(*response_);

    asio::async_read_until(*socket_, response_buffer_, "\r\n",
                           boost::bind(&async_client::handle_read_chunk_size, this, asio::placeholders::error));
  } else if (error != asio::error::eof) {
    std::cerr << "twitpp::net::async_client: " << "read chunk failed: " << error.value() << std::endl;
  }
}

void async_client::handle_read_content(std::size_t content_length, const boost::system::error_code& error) {
  if (!error) {
    response_->body.append(asio::buffers_begin(response_buffer_.data()), asio::buffers_end(response_buffer_.data()));
    response_buffer_.consume(content_length);
    handler_(*response_);
  } else if (error != asio::error::eof) {
    std::cerr << "twitpp::net::async_client: " << "read content failed: " << error.value() << std::endl;
  }
}

void async_client::handle_read_content_all(const boost::system::error_code& error) {
  if (!error) {
    std::ostringstream tmp;
    tmp << &response_buffer_;
    response_->body = tmp.str();
    handler_(*response_);

    // Continue reading remaining data until EOF.
    asio::async_read(*socket_, response_buffer_, asio::transfer_at_least(1),
                     boost::bind(&async_client::handle_read_content_all, this, asio::placeholders::error));
  } else if (error != asio::error::eof) {
    std::cerr << "twitpp::net::async_client: " << "read content all failed: " << error.value() << std::endl;
  }
}

} // namespace net
} // namespace twitpp
<commit_msg>fix typo<commit_after>#include <iostream>
#include <boost/bind.hpp>
#include "../util/util.h"
#include "async_client.h"

namespace twitpp {
namespace net {

namespace asio = boost::asio;

async_client::async_client(const net::method& method, const std::string& url, const std::string& header, const std::string& data)
    : io_service_(std::make_shared<boost::asio::io_service>()), context_(boost::asio::ssl::context_base::tlsv12),
      resolver_(*io_service_), request_stream_(&request_), response_(std::make_shared<net::response>()) {
  auto parsed_url = util::url_parser(url);

  if (!parsed_url) {
    throw std::invalid_argument("failed to parse the url");
  }

  context_.set_verify_mode(boost::asio::ssl::verify_none);
  socket_ = std::make_shared<boost::asio::ssl::stream<boost::asio::ip::tcp::socket>>(*io_service_, context_);

  query_ = std::make_shared<boost::asio::ip::tcp::resolver::query>(std::get<1>(*parsed_url), std::get<0>(*parsed_url));

  switch (method) {
    case net::method::GET:
      request_stream_ << "GET " << std::get<2>(*parsed_url);

      if (!data.empty()) {
        request_stream_ << "?" << data;
      }

      request_stream_ << " HTTP/1.1\r\n";
      break;
    case net::method::POST:
      request_stream_ << "POST " << std::get<2>(*parsed_url) << std::get<3>(*parsed_url) << " HTTP/1.1\r\n";
      break;
  }

  request_stream_ << "Host: " << std::get<1>(*parsed_url) << "\r\n";
  request_stream_ << "Accept: */*\r\n";

  if (!header.empty()) {
    request_stream_ << header << "\r\n";
  }

  if (method == net::method::POST && !data.empty()) {
    request_stream_ << "Content-Length: " << data.length() << "\r\n";
    request_stream_ << "Content-Type: application/x-www-form-urlencoded\r\n";
    request_stream_ << "Connection: close\r\n\r\n";
    request_stream_ << data << "\r\n";
  } else {
    request_stream_ << "Connection: close\r\n\r\n";
  }
}

void async_client::run(const response_handler& handler) {
  handler_ = handler;

  // name resolving
  resolver_.async_resolve(
      *query_, boost::bind(&async_client::handle_resolve, this, asio::placeholders::error, asio::placeholders::iterator));

  io_service_->run();
}

void async_client::handle_resolve(const boost::system::error_code& error, asio::ip::tcp::resolver::iterator endpoint_iterator) {
  if (!error) {
    asio::async_connect(socket_->lowest_layer(), endpoint_iterator,
                        boost::bind(&async_client::handle_connect, this, asio::placeholders::error));
  } else {
    std::cerr << "twitpp::net::async_client: " << "resolve failed: " << error.value() << std::endl;
  }
}

void async_client::handle_connect(const boost::system::error_code& error) {
  if (!error) {
    socket_->async_handshake(asio::ssl::stream_base::client,
                            boost::bind(&async_client::handle_handshake, this, asio::placeholders::error));
  } else {
    std::cerr << "twitpp::net::async_client: " << "connect failed: " << error.value() << std::endl;
  }
}

void async_client::handle_handshake(const boost::system::error_code& error) {
  if (!error) {
    asio::async_write(*socket_, request_, boost::bind(&async_client::handle_write, this, asio::placeholders::error));
  } else {
    std::cerr << "twitpp::net::async_client: " << "handshake failed: " << error.value() << std::endl;
  }
}

void async_client::handle_write(const boost::system::error_code& error) {
  if (!error) {
    asio::async_read_until(*socket_, response_buffer_, "\r\n",
                           boost::bind(&async_client::handle_read_status, this, asio::placeholders::error));
  } else {
    std::cerr << "twitpp::net::async_client: " << "write failed: " << error.value() << std::endl;
  }
}

void async_client::handle_read_status(const boost::system::error_code& error) {
  if (!error) {
    // check response
    std::istream response_stream(&response_buffer_);
    response_stream >> response_->http_version >> response_->status_code >> std::ws;
    std::getline(response_stream, response_->status_message);

    if (!response_stream || response_->http_version.substr(0, 5) != "HTTP/") {
      std::cerr << "twitpp::net::async_client: " << "invalid response" << std::endl;
      return;
    }

    // read response header
    asio::async_read_until(*socket_, response_buffer_, "\r\n\r\n",
                           boost::bind(&async_client::handle_read_header, this, asio::placeholders::error));
  } else {
    std::cerr << "twitpp::net::async_client: " << "read status failed: " << error.value() << std::endl;
  }
}

void async_client::handle_read_header(const boost::system::error_code& error) {
  if (!error) {
    // read response header
    std::istream response_stream(&response_buffer_);
    for (std::string s; std::getline(response_stream, s, ':') && s[0] != '\r';) {
      response_stream >> std::ws;
      std::getline(response_stream, response_->header[s], '\r');
      response_stream >> std::ws;
    }

    if (response_->header["transfer-encoding"] == "chunked") {
      // chuncked transfer
      asio::async_read_until(*socket_, response_buffer_, "\r\n",
                             boost::bind(&async_client::handle_read_chunk_size, this, asio::placeholders::error));
    } else if (response_->header.count("Content-Length") != 0) {
      // use content length
      std::size_t content_length = std::stoi(response_->header["Content-Length"]);

      asio::async_read(*socket_, response_buffer_,
                       asio::transfer_at_least(content_length - asio::buffer_size(response_buffer_.data())),
                       boost::bind(&async_client::handle_read_content, this, content_length, asio::placeholders::error));
    } else if (response_->header.count("content-length") != 0) {
      std::size_t content_length = std::stoi(response_->header["content-length"]);

      asio::async_read(*socket_, response_buffer_,
                       asio::transfer_at_least(content_length - asio::buffer_size(response_buffer_.data())),
                       boost::bind(&async_client::handle_read_content, this, content_length, asio::placeholders::error));
    } else {
      // other (not working now
      asio::async_read(*socket_, response_buffer_, asio::transfer_all(),
                       boost::bind(&async_client::handle_read_content_all, this, asio::placeholders::error));
    }

  } else {
    std::cerr << "twitpp::net::async_client: " << "read header failed: " << error.value() << std::endl;
  }
}

void async_client::handle_read_chunk_size(const boost::system::error_code& error) {
  if (!error) {
    if (response_buffer_.size() == 0) {
      return;
    } else if (response_buffer_.size() <= 2) {
      response_buffer_.consume(response_buffer_.size());
      asio::async_read_until(*socket_, response_buffer_, "\r\n",
                             boost::bind(&async_client::handle_read_chunk_size, this, asio::placeholders::error));
    } else {
      // read chunk size
      std::size_t chunk_size = std::strtoul(asio::buffer_cast<const char*>(response_buffer_.data()), nullptr, 16);
      response_buffer_.consume(chunk_size);

      if (chunk_size > 0) {
        // read chunk
        asio::async_read(*socket_, response_buffer_,
                         asio::transfer_at_least(chunk_size - asio::buffer_size(response_buffer_.data())),
                         boost::bind(&async_client::handle_read_chunk_body, this, chunk_size, asio::placeholders::error));
      } else {
        // end
        return;
      }
    }
  } else if (error != asio::error::eof) {
    std::cerr << "twitpp::net::async_client: " << "read chunksize failed: " << error.value() << std::endl;
  }
}

void async_client::handle_read_chunk_body(std::size_t content_length, const boost::system::error_code& error) {
  if (!error) {
    boost::system::error_code ec;
    asio::read(*socket_, response_buffer_,
               asio::transfer_at_least((content_length + 2) - asio::buffer_size(response_buffer_.data())), ec);

    response_->body.append(boost::asio::buffer_cast<const char*>(response_buffer_.data()), content_length);
    response_buffer_.consume(content_length + 2);
    handler_(*response_);

    asio::async_read_until(*socket_, response_buffer_, "\r\n",
                           boost::bind(&async_client::handle_read_chunk_size, this, asio::placeholders::error));
  } else if (error != asio::error::eof) {
    std::cerr << "twitpp::net::async_client: " << "read chunk failed: " << error.value() << std::endl;
  }
}

void async_client::handle_read_content(std::size_t content_length, const boost::system::error_code& error) {
  if (!error) {
    response_->body.append(asio::buffers_begin(response_buffer_.data()), asio::buffers_end(response_buffer_.data()));
    response_buffer_.consume(content_length);
    handler_(*response_);
  } else if (error != asio::error::eof) {
    std::cerr << "twitpp::net::async_client: " << "read content failed: " << error.value() << std::endl;
  }
}

void async_client::handle_read_content_all(const boost::system::error_code& error) {
  if (!error) {
    std::ostringstream tmp;
    tmp << &response_buffer_;
    response_->body = tmp.str();
    handler_(*response_);

    // Continue reading remaining data until EOF.
    asio::async_read(*socket_, response_buffer_, asio::transfer_at_least(1),
                     boost::bind(&async_client::handle_read_content_all, this, asio::placeholders::error));
  } else if (error != asio::error::eof) {
    std::cerr << "twitpp::net::async_client: " << "read content all failed: " << error.value() << std::endl;
  }
}

} // namespace net
} // namespace twitpp
<|endoftext|>


<commit_before>#include "Dual_Constraint_Group.hxx"
#include "../../../SDP.hxx"

// Collect a bunch of Dual_Constraint_Group's and a dual objective
// function into an SDP.

void fill_from_dual_constraint_groups(
  const Vector &dual_objective_b, const Real &objective_const,
  const std::vector<Dual_Constraint_Group> &dualConstraintGroups, SDP &sdp)
{
  sdp.dual_objective_b = dual_objective_b;
  sdp.objective_const = objective_const;

  for(std::vector<Dual_Constraint_Group>::const_iterator g
      = dualConstraintGroups.begin();
      g != dualConstraintGroups.end(); g++)
    {
      sdp.dimensions.push_back(g->dim);
      sdp.degrees.push_back(g->degree);

      // sdp.primal_objective is the concatenation of the
      // g.constraintConstants
      sdp.primal_objective_c.insert(sdp.primal_objective_c.end(),
                                    g->constraintConstants.begin(),
                                    g->constraintConstants.end());
    }
  sdp.free_var_matrix
    = Matrix(sdp.primal_objective_c.size(), sdp.dual_objective_b.size());

  int p = 0;
  // Each g corresponds to an index 0 <= j < J (not used explicitly here)
  for(std::vector<Dual_Constraint_Group>::const_iterator g
      = dualConstraintGroups.begin();
      g != dualConstraintGroups.end(); g++)
    {
      // sdp.bilinear_bases is the concatenation of the g.bilinearBases.
      // The matrix Y is a BlockDiagonalMatrix built from the
      // concatenation of the blocks for each individual
      // Dual_Constraint_Group.  sdp.blocks[j] = {b1, b2, ... } contains
      // the indices for the blocks of Y corresponding to the j-th
      // group.
      std::vector<int> blocks;
      for(std::vector<Matrix>::const_iterator b = g->bilinearBases.begin();
          b != g->bilinearBases.end(); b++)
        {
          // Ensure that each bilinearBasis is sampled the correct number
          // of times
          assert(b->cols == g->degree + 1);
          blocks.push_back(sdp.bilinear_bases.size());
          sdp.bilinear_bases.push_back(*b);
        }
      sdp.blocks.push_back(blocks);

      // sdp.free_var_matrix is the block-wise concatenation of the
      // g.constraintMatrix's
      for(int k = 0; k < g->constraintMatrix.rows; k++, p++)
        for(int n = 0; n < g->constraintMatrix.cols; n++)
          sdp.free_var_matrix.elt(p, n) = g->constraintMatrix.elt(k, n);
    }
  assert(p == static_cast<int>(sdp.primal_objective_c.size()));

  sdp.initialize_constraint_indices();
}
<commit_msg>Use range-based for<commit_after>#include "Dual_Constraint_Group.hxx"
#include "../../../SDP.hxx"

// Collect a bunch of Dual_Constraint_Group's and a dual objective
// function into an SDP.

void fill_from_dual_constraint_groups(
  const Vector &dual_objective_b, const Real &objective_const,
  const std::vector<Dual_Constraint_Group> &dualConstraintGroups, SDP &sdp)
{
  sdp.dual_objective_b = dual_objective_b;
  sdp.objective_const = objective_const;

  for(auto &g : dualConstraintGroups)
    {
      sdp.dimensions.push_back(g.dim);
      sdp.degrees.push_back(g.degree);

      // sdp.primal_objective is the concatenation of the
      // g.constraintConstants
      sdp.primal_objective_c.insert(sdp.primal_objective_c.end(),
                                    g.constraintConstants.begin(),
                                    g.constraintConstants.end());
    }
  sdp.free_var_matrix
    = Matrix(sdp.primal_objective_c.size(), sdp.dual_objective_b.size());

  int p = 0;
  // Each g corresponds to an index 0 <= j < J (not used explicitly here)
  for(auto &g : dualConstraintGroups)
    {
      // sdp.bilinear_bases is the concatenation of the g.bilinearBases.
      // The matrix Y is a BlockDiagonalMatrix built from the
      // concatenation of the blocks for each individual
      // Dual_Constraint_Group.  sdp.blocks[j] = {b1, b2, ... } contains
      // the indices for the blocks of Y corresponding to the j-th
      // group.
      std::vector<int> blocks;
      for(auto &b : g.bilinearBases)
        {
          // Ensure that each bilinearBasis is sampled the correct number
          // of times
          assert(b.cols == g.degree + 1);
          blocks.push_back(sdp.bilinear_bases.size());
          sdp.bilinear_bases.push_back(b);
        }
      sdp.blocks.push_back(blocks);

      // sdp.free_var_matrix is the block-wise concatenation of the
      // g.constraintMatrix's
      for(int k = 0; k < g.constraintMatrix.rows; k++, p++)
        for(int n = 0; n < g.constraintMatrix.cols; n++)
          {
            sdp.free_var_matrix.elt(p, n) = g.constraintMatrix.elt(k, n);
          }
    }
  assert(p == static_cast<int>(sdp.primal_objective_c.size()));

  sdp.initialize_constraint_indices();
}
<|endoftext|>