<commit_before>//===--- RuntimeEntrySymbols.cpp - Define symbols for runtime entries  --===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
//  This file defines function pointer symbols for runtime entries.
//
//===----------------------------------------------------------------------===//

// Produce global symbols referencing runtime function implementations only for
// those runtime entries that demand it.
//
// Each runtime function definition in RuntimeFunctions.def should
// indicate if it requires a global referencing it.
//
// For example, all entries using the RegisterPreservingCC calling convention
// need a global, because they are currently always invoked indirectly using a
// client-side wrapper.
//
// Runtime entries using the DefaultCC calling convention do not
// demand a global symbol by default. But they can optionally ask for it, in
// case it is needed. For example, _swift_isDeallocating is required by
// Instruments.

#include "swift/Runtime/Config.h"

// Entry points using a standard C calling convention or not using the new
// calling convention do not need to have global symbols referring to their
// implementations.
#define FOR_CONV_DefaultCC(...)
#define FOR_CONV_C_CC(...)
// Entry points using the new calling convention require global symbols
// referring to their implementations.
#define FOR_CONV_RegisterPreservingCC(x) x

typedef void (*RuntimeEntry)();

// Generate a forward declaration of the runtime entry implementation.
// Define a global symbol referring to this implementation.

#define DEFINE_SYMBOL(SymbolName, Name, CC)                                    \
  SWIFT_RT_ENTRY_VISIBILITY extern "C" void Name()                             \
      SWIFT_CC(CC);                                                            \
  SWIFT_RUNTIME_EXPORT extern "C" RuntimeEntry SymbolName =                    \
      reinterpret_cast<RuntimeEntry>(Name);

#define FUNCTION1(Id, Name, CC, ReturnTys, ArgTys, Attrs)                      \
  DEFINE_SYMBOL(SWIFT_RT_ENTRY_REF(Name), Name, CC)

#if defined(SWIFT_RT_USE_WRAPPERS)
// Automatically generate a global symbol name if it is required by the calling
// convention.
#define FUNCTION(Id, Name, CC, ReturnTys, ArgTys, Attrs)                       \
  FOR_CONV_##CC(FUNCTION1(Id, Name, CC, ReturnTys, ArgTys, Attrs))
#else
// No need to generate any global symbols for entries that do not provide their
// own symbols.
#define FUNCTION(Id, Name, CC, ReturnTys, ArgTys, Attrs)
#endif
// Allow for a custom global symbol name and implementation.
#define FUNCTION_WITH_GLOBAL_SYMBOL_AND_IMPL(Id, Name, GlobalSymbolName, Impl, \
                                             CC, ReturnTys, ArgTys, Attrs)     \
  DEFINE_SYMBOL(GlobalSymbolName, Impl, CC)

// Indicate that we are going to generate the global symbols for those runtime
// functions that require it.
#define SWIFT_RUNTIME_GENERATE_GLOBAL_SYMBOLS 1

namespace swift {
// Generate global symbols which are function pointers to the actual
// implementations of runtime entry points.
// This is done only for entry points using a new calling convention or
// for those entry points which explicitly require it.
#include "swift/Runtime/RuntimeFunctions.def"
}

<commit_msg>Set proper linkage on external declarations of runtime functions implementations.<commit_after>//===--- RuntimeEntrySymbols.cpp - Define symbols for runtime entries  --===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
//  This file defines function pointer symbols for runtime entries.
//
//===----------------------------------------------------------------------===//

// Produce global symbols referencing runtime function implementations only for
// those runtime entries that demand it.
//
// Each runtime function definition in RuntimeFunctions.def should
// indicate if it requires a global referencing it.
//
// For example, all entries using the RegisterPreservingCC calling convention
// need a global, because they are currently always invoked indirectly using a
// client-side wrapper.
//
// Runtime entries using the DefaultCC calling convention do not
// demand a global symbol by default. But they can optionally ask for it, in
// case it is needed. For example, _swift_isDeallocating is required by
// Instruments.

#include "swift/Runtime/Config.h"

// Entry points using a standard C calling convention or not using the new
// calling convention do not need to have global symbols referring to their
// implementations.
#define FOR_CONV_DefaultCC(...)
#define FOR_CONV_C_CC(...)
// Entry points using the new calling convention require global symbols
// referring to their implementations.
#define FOR_CONV_RegisterPreservingCC(x) x

typedef void (*RuntimeEntry)();

// Generate a forward declaration of the runtime entry implementation.
// Define a global symbol referring to this implementation.

#define DEFINE_SYMBOL(SymbolName, Name, CC)                                    \
  SWIFT_RT_ENTRY_IMPL_VISIBILITY extern "C" void Name()                        \
      SWIFT_CC(CC);                                                            \
  SWIFT_RUNTIME_EXPORT extern "C" RuntimeEntry SymbolName =                    \
      reinterpret_cast<RuntimeEntry>(Name);

#define FUNCTION1(Id, Name, CC, ReturnTys, ArgTys, Attrs)                      \
  DEFINE_SYMBOL(SWIFT_RT_ENTRY_REF(Name), Name, CC)

#if defined(SWIFT_RT_USE_WRAPPERS)
// Automatically generate a global symbol name if it is required by the calling
// convention.
#define FUNCTION(Id, Name, CC, ReturnTys, ArgTys, Attrs)                       \
  FOR_CONV_##CC(FUNCTION1(Id, Name, CC, ReturnTys, ArgTys, Attrs))
#else
// No need to generate any global symbols for entries that do not provide their
// own symbols.
#define FUNCTION(Id, Name, CC, ReturnTys, ArgTys, Attrs)
#endif
// Allow for a custom global symbol name and implementation.
#define FUNCTION_WITH_GLOBAL_SYMBOL_AND_IMPL(Id, Name, GlobalSymbolName, Impl, \
                                             CC, ReturnTys, ArgTys, Attrs)     \
  DEFINE_SYMBOL(GlobalSymbolName, Impl, CC)

// Indicate that we are going to generate the global symbols for those runtime
// functions that require it.
#define SWIFT_RUNTIME_GENERATE_GLOBAL_SYMBOLS 1

namespace swift {
// Generate global symbols which are function pointers to the actual
// implementations of runtime entry points.
// This is done only for entry points using a new calling convention or
// for those entry points which explicitly require it.
#include "swift/Runtime/RuntimeFunctions.def"
}

<|endoftext|>


<commit_before>#include "selectsignaldialog.h"
#include "ui_selectsignaldialog.h"

#include "signaldescription.h"
#include "signalhandler.h"
#include "jointnames.h"

#include <cstdio>
#include <cassert>

class SelectSignalDialog::Internal : public Ui::SelectSignalDialog
{
public:

  QList<QListWidget*> ArrayKeyWidgets;

};

SelectSignalDialog::SelectSignalDialog(QWidget* parent) : QDialog(parent)
{
  mInternal = new Internal;
  mInternal->setupUi(this);

  QStringList channels;
  channels << "ATLAS_COMMAND" << "ATLAS_FOOT_POS_EST"
           << "ATLAS_IMU_PACKET" << "ATLAS_IMU_PACKET_FILTERED"
           << "ATLAS_STATE" << "ATLAS_STATE_FILTERED" << "ATLAS_STATE_FILTERED_ALT"
           << "ATLAS_STATE_EXTRA"
           << "ATLAS_STATUS" << "EST_ROBOT_STATE"
           << "EST_ROBOT_STATE_KF" << "EST_ROBOT_STATE_LP" << "EST_ROBOT_STATE_ECHO"
           << "FOOT_CONTACT_ESTIMATE" << "FOOT_CONTACT_CLASSIFY"
           << "FORCE_PLATE_DATA"
           << "INS_ERR_UPDATE" << "MICROSTRAIN_INS"
           << "POSE_BDI"
           << "POSE_BODY" << "POSE_BODY_ALT"
           << "POSE_BODY_FOVIS_VELOCITY"
           << "POSE_BODY_LEGODO_VELOCITY" << "POSE_BODY_LEGODO_VELOCITY_FAIL"
           << "POSE_VICON"
           << "SCALED_ROBOT_STATE"
           << "SE_INS_POSE_STATE" << "SE_MATLAB_DATAFUSION_REQ"
           << "STATE_ESTIMATOR_POSE"
           << "STATE_ESTIMATOR_STATE"
           << "TRUE_ROBOT_STATE"
           << "VICON_ATLAS" << "CONTROLLER_DEBUG"
           << "ROBOTIQ_LEFT_STATUS" << "ROBOTIQ_RIGHT_STATUS" ;

  QStringList messageTypes = SignalHandlerFactory::instance().messageTypes();
  QStringList messageFields;

  mInternal->ChannelListBox->addItems(channels);
  mInternal->MessageTypeListBox->addItems(messageTypes);
  mInternal->MessageFieldListBox->addItems(messageFields);

  mInternal->ChannelListBox->setCurrentRow(0);
  mInternal->MessageTypeListBox->setCurrentRow(0);
  mInternal->MessageFieldListBox->setCurrentRow(0);

  this->connect(mInternal->MessageTypeListBox, SIGNAL(currentRowChanged(int)), SLOT(onMessageTypeChanged()));
  this->connect(mInternal->MessageFieldListBox, SIGNAL(currentRowChanged(int)), SLOT(onFieldNameChanged()));
  this->onMessageTypeChanged();
}

void SelectSignalDialog::onMessageTypeChanged()
{
  if (!mInternal->MessageTypeListBox->currentItem())
  {
    return;
  }

  QString messageType = mInternal->MessageTypeListBox->currentItem()->text();

  QStringList fieldNames = SignalHandlerFactory::instance().fieldNames(messageType);
  fieldNames.sort();

  mInternal->MessageFieldListBox->clear();
  mInternal->MessageFieldListBox->addItems(fieldNames);
  mInternal->MessageFieldListBox->setCurrentRow(0);
  this->onFieldNameChanged();
}

void SelectSignalDialog::onFieldNameChanged()
{
  if (!mInternal->MessageFieldListBox->currentItem())
  {
    return;
  }

  QString messageType = mInternal->MessageTypeListBox->currentItem()->text();
  QString fieldName = mInternal->MessageFieldListBox->currentItem()->text();

  foreach (QListWidget* listWidget, mInternal->ArrayKeyWidgets)
  {
    delete listWidget;
  }
  mInternal->ArrayKeyWidgets.clear();

  const QList<QList<QString> >& validArrayKeys = SignalHandlerFactory::instance().validArrayKeys(messageType, fieldName);

  bool useArrayKeys = !validArrayKeys.empty();
  mInternal->ArrayKeysLabel->setVisible(useArrayKeys);
  mInternal->ArrayKeysContainer->setVisible(useArrayKeys);

  foreach (const QList<QString> & keys, validArrayKeys)
  {
    assert(keys.size());
    QListWidget* listWidget = new QListWidget;
    listWidget->addItems(keys);
    listWidget->setCurrentRow(0);
    mInternal->ArrayKeyWidgets.append(listWidget);
    mInternal->ArrayKeysContainer->layout()->addWidget(listWidget);
  }

  if (mInternal->ArrayKeyWidgets.size())
  {
    mInternal->ArrayKeyWidgets.back()->setSelectionMode(QAbstractItemView::ExtendedSelection);
  }

}

SelectSignalDialog::~SelectSignalDialog()
{
  delete mInternal;
}

QList<SignalHandler*> SelectSignalDialog::createSignalHandlers() const
{
  QString channel = mInternal->ChannelListBox->currentItem()->text();
  QString messageType = mInternal->MessageTypeListBox->currentItem()->text();
  QString messageField = mInternal->MessageFieldListBox->currentItem()->text();

  SignalDescription desc;
  desc.mChannel = channel;
  desc.mMessageType = messageType;
  desc.mFieldName = messageField;

  QList<SignalDescription> descriptions;

  if (mInternal->ArrayKeyWidgets.length())
  {
    foreach (QListWidget* listWidget, mInternal->ArrayKeyWidgets)
    {
      if (listWidget == mInternal->ArrayKeyWidgets.back())
      {
        foreach (QListWidgetItem*	selectedItem, listWidget->selectedItems())
        {
          QString arrayKey = selectedItem->text();
          SignalDescription descCopy(desc);
          descCopy.mArrayKeys.append(arrayKey);
          descriptions.append(descCopy);
        }
      }
      else
      {
        QString arrayKey = listWidget->currentItem()->text();
        desc.mArrayKeys.append(arrayKey);
      }
    }
  }
  else
  {
    descriptions.append(desc);
  }

  QList<SignalHandler*> signalHandlers;
  foreach (const SignalDescription& description, descriptions)
  {
    SignalHandler* signalHandler = SignalHandlerFactory::instance().createHandler(&description);
    assert(signalHandler);
    signalHandlers.append(signalHandler);
  }

  return signalHandlers;
}

<commit_msg>adding signal<commit_after>#include "selectsignaldialog.h"
#include "ui_selectsignaldialog.h"

#include "signaldescription.h"
#include "signalhandler.h"
#include "jointnames.h"

#include <cstdio>
#include <cassert>

class SelectSignalDialog::Internal : public Ui::SelectSignalDialog
{
public:

  QList<QListWidget*> ArrayKeyWidgets;

};

SelectSignalDialog::SelectSignalDialog(QWidget* parent) : QDialog(parent)
{
  mInternal = new Internal;
  mInternal->setupUi(this);

  QStringList channels;
  channels << "ATLAS_COMMAND" << "ATLAS_FOOT_POS_EST"
           << "ATLAS_IMU_PACKET" << "ATLAS_IMU_PACKET_FILTERED"
           << "ATLAS_STATE" << "ATLAS_STATE_FILTERED" << "ATLAS_STATE_FILTERED_ALT"
           << "ATLAS_STATE_EXTRA"
           << "ATLAS_STATUS" << "EST_ROBOT_STATE"
           << "EST_ROBOT_STATE_KF" << "EST_ROBOT_STATE_LP" << "EST_ROBOT_STATE_ECHO"
           << "EXPD_ROBOT_STATE"
           << "FOOT_CONTACT_ESTIMATE" << "FOOT_CONTACT_CLASSIFY"
           << "FORCE_PLATE_DATA"
           << "INS_ERR_UPDATE" << "MICROSTRAIN_INS"
           << "POSE_BDI"
           << "POSE_BODY" << "POSE_BODY_ALT"
           << "POSE_BODY_FOVIS_VELOCITY"
           << "POSE_BODY_LEGODO_VELOCITY" << "POSE_BODY_LEGODO_VELOCITY_FAIL"
           << "POSE_VICON"
           << "SCALED_ROBOT_STATE"
           << "SE_INS_POSE_STATE" << "SE_MATLAB_DATAFUSION_REQ"
           << "STATE_ESTIMATOR_POSE"
           << "STATE_ESTIMATOR_STATE"
           << "TRUE_ROBOT_STATE"
           << "VICON_ATLAS" << "CONTROLLER_DEBUG"
           << "ROBOTIQ_LEFT_STATUS" << "ROBOTIQ_RIGHT_STATUS" ;

  QStringList messageTypes = SignalHandlerFactory::instance().messageTypes();
  QStringList messageFields;

  mInternal->ChannelListBox->addItems(channels);
  mInternal->MessageTypeListBox->addItems(messageTypes);
  mInternal->MessageFieldListBox->addItems(messageFields);

  mInternal->ChannelListBox->setCurrentRow(0);
  mInternal->MessageTypeListBox->setCurrentRow(0);
  mInternal->MessageFieldListBox->setCurrentRow(0);

  this->connect(mInternal->MessageTypeListBox, SIGNAL(currentRowChanged(int)), SLOT(onMessageTypeChanged()));
  this->connect(mInternal->MessageFieldListBox, SIGNAL(currentRowChanged(int)), SLOT(onFieldNameChanged()));
  this->onMessageTypeChanged();
}

void SelectSignalDialog::onMessageTypeChanged()
{
  if (!mInternal->MessageTypeListBox->currentItem())
  {
    return;
  }

  QString messageType = mInternal->MessageTypeListBox->currentItem()->text();

  QStringList fieldNames = SignalHandlerFactory::instance().fieldNames(messageType);
  fieldNames.sort();

  mInternal->MessageFieldListBox->clear();
  mInternal->MessageFieldListBox->addItems(fieldNames);
  mInternal->MessageFieldListBox->setCurrentRow(0);
  this->onFieldNameChanged();
}

void SelectSignalDialog::onFieldNameChanged()
{
  if (!mInternal->MessageFieldListBox->currentItem())
  {
    return;
  }

  QString messageType = mInternal->MessageTypeListBox->currentItem()->text();
  QString fieldName = mInternal->MessageFieldListBox->currentItem()->text();

  foreach (QListWidget* listWidget, mInternal->ArrayKeyWidgets)
  {
    delete listWidget;
  }
  mInternal->ArrayKeyWidgets.clear();

  const QList<QList<QString> >& validArrayKeys = SignalHandlerFactory::instance().validArrayKeys(messageType, fieldName);

  bool useArrayKeys = !validArrayKeys.empty();
  mInternal->ArrayKeysLabel->setVisible(useArrayKeys);
  mInternal->ArrayKeysContainer->setVisible(useArrayKeys);

  foreach (const QList<QString> & keys, validArrayKeys)
  {
    assert(keys.size());
    QListWidget* listWidget = new QListWidget;
    listWidget->addItems(keys);
    listWidget->setCurrentRow(0);
    mInternal->ArrayKeyWidgets.append(listWidget);
    mInternal->ArrayKeysContainer->layout()->addWidget(listWidget);
  }

  if (mInternal->ArrayKeyWidgets.size())
  {
    mInternal->ArrayKeyWidgets.back()->setSelectionMode(QAbstractItemView::ExtendedSelection);
  }

}

SelectSignalDialog::~SelectSignalDialog()
{
  delete mInternal;
}

QList<SignalHandler*> SelectSignalDialog::createSignalHandlers() const
{
  QString channel = mInternal->ChannelListBox->currentItem()->text();
  QString messageType = mInternal->MessageTypeListBox->currentItem()->text();
  QString messageField = mInternal->MessageFieldListBox->currentItem()->text();

  SignalDescription desc;
  desc.mChannel = channel;
  desc.mMessageType = messageType;
  desc.mFieldName = messageField;

  QList<SignalDescription> descriptions;

  if (mInternal->ArrayKeyWidgets.length())
  {
    foreach (QListWidget* listWidget, mInternal->ArrayKeyWidgets)
    {
      if (listWidget == mInternal->ArrayKeyWidgets.back())
      {
        foreach (QListWidgetItem*	selectedItem, listWidget->selectedItems())
        {
          QString arrayKey = selectedItem->text();
          SignalDescription descCopy(desc);
          descCopy.mArrayKeys.append(arrayKey);
          descriptions.append(descCopy);
        }
      }
      else
      {
        QString arrayKey = listWidget->currentItem()->text();
        desc.mArrayKeys.append(arrayKey);
      }
    }
  }
  else
  {
    descriptions.append(desc);
  }

  QList<SignalHandler*> signalHandlers;
  foreach (const SignalDescription& description, descriptions)
  {
    SignalHandler* signalHandler = SignalHandlerFactory::instance().createHandler(&description);
    assert(signalHandler);
    signalHandlers.append(signalHandler);
  }

  return signalHandlers;
}

<|endoftext|>


<commit_before>#include "loader.h"

#include<dlfcn.h>

BVS::ModuleMap BVS::Loader::modules;

BVS::ModuleVector BVS::Loader::masterModules;

BVS::Loader::Loader(Control& control, Config& config)
	: control(control)
	, logger("Loader")
	, config(config)
{

}

void BVS::Loader::registerModule(const std::string& id, Module* module)
{
	modules[id] = std::shared_ptr<ModuleData>(new ModuleData{ \
			id, \
			std::string(), \
			std::string(), \
			module, \
			nullptr, \
			std::thread(), \
			false, \
			ModuleFlag::WAIT, \
			Status::NONE, \
			ConnectorMap()});
}

BVS::Loader& BVS::Loader::load(const std::string& moduleTraits, const bool asThread)
{
	/* algorithm:
	 * SEPARATE id(library).options
	 * CHECK for duplicate ids
	 * LOAD the library and CHECK errors
	 * LINK and execute register function, CHECK errors
	 * SAVE metadata
	 * MOVE connectors to metadata
	 * START (un/)threaded module
	 */
	std::string id;
	std::string library;
	std::string options;

	// search for '.' in id and separate id and options
	size_t separator = moduleTraits.find_first_of('.');
	if (separator!=std::string::npos)
	{
		id = moduleTraits.substr(0, separator);
		options = moduleTraits.substr(separator+1, std::string::npos);
	}
	else
		id = moduleTraits;

	// search for '(' in id and separate if necessary
	separator = id.find_first_of('(');
	if (separator!=std::string::npos)
	{
		library = id.substr(separator+1, std::string::npos);
		library.erase(library.length()-1);
		id = id.erase(separator, std::string::npos);
	}
	else
		library = id;

	// search for duplicate id in modules
	if (modules.find(id)!=modules.end())
	{
		LOG(0, "Duplicate id: " << id);
		LOG(0, "If you try to load a module more than once, use unique ids and the id(library).options syntax!");
		exit(-1);
	}

	// prepare path and load the lib
	std::string modulePath = "./lib" + library + ".so";
	LOG(3, id << " will be loaded from " << modulePath);
	void* dlib = dlopen(modulePath.c_str(), RTLD_NOW);

	// check for errors
	if (dlib == NULL)
	{
		LOG(0, "While loading " << modulePath << ", following error occured: " << dlerror());
		exit(-1);
	}

	// look for bvsRegisterModule in loaded lib, check for errors and execute register function
	typedef void (*bvsRegisterModule_t)(const std::string& id, const Config& config);
	bvsRegisterModule_t bvsRegisterModule;
	*reinterpret_cast<void**>(&bvsRegisterModule)=dlsym(dlib, "bvsRegisterModule");

	// check for errors
	char* dlerr = dlerror();
	if (dlerr)
	{
		LOG(0, "Loading function bvsRegisterModule() in " << modulePath << " resulted in: " << dlerr);
		exit(-1);
	}

	// register
	bvsRegisterModule(id, config);
	LOG(2, id << " loaded and registered!");

	// save handle,library name and option string for later use
	modules[id]->dlib = dlib;
	modules[id]->library = library;
	modules[id]->options = options;

	// move connectors from temporary to metadata
	modules[id]->connectors = std::move(ConnectorDataCollector::connectors);

	// set metadata and start as thread if needed
	if (asThread==true)
	{
		LOG(3, id << " will be started in own thread!");
		modules[id]->asThread = true;
		modules[id]->thread = std::thread(&Control::threadController, &control, modules[id]);
		Control::threadedModules++;
	}
	else
	{
		LOG(3, id << " will be executed by Control!");
		modules[id]->asThread = false;
		masterModules.push_back(modules[id]);
	}

	return *this;
}

BVS::Loader& BVS::Loader::unload(const std::string& id, const bool eraseFromMap)
{
	/* algorithm:
	 * CHECK thread, signal exit
	 * DISCONNECT connectors
	 * DELETE module instance and connectors
	 * CHECK library handle
	 * CLOSE library
	 * CHECK errors
	 */
	// wait for thread to join, first check if it is still running
	if (modules[id]->asThread == true)
	{
		if (modules[id]->thread.joinable())
		{
			modules[id]->flag = ModuleFlag::QUIT;
			control.threadCond.notify_all();
			LOG(3, "joining: " << id);
			modules[id]->thread.join();
		}
	}

	// disconnect connectors
	for (auto& it: modules)
	{
		for (auto& con: it.second->connectors)
		{
			if (con.second->type==ConnectorType::INPUT) continue;

			// find and reset all inputs connected to output
			for (auto& mods: modules)
			{
				for (auto& modCon: mods.second->connectors)
				{
					if (con.second->pointer==modCon.second->pointer)
					{
						modCon.second->pointer = nullptr;
						modCon.second->active = false;
					}
				}

			}
		}
	}

	// delete module and connectors
	modules[id]->connectors.clear();
	delete modules[id]->module;
	modules[id]->module = nullptr;

	// close lib and check for errors
	std::string modulePath = "./lib" + modules[id]->library + ".so";
	LOG(3, id << " will be closed using " << modulePath);

	// get handle from internals
	void* dlib = modules[id]->dlib;
	if (dlib==nullptr)
	{
		LOG(0, "Requested module " << id << " not found!");
		exit(-1);
	}

	// close the module
	dlclose(dlib);

	// check for errors
	char* dlerr = dlerror();
	if (dlerr)
	{
		LOG(0, "While closing " << modulePath << " following error occured: " << dlerror());
		exit(-1);
	}
	LOG(2, id << " unloaded and deregistered!");

	if (eraseFromMap)
	{
		modules.erase(id);
		LOG(2, id << " erased from map!");
	}

	return *this;
}

BVS::Loader& BVS::Loader::unloadAll()
{
	for (auto& it: modules)
		unload(it.second->id, false);

	modules.clear();

	return *this;
}

BVS::Loader& BVS::Loader::connectModules(bool connectorTypeMatching)
{
	/* algorithm:
	 * FOR EACH module
	 * DO
	 *		SEPARATE input and remove parsed part
	 *		CHECK input exists
	 *		CHECK input type
	 *		SEPARATE module and output
	 *		CHECK module exists and self reference
	 *		CHECK output exists
	 *		CHECK output type
	 *		CHECK input typeid hash == output typeid hash
	 *		CHECK input already connected
	 *		CONNECT
	 * DONE
	 */

	std::string options;
	std::string selection;
	std::string input;
	std::string module;
	std::string output;
	size_t separator;
	size_t separator2;

	// check options for each module
	for (auto& it: modules)
	{
		options = it.second->options;

		while (!options.empty())
		{
			// get input name and selection
			separator = options.find_first_of('(');
			separator2 = options.find_first_of(')');
			selection = options.substr(0, separator2+1);
			if (separator!=std::string::npos)
			{
				module= options.substr(separator+1, separator2-separator-1);
				input = options.substr(0, separator);
			}
			else
			{
				LOG(0, "no input selection found: " << selection);
				exit(1);
			}

			// remove parsed part
			options.erase(0, separator2+1);
			if (options[0] == '.') options.erase(options.begin());

			// check if desired input exists
			if (it.second->connectors.find(input) == it.second->connectors.end())
			{
				LOG(0, "selected input does not exist: " << selection);
				exit(1);
			}

			// check input type
			if (it.second->connectors[input]->type != ConnectorType::INPUT)
			{
				LOG(0, "selected input is not of input type: " << it.second->id << "." << selection);
				exit(1);
			}

			// search for '.' in selection and separate module and output
			separator = module.find_first_of('.');
			if (separator!=std::string::npos)
			{
				output = module.substr(separator+1, std::string::npos);
				module = module.substr(0, separator);
			}
			else
			{
				LOG(0, "no module output selected: " << selection);
				exit(1);
			}

			// check if desired module exists
			if (modules.find(module) == modules.end())
			{
				LOG(0, "could not find module: " << module);
				exit(1);
			}

			// check for sending data to oneself...
			if (module == it.second->id)
			{
				LOG(0, "can not request data from self: " << selection);
				exit(1);
			}

			// check if desired output exists
			if (modules[module]->connectors.find(output) == modules[module]->connectors.end())
			{
				LOG(0, "selected output does not exist: " << selection);
				exit(1);
			}

			// check output type
			if (modules[module]->connectors[output]->type != ConnectorType::OUTPUT)
			{
				LOG(0, "selected output is not of output type: " << selection);
				exit(1);
			}

			// check input typeid hash == output typeid hash
			if (connectorTypeMatching && it.second->connectors[input]->typeIDHash != modules[module]->connectors[output]->typeIDHash)
			{
				LOG(0, "selected input and output connector template instantiations are of different type: " \
						<< it.second->id << "." << selection << " -> " \
						<< it.second->connectors[input]->typeIDName << "!=" << modules[module]->connectors[output]->typeIDName);
				exit(1);
			}

			// check if input is already connected
			if (it.second->connectors[input]->active)
			{
				LOG(0, "selected input is alreade connected to another output: " << selection);
				exit(1);
			}

			// connect
			it.second->connectors[input]->pointer = modules[module]->connectors[output]->pointer;
			it.second->connectors[input]->active = true;
			it.second->connectors[input]->mutex = modules[module]->connectors[output]->mutex;
			LOG(3, "connected: " << it.second->id << "." << it.second->connectors[input]->id << " <- " << modules[module]->id << "." << modules[module]->connectors[output]->id);
		}
	}

	// do maintenance for load/unload, e.g. remove all connections for unloaded module...
	return *this;
}

<commit_msg>loader: unset mutex when unloading<commit_after>#include "loader.h"

#include<dlfcn.h>

BVS::ModuleMap BVS::Loader::modules;

BVS::ModuleVector BVS::Loader::masterModules;

BVS::Loader::Loader(Control& control, Config& config)
	: control(control)
	, logger("Loader")
	, config(config)
{

}

void BVS::Loader::registerModule(const std::string& id, Module* module)
{
	modules[id] = std::shared_ptr<ModuleData>(new ModuleData{ \
			id, \
			std::string(), \
			std::string(), \
			module, \
			nullptr, \
			std::thread(), \
			false, \
			ModuleFlag::WAIT, \
			Status::NONE, \
			ConnectorMap()});
}

BVS::Loader& BVS::Loader::load(const std::string& moduleTraits, const bool asThread)
{
	/* algorithm:
	 * SEPARATE id(library).options
	 * CHECK for duplicate ids
	 * LOAD the library and CHECK errors
	 * LINK and execute register function, CHECK errors
	 * SAVE metadata
	 * MOVE connectors to metadata
	 * START (un/)threaded module
	 */
	std::string id;
	std::string library;
	std::string options;

	// search for '.' in id and separate id and options
	size_t separator = moduleTraits.find_first_of('.');
	if (separator!=std::string::npos)
	{
		id = moduleTraits.substr(0, separator);
		options = moduleTraits.substr(separator+1, std::string::npos);
	}
	else
		id = moduleTraits;

	// search for '(' in id and separate if necessary
	separator = id.find_first_of('(');
	if (separator!=std::string::npos)
	{
		library = id.substr(separator+1, std::string::npos);
		library.erase(library.length()-1);
		id = id.erase(separator, std::string::npos);
	}
	else
		library = id;

	// search for duplicate id in modules
	if (modules.find(id)!=modules.end())
	{
		LOG(0, "Duplicate id: " << id);
		LOG(0, "If you try to load a module more than once, use unique ids and the id(library).options syntax!");
		exit(-1);
	}

	// prepare path and load the lib
	std::string modulePath = "./lib" + library + ".so";
	LOG(3, id << " will be loaded from " << modulePath);
	void* dlib = dlopen(modulePath.c_str(), RTLD_NOW);

	// check for errors
	if (dlib == NULL)
	{
		LOG(0, "While loading " << modulePath << ", following error occured: " << dlerror());
		exit(-1);
	}

	// look for bvsRegisterModule in loaded lib, check for errors and execute register function
	typedef void (*bvsRegisterModule_t)(const std::string& id, const Config& config);
	bvsRegisterModule_t bvsRegisterModule;
	*reinterpret_cast<void**>(&bvsRegisterModule)=dlsym(dlib, "bvsRegisterModule");

	// check for errors
	char* dlerr = dlerror();
	if (dlerr)
	{
		LOG(0, "Loading function bvsRegisterModule() in " << modulePath << " resulted in: " << dlerr);
		exit(-1);
	}

	// register
	bvsRegisterModule(id, config);
	LOG(2, id << " loaded and registered!");

	// save handle,library name and option string for later use
	modules[id]->dlib = dlib;
	modules[id]->library = library;
	modules[id]->options = options;

	// move connectors from temporary to metadata
	modules[id]->connectors = std::move(ConnectorDataCollector::connectors);

	// set metadata and start as thread if needed
	if (asThread==true)
	{
		LOG(3, id << " will be started in own thread!");
		modules[id]->asThread = true;
		modules[id]->thread = std::thread(&Control::threadController, &control, modules[id]);
		Control::threadedModules++;
	}
	else
	{
		LOG(3, id << " will be executed by Control!");
		modules[id]->asThread = false;
		masterModules.push_back(modules[id]);
	}

	return *this;
}

BVS::Loader& BVS::Loader::unload(const std::string& id, const bool eraseFromMap)
{
	/* algorithm:
	 * CHECK thread, signal exit
	 * DISCONNECT connectors
	 * DELETE module instance and connectors
	 * CHECK library handle
	 * CLOSE library
	 * CHECK errors
	 */
	// wait for thread to join, first check if it is still running
	if (modules[id]->asThread == true)
	{
		if (modules[id]->thread.joinable())
		{
			modules[id]->flag = ModuleFlag::QUIT;
			control.threadCond.notify_all();
			LOG(3, "joining: " << id);
			modules[id]->thread.join();
		}
	}

	// disconnect connectors
	for (auto& it: modules)
	{
		for (auto& con: it.second->connectors)
		{
			if (con.second->type==ConnectorType::INPUT) continue;

			// find and reset all inputs connected to output
			for (auto& mods: modules)
			{
				for (auto& modCon: mods.second->connectors)
				{
					if (con.second->pointer==modCon.second->pointer)
					{
						modCon.second->pointer = nullptr;
						modCon.second->active = false;
						modCon.second->mutex = nullptr;
					}
				}

			}
		}
	}

	// delete module and connectors
	modules[id]->connectors.clear();
	delete modules[id]->module;
	modules[id]->module = nullptr;

	// close lib and check for errors
	std::string modulePath = "./lib" + modules[id]->library + ".so";
	LOG(3, id << " will be closed using " << modulePath);

	// get handle from internals
	void* dlib = modules[id]->dlib;
	if (dlib==nullptr)
	{
		LOG(0, "Requested module " << id << " not found!");
		exit(-1);
	}

	// close the module
	dlclose(dlib);

	// check for errors
	char* dlerr = dlerror();
	if (dlerr)
	{
		LOG(0, "While closing " << modulePath << " following error occured: " << dlerror());
		exit(-1);
	}
	LOG(2, id << " unloaded and deregistered!");

	if (eraseFromMap)
	{
		modules.erase(id);
		LOG(2, id << " erased from map!");
	}

	return *this;
}

BVS::Loader& BVS::Loader::unloadAll()
{
	for (auto& it: modules)
		unload(it.second->id, false);

	modules.clear();

	return *this;
}

BVS::Loader& BVS::Loader::connectModules(bool connectorTypeMatching)
{
	/* algorithm:
	 * FOR EACH module
	 * DO
	 *		SEPARATE input and remove parsed part
	 *		CHECK input exists
	 *		CHECK input type
	 *		SEPARATE module and output
	 *		CHECK module exists and self reference
	 *		CHECK output exists
	 *		CHECK output type
	 *		CHECK input typeid hash == output typeid hash
	 *		CHECK input already connected
	 *		CONNECT
	 * DONE
	 */

	std::string options;
	std::string selection;
	std::string input;
	std::string module;
	std::string output;
	size_t separator;
	size_t separator2;

	// check options for each module
	for (auto& it: modules)
	{
		options = it.second->options;

		while (!options.empty())
		{
			// get input name and selection
			separator = options.find_first_of('(');
			separator2 = options.find_first_of(')');
			selection = options.substr(0, separator2+1);
			if (separator!=std::string::npos)
			{
				module= options.substr(separator+1, separator2-separator-1);
				input = options.substr(0, separator);
			}
			else
			{
				LOG(0, "no input selection found: " << selection);
				exit(1);
			}

			// remove parsed part
			options.erase(0, separator2+1);
			if (options[0] == '.') options.erase(options.begin());

			// check if desired input exists
			if (it.second->connectors.find(input) == it.second->connectors.end())
			{
				LOG(0, "selected input does not exist: " << selection);
				exit(1);
			}

			// check input type
			if (it.second->connectors[input]->type != ConnectorType::INPUT)
			{
				LOG(0, "selected input is not of input type: " << it.second->id << "." << selection);
				exit(1);
			}

			// search for '.' in selection and separate module and output
			separator = module.find_first_of('.');
			if (separator!=std::string::npos)
			{
				output = module.substr(separator+1, std::string::npos);
				module = module.substr(0, separator);
			}
			else
			{
				LOG(0, "no module output selected: " << selection);
				exit(1);
			}

			// check if desired module exists
			if (modules.find(module) == modules.end())
			{
				LOG(0, "could not find module: " << module);
				exit(1);
			}

			// check for sending data to oneself...
			if (module == it.second->id)
			{
				LOG(0, "can not request data from self: " << selection);
				exit(1);
			}

			// check if desired output exists
			if (modules[module]->connectors.find(output) == modules[module]->connectors.end())
			{
				LOG(0, "selected output does not exist: " << selection);
				exit(1);
			}

			// check output type
			if (modules[module]->connectors[output]->type != ConnectorType::OUTPUT)
			{
				LOG(0, "selected output is not of output type: " << selection);
				exit(1);
			}

			// check input typeid hash == output typeid hash
			if (connectorTypeMatching && it.second->connectors[input]->typeIDHash != modules[module]->connectors[output]->typeIDHash)
			{
				LOG(0, "selected input and output connector template instantiations are of different type: " \
						<< it.second->id << "." << selection << " -> " \
						<< it.second->connectors[input]->typeIDName << "!=" << modules[module]->connectors[output]->typeIDName);
				exit(1);
			}

			// check if input is already connected
			if (it.second->connectors[input]->active)
			{
				LOG(0, "selected input is alreade connected to another output: " << selection);
				exit(1);
			}

			// connect
			it.second->connectors[input]->pointer = modules[module]->connectors[output]->pointer;
			it.second->connectors[input]->active = true;
			it.second->connectors[input]->mutex = modules[module]->connectors[output]->mutex;
			LOG(3, "connected: " << it.second->id << "." << it.second->connectors[input]->id << " <- " << modules[module]->id << "." << modules[module]->connectors[output]->id);
		}
	}

	// do maintenance for load/unload, e.g. remove all connections for unloaded module...
	return *this;
}

<|endoftext|>


<commit_before>AliAnalysisTaskStrangenessVsMultiplicityMCRun2 *AddTaskStrangenessVsMultiplicityMCRun2( Bool_t lSaveEventTree = kTRUE, Bool_t lSaveV0 = kTRUE, Bool_t lSaveCascade = kTRUE, TString lExtraOptions = "", const TString lMasterJobSessionFlag = "", TString lExtraOutputName = "")
{
    // Creates, configures and attaches to the train a cascades check task.
    // Get the pointer to the existing analysis manager via the static access method.
    //==============================================================================
    AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
    if (!mgr) {
        ::Error("AddTaskStrangenessVsMultiplicity", "No analysis manager to connect to.");
        return NULL;
    }

    // Check the analysis type using the event handlers connected to the analysis manager.
    //==============================================================================
    if (!mgr->GetInputEventHandler()) {
        ::Error("AddTaskStrangenessVsMultiplicity", "This task requires an input event handler");
        return NULL;
    }
    TString type = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"

    // Create and configure the task
    AliAnalysisTaskStrangenessVsMultiplicityMCRun2 *taskAuxiliary = new AliAnalysisTaskStrangenessVsMultiplicityMCRun2(lSaveEventTree, lSaveV0, lSaveCascade, Form("taskAuxiliary%s",lExtraOutputName.Data()), lExtraOptions);
    mgr->AddTask(taskAuxiliary);
    TString outputFileName = AliAnalysisManager::GetCommonFileName();

    outputFileName += ":PWGLF_StrVsMult";
    if (mgr->GetMCtruthEventHandler()) outputFileName += "_MC";
    outputFileName += lExtraOutputName.Data();

    Printf("Set OutputFileName : \n %s\n", outputFileName.Data() );

    TString lC[9];
    lC[0] = "cList";
    lC[1] = "cListV0";
    lC[2] = "cListXiMinus";
    lC[3] = "cListXiPlus";
    lC[4] = "cListOmegaMinus";
    lC[5] = "cListOmegaPlus";
    lC[6] = "cTreeEvent";
    lC[7] = "cTreeV0";
    lC[8] = "cTreeCascade";

    for(Int_t iname=0;iname<9;iname++)
        lC[iname] += lExtraOutputName.Data();

    AliAnalysisDataContainer *coutputLists[6];
    for(Int_t ilist=0;ilist<6;ilist++){
        coutputLists[ilist] = mgr->CreateContainer(lC[ilist].Data(),
                                                   TList::Class(),
                                                   AliAnalysisManager::kOutputContainer,
                                                   outputFileName );
    }

    AliAnalysisDataContainer *coutputTree = 0x0;
    AliAnalysisDataContainer *coutputTreeV0 = 0x0;
    AliAnalysisDataContainer *coutputTreeCascade = 0x0;

    if( lSaveEventTree ){
        AliAnalysisDataContainer *coutputTree = mgr->CreateContainer(Form("cTreeEvent%s",lExtraOutputName.Data()),
                                                                     TTree::Class(),
                                                                     AliAnalysisManager::kOutputContainer,
                                                                     outputFileName );
        coutputTree->SetSpecialOutput();
    }
    if( lSaveV0 ){
        AliAnalysisDataContainer *coutputTreeV0 = mgr->CreateContainer(Form("cTreeV0%s",lExtraOutputName.Data()),
                                                                       TTree::Class(),
                                                                       AliAnalysisManager::kOutputContainer,
                                                                       outputFileName );
        coutputTreeV0->SetSpecialOutput();
    }
    if (lSaveCascade){
        AliAnalysisDataContainer *coutputTreeCascade = mgr->CreateContainer(Form("cTreeCascade%s",lExtraOutputName.Data()),
                                                                            TTree::Class(),
                                                                            AliAnalysisManager::kOutputContainer,
                                                                            outputFileName );
        coutputTreeCascade->SetSpecialOutput();
    }
    //This one you should merge in file-resident ways...

    //Recommendation: Tree as a single output slot
    mgr->ConnectInput (taskAuxiliary, 0, mgr->GetCommonInputContainer());
    for(Int_t ilist=0;ilist<6;ilist++){
        mgr->ConnectOutput(taskAuxiliary, ilist+1, coutputLists[ilist]);

    if ( lSaveEventTree ) mgr->ConnectOutput(taskAuxiliary, 4, coutputTree);
    if ( lSaveV0 )        mgr->ConnectOutput(taskAuxiliary, 5, coutputTreeV0);
    if ( lSaveCascade )   mgr->ConnectOutput(taskAuxiliary, 6, coutputTreeCascade);

    return taskAuxiliary;
}
<commit_msg>Fix indices<commit_after>AliAnalysisTaskStrangenessVsMultiplicityMCRun2 *AddTaskStrangenessVsMultiplicityMCRun2( Bool_t lSaveEventTree = kTRUE, Bool_t lSaveV0 = kTRUE, Bool_t lSaveCascade = kTRUE, TString lExtraOptions = "", const TString lMasterJobSessionFlag = "", TString lExtraOutputName = "")
{
    // Creates, configures and attaches to the train a cascades check task.
    // Get the pointer to the existing analysis manager via the static access method.
    //==============================================================================
    AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
    if (!mgr) {
        ::Error("AddTaskStrangenessVsMultiplicity", "No analysis manager to connect to.");
        return NULL;
    }

    // Check the analysis type using the event handlers connected to the analysis manager.
    //==============================================================================
    if (!mgr->GetInputEventHandler()) {
        ::Error("AddTaskStrangenessVsMultiplicity", "This task requires an input event handler");
        return NULL;
    }
    TString type = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"

    // Create and configure the task
    AliAnalysisTaskStrangenessVsMultiplicityMCRun2 *taskAuxiliary = new AliAnalysisTaskStrangenessVsMultiplicityMCRun2(lSaveEventTree, lSaveV0, lSaveCascade, Form("taskAuxiliary%s",lExtraOutputName.Data()), lExtraOptions);
    mgr->AddTask(taskAuxiliary);
    TString outputFileName = AliAnalysisManager::GetCommonFileName();

    outputFileName += ":PWGLF_StrVsMult";
    if (mgr->GetMCtruthEventHandler()) outputFileName += "_MC";
    outputFileName += lExtraOutputName.Data();

    Printf("Set OutputFileName : \n %s\n", outputFileName.Data() );

    TString lC[9];
    lC[0] = "cList";
    lC[1] = "cListV0";
    lC[2] = "cListXiMinus";
    lC[3] = "cListXiPlus";
    lC[4] = "cListOmegaMinus";
    lC[5] = "cListOmegaPlus";
    lC[6] = "cTreeEvent";
    lC[7] = "cTreeV0";
    lC[8] = "cTreeCascade";

    for(Int_t iname=0;iname<9;iname++)
        lC[iname] += lExtraOutputName.Data();

    AliAnalysisDataContainer *coutputLists[6];
    for(Int_t ilist=0;ilist<6;ilist++){
        coutputLists[ilist] = mgr->CreateContainer(lC[ilist].Data(),
                                                   TList::Class(),
                                                   AliAnalysisManager::kOutputContainer,
                                                   outputFileName );
    }

    AliAnalysisDataContainer *coutputTree = 0x0;
    AliAnalysisDataContainer *coutputTreeV0 = 0x0;
    AliAnalysisDataContainer *coutputTreeCascade = 0x0;

    if( lSaveEventTree ){
        AliAnalysisDataContainer *coutputTree = mgr->CreateContainer(Form("cTreeEvent%s",lExtraOutputName.Data()),
                                                                     TTree::Class(),
                                                                     AliAnalysisManager::kOutputContainer,
                                                                     outputFileName );
        coutputTree->SetSpecialOutput();
    }
    if( lSaveV0 ){
        AliAnalysisDataContainer *coutputTreeV0 = mgr->CreateContainer(Form("cTreeV0%s",lExtraOutputName.Data()),
                                                                       TTree::Class(),
                                                                       AliAnalysisManager::kOutputContainer,
                                                                       outputFileName );
        coutputTreeV0->SetSpecialOutput();
    }
    if (lSaveCascade){
        AliAnalysisDataContainer *coutputTreeCascade = mgr->CreateContainer(Form("cTreeCascade%s",lExtraOutputName.Data()),
                                                                            TTree::Class(),
                                                                            AliAnalysisManager::kOutputContainer,
                                                                            outputFileName );
        coutputTreeCascade->SetSpecialOutput();
    }
    //This one you should merge in file-resident ways...

    //Recommendation: Tree as a single output slot
    mgr->ConnectInput (taskAuxiliary, 0, mgr->GetCommonInputContainer());
    for(Int_t ilist=0;ilist<6;ilist++){
        mgr->ConnectOutput(taskAuxiliary, ilist+1, coutputLists[ilist]);

    if ( lSaveEventTree ) mgr->ConnectOutput(taskAuxiliary, 7, coutputTree);
    if ( lSaveV0 )        mgr->ConnectOutput(taskAuxiliary, 8, coutputTreeV0);
    if ( lSaveCascade )   mgr->ConnectOutput(taskAuxiliary, 9, coutputTreeCascade);

    return taskAuxiliary;
}
<|endoftext|>


<commit_before>/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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 <pthread.h>

#include <cstdlib>
#include <iostream>

#include <tr1/functional>

#include <mesos/executor.hpp>

using namespace mesos;

using std::cout;
using std::endl;
using std::string;

void run(ExecutorDriver* driver, const TaskInfo& task)
{
  sleep(100);

  TaskStatus status;
  status.mutable_task_id()->MergeFrom(task.task_id());
  status.set_state(TASK_FINISHED);

  driver->sendStatusUpdate(status);
}

void* start(void* arg)
{
  std::tr1::function<void(void)>* thunk = (std::tr1::function<void(void)>*) arg;
  (*thunk)();
  delete thunk;
  return NULL;
}

class LongLivedExecutor : public Executor
{
public:
  virtual ~LongLivedExecutor() {}

  virtual void registered(ExecutorDriver* driver,
                          const ExecutorInfo& executorInfo,
                          const FrameworkInfo& frameworkInfo,
                          const SlaveInfo& slaveInfo)
  {
    cout << "Registered executor on " << slaveInfo.hostname() << endl;
  }

  virtual void reregistered(ExecutorDriver* driver,
                            const SlaveInfo& slaveInfo)
  {
    cout << "Re-registered executor on " << slaveInfo.hostname() << endl;
  }

  virtual void disconnected(ExecutorDriver* driver) {}

  virtual void launchTask(ExecutorDriver* driver, const TaskInfo& task)
  {
    cout << "Starting task " << task.task_id().value() << endl;

    std::tr1::function<void(void)>* thunk =
      new std::tr1::function<void(void)>(std::tr1::bind(&run, driver, task));

    pthread_t pthread;
    if (pthread_create(&pthread, NULL, &start, thunk) != 0) {
      TaskStatus status;
      status.mutable_task_id()->MergeFrom(task.task_id());
      status.set_state(TASK_FAILED);

      driver->sendStatusUpdate(status);
    } else {
      pthread_detach(pthread);

      TaskStatus status;
      status.mutable_task_id()->MergeFrom(task.task_id());
      status.set_state(TASK_RUNNING);

      driver->sendStatusUpdate(status);
    }
  }

  virtual void killTask(ExecutorDriver* driver, const TaskID& taskId) {}
  virtual void frameworkMessage(ExecutorDriver* driver, const string& data) {}
  virtual void shutdown(ExecutorDriver* driver) {}
  virtual void error(ExecutorDriver* driver, const string& message) {}
};

int main(int argc, char** argv)
{
  LongLivedExecutor executor;
  MesosExecutorDriver driver(&executor);
  return driver.run() == DRIVER_STOPPED ? 0 : 1;
}
<commit_msg>Made tasks of the "long-lived-framework" have varying runtimes (https://reviews.apache.org/r/5267).<commit_after>/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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 <pthread.h>
#include <stdlib.h> // For random.

#include <cstdlib>
#include <iostream>

#include <tr1/functional>

#include <mesos/executor.hpp>

using namespace mesos;

using std::cout;
using std::endl;
using std::string;

void run(ExecutorDriver* driver, const TaskInfo& task)
{
  sleep(random() % 10);

  TaskStatus status;
  status.mutable_task_id()->MergeFrom(task.task_id());
  status.set_state(TASK_FINISHED);

  driver->sendStatusUpdate(status);
}

void* start(void* arg)
{
  std::tr1::function<void(void)>* thunk = (std::tr1::function<void(void)>*) arg;
  (*thunk)();
  delete thunk;
  return NULL;
}

class LongLivedExecutor : public Executor
{
public:
  virtual ~LongLivedExecutor() {}

  virtual void registered(ExecutorDriver* driver,
                          const ExecutorInfo& executorInfo,
                          const FrameworkInfo& frameworkInfo,
                          const SlaveInfo& slaveInfo)
  {
    cout << "Registered executor on " << slaveInfo.hostname() << endl;
  }

  virtual void reregistered(ExecutorDriver* driver,
                            const SlaveInfo& slaveInfo)
  {
    cout << "Re-registered executor on " << slaveInfo.hostname() << endl;
  }

  virtual void disconnected(ExecutorDriver* driver) {}

  virtual void launchTask(ExecutorDriver* driver, const TaskInfo& task)
  {
    cout << "Starting task " << task.task_id().value() << endl;

    std::tr1::function<void(void)>* thunk =
      new std::tr1::function<void(void)>(std::tr1::bind(&run, driver, task));

    pthread_t pthread;
    if (pthread_create(&pthread, NULL, &start, thunk) != 0) {
      TaskStatus status;
      status.mutable_task_id()->MergeFrom(task.task_id());
      status.set_state(TASK_FAILED);

      driver->sendStatusUpdate(status);
    } else {
      pthread_detach(pthread);

      TaskStatus status;
      status.mutable_task_id()->MergeFrom(task.task_id());
      status.set_state(TASK_RUNNING);

      driver->sendStatusUpdate(status);
    }
  }

  virtual void killTask(ExecutorDriver* driver, const TaskID& taskId) {}
  virtual void frameworkMessage(ExecutorDriver* driver, const string& data) {}
  virtual void shutdown(ExecutorDriver* driver) {}
  virtual void error(ExecutorDriver* driver, const string& message) {}
};

int main(int argc, char** argv)
{
  LongLivedExecutor executor;
  MesosExecutorDriver driver(&executor);
  return driver.run() == DRIVER_STOPPED ? 0 : 1;
}
<|endoftext|>


<commit_before>#pragma once
#ifndef DELEGATE_HPP
# define DELEGATE_HPP

#include <cassert>

#include <memory>

#include <new>

#include <type_traits>

#include <utility>

template <typename T> class delegate;

template<class R, class ...A>
class delegate<R (A...)>
{
  template <typename U, typename = void> struct is_functora
    : std::false_type { };

  template <typename U>
  struct is_functora<U,
    typename std::enable_if<bool(sizeof((R (U::*)(A...))
      &U::operator()))>::type
  > : std::true_type { };

  template <typename U, typename = void> struct is_functorb
    : std::false_type { };

  template <typename U>
  struct is_functorb<U,
    typename std::enable_if<bool(sizeof((R (U::*)(A...) const)
      &U::operator()))>::type
  > : std::true_type { };

  template <typename U>
  struct is_functor
  {
    static constexpr bool const value = is_functora<U>::value
      || is_functorb<U>::value;
  };

  typedef R (*stub_ptr_type)(void*, A...);

  constexpr delegate(void* const o, stub_ptr_type const m)
    : object_ptr_(o),
      stub_ptr_(m)
  {
  }

public:
  constexpr delegate() = default;

  constexpr delegate(delegate const&) = default;

  constexpr delegate(delegate&&) = default;

  template <class C>
  constexpr delegate(C const* const o)
    : object_ptr_(const_cast<C*>(o))
  {
  }

  template <class C>
  constexpr delegate(C const& o)
    : object_ptr_(const_cast<C*>(&o))
  {
  }

  delegate(R (* const function_ptr)(A...))
  {
    *this = from(function_ptr);
  }

  template <class C>
  delegate(C* const object_ptr_, R (C::* const method_ptr)(A...))
  {
    *this = from(object_ptr_, method_ptr);
  }

  template <class C>
  delegate(C* const object_ptr_, R (C::* const method_ptr)(A...) const)
  {
    *this = from(object_ptr_, method_ptr);
  }

  template <class C>
  delegate(C& object, R (C::* const method_ptr)(A...))
  {
    *this = from(object, method_ptr);
  }

  template <class C>
  delegate(C const& object, R (C::* const method_ptr)(A...) const)
  {
    *this = from(object, method_ptr);
  }

  template <
    typename T,
    typename = typename std::enable_if<
      !std::is_same<delegate, typename std::remove_const<
        typename std::remove_reference<T>::type>::type>::value
      && is_functor<typename std::remove_reference<T>::type>::value
    >::type
  >
  delegate(T&& f)
    : store_(operator new(sizeof(T)),
        functor_deleter<typename std::remove_reference<T>::type>),
      store_size_(sizeof(T))
  {
    typedef typename std::remove_reference<T>::type functor_type;

    object_ptr_ = new (store_.get()) functor_type(std::forward<T>(f));

    stub_ptr_ = functor_stub<functor_type>;

    deleter_ = destructor_stub<functor_type>;
  }

  delegate& operator=(delegate const&) = default;

  delegate& operator=(delegate&& rhs) = default;

  template <class C>
  delegate& operator=(R (C::* const rhs)(A...))
  {
    return *this = from(static_cast<C*>(object_ptr_), rhs);
  }

  template <class C>
  delegate& operator=(R (C::* const rhs)(A...) const)
  {
    return *this = from(static_cast<C const*>(object_ptr_), rhs);
  }

  template <
    typename T,
    typename = typename std::enable_if<
      !std::is_same<delegate, typename std::remove_const<
        typename std::remove_reference<T>::type>::type>::value
      && is_functor<typename std::remove_reference<T>::type>::value
    >::type
  >
  delegate& operator=(T&& f)
  {
    typedef typename std::remove_reference<T>::type functor_type;

    if ((sizeof(T) > store_size_)
      || (decltype(store_.use_count())(1) != store_.use_count()))
    {
      store_.reset(operator new(sizeof(T)),
        functor_deleter<functor_type>);

      store_size_ = sizeof(T);
    }
    else
    {
      deleter_(store_.get());
    }

    object_ptr_ = new (store_.get()) functor_type(std::forward<T>(f));

    stub_ptr_ = functor_stub<functor_type>;

    deleter_ = destructor_stub<functor_type>;

    return *this;
  }

  template <R (*function_ptr)(A...)>
  static constexpr delegate from()
  {
    return { nullptr, function_stub<function_ptr> };
  }

  template <class C, R (C::*method_ptr)(A...)>
  static constexpr delegate from(C* const object_ptr_)
  {
    return { object_ptr_, method_stub<C, method_ptr> };
  }

  template <class C, R (C::*method_ptr)(A...) const>
  static constexpr delegate from(C const* const object_ptr_)
  {
    return { const_cast<C*>(object_ptr_), const_method_stub<C, method_ptr> };
  }

  template <class C, R (C::*method_ptr)(A...)>
  static constexpr delegate from(C& object)
  {
    return { &object, method_stub<C, method_ptr> };
  }

  template <class C, R (C::*method_ptr)(A...) const>
  static constexpr delegate from(C const& object)
  {
    return { const_cast<C*>(&object), const_method_stub<C, method_ptr> };
  }

  template <typename T>
  static delegate from(T&& f)
  {
    return { std::forward<T>(f) };
  }

  static constexpr delegate from(R (* const function_ptr)(A...))
  {
    return { [function_ptr](A const... args){
      return (*function_ptr)(args...); } };
  }

  template <class C>
  static constexpr delegate from(C* const object_ptr_,
    R (C::* const method_ptr)(A...))
  {
    return { [object_ptr_, method_ptr](A const... args){
      return (object_ptr_->*method_ptr)(args...); } };
  }

  template <class C>
  static constexpr delegate from(C const* const object_ptr_,
    R (C::* const method_ptr)(A...) const)
  {
    return { [object_ptr_, method_ptr](A const... args){
      return (object_ptr_->*method_ptr)(args...); } };
  }

  template <class C>
  static constexpr delegate from(C& object,
    R (C::* const method_ptr)(A...))
  {
    return { [&object, method_ptr](A const... args){
      return (object.*method_ptr)(args...); } };
  }

  template <class C>
  static constexpr delegate from(C const& object,
    R (C::* const method_ptr)(A...) const)
  {
    return { [&object, method_ptr](A const... args){
      return (object.*method_ptr)(args...); } };
  }

  void reset() { stub_ptr_ = nullptr; }

  void swap(delegate& other)
  {
    std::swap(object_ptr_, other.object_ptr_);
    std::swap(stub_ptr_, other.stub_ptr_);
  }

  constexpr bool operator==(delegate const& rhs) const
  {
    return (stub_ptr_ == rhs.stub_ptr_)
      && (object_ptr_ == rhs.object_ptr_);
  }

  constexpr bool operator!=(delegate const& rhs) const
  {
    return !operator==(rhs);
  }

  constexpr bool operator<(delegate const& rhs) const
  {
    return (object_ptr_ < rhs.object_ptr_)
      || (stub_ptr_ < rhs.stub_ptr_);
  }

  constexpr explicit operator bool() const { return stub_ptr_; }

  template <typename ...B>
  constexpr R operator()(B&&... args) const
  {
//  assert(stub_ptr);
    return (*stub_ptr_)(object_ptr_, std::forward<B>(args)...);
  }

private:
  friend class ::std::hash<delegate>;

  typedef void (*deleter_type)(void*);

  void* object_ptr_{};
  stub_ptr_type stub_ptr_{};

  deleter_type deleter_;

  std::shared_ptr<void> store_;
  std::size_t store_size_;

  template <class T>
  static void destructor_stub(void* const p)
  {
    static_cast<T*>(p)->~T();
  }

  template <class T>
  static void functor_deleter(void* const p)
  {
    static_cast<T*>(p)->~T();

    operator delete(p);
  }

  template <R (*function_ptr)(A...)>
  static constexpr R function_stub(void* const,
    A const... args)
  {
    return (*function_ptr)(args...);
  }

  template <class C, R (C::*method_ptr)(A...)>
  static constexpr R method_stub(void* const object_ptr_,
    A const... args)
  {
    return (static_cast<C*>(object_ptr_)->*method_ptr)(args...);
  }

  template <class C, R (C::*method_ptr)(A...) const>
  static constexpr R const_method_stub(void* const object_ptr_,
    A const... args)
  {
    return (static_cast<C const*>(object_ptr_)->*method_ptr)(args...);
  }

  template <typename T>
  static constexpr R functor_stub(void* const object_ptr_,
    A const... args)
  {
    return (*static_cast<T*>(object_ptr_))(args...);
  }
};

namespace std
{
  template <typename R, typename ...A>
  struct hash<delegate<R (A...)> >
  {
    size_t operator()(delegate<R (A...)> const& d) const
    {
      auto const seed(hash<void*>()(d.object_ptr_) + 0x9e3779b9);

      return hash<typename delegate<R (A...)>::stub_ptr_type>()(d.stub_ptr_)
        + 0x9e3779b9 + (seed << 6) + (seed >> 2);
    }
  };
}

#endif // DELEGATE_HPP
<commit_msg>hash added<commit_after>#pragma once
#ifndef DELEGATE_HPP
# define DELEGATE_HPP

#include <cassert>

#include <memory>

#include <new>

#include <type_traits>

#include <utility>

template <typename T> class delegate;

template<class R, class ...A>
class delegate<R (A...)>
{
  template <typename U, typename = void> struct is_functora
    : std::false_type { };

  template <typename U>
  struct is_functora<U,
    typename std::enable_if<bool(sizeof((R (U::*)(A...))
      &U::operator()))>::type
  > : std::true_type { };

  template <typename U, typename = void> struct is_functorb
    : std::false_type { };

  template <typename U>
  struct is_functorb<U,
    typename std::enable_if<bool(sizeof((R (U::*)(A...) const)
      &U::operator()))>::type
  > : std::true_type { };

  template <typename U>
  struct is_functor
  {
    static constexpr bool const value = is_functora<U>::value
      || is_functorb<U>::value;
  };

  typedef R (*stub_ptr_type)(void*, A...);

  constexpr delegate(void* const o, stub_ptr_type const m)
    : object_ptr_(o),
      stub_ptr_(m)
  {
  }

public:
  constexpr delegate() = default;

  constexpr delegate(delegate const&) = default;

  constexpr delegate(delegate&&) = default;

  template <class C>
  constexpr delegate(C const* const o)
    : object_ptr_(const_cast<C*>(o))
  {
  }

  template <class C>
  constexpr delegate(C const& o)
    : object_ptr_(const_cast<C*>(&o))
  {
  }

  delegate(R (* const function_ptr)(A...))
  {
    *this = from(function_ptr);
  }

  template <class C>
  delegate(C* const object_ptr_, R (C::* const method_ptr)(A...))
  {
    *this = from(object_ptr_, method_ptr);
  }

  template <class C>
  delegate(C* const object_ptr_, R (C::* const method_ptr)(A...) const)
  {
    *this = from(object_ptr_, method_ptr);
  }

  template <class C>
  delegate(C& object, R (C::* const method_ptr)(A...))
  {
    *this = from(object, method_ptr);
  }

  template <class C>
  delegate(C const& object, R (C::* const method_ptr)(A...) const)
  {
    *this = from(object, method_ptr);
  }

  template <
    typename T,
    typename = typename std::enable_if<
      !std::is_same<delegate, typename std::remove_const<
        typename std::remove_reference<T>::type>::type>::value
      && is_functor<typename std::remove_reference<T>::type>::value
    >::type
  >
  delegate(T&& f)
    : store_(operator new(sizeof(T)),
        functor_deleter<typename std::remove_reference<T>::type>),
      store_size_(sizeof(T))
  {
    typedef typename std::remove_reference<T>::type functor_type;

    object_ptr_ = new (store_.get()) functor_type(std::forward<T>(f));

    stub_ptr_ = functor_stub<functor_type>;

    deleter_ = destructor_stub<functor_type>;
  }

  delegate& operator=(delegate const&) = default;

  delegate& operator=(delegate&& rhs) = default;

  template <class C>
  delegate& operator=(R (C::* const rhs)(A...))
  {
    return *this = from(static_cast<C*>(object_ptr_), rhs);
  }

  template <class C>
  delegate& operator=(R (C::* const rhs)(A...) const)
  {
    return *this = from(static_cast<C const*>(object_ptr_), rhs);
  }

  template <
    typename T,
    typename = typename std::enable_if<
      !std::is_same<delegate, typename std::remove_const<
        typename std::remove_reference<T>::type>::type>::value
      && is_functor<typename std::remove_reference<T>::type>::value
    >::type
  >
  delegate& operator=(T&& f)
  {
    typedef typename std::remove_reference<T>::type functor_type;

    if ((sizeof(T) > store_size_)
      || (decltype(store_.use_count())(1) != store_.use_count()))
    {
      store_.reset(operator new(sizeof(T)),
        functor_deleter<functor_type>);

      store_size_ = sizeof(T);
    }
    else
    {
      deleter_(store_.get());
    }

    object_ptr_ = new (store_.get()) functor_type(std::forward<T>(f));

    stub_ptr_ = functor_stub<functor_type>;

    deleter_ = destructor_stub<functor_type>;

    return *this;
  }

  template <R (*function_ptr)(A...)>
  static constexpr delegate from()
  {
    return { nullptr, function_stub<function_ptr> };
  }

  template <class C, R (C::*method_ptr)(A...)>
  static constexpr delegate from(C* const object_ptr_)
  {
    return { object_ptr_, method_stub<C, method_ptr> };
  }

  template <class C, R (C::*method_ptr)(A...) const>
  static constexpr delegate from(C const* const object_ptr_)
  {
    return { const_cast<C*>(object_ptr_), const_method_stub<C, method_ptr> };
  }

  template <class C, R (C::*method_ptr)(A...)>
  static constexpr delegate from(C& object)
  {
    return { &object, method_stub<C, method_ptr> };
  }

  template <class C, R (C::*method_ptr)(A...) const>
  static constexpr delegate from(C const& object)
  {
    return { const_cast<C*>(&object), const_method_stub<C, method_ptr> };
  }

  template <typename T>
  static delegate from(T&& f)
  {
    return { std::forward<T>(f) };
  }

  static constexpr delegate from(R (* const function_ptr)(A...))
  {
    return { [function_ptr](A const... args){
      return (*function_ptr)(args...); } };
  }

  template <class C>
  static constexpr delegate from(C* const object_ptr_,
    R (C::* const method_ptr)(A...))
  {
    return { [object_ptr_, method_ptr](A const... args){
      return (object_ptr_->*method_ptr)(args...); } };
  }

  template <class C>
  static constexpr delegate from(C const* const object_ptr_,
    R (C::* const method_ptr)(A...) const)
  {
    return { [object_ptr_, method_ptr](A const... args){
      return (object_ptr_->*method_ptr)(args...); } };
  }

  template <class C>
  static constexpr delegate from(C& object,
    R (C::* const method_ptr)(A...))
  {
    return { [&object, method_ptr](A const... args){
      return (object.*method_ptr)(args...); } };
  }

  template <class C>
  static constexpr delegate from(C const& object,
    R (C::* const method_ptr)(A...) const)
  {
    return { [&object, method_ptr](A const... args){
      return (object.*method_ptr)(args...); } };
  }

  void reset() { stub_ptr_ = nullptr; }

  void swap(delegate& other)
  {
    std::swap(*this, other);
  }

  constexpr bool operator==(delegate const& rhs) const
  {
    return (stub_ptr_ == rhs.stub_ptr_)
      && (object_ptr_ == rhs.object_ptr_);
  }

  constexpr bool operator!=(delegate const& rhs) const
  {
    return !operator==(rhs);
  }

  constexpr bool operator<(delegate const& rhs) const
  {
    return (object_ptr_ < rhs.object_ptr_)
      || (stub_ptr_ < rhs.stub_ptr_);
  }

  constexpr explicit operator bool() const { return stub_ptr_; }

  template <typename ...B>
  constexpr R operator()(B&&... args) const
  {
//  assert(stub_ptr);
    return (*stub_ptr_)(object_ptr_, std::forward<B>(args)...);
  }

private:
  friend class ::std::hash<delegate>;

  typedef void (*deleter_type)(void*);

  void* object_ptr_{};
  stub_ptr_type stub_ptr_{};

  deleter_type deleter_;

  std::shared_ptr<void> store_;
  std::size_t store_size_;

  template <class T>
  static void destructor_stub(void* const p)
  {
    static_cast<T*>(p)->~T();
  }

  template <class T>
  static void functor_deleter(void* const p)
  {
    static_cast<T*>(p)->~T();

    operator delete(p);
  }

  template <R (*function_ptr)(A...)>
  static constexpr R function_stub(void* const,
    A const... args)
  {
    return (*function_ptr)(args...);
  }

  template <class C, R (C::*method_ptr)(A...)>
  static constexpr R method_stub(void* const object_ptr_,
    A const... args)
  {
    return (static_cast<C*>(object_ptr_)->*method_ptr)(args...);
  }

  template <class C, R (C::*method_ptr)(A...) const>
  static constexpr R const_method_stub(void* const object_ptr_,
    A const... args)
  {
    return (static_cast<C const*>(object_ptr_)->*method_ptr)(args...);
  }

  template <typename T>
  static constexpr R functor_stub(void* const object_ptr_,
    A const... args)
  {
    return (*static_cast<T*>(object_ptr_))(args...);
  }
};

namespace std
{
  template <typename R, typename ...A>
  struct hash<delegate<R (A...)> >
  {
    size_t operator()(delegate<R (A...)> const& d) const
    {
      auto const seed(hash<void*>()(d.object_ptr_) + 0x9e3779b9);

      return hash<typename delegate<R (A...)>::stub_ptr_type>()(d.stub_ptr_)
        + 0x9e3779b9 + (seed << 6) + (seed >> 2);
    }
  };
}

#endif // DELEGATE_HPP
<|endoftext|>


<commit_before>#include <gtest/gtest.h>
#include "utTerm.h"

int main( int argc , char **argv )
{
    testing :: InitGoogleTest( &argc , argv ) ;
    return RUN_ALL_TESTS( ) ;
}
<commit_msg>Delete MainTerm.cpp<commit_after><|endoftext|>


<commit_before>/***********************************************************************
    filename:   ItemViewRenderer.cpp
    created:    Mon Jun 02 2014
    author:     Timotei Dolean <timotei21@gmail.com>
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team
 *
 *   Permission is hereby granted, free of charge, to any person obtaining
 *   a copy of this software and associated documentation files (the
 *   "Software"), to deal in the Software without restriction, including
 *   without limitation the rights to use, copy, modify, merge, publish,
 *   distribute, sublicense, and/or sell copies of the Software, and to
 *   permit persons to whom the Software is furnished to do so, subject to
 *   the following conditions:
 *
 *   The above copyright notice and this permission notice shall be
 *   included in all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *   OTHER DEALINGS IN THE SOFTWARE.
 ***************************************************************************/
#include "CEGUI/WindowRendererSets/Core/ItemViewRenderer.h"
#include "CEGUI/falagard/WidgetLookManager.h"

namespace CEGUI
{

//----------------------------------------------------------------------------//
ItemViewRenderer::ItemViewRenderer(const String& type) :
    WindowRenderer(type)
{
}

//----------------------------------------------------------------------------//
Rectf ItemViewRenderer::getItemRenderingArea(bool hscroll, bool vscroll) const
{
    const WidgetLookFeel& wlf = getLookNFeel();
    String scroll_suffix;

    if (vscroll)
        scroll_suffix += "V";

    if (hscroll)
        scroll_suffix += "H";

    if(!scroll_suffix.empty())
        scroll_suffix += "Scroll";

    const String area_names[] = { "ItemRenderingArea", "ItemRenderArea" };
    const String suffixes[] = { scroll_suffix, "" };

    for (size_t suffix_id = 0; suffix_id < 2; suffix_id++)
    {
        const String& suffix = suffixes[suffix_id];

        for (size_t area_id = 0; area_id < 2; ++area_id)
        {
            const String& full_area_name = area_names[area_id] + suffix;

            if (wlf.isNamedAreaDefined(full_area_name))
                return wlf.getNamedArea(full_area_name).getArea().getPixelRect(*d_window);
        }
    }

    CEGUI_THROW(UnknownObjectException("There is no item rendering area defined!"));
}

}
<commit_msg>Fix the instantiating of a string<commit_after>/***********************************************************************
    filename:   ItemViewRenderer.cpp
    created:    Mon Jun 02 2014
    author:     Timotei Dolean <timotei21@gmail.com>
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team
 *
 *   Permission is hereby granted, free of charge, to any person obtaining
 *   a copy of this software and associated documentation files (the
 *   "Software"), to deal in the Software without restriction, including
 *   without limitation the rights to use, copy, modify, merge, publish,
 *   distribute, sublicense, and/or sell copies of the Software, and to
 *   permit persons to whom the Software is furnished to do so, subject to
 *   the following conditions:
 *
 *   The above copyright notice and this permission notice shall be
 *   included in all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *   OTHER DEALINGS IN THE SOFTWARE.
 ***************************************************************************/
#include "CEGUI/WindowRendererSets/Core/ItemViewRenderer.h"
#include "CEGUI/falagard/WidgetLookManager.h"

namespace CEGUI
{

//----------------------------------------------------------------------------//
ItemViewRenderer::ItemViewRenderer(const String& type) :
    WindowRenderer(type)
{
}

//----------------------------------------------------------------------------//
Rectf ItemViewRenderer::getItemRenderingArea(bool hscroll, bool vscroll) const
{
    const WidgetLookFeel& wlf = getLookNFeel();
    String scroll_suffix;

    if (vscroll)
        scroll_suffix += "V";

    if (hscroll)
        scroll_suffix += "H";

    if(!scroll_suffix.empty())
        scroll_suffix += "Scroll";

    const String area_names[] = { "ItemRenderingArea", "ItemRenderArea" };
    const String suffixes[] = { scroll_suffix, "" };

    for (size_t suffix_id = 0; suffix_id < 2; suffix_id++)
    {
        const String& suffix = suffixes[suffix_id];

        for (size_t area_id = 0; area_id < 2; ++area_id)
        {
            const String full_area_name(area_names[area_id] + suffix);

            if (wlf.isNamedAreaDefined(full_area_name))
                return wlf.getNamedArea(full_area_name).getArea().getPixelRect(*d_window);
        }
    }

    CEGUI_THROW(UnknownObjectException("There is no item rendering area defined!"));
}

}
<|endoftext|>


<commit_before>// Copyright (c) 2010 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 "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"

#if defined(OS_WIN)
#define MAYBE_Infobars Infobars
#else
// Need to finish port to Linux. See http://crbug.com/39916 for details.
// Temporarily marked as DISABLED on OSX too. See http://crbug.com/60990 for details.
#define MAYBE_Infobars DISABLED_Infobars
#endif

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Infobars) {
  // TODO(finnur): Remove once infobars are no longer experimental (bug 39511).
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

  ASSERT_TRUE(RunExtensionTest("infobars")) << message_;
}
<commit_msg>Marking ExtensionApiTest.Infobars as DISABLED on Windows.<commit_after>// Copyright (c) 2010 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 "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"

#if defined(OS_WIN)
// Also marking this as disabled on Windows. See http://crbug.com/75451.
#define MAYBE_Infobars DISABLED_Infobars
#else
// Need to finish port to Linux. See http://crbug.com/39916 for details.
// Temporarily marked as DISABLED on OSX too. See http://crbug.com/60990 for details.
#define MAYBE_Infobars DISABLED_Infobars
#endif

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Infobars) {
  // TODO(finnur): Remove once infobars are no longer experimental (bug 39511).
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

  ASSERT_TRUE(RunExtensionTest("infobars")) << message_;
}
<|endoftext|>


<commit_before>// Copyright (c) 2010 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 "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"

#if defined(TOOLKIT_VIEWS)
#define MAYBE_Infobars Infobars
#else
// Need to finish port to Linux. See http://crbug.com/39916 for details.
// Temporarily marked as DISABLED on OSX too. See http://crbug.com/60990 for details.
#define MAYBE_Infobars DISABLED_Infobars
#endif

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Infobars) {
  // TODO(finnur): Remove once infobars are no longer experimental (bug 39511).
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

  ASSERT_TRUE(RunExtensionTest("infobars")) << message_;
}
<commit_msg>Marking ExtensionApiTest, Infobars as DISABLED on everything but Windows.<commit_after>// Copyright (c) 2010 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 "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"

#if defined(OS_WIN)
#define MAYBE_Infobars Infobars
#else
// Need to finish port to Linux. See http://crbug.com/39916 for details.
// Temporarily marked as DISABLED on OSX too. See http://crbug.com/60990 for details.
#define MAYBE_Infobars DISABLED_Infobars
#endif

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Infobars) {
  // TODO(finnur): Remove once infobars are no longer experimental (bug 39511).
  CommandLine::ForCurrentProcess()->AppendSwitch(
      switches::kEnableExperimentalExtensionApis);

  ASSERT_TRUE(RunExtensionTest("infobars")) << message_;
}
<|endoftext|>


<commit_before>// Copyright (c) 2011 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 "chrome/browser/prerender/prerender_resource_handler.h"

#include "chrome/browser/net/chrome_url_request_context.h"
#include "content/common/resource_response.h"
#include "net/base/load_flags.h"
#include "net/http/http_response_headers.h"
#include "net/url_request/url_request.h"

namespace prerender {

namespace {

bool ShouldPrerenderURL(const GURL& url) {
  if (!url.is_valid())
    return false;
  if (!url.SchemeIs("http")) {
    RecordFinalStatus(FINAL_STATUS_HTTPS);
    return false;
  }
  return true;
}

bool ValidateAliasURLs(const std::vector<GURL>& urls) {
  for (std::vector<GURL>::const_iterator it = urls.begin();
       it != urls.end();
       ++it) {
    if (!ShouldPrerenderURL(*it))
      return false;
  }
  return true;
}

bool ShouldPrerender(const ResourceResponse* response) {
  if (!response)
    return false;
  const ResourceResponseHead& rrh = response->response_head;
  if (!rrh.headers)
    return false;
  if (rrh.mime_type != "text/html")
    return false;
  if (rrh.headers->response_code() != 200)
    return false;
  return true;
}

}  // namespace

PrerenderResourceHandler* PrerenderResourceHandler::MaybeCreate(
    const net::URLRequest& request,
    ChromeURLRequestContext* context,
    ResourceHandler* next_handler) {
  if (!context || !context->prerender_manager())
    return NULL;
  if (request.load_flags() & net::LOAD_PRERENDER) {
    RecordFinalStatus(FINAL_STATUS_NESTED);
    return NULL;
  }
  if (!(request.load_flags() & net::LOAD_PREFETCH))
    return NULL;
  if (!ShouldPrerenderURL(request.url()))
    return NULL;
  if (request.method() != "GET")
    return NULL;
  return new PrerenderResourceHandler(request,
                                      next_handler,
                                      context->prerender_manager());
}

PrerenderResourceHandler::PrerenderResourceHandler(
    const net::URLRequest& request,
    ResourceHandler* next_handler,
    PrerenderManager* prerender_manager)
    : next_handler_(next_handler),
      prerender_manager_(prerender_manager),
      ALLOW_THIS_IN_INITIALIZER_LIST(
          prerender_callback_(NewCallback(
              this, &PrerenderResourceHandler::StartPrerender))),
      request_(request) {
  DCHECK(next_handler);
  DCHECK(prerender_manager);
}

PrerenderResourceHandler::PrerenderResourceHandler(
    const net::URLRequest& request,
    ResourceHandler* next_handler,
    PrerenderCallback* callback)
    : next_handler_(next_handler),
      prerender_callback_(callback),
      request_(request) {
  DCHECK(next_handler);
  DCHECK(callback);
}

PrerenderResourceHandler::~PrerenderResourceHandler() {
}

bool PrerenderResourceHandler::OnUploadProgress(int request_id,
                                                uint64 position,
                                                uint64 size) {
  return next_handler_->OnUploadProgress(request_id, position, size);
}

bool PrerenderResourceHandler::OnRequestRedirected(int request_id,
                                                   const GURL& url,
                                                   ResourceResponse* response,
                                                   bool* defer) {
  bool will_redirect = next_handler_->OnRequestRedirected(
      request_id, url, response, defer);
  if (will_redirect) {
    if (!ShouldPrerenderURL(url))
      return false;
    alias_urls_.push_back(url);
    url_ = url;
  }
  return will_redirect;
}

bool PrerenderResourceHandler::OnResponseStarted(int request_id,
                                                 ResourceResponse* response) {
  if (ShouldPrerender(response)) {
    DCHECK(ValidateAliasURLs(alias_urls_));
    BrowserThread::PostTask(
        BrowserThread::UI,
        FROM_HERE,
        NewRunnableMethod(
            this,
            &PrerenderResourceHandler::RunCallbackFromUIThread,
            url_,
            alias_urls_,
            GURL(request_.referrer())));
  }
  return next_handler_->OnResponseStarted(request_id, response);
}

bool PrerenderResourceHandler::OnWillStart(int request_id,
                                           const GURL& url,
                                           bool* defer) {
  bool will_start = next_handler_->OnWillStart(request_id, url, defer);
  if (will_start) {
    if (!ShouldPrerenderURL(url))
      return false;
    alias_urls_.push_back(url);
    url_ = url;
  }
  return will_start;
}

bool PrerenderResourceHandler::OnWillRead(int request_id,
                                          net::IOBuffer** buf,
                                          int* buf_size,
                                          int min_size) {
  return next_handler_->OnWillRead(request_id, buf, buf_size, min_size);
}

bool PrerenderResourceHandler::OnReadCompleted(int request_id,
                                               int* bytes_read) {
  return next_handler_->OnReadCompleted(request_id, bytes_read);
}

bool PrerenderResourceHandler::OnResponseCompleted(
    int request_id,
    const net::URLRequestStatus& status,
    const std::string& security_info) {
  return next_handler_->OnResponseCompleted(request_id, status, security_info);
}

void PrerenderResourceHandler::OnRequestClosed() {
  next_handler_->OnRequestClosed();
}

void PrerenderResourceHandler::RunCallbackFromUIThread(
    const GURL& url,
    const std::vector<GURL>& alias_urls,
    const GURL& referrer) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  prerender_callback_->Run(url, alias_urls, referrer);
}

void PrerenderResourceHandler::StartPrerender(
    const GURL& url,
    const std::vector<GURL>& alias_urls,
    const GURL& referrer) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  prerender_manager_->AddPreload(url, alias_urls, referrer);
}

}  // namespace prerender
<commit_msg>Move FINAL_STATUS_NESTED later so it is not counted too heavily.<commit_after>// Copyright (c) 2011 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 "chrome/browser/prerender/prerender_resource_handler.h"

#include "chrome/browser/net/chrome_url_request_context.h"
#include "content/common/resource_response.h"
#include "net/base/load_flags.h"
#include "net/http/http_response_headers.h"
#include "net/url_request/url_request.h"

namespace prerender {

namespace {

bool ShouldPrerenderURL(const GURL& url) {
  if (!url.is_valid())
    return false;
  if (!url.SchemeIs("http")) {
    RecordFinalStatus(FINAL_STATUS_HTTPS);
    return false;
  }
  return true;
}

bool ValidateAliasURLs(const std::vector<GURL>& urls) {
  for (std::vector<GURL>::const_iterator it = urls.begin();
       it != urls.end();
       ++it) {
    if (!ShouldPrerenderURL(*it))
      return false;
  }
  return true;
}

bool ShouldPrerender(const ResourceResponse* response) {
  if (!response)
    return false;
  const ResourceResponseHead& rrh = response->response_head;
  if (!rrh.headers)
    return false;
  if (rrh.mime_type != "text/html")
    return false;
  if (rrh.headers->response_code() != 200)
    return false;
  return true;
}

}  // namespace

PrerenderResourceHandler* PrerenderResourceHandler::MaybeCreate(
    const net::URLRequest& request,
    ChromeURLRequestContext* context,
    ResourceHandler* next_handler) {
  if (!context || !context->prerender_manager())
    return NULL;
  if (!(request.load_flags() & net::LOAD_PREFETCH))
    return NULL;
  if (!ShouldPrerenderURL(request.url()))
    return NULL;
  if (request.method() != "GET")
    return NULL;
  if (request.load_flags() & net::LOAD_PRERENDER) {
    RecordFinalStatus(FINAL_STATUS_NESTED);
    return NULL;
  }
  return new PrerenderResourceHandler(request,
                                      next_handler,
                                      context->prerender_manager());
}

PrerenderResourceHandler::PrerenderResourceHandler(
    const net::URLRequest& request,
    ResourceHandler* next_handler,
    PrerenderManager* prerender_manager)
    : next_handler_(next_handler),
      prerender_manager_(prerender_manager),
      ALLOW_THIS_IN_INITIALIZER_LIST(
          prerender_callback_(NewCallback(
              this, &PrerenderResourceHandler::StartPrerender))),
      request_(request) {
  DCHECK(next_handler);
  DCHECK(prerender_manager);
}

PrerenderResourceHandler::PrerenderResourceHandler(
    const net::URLRequest& request,
    ResourceHandler* next_handler,
    PrerenderCallback* callback)
    : next_handler_(next_handler),
      prerender_callback_(callback),
      request_(request) {
  DCHECK(next_handler);
  DCHECK(callback);
}

PrerenderResourceHandler::~PrerenderResourceHandler() {
}

bool PrerenderResourceHandler::OnUploadProgress(int request_id,
                                                uint64 position,
                                                uint64 size) {
  return next_handler_->OnUploadProgress(request_id, position, size);
}

bool PrerenderResourceHandler::OnRequestRedirected(int request_id,
                                                   const GURL& url,
                                                   ResourceResponse* response,
                                                   bool* defer) {
  bool will_redirect = next_handler_->OnRequestRedirected(
      request_id, url, response, defer);
  if (will_redirect) {
    if (!ShouldPrerenderURL(url))
      return false;
    alias_urls_.push_back(url);
    url_ = url;
  }
  return will_redirect;
}

bool PrerenderResourceHandler::OnResponseStarted(int request_id,
                                                 ResourceResponse* response) {
  if (ShouldPrerender(response)) {
    DCHECK(ValidateAliasURLs(alias_urls_));
    BrowserThread::PostTask(
        BrowserThread::UI,
        FROM_HERE,
        NewRunnableMethod(
            this,
            &PrerenderResourceHandler::RunCallbackFromUIThread,
            url_,
            alias_urls_,
            GURL(request_.referrer())));
  }
  return next_handler_->OnResponseStarted(request_id, response);
}

bool PrerenderResourceHandler::OnWillStart(int request_id,
                                           const GURL& url,
                                           bool* defer) {
  bool will_start = next_handler_->OnWillStart(request_id, url, defer);
  if (will_start) {
    if (!ShouldPrerenderURL(url))
      return false;
    alias_urls_.push_back(url);
    url_ = url;
  }
  return will_start;
}

bool PrerenderResourceHandler::OnWillRead(int request_id,
                                          net::IOBuffer** buf,
                                          int* buf_size,
                                          int min_size) {
  return next_handler_->OnWillRead(request_id, buf, buf_size, min_size);
}

bool PrerenderResourceHandler::OnReadCompleted(int request_id,
                                               int* bytes_read) {
  return next_handler_->OnReadCompleted(request_id, bytes_read);
}

bool PrerenderResourceHandler::OnResponseCompleted(
    int request_id,
    const net::URLRequestStatus& status,
    const std::string& security_info) {
  return next_handler_->OnResponseCompleted(request_id, status, security_info);
}

void PrerenderResourceHandler::OnRequestClosed() {
  next_handler_->OnRequestClosed();
}

void PrerenderResourceHandler::RunCallbackFromUIThread(
    const GURL& url,
    const std::vector<GURL>& alias_urls,
    const GURL& referrer) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  prerender_callback_->Run(url, alias_urls, referrer);
}

void PrerenderResourceHandler::StartPrerender(
    const GURL& url,
    const std::vector<GURL>& alias_urls,
    const GURL& referrer) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  prerender_manager_->AddPreload(url, alias_urls, referrer);
}

}  // namespace prerender
<|endoftext|>