<commit_before>//
// Copyright (c) 2017 Kimball Thurston
// All rights reserved.
// Copyrights licensed under the MIT License.
// See the accompanying LICENSE.txt file for terms
//

#if defined(HAVE_PYTHON2) || defined(HAVE_PYTHON3)
# define HAVE_PYTHON 1
#endif

#ifdef HAVE_PYTHON
#pragma GCC diagnostic ignored "-Wreserved-id-macro"
#pragma GCC diagnostic ignored "-Wold-style-cast"
#include <Python.h>
#endif
#if PY_MAJOR_VERSION <= 1
#error python 2 or higher is required
#else
# if PY_MAJOR_VERSION < 3
#  define IS_PYTHON2 1
# elif PY_MAJOR_VERSION < 4
#  define IS_PYTHON3 1
# endif
#endif

#include "context.h"
#include <stdexcept>
#include <atomic>
#include <map>

////////////////////////////////////////

namespace python_bridge
{

#ifdef HAVE_PYTHON
static std::atomic_flag _active_context = ATOMIC_FLAG_INIT;
class context::priv_Impl
{
public:
	priv_Impl( const std::string &argv0 )
	{
		if ( _active_context.test_and_set( std::memory_order_acquire ) )
			throw std::runtime_error( "Current version of python does not allow multiple active contexts at once" );

#ifdef IS_PYTHON2
		_progname = strdup( argv0.c_str() );
#else
		_progname = Py_DecodeLocale( argv0.c_str(), nullptr );
		if ( ! _progname )
			throw std::runtime_error( "Unable to decode argv[0]" );
#endif
		Py_SetProgramName( _progname );
		Py_Initialize();
	}

	~priv_Impl( void )
	{
#ifdef IS_PYTHON2
		Py_Finalize();
		if ( _progname )
			::free( _progname );
#else
		if ( Py_FinalizeEx() < 0 )
			std::cerr << "ERROR shutting down python interpreter" << std::endl;
		if ( _progname )
			PyMem_RawFree( _progname );
#endif
		_active_context.clear( std::memory_order_release );
	}

	bool load_module( const char *fn, const std::string &tag )
	{
		auto i = _glob_modules.find( tag );
		if ( i != _glob_modules.end() )
			Py_DECREF( i->second );

#ifdef IS_PYTHON2
		PyObject *pName = PyString_FromString( fn );
#else
		PyObject *pName = PyUnicode_DecodeFSDefault( fn );
#endif
		// TODO: add error checks
		PyObject *pModule = PyImport_Import( pName );
		Py_DECREF( pName );
		if ( pModule )
		{
			_glob_modules[tag] = pModule;
			return true;
		}
		return false;
	}

private:
#ifdef IS_PYTHON2
	char *_progname = nullptr;
#else
	wchar_t *_progname = nullptr;
#endif
	std::map<std::string, PyObject *> _glob_modules;
};
#endif

////////////////////////////////////////

context::context( const std::string &argv0 )
#ifdef HAVE_PYTHON
		: _impl( new priv_Impl( argv0 ) )
#endif
{
}

////////////////////////////////////////

context::~context( void )
{
}

////////////////////////////////////////

bool context::run( const std::string &fn )
{
#ifdef HAVE_PYTHON
	return _impl->load_module( fn.c_str(), fn );
#else
	return false;
#endif
}

////////////////////////////////////////

bool context::run( const base::uri &u )
{
#ifdef HAVE_PYTHON
	throw std::logic_error( "Not Yet Implemented" );
#else
	return false;
#endif
}

////////////////////////////////////////

void context::push_eval_lookup( lookup &l )
{
#ifdef HAVE_PYTHON
#endif
}

////////////////////////////////////////

void context::pop_eval_lookup( void )
{
#ifdef HAVE_PYTHON
#endif
}

////////////////////////////////////////

bool context::evaluate( bool &result, const char *s )
{
#ifdef HAVE_PYTHON
#else
	return false;
#endif
}

////////////////////////////////////////

bool context::evaluate( int &result, const char *s )
{
#ifdef HAVE_PYTHON
#else
	return false;
#endif
}

////////////////////////////////////////

bool context::evaluate( float &result, const char *s )
{
#ifdef HAVE_PYTHON
#else
	return false;
#endif
}

////////////////////////////////////////

bool context::evaluate( double &result, const char *s )
{
#ifdef HAVE_PYTHON
#else
	return false;
#endif
}

////////////////////////////////////////

bool context::evaluate( int64_t &result, const char *s )
{
#ifdef HAVE_PYTHON
#else
	return false;
#endif
}

////////////////////////////////////////

bool context::evaluate( std::string &result, const char *s )
{
#ifdef HAVE_PYTHON
#else
	return false;
#endif
}

////////////////////////////////////////

bool context::evaluate( std::wstring &result, const char *s )
{
#ifdef HAVE_PYTHON
#else
	return false;
#endif
}

////////////////////////////////////////

} // namespace python_bridge

<commit_msg>fix includes for prototype<commit_after>//
// Copyright (c) 2017 Kimball Thurston
// All rights reserved.
// Copyrights licensed under the MIT License.
// See the accompanying LICENSE.txt file for terms
//

#if defined(HAVE_PYTHON2) || defined(HAVE_PYTHON3)
# define HAVE_PYTHON 1
#endif

#ifdef HAVE_PYTHON
# if defined(__clang__)
#  pragma GCC diagnostic ignored "-Wreserved-id-macro"
#  pragma GCC diagnostic ignored "-Wold-style-cast"
# endif
# include <Python.h>
# if PY_MAJOR_VERSION <= 1
#  error python 2 or higher is required
# else
#  if PY_MAJOR_VERSION < 3
#   define IS_PYTHON2 1
#  elif PY_MAJOR_VERSION < 4
#   define IS_PYTHON3 1
#  endif
# endif
#endif

#include "context.h"
#include <stdexcept>
#include <atomic>
#include <map>

////////////////////////////////////////

namespace python_bridge
{

#ifdef HAVE_PYTHON
static std::atomic_flag _active_context = ATOMIC_FLAG_INIT;
class context::priv_Impl
{
public:
	priv_Impl( const std::string &argv0 )
	{
		if ( _active_context.test_and_set( std::memory_order_acquire ) )
			throw std::runtime_error( "Current version of python does not allow multiple active contexts at once" );

#ifdef IS_PYTHON2
		_progname = strdup( argv0.c_str() );
#else
		_progname = Py_DecodeLocale( argv0.c_str(), nullptr );
		if ( ! _progname )
			throw std::runtime_error( "Unable to decode argv[0]" );
#endif
		Py_SetProgramName( _progname );
		Py_Initialize();
	}

	~priv_Impl( void )
	{
#ifdef IS_PYTHON2
		Py_Finalize();
		if ( _progname )
			::free( _progname );
#else
		if ( Py_FinalizeEx() < 0 )
			std::cerr << "ERROR shutting down python interpreter" << std::endl;
		if ( _progname )
			PyMem_RawFree( _progname );
#endif
		_active_context.clear( std::memory_order_release );
	}

	bool load_module( const char *fn, const std::string &tag )
	{
		auto i = _glob_modules.find( tag );
		if ( i != _glob_modules.end() )
			Py_DECREF( i->second );

#ifdef IS_PYTHON2
		PyObject *pName = PyString_FromString( fn );
#else
		PyObject *pName = PyUnicode_DecodeFSDefault( fn );
#endif
		// TODO: add error checks
		PyObject *pModule = PyImport_Import( pName );
		Py_DECREF( pName );
		if ( pModule )
		{
			_glob_modules[tag] = pModule;
			return true;
		}
		return false;
	}

private:
#ifdef IS_PYTHON2
	char *_progname = nullptr;
#else
	wchar_t *_progname = nullptr;
#endif
	std::map<std::string, PyObject *> _glob_modules;
};
#endif

////////////////////////////////////////

context::context( const std::string &argv0 )
#ifdef HAVE_PYTHON
		: _impl( new priv_Impl( argv0 ) )
#endif
{
}

////////////////////////////////////////

context::~context( void )
{
}

////////////////////////////////////////

bool context::run( const std::string &fn )
{
#ifdef HAVE_PYTHON
	return _impl->load_module( fn.c_str(), fn );
#else
	return false;
#endif
}

////////////////////////////////////////

bool context::run( const base::uri &u )
{
#ifdef HAVE_PYTHON
	throw std::logic_error( "Not Yet Implemented" );
#else
	return false;
#endif
}

////////////////////////////////////////

void context::push_eval_lookup( lookup &l )
{
#ifdef HAVE_PYTHON
#endif
}

////////////////////////////////////////

void context::pop_eval_lookup( void )
{
#ifdef HAVE_PYTHON
#endif
}

////////////////////////////////////////

bool context::evaluate( bool &result, const char *s )
{
#ifdef HAVE_PYTHON
	return true;
#else
	return false;
#endif
}

////////////////////////////////////////

bool context::evaluate( int &result, const char *s )
{
#ifdef HAVE_PYTHON
	return true;
#else
	return false;
#endif
}

////////////////////////////////////////

bool context::evaluate( float &result, const char *s )
{
#ifdef HAVE_PYTHON
	return true;
#else
	return false;
#endif
}

////////////////////////////////////////

bool context::evaluate( double &result, const char *s )
{
#ifdef HAVE_PYTHON
	return true;
#else
	return false;
#endif
}

////////////////////////////////////////

bool context::evaluate( int64_t &result, const char *s )
{
#ifdef HAVE_PYTHON
	return true;
#else
	return false;
#endif
}

////////////////////////////////////////

bool context::evaluate( std::string &result, const char *s )
{
#ifdef HAVE_PYTHON
	return true;
#else
	return false;
#endif
}

////////////////////////////////////////

bool context::evaluate( std::wstring &result, const char *s )
{
#ifdef HAVE_PYTHON
	return true;
#else
	return false;
#endif
}

////////////////////////////////////////

} // namespace python_bridge

<|endoftext|>


<commit_before>#include "ui/socket_item.h"

#include <QApplication>
#include <QCursor>
#include <QDebug>
#include <QDrag>
#include <QGraphicsSceneMouseEvent>
#include <QGraphicsWidget>
#include <QMimeData>
#include <QWidget>

#include "elements/package.h"
#include "ui/colors.h"
#include "ui/link_item.h"
#include "ui/package_view.h"

SocketItem::SocketItem(Type a_type, QGraphicsItem *const a_parent)
  : QGraphicsItem{ a_parent }
  , m_type{ a_type }
{
  m_font.setFamily("Consolas");
  m_font.setPointSize(12);

  setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsFocusable |
           QGraphicsItem::ItemSendsScenePositionChanges);
  setAcceptHoverEvents(true);
  setAcceptedMouseButtons(Qt::LeftButton);

  setZValue(1);

  if (a_type == Type::eOutput)
    setCursor(Qt::OpenHandCursor);
  else
    setAcceptDrops(true);
}

QRectF SocketItem::boundingRect() const
{
  return QRectF{ -(static_cast<qreal>(SIZE) / 2.), 0, static_cast<qreal>(SIZE), static_cast<qreal>(SIZE) };
}

void SocketItem::paint(QPainter *a_painter, const QStyleOptionGraphicsItem *a_option, QWidget *a_widget)
{
  Q_UNUSED(a_option);
  Q_UNUSED(a_widget);

  QRectF const rect{ boundingRect() };

  QPen pen{ get_color(Color::eSocketBorder) };
  pen.setWidth(2);

  QBrush brush{};
  if (m_isHover)
    brush.setColor(get_color(Color::eSocketHover));
  else if (m_isDrop)
    brush.setColor(get_color(Color::eSocketDrop));
  else if (m_isSignalOn)
    brush.setColor(m_colorSignalOn);
  else if (!m_isSignalOn)
    brush.setColor(m_colorSignalOff);
  //  else if (m_type == Type::eInput)
  //    brush.setColor(config.getColor(Config::Color::eSocketInput));
  //  else if (m_type == Type::eOutput)
  //    brush.setColor(config.getColor(Config::Color::eSocketOutput));
  brush.setStyle(Qt::SolidPattern);

  a_painter->setPen(pen);
  a_painter->setBrush(brush);
  a_painter->drawEllipse(rect);

  if (m_used) {
    a_painter->save();
    a_painter->setPen(Qt::NoPen);
    a_painter->setBrush(pen.color());
    a_painter->drawEllipse(rect.adjusted(4, 4, -4, -4));
    a_painter->restore();
  }

  if (!m_nameHidden) {
    pen.setColor(get_color(Color::eFontName));
    a_painter->setPen(pen);
    QFont font{ a_painter->font() };
    font.setPointSize(12);
    a_painter->setFont(font);

    QFontMetrics const metrics{ font };

    if (m_type == Type::eInput)
      a_painter->drawText(static_cast<int>(rect.width()) - 2, 13, m_name);
    else
      a_painter->drawText(-metrics.width(m_name) - 14, 13, m_name);
  }
}

void SocketItem::hoverEnterEvent(QGraphicsSceneHoverEvent *a_event)
{
  Q_UNUSED(a_event);

  m_isHover = true;

  for (auto const link : m_links) link->setHover(m_isHover);
}

void SocketItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *a_event)
{
  Q_UNUSED(a_event);

  m_isHover = false;

  for (auto const link : m_links) link->setHover(m_isHover);
}

void SocketItem::dragEnterEvent(QGraphicsSceneDragDropEvent *a_event)
{
  Q_UNUSED(a_event);

  if (m_used) {
    a_event->ignore();
    return;
  }

  PackageView *const view{ reinterpret_cast<PackageView *const>(scene()->views()[0]) };

  LinkItem *const linkItem{ view->dragLink() };
  if (!linkItem || m_valueType != linkItem->valueType()) {
    a_event->ignore();
    return;
  }

  linkItem->setTo(this);
  m_isDrop = true;
}

void SocketItem::dragLeaveEvent(QGraphicsSceneDragDropEvent *a_event)
{
  Q_UNUSED(a_event);

  m_isDrop = false;

  PackageView *const view{ reinterpret_cast<PackageView *const>(scene()->views()[0]) };

  LinkItem *const linkItem{ view->dragLink() };
  if (!linkItem) return;
  linkItem->setTo(nullptr);
}

void SocketItem::dragMoveEvent(QGraphicsSceneDragDropEvent *a_event)
{
  Q_UNUSED(a_event);
}

void SocketItem::dropEvent(QGraphicsSceneDragDropEvent *a_event)
{
  Q_UNUSED(a_event);

  PackageView *const packageView{ reinterpret_cast<PackageView *const>(scene()->views()[0]) };

  LinkItem *const linkItem{ packageView->dragLink() };
  if (!linkItem) return;

  m_links.push_back(linkItem);
  linkItem->setTo(this);
  m_used = true;
  m_isDrop = false;

  packageView->acceptDragLink();

  auto const package = packageView->package();
  auto const from = linkItem->from();

  package->connect(from->elementId(), from->socketId(), m_elementId, m_socketId);

}

void SocketItem::mousePressEvent(QGraphicsSceneMouseEvent *a_event)
{
  Q_UNUSED(a_event);

  if (m_type == Type::eInput) return;

  setCursor(Qt::ClosedHandCursor);
}

void SocketItem::mouseMoveEvent(QGraphicsSceneMouseEvent *a_event)
{
  Q_UNUSED(a_event);

  if (m_type == Type::eInput) return;

  if (QLineF(a_event->screenPos(), a_event->buttonDownScreenPos(Qt::LeftButton)).length() <
      QApplication::startDragDistance())
    return;

  //  QRectF const rect{ boundingRect() };

  QDrag *const drag = new QDrag(a_event->widget());

  QMimeData *const mime = new QMimeData;
  //  mime->setData("data/x-element", QByteArray());
  drag->setMimeData(mime);

  LinkItem *linkItem{ new LinkItem };
  linkItem->setColors(m_colorSignalOff, m_colorSignalOn);
  linkItem->setFrom(this);

  scene()->addItem(linkItem);

  PackageView *const view{ reinterpret_cast<PackageView *const>(scene()->views()[0]) };
  view->setDragLink(linkItem);

  Qt::DropAction const action{ drag->exec() };
  if (action == Qt::IgnoreAction)
    view->cancelDragLink();
  else {
    m_links.push_back(linkItem);
    m_used = true;
  }

  setCursor(Qt::OpenHandCursor);
}

void SocketItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *a_event)
{
  Q_UNUSED(a_event);

  if (m_type == Type::eInput) return;

  setCursor(Qt::OpenHandCursor);
}

QVariant SocketItem::itemChange(QGraphicsItem::GraphicsItemChange a_change, const QVariant &a_value)
{
  if (a_change == QGraphicsItem::ItemScenePositionHasChanged) {
    for (LinkItem *const link : m_links) link->trackNodes();
  }
  return QGraphicsItem::itemChange(a_change, a_value);
}

int SocketItem::nameWidth() const
{
  QFontMetrics const metrics{ m_font };
  return metrics.width(m_name);
}

void SocketItem::setColors(QColor const a_signalOff, QColor const a_signalOn)
{
  m_colorSignalOff = a_signalOff;
  m_colorSignalOn = a_signalOn;
}

void SocketItem::setSignal(const bool a_signal)
{
  m_isSignalOn = a_signal;

  if (m_type == Type::eOutput) {
    for (LinkItem *const link : m_links) link->setSignal(a_signal);
  }
}

void SocketItem::connect(SocketItem *const a_other)
{
  auto const linkItem = new LinkItem;
  linkItem->setColors(m_colorSignalOff, m_colorSignalOn);
  linkItem->setFrom(this);
  linkItem->setTo(a_other);

  m_links.push_back(linkItem);
  m_used = true;

  a_other->m_links.push_back(linkItem);
  a_other->m_used = true;
  a_other->m_isDrop = false;

  scene()->addItem(linkItem);
}
<commit_msg>Call setSignal in SocketItem::dropEvent<commit_after>#include "ui/socket_item.h"

#include <QApplication>
#include <QCursor>
#include <QDebug>
#include <QDrag>
#include <QGraphicsSceneMouseEvent>
#include <QGraphicsWidget>
#include <QMimeData>
#include <QWidget>

#include "elements/package.h"
#include "ui/colors.h"
#include "ui/link_item.h"
#include "ui/package_view.h"

SocketItem::SocketItem(Type a_type, QGraphicsItem *const a_parent)
  : QGraphicsItem{ a_parent }
  , m_type{ a_type }
{
  m_font.setFamily("Consolas");
  m_font.setPointSize(12);

  setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsFocusable |
           QGraphicsItem::ItemSendsScenePositionChanges);
  setAcceptHoverEvents(true);
  setAcceptedMouseButtons(Qt::LeftButton);

  setZValue(1);

  if (a_type == Type::eOutput)
    setCursor(Qt::OpenHandCursor);
  else
    setAcceptDrops(true);
}

QRectF SocketItem::boundingRect() const
{
  return QRectF{ -(static_cast<qreal>(SIZE) / 2.), 0, static_cast<qreal>(SIZE), static_cast<qreal>(SIZE) };
}

void SocketItem::paint(QPainter *a_painter, const QStyleOptionGraphicsItem *a_option, QWidget *a_widget)
{
  Q_UNUSED(a_option);
  Q_UNUSED(a_widget);

  QRectF const rect{ boundingRect() };

  QPen pen{ get_color(Color::eSocketBorder) };
  pen.setWidth(2);

  QBrush brush{};
  if (m_isHover)
    brush.setColor(get_color(Color::eSocketHover));
  else if (m_isDrop)
    brush.setColor(get_color(Color::eSocketDrop));
  else if (m_isSignalOn)
    brush.setColor(m_colorSignalOn);
  else if (!m_isSignalOn)
    brush.setColor(m_colorSignalOff);
  //  else if (m_type == Type::eInput)
  //    brush.setColor(config.getColor(Config::Color::eSocketInput));
  //  else if (m_type == Type::eOutput)
  //    brush.setColor(config.getColor(Config::Color::eSocketOutput));
  brush.setStyle(Qt::SolidPattern);

  a_painter->setPen(pen);
  a_painter->setBrush(brush);
  a_painter->drawEllipse(rect);

  if (m_used) {
    a_painter->save();
    a_painter->setPen(Qt::NoPen);
    a_painter->setBrush(pen.color());
    a_painter->drawEllipse(rect.adjusted(4, 4, -4, -4));
    a_painter->restore();
  }

  if (!m_nameHidden) {
    pen.setColor(get_color(Color::eFontName));
    a_painter->setPen(pen);
    QFont font{ a_painter->font() };
    font.setPointSize(12);
    a_painter->setFont(font);

    QFontMetrics const metrics{ font };

    if (m_type == Type::eInput)
      a_painter->drawText(static_cast<int>(rect.width()) - 2, 13, m_name);
    else
      a_painter->drawText(-metrics.width(m_name) - 14, 13, m_name);
  }
}

void SocketItem::hoverEnterEvent(QGraphicsSceneHoverEvent *a_event)
{
  Q_UNUSED(a_event);

  m_isHover = true;

  for (auto const link : m_links) link->setHover(m_isHover);
}

void SocketItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *a_event)
{
  Q_UNUSED(a_event);

  m_isHover = false;

  for (auto const link : m_links) link->setHover(m_isHover);
}

void SocketItem::dragEnterEvent(QGraphicsSceneDragDropEvent *a_event)
{
  Q_UNUSED(a_event);

  if (m_used) {
    a_event->ignore();
    return;
  }

  PackageView *const view{ reinterpret_cast<PackageView *const>(scene()->views()[0]) };

  LinkItem *const linkItem{ view->dragLink() };
  if (!linkItem || m_valueType != linkItem->valueType()) {
    a_event->ignore();
    return;
  }

  linkItem->setTo(this);
  m_isDrop = true;
}

void SocketItem::dragLeaveEvent(QGraphicsSceneDragDropEvent *a_event)
{
  Q_UNUSED(a_event);

  m_isDrop = false;

  PackageView *const view{ reinterpret_cast<PackageView *const>(scene()->views()[0]) };

  LinkItem *const linkItem{ view->dragLink() };
  if (!linkItem) return;
  linkItem->setTo(nullptr);
}

void SocketItem::dragMoveEvent(QGraphicsSceneDragDropEvent *a_event)
{
  Q_UNUSED(a_event);
}

void SocketItem::dropEvent(QGraphicsSceneDragDropEvent *a_event)
{
  Q_UNUSED(a_event);

  PackageView *const packageView{ reinterpret_cast<PackageView *const>(scene()->views()[0]) };

  LinkItem *const linkItem{ packageView->dragLink() };
  if (!linkItem) return;

  m_links.push_back(linkItem);
  linkItem->setTo(this);
  m_used = true;
  m_isDrop = false;

  packageView->acceptDragLink();

  auto const package = packageView->package();
  auto const from = linkItem->from();

  package->connect(from->elementId(), from->socketId(), m_elementId, m_socketId);

  setSignal(linkItem->isSignalOn());
}

void SocketItem::mousePressEvent(QGraphicsSceneMouseEvent *a_event)
{
  Q_UNUSED(a_event);

  if (m_type == Type::eInput) return;

  setCursor(Qt::ClosedHandCursor);
}

void SocketItem::mouseMoveEvent(QGraphicsSceneMouseEvent *a_event)
{
  Q_UNUSED(a_event);

  if (m_type == Type::eInput) return;

  if (QLineF(a_event->screenPos(), a_event->buttonDownScreenPos(Qt::LeftButton)).length() <
      QApplication::startDragDistance())
    return;

  //  QRectF const rect{ boundingRect() };

  QDrag *const drag = new QDrag(a_event->widget());

  QMimeData *const mime = new QMimeData;
  //  mime->setData("data/x-element", QByteArray());
  drag->setMimeData(mime);

  LinkItem *linkItem{ new LinkItem };
  linkItem->setColors(m_colorSignalOff, m_colorSignalOn);
  linkItem->setFrom(this);

  scene()->addItem(linkItem);

  PackageView *const view{ reinterpret_cast<PackageView *const>(scene()->views()[0]) };
  view->setDragLink(linkItem);

  Qt::DropAction const action{ drag->exec() };
  if (action == Qt::IgnoreAction)
    view->cancelDragLink();
  else {
    m_links.push_back(linkItem);
    m_used = true;
  }

  setCursor(Qt::OpenHandCursor);
}

void SocketItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *a_event)
{
  Q_UNUSED(a_event);

  if (m_type == Type::eInput) return;

  setCursor(Qt::OpenHandCursor);
}

QVariant SocketItem::itemChange(QGraphicsItem::GraphicsItemChange a_change, const QVariant &a_value)
{
  if (a_change == QGraphicsItem::ItemScenePositionHasChanged) {
    for (LinkItem *const link : m_links) link->trackNodes();
  }
  return QGraphicsItem::itemChange(a_change, a_value);
}

int SocketItem::nameWidth() const
{
  QFontMetrics const metrics{ m_font };
  return metrics.width(m_name);
}

void SocketItem::setColors(QColor const a_signalOff, QColor const a_signalOn)
{
  m_colorSignalOff = a_signalOff;
  m_colorSignalOn = a_signalOn;
}

void SocketItem::setSignal(const bool a_signal)
{
  m_isSignalOn = a_signal;

  if (m_type == Type::eOutput) {
    for (LinkItem *const link : m_links) link->setSignal(a_signal);
  }
}

void SocketItem::connect(SocketItem *const a_other)
{
  auto const linkItem = new LinkItem;
  linkItem->setColors(m_colorSignalOff, m_colorSignalOn);
  linkItem->setFrom(this);
  linkItem->setTo(a_other);

  m_links.push_back(linkItem);
  m_used = true;

  a_other->m_links.push_back(linkItem);
  a_other->m_used = true;
  a_other->m_isDrop = false;

  scene()->addItem(linkItem);
}
<|endoftext|>


<commit_before>#ifdef NG_PYTHON

#include <boost/python.hpp>
#include <boost/python/slice.hpp>

#include <mystdlib.h>
#include "meshing.hpp"

using namespace netgen;
namespace bp = boost::python;

//////////////////////////////////////////////////////////////////////
// Lambda to function pointer conversion
template <typename Function>
struct function_traits
  : public function_traits<decltype(&Function::operator())> {};

template <typename ClassType, typename ReturnType, typename... Args>
struct function_traits<ReturnType(ClassType::*)(Args...) const> {
  typedef ReturnType (*pointer)(Args...);
  typedef ReturnType return_type;
};

template <typename Function>
typename function_traits<Function>::pointer
FunctionPointer (const Function& lambda) {
  return static_cast<typename function_traits<Function>::pointer>(lambda);
}

template <class T>
inline string ToString (const T& t)
{
  stringstream ss;
  ss << t;
  return ss.str();
}

template <typename T, int BASE = 0, typename TIND = int>
void ExportArray ()
{
  string name = string("Array_") + typeid(T).name();
  bp::class_<Array<T,BASE,TIND>,boost::noncopyable>(name.c_str())
    .def ("__len__", &Array<T,BASE,TIND>::Size)
    .def ("__getitem__",
          FunctionPointer ([](Array<T,BASE,TIND> & self, TIND i) -> T&
                           {
                             if (i < BASE || i >= BASE+self.Size())
                               bp::exec("raise IndexError()\n");
                             return self[i];
                           }),
          bp::return_value_policy<bp::reference_existing_object>())

    .def ("__iter__",
          bp::range (FunctionPointer([](Array<T,BASE,TIND> & self) { return &self[BASE]; }),
                     FunctionPointer([](Array<T,BASE,TIND> & self) { return &self[BASE+self.Size()]; })))

    ;
}

void ExportNetgenMeshing()
{

  std::string nested_name = "meshing";
  if( bp::scope() )
    nested_name = bp::extract<std::string>(bp::scope().attr("__name__") + ".meshing");

  bp::object module(bp::handle<>(bp::borrowed(PyImport_AddModule(nested_name.c_str()))));

  cout << "exporting meshing " << nested_name << endl;
  bp::object parent = bp::scope() ? bp::scope() : bp::import("__main__");
  parent.attr("meshing") = module ;

  bp::scope local_scope(module);

  bp::class_<PointIndex>("PointId", bp::init<int>())
    .def("__repr__", &ToString<PointIndex>)
    .def("__str__", &ToString<PointIndex>)
    .add_property("nr", &PointIndex::operator int)
    ;

  bp::class_<Point<3>> ("Point")
    .def(bp::init<double,double,double>())
    ;

  bp::class_<MeshPoint,bp::bases<Point<3>>>("MeshPoint")
    .def(bp::init<Point<3>>())
    .add_property("p", FunctionPointer([](const MeshPoint & self)
                                       {
                                         bp::list l;
                                         l.append ( (self)[0] );
                                         l.append ( (self)[1] );
                                         l.append ( (self)[2] );
                                         return l;
                                       }))
    ;

  bp::class_<Element>("Element3D")
    .add_property("index", &Element::GetIndex, &Element::SetIndex)
    .add_property("vertices",
                  FunctionPointer ([](const Element & self) -> bp::list
                                   {
                                     bp::list li;
                                     for (int i = 0; i < self.GetNV(); i++)
                                       li.append (self[i]);
                                     return li;
                                   }))
    ;

  ExportArray<Element>();
  ExportArray<Element2d>();
  ExportArray<MeshPoint,PointIndex::BASE,PointIndex>();
  ;

  bp::class_<Mesh,shared_ptr<Mesh>,boost::noncopyable>("Mesh")
    .def("__str__", &ToString<Mesh>)
    .def("Load", static_cast<void(Mesh::*)(const string & name)>(&Mesh::Load))
    .def("Save", static_cast<void(Mesh::*)(const string & name)const>(&Mesh::Save))

    .def("Elements3D",
         static_cast<Array<Element>&(Mesh::*)()> (& &Mesh::VolumeElements),
         bp::return_value_policy<bp::reference_existing_object>())

    .def("Elements2D",
         static_cast<Array<Element2d>&(Mesh::*)()> (& &Mesh::SurfaceElements),
         bp::return_value_policy<bp::reference_existing_object>())

    .def("Points",
         static_cast<Mesh::T_POINTS&(Mesh::*)()> (& &Mesh::Points),
         bp::return_value_policy<bp::reference_existing_object>())

    .def("__getitem__", FunctionPointer ([](const Mesh & self, PointIndex pi)
                                         {
                                           return self[pi];
                                         }))

    .def ("Add", FunctionPointer ([](Mesh & self, MeshPoint p)
                                  {
                                    return self.AddPoint (Point3d(p));
                                  }))
    ;

  typedef MeshingParameters MP;
  bp::class_<MP> ("MeshingParameters")
    .def("__str__", &ToString<MP>)
    .add_property("maxh",
                  FunctionPointer ([](const MP & mp ) { return mp.maxh; }),
                  FunctionPointer ([](MP & mp, double maxh) { return mp.maxh = maxh; }))

    ;
}

BOOST_PYTHON_MODULE(libmesh) {
  ExportNetgenMeshing();
}

#endif

<commit_msg>removed & &<commit_after>#ifdef NG_PYTHON

#include <boost/python.hpp>
#include <boost/python/slice.hpp>

#include <mystdlib.h>
#include "meshing.hpp"

using namespace netgen;
namespace bp = boost::python;

//////////////////////////////////////////////////////////////////////
// Lambda to function pointer conversion
template <typename Function>
struct function_traits
  : public function_traits<decltype(&Function::operator())> {};

template <typename ClassType, typename ReturnType, typename... Args>
struct function_traits<ReturnType(ClassType::*)(Args...) const> {
  typedef ReturnType (*pointer)(Args...);
  typedef ReturnType return_type;
};

template <typename Function>
typename function_traits<Function>::pointer
FunctionPointer (const Function& lambda) {
  return static_cast<typename function_traits<Function>::pointer>(lambda);
}

template <class T>
inline string ToString (const T& t)
{
  stringstream ss;
  ss << t;
  return ss.str();
}

template <typename T, int BASE = 0, typename TIND = int>
void ExportArray ()
{
  string name = string("Array_") + typeid(T).name();
  bp::class_<Array<T,BASE,TIND>,boost::noncopyable>(name.c_str())
    .def ("__len__", &Array<T,BASE,TIND>::Size)
    .def ("__getitem__",
          FunctionPointer ([](Array<T,BASE,TIND> & self, TIND i) -> T&
                           {
                             if (i < BASE || i >= BASE+self.Size())
                               bp::exec("raise IndexError()\n");
                             return self[i];
                           }),
          bp::return_value_policy<bp::reference_existing_object>())

    .def ("__iter__",
          bp::range (FunctionPointer([](Array<T,BASE,TIND> & self) { return &self[BASE]; }),
                     FunctionPointer([](Array<T,BASE,TIND> & self) { return &self[BASE+self.Size()]; })))

    ;
}

void ExportNetgenMeshing()
{

  std::string nested_name = "meshing";
  if( bp::scope() )
    nested_name = bp::extract<std::string>(bp::scope().attr("__name__") + ".meshing");

  bp::object module(bp::handle<>(bp::borrowed(PyImport_AddModule(nested_name.c_str()))));

  cout << "exporting meshing " << nested_name << endl;
  bp::object parent = bp::scope() ? bp::scope() : bp::import("__main__");
  parent.attr("meshing") = module ;

  bp::scope local_scope(module);

  bp::class_<PointIndex>("PointId", bp::init<int>())
    .def("__repr__", &ToString<PointIndex>)
    .def("__str__", &ToString<PointIndex>)
    .add_property("nr", &PointIndex::operator int)
    ;

  bp::class_<Point<3>> ("Point")
    .def(bp::init<double,double,double>())
    ;

  bp::class_<MeshPoint,bp::bases<Point<3>>>("MeshPoint")
    .def(bp::init<Point<3>>())
    .add_property("p", FunctionPointer([](const MeshPoint & self)
                                       {
                                         bp::list l;
                                         l.append ( (self)[0] );
                                         l.append ( (self)[1] );
                                         l.append ( (self)[2] );
                                         return l;
                                       }))
    ;

  bp::class_<Element>("Element3D")
    .add_property("index", &Element::GetIndex, &Element::SetIndex)
    .add_property("vertices",
                  FunctionPointer ([](const Element & self) -> bp::list
                                   {
                                     bp::list li;
                                     for (int i = 0; i < self.GetNV(); i++)
                                       li.append (self[i]);
                                     return li;
                                   }))
    ;

  ExportArray<Element>();
  ExportArray<Element2d>();
  ExportArray<MeshPoint,PointIndex::BASE,PointIndex>();
  ;

  bp::class_<Mesh,shared_ptr<Mesh>,boost::noncopyable>("Mesh")
    .def("__str__", &ToString<Mesh>)
    .def("Load", static_cast<void(Mesh::*)(const string & name)>(&Mesh::Load))
    .def("Save", static_cast<void(Mesh::*)(const string & name)const>(&Mesh::Save))

    .def("Elements3D",
         static_cast<Array<Element>&(Mesh::*)()> (&Mesh::VolumeElements),
         bp::return_value_policy<bp::reference_existing_object>())

    .def("Elements2D",
         static_cast<Array<Element2d>&(Mesh::*)()> (&Mesh::SurfaceElements),
         bp::return_value_policy<bp::reference_existing_object>())

    .def("Points",
         static_cast<Mesh::T_POINTS&(Mesh::*)()> (&Mesh::Points),
         bp::return_value_policy<bp::reference_existing_object>())

    .def("__getitem__", FunctionPointer ([](const Mesh & self, PointIndex pi)
                                         {
                                           return self[pi];
                                         }))

    .def ("Add", FunctionPointer ([](Mesh & self, MeshPoint p)
                                  {
                                    return self.AddPoint (Point3d(p));
                                  }))
    ;

  typedef MeshingParameters MP;
  bp::class_<MP> ("MeshingParameters")
    .def("__str__", &ToString<MP>)
    .add_property("maxh",
                  FunctionPointer ([](const MP & mp ) { return mp.maxh; }),
                  FunctionPointer ([](MP & mp, double maxh) { return mp.maxh = maxh; }))

    ;
}

BOOST_PYTHON_MODULE(libmesh) {
  ExportNetgenMeshing();
}

#endif

<|endoftext|>


<commit_before>/*
* Copyright (c) 2011-2013 MLBA-Team. All rights reserved.
*
* @MLBA_OPEN_LICENSE_HEADER_START@
*
* 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.
*
* @MLBA_OPEN_LICENSE_HEADER_END@
*/

#include <iostream>
#include <stdlib.h>
#include "xdispatch_internal.h"

__XDISPATCH_USE_NAMESPACE iteration_wrap::iteration_wrap (
    iteration_operation *o,
    size_t ct
)
    : op( o ),
      ref( ct )
{
    XDISPATCH_ASSERT( o );
}

iteration_wrap::~iteration_wrap ()
{
    if( op && op->auto_delete() )
        delete op;
}

iteration_operation * iteration_wrap::operation()
{
    return op;
}

bool iteration_wrap::deref()
{
    return dispatch_atomic_dec( &ref ) == 0;
}

void set_debugger_threadname()
{
#ifdef DEBUG

#endif
}

extern "C"
void _xdispatch_run_operation(
    void *dt
)
{
    XDISPATCH_ASSERT( dt );
    operation *w = static_cast< operation * > ( dt );
    XDISPATCH_ASSERT( w );

    try
    {
        ( *w )();
    }
    catch( const std::exception &e )
    {
        std::cerr << "##################################################################" << std::endl;
        std::cerr << "           Queue '" << xdispatch::current_queue().label() << "'" << std::endl;
        std::cerr << "xdispatch: Throwing exceptions within an xdispatch::operation is" << std::endl;
        std::cerr << "           not recommended, please make sure to catch them before:\n" << std::endl;
        std::cerr << e.what() << std::endl;
        std::cerr << "##################################################################" << std::endl;
        throw;
    }
    catch( ... )
    {
        std::cerr << "##################################################################" << std::endl;
        std::cerr << "           Queue '" << xdispatch::current_queue().label() << "'" << std::endl;
        std::cerr << "xdispatch: Throwing exceptions within an xdispatch::operation is" << std::endl;
        std::cerr << "           not recommended, please make sure to catch them before!" << std::endl;
        std::cerr << "##################################################################" << std::endl;
        std::terminate();
    }
    if( w->auto_delete() )
        delete w;
} // _xdispatch_run_operation

extern "C"
void _xdispatch_run_iter_wrap(
    void *dt,
    size_t index
)
{
    XDISPATCH_ASSERT( dt );
    iteration_wrap *wrap = static_cast< iteration_wrap * > ( dt );
    XDISPATCH_ASSERT( wrap );

    try
    {
        ( *( wrap->operation() ) )( index );
    }
    catch( const std::exception &e )
    {
        std::cerr << "##################################################################" << std::endl;
        std::cerr << "           Queue '" << xdispatch::current_queue().label() << "'" << std::endl;
        std::cerr << "xdispatch: Throwing exceptions within an xdispatch::operation is" << std::endl;
        std::cerr << "           not recommended, please make sure to catch them before:\n" << std::endl;
        std::cerr << e.what() << std::endl;
        std::cerr << "##################################################################" << std::endl;
        throw;
    }
    catch( ... )
    {
        std::cerr << "##################################################################" << std::endl;
        std::cerr << "           Queue '" << xdispatch::current_queue().label() << "'" << std::endl;
        std::cerr << "xdispatch: Throwing exceptions within an xdispatch::operation is" << std::endl;
        std::cerr << "           not recommended, please make sure to catch them before!" << std::endl;
        std::cerr << "##################################################################" << std::endl;
        std::terminate();
    }
} // _xdispatch_run_iter_wrap

<commit_msg>Set threadname according to queue<commit_after>/*
* Copyright (c) 2011-2013 MLBA-Team. All rights reserved.
*
* @MLBA_OPEN_LICENSE_HEADER_START@
*
* 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.
*
* @MLBA_OPEN_LICENSE_HEADER_END@
*/

#include <iostream>
#include <stdlib.h>
#include "xdispatch_internal.h"

__XDISPATCH_USE_NAMESPACE iteration_wrap::iteration_wrap (
    iteration_operation *o,
    size_t ct
)
    : op( o ),
      ref( ct )
{
    XDISPATCH_ASSERT( o );
}

iteration_wrap::~iteration_wrap ()
{
    if( op && op->auto_delete() )
        delete op;
}

iteration_operation * iteration_wrap::operation()
{
    return op;
}

bool iteration_wrap::deref()
{
    return dispatch_atomic_dec( &ref ) == 0;
}

inline void set_debugger_threadname( const std::string& name = std::string() )
{
#if (defined DEBUG) && (defined __APPLE__ || defined __linux__)
#  if (defined __linux__)
    prctl(PR_SET_NAME, (unsigned long)( name.c_str() ), 0, 0, 0);
#  elif (defined __APPLE__)
    pthread_setname_np( name.c_str() );
#  endif
#endif
}

extern "C"
void _xdispatch_run_operation(
    void *dt
)
{
    XDISPATCH_ASSERT( dt );
    operation *w = static_cast< operation * > ( dt );
    XDISPATCH_ASSERT( w );

    try
    {
        set_debugger_threadname( xdispatch::current_queue().label() );
        ( *w )();
        set_debugger_threadname();
    }
    catch( const std::exception &e )
    {
        std::cerr << "##################################################################" << std::endl;
        std::cerr << "           Queue '" << xdispatch::current_queue().label() << "'" << std::endl;
        std::cerr << "xdispatch: Throwing exceptions within an xdispatch::operation is" << std::endl;
        std::cerr << "           not recommended, please make sure to catch them before:\n" << std::endl;
        std::cerr << e.what() << std::endl;
        std::cerr << "##################################################################" << std::endl;
        throw;
    }
    catch( ... )
    {
        std::cerr << "##################################################################" << std::endl;
        std::cerr << "           Queue '" << xdispatch::current_queue().label() << "'" << std::endl;
        std::cerr << "xdispatch: Throwing exceptions within an xdispatch::operation is" << std::endl;
        std::cerr << "           not recommended, please make sure to catch them before!" << std::endl;
        std::cerr << "##################################################################" << std::endl;
        std::terminate();
    }
    if( w->auto_delete() )
        delete w;
} // _xdispatch_run_operation

extern "C"
void _xdispatch_run_iter_wrap(
    void *dt,
    size_t index
)
{
    XDISPATCH_ASSERT( dt );
    iteration_wrap *wrap = static_cast< iteration_wrap * > ( dt );
    XDISPATCH_ASSERT( wrap );

    try
    {
        set_debugger_threadname( xdispatch::current_queue().label() );
        ( *( wrap->operation() ) )( index );
        set_debugger_threadname();
    }
    catch( const std::exception &e )
    {
        std::cerr << "##################################################################" << std::endl;
        std::cerr << "           Queue '" << xdispatch::current_queue().label() << "'" << std::endl;
        std::cerr << "xdispatch: Throwing exceptions within an xdispatch::operation is" << std::endl;
        std::cerr << "           not recommended, please make sure to catch them before:\n" << std::endl;
        std::cerr << e.what() << std::endl;
        std::cerr << "##################################################################" << std::endl;
        throw;
    }
    catch( ... )
    {
        std::cerr << "##################################################################" << std::endl;
        std::cerr << "           Queue '" << xdispatch::current_queue().label() << "'" << std::endl;
        std::cerr << "xdispatch: Throwing exceptions within an xdispatch::operation is" << std::endl;
        std::cerr << "           not recommended, please make sure to catch them before!" << std::endl;
        std::cerr << "##################################################################" << std::endl;
        std::terminate();
    }
} // _xdispatch_run_iter_wrap

<|endoftext|>


<commit_before>// Copyright (c) 2003 Daniel Wallin and Arvid Norberg

// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
// ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
// OR OTHER DEALINGS IN THE SOFTWARE.

#if !BOOST_PP_IS_ITERATING

#ifndef LUABIND_CALL_MEMBER_HPP_INCLUDED
#define LUABIND_CALL_MEMBER_HPP_INCLUDED

#include <luabind/config.hpp>
#include <luabind/detail/convert_to_lua.hpp>
#include <luabind/detail/pcall.hpp>
#include <luabind/detail/stack_utils.hpp>
#include <luabind/error.hpp>
#include <luabind/detail/object.hpp> // TODO: REMOVE DEPENDENCY

#include <boost/mpl/apply_wrap.hpp>
#include <boost/preprocessor/control/if.hpp>
#include <boost/preprocessor/facilities/expand.hpp>
#include <boost/preprocessor/repetition/enum.hpp>
#include <boost/tuple/tuple.hpp>

namespace luabind
{
    namespace detail
    {

        namespace mpl = boost::mpl;

        // if the proxy_member_caller returns non-void
            template<class Ret, class Tuple>
            class proxy_member_caller
            {
//          friend class luabind::object;
            public:

                proxy_member_caller(lua_State* L_, const Tuple args)
                    : L(L_)
                    , m_args(args)
                    , m_called(false)
                {
                }

                proxy_member_caller(const proxy_member_caller& rhs)
                    : L(rhs.L)
                    , m_args(rhs.m_args)
                    , m_called(rhs.m_called)
                {
                    rhs.m_called = true;
                }

                ~proxy_member_caller()
                {
                    if (m_called) return;

                    m_called = true;

                    // don't count the function and self-reference
                    // since those will be popped by pcall
                    int top = lua_gettop(L) - 2;

                    // pcall will pop the function and self reference
                    // and all the parameters

                    push_args_from_tuple<1>::apply(L, m_args);
                    if (pcall(L, boost::tuples::length<Tuple>::value + 1, 0))
                    {
                        assert(lua_gettop(L) == top + 1);
#ifndef LUABIND_NO_EXCEPTIONS
                        throw luabind::error(L);
#else
                        error_callback_fun e = get_error_callback();
                        if (e) e(L);

                        assert(0 && "the lua function threw an error and exceptions are disabled."
                                "If you want to handle this error use luabind::set_error_callback()");
                        std::terminate();
#endif
                    }
                    // pops the return values from the function
                    stack_pop pop(L, lua_gettop(L) - top);
                }

                operator Ret()
                {
                    typename mpl::apply_wrap2<default_policy,Ret,lua_to_cpp>::type converter;

                    m_called = true;

                    // don't count the function and self-reference
                    // since those will be popped by pcall
                    int top = lua_gettop(L) - 2;

                    // pcall will pop the function and self reference
                    // and all the parameters
                    push_args_from_tuple<1>::apply(L, m_args);
                    if (pcall(L, boost::tuples::length<Tuple>::value + 1, 1))
                    {
                        assert(lua_gettop(L) == top + 1);
#ifndef LUABIND_NO_EXCEPTIONS
                        throw luabind::error(L);
#else
                        error_callback_fun e = get_error_callback();
                        if (e) e(L);

                        assert(0 && "the lua function threw an error and exceptions are disabled."
                            "If you want to handle this error use luabind::set_error_callback()");
                        std::terminate();
#endif
                    }

                    // pops the return values from the function
                    stack_pop pop(L, lua_gettop(L) - top);

                    if (converter.match(L, LUABIND_DECORATE_TYPE(Ret), -1) < 0)
                    {
                        assert(lua_gettop(L) == top + 1);
#ifndef LUABIND_NO_EXCEPTIONS
                        throw cast_failed(L, typeid(Ret));
#else
                        cast_failed_callback_fun e = get_cast_failed_callback();
                        if (e) e(L, typeid(Ret));

                        assert(0 && "the lua function's return value could not be converted."
                            "If you want to handle this error use luabind::set_error_callback()");
                        std::terminate();
#endif
                    }

                    return converter.apply(L, LUABIND_DECORATE_TYPE(Ret), -1);
                }

                template<class Policies>
                Ret operator[](const Policies& p)
                {
                    typedef typename find_conversion_policy<0, Policies>::type converter_policy;
                    typename mpl::apply_wrap2<converter_policy,Ret,lua_to_cpp>::type converter;

                    m_called = true;

                    // don't count the function and self-reference
                    // since those will be popped by pcall
                    int top = lua_gettop(L) - 2;

                    // pcall will pop the function and self reference
                    // and all the parameters

                    detail::push_args_from_tuple<1>::apply(L, m_args, p);
                    if (pcall(L, boost::tuples::length<Tuple>::value + 1, 1))
                    {
                        assert(lua_gettop(L) == top + 1);
#ifndef LUABIND_NO_EXCEPTIONS
                        throw error(L);
#else
                        error_callback_fun e = get_error_callback();
                        if (e) e(L);

                        assert(0 && "the lua function threw an error and exceptions are disabled."
                            "If you want to handle this error use luabind::set_error_callback()");
                        std::terminate();
#endif
                    }

                    // pops the return values from the function
                    stack_pop pop(L, lua_gettop(L) - top);

                    if (converter.match(L, LUABIND_DECORATE_TYPE(Ret), -1) < 0)
                    {
                        assert(lua_gettop(L) == top + 1);
#ifndef LUABIND_NO_EXCEPTIONS
                        throw cast_failed(L, typeid(Ret));
#else
                        cast_failed_callback_fun e = get_cast_failed_callback();
                        if (e) e(L, typeid(Ret));

                        assert(0 && "the lua function's return value could not be converted."
                            "If you want to handle this error use luabind::set_error_callback()");
                        std::terminate();
#endif
                    }
                    return converter.apply(L, LUABIND_DECORATE_TYPE(Ret), -1);
                }

            private:

                lua_State* L;
                Tuple m_args;
                mutable bool m_called;

            };

        // if the proxy_member_caller returns void
            template<class Tuple>
            class proxy_member_void_caller
            {
            friend class luabind::object;
            public:

                proxy_member_void_caller(lua_State* L_, const Tuple args)
                    : L(L_)
                    , m_args(args)
                    , m_called(false)
                {
                }

                proxy_member_void_caller(const proxy_member_void_caller& rhs)
                    : L(rhs.L)
                    , m_args(rhs.m_args)
                    , m_called(rhs.m_called)
                {
                    rhs.m_called = true;
                }

                ~proxy_member_void_caller()
                {
                    if (m_called) return;

                    m_called = true;

                    // don't count the function and self-reference
                    // since those will be popped by pcall
                    int top = lua_gettop(L) - 2;

                    // pcall will pop the function and self reference
                    // and all the parameters

                    push_args_from_tuple<1>::apply(L, m_args);
                    if (pcall(L, boost::tuples::length<Tuple>::value + 1, 0))
                    {
                        assert(lua_gettop(L) == top + 1);
#ifndef LUABIND_NO_EXCEPTIONS
                        throw luabind::error(L);
#else
                        error_callback_fun e = get_error_callback();
                        if (e) e(L);

                        assert(0 && "the lua function threw an error and exceptions are disabled."
                            "If you want to handle this error use luabind::set_error_callback()");
                        std::terminate();
#endif
                    }
                    // pops the return values from the function
                    stack_pop pop(L, lua_gettop(L) - top);
                }

                template<class Policies>
                void operator[](const Policies& p)
                {
                    m_called = true;

                    // don't count the function and self-reference
                    // since those will be popped by pcall
                    int top = lua_gettop(L) - 2;

                    // pcall will pop the function and self reference
                    // and all the parameters

                    detail::push_args_from_tuple<1>::apply(L, m_args, p);
                    if (pcall(L, boost::tuples::length<Tuple>::value + 1, 0))
                    {
                        assert(lua_gettop(L) == top + 1);
#ifndef LUABIND_NO_EXCEPTIONS
                        throw error(L);
#else
                        error_callback_fun e = get_error_callback();
                        if (e) e(L);

                        assert(0 && "the lua function threw an error and exceptions are disabled."
                            "If you want to handle this error use luabind::set_error_callback()");
                        std::terminate();
#endif
                    }
                    // pops the return values from the function
                    stack_pop pop(L, lua_gettop(L) - top);
                }

            private:
                lua_State* L;
                Tuple m_args;
                mutable bool m_called;

            };

    } // detail

    #define BOOST_PP_ITERATION_PARAMS_1 (4, (0, LUABIND_MAX_ARITY, <luabind/detail/call_member.hpp>, 1))
    #include BOOST_PP_ITERATE()

}

#endif // LUABIND_CALL_MEMBER_HPP_INCLUDED

#else
#if BOOST_PP_ITERATION_FLAGS() == 1

#define LUABIND_TUPLE_PARAMS(z, n, data) const A##n *
#define LUABIND_OPERATOR_PARAMS(z, n, data) const A##n & a##n

    template<class R BOOST_PP_COMMA_IF(BOOST_PP_ITERATION()) BOOST_PP_ENUM_PARAMS(BOOST_PP_ITERATION(), class A)>
    typename boost::mpl::if_<boost::is_void<R>
            , luabind::detail::proxy_member_void_caller<boost::tuples::tuple<BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_TUPLE_PARAMS, _)> >
            , luabind::detail::proxy_member_caller<R, boost::tuples::tuple<BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_TUPLE_PARAMS, _)> > >::type
    call_member(object const& obj, const char* name BOOST_PP_COMMA_IF(BOOST_PP_ITERATION()) BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_OPERATOR_PARAMS, _))
    {
        typedef boost::tuples::tuple<BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_TUPLE_PARAMS, _)> tuple_t;
#if BOOST_PP_ITERATION() == 0
        tuple_t args;
#else
        tuple_t args(BOOST_PP_ENUM_PARAMS(BOOST_PP_ITERATION(), &a));
#endif

        typedef typename boost::mpl::if_<boost::is_void<R>
            , luabind::detail::proxy_member_void_caller<boost::tuples::tuple<BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_TUPLE_PARAMS, _)> >
            , luabind::detail::proxy_member_caller<R, boost::tuples::tuple<BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_TUPLE_PARAMS, _)> > >::type proxy_type;

        // this will be cleaned up by the proxy object
        // once the call has been made

        // get the function
        obj.push(obj.interpreter());
        lua_pushstring(obj.interpreter(), name);
        lua_gettable(obj.interpreter(), -2);
        // duplicate the self-object
        lua_pushvalue(obj.interpreter(), -2);
        // remove the bottom self-object
        lua_remove(obj.interpreter(), -3);

        // now the function and self objects
        // are on the stack. These will both
        // be popped by pcall
        return proxy_type(obj.interpreter(), args);
    }

#undef LUABIND_OPERATOR_PARAMS
#undef LUABIND_TUPLE_PARAMS

#endif
#endif
<commit_msg>Fix missing LUABIND_MAY_THROW in member caller.<commit_after>// Copyright (c) 2003 Daniel Wallin and Arvid Norberg

// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
// ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
// OR OTHER DEALINGS IN THE SOFTWARE.

#if !BOOST_PP_IS_ITERATING

#ifndef LUABIND_CALL_MEMBER_HPP_INCLUDED
#define LUABIND_CALL_MEMBER_HPP_INCLUDED

#include <luabind/config.hpp>
#include <luabind/detail/convert_to_lua.hpp>
#include <luabind/detail/pcall.hpp>
#include <luabind/detail/stack_utils.hpp>
#include <luabind/error.hpp>
#include <luabind/detail/object.hpp> // TODO: REMOVE DEPENDENCY

#include <boost/mpl/apply_wrap.hpp>
#include <boost/preprocessor/control/if.hpp>
#include <boost/preprocessor/facilities/expand.hpp>
#include <boost/preprocessor/repetition/enum.hpp>
#include <boost/tuple/tuple.hpp>

namespace luabind
{
    namespace detail
    {

        namespace mpl = boost::mpl;

        // if the proxy_member_caller returns non-void
            template<class Ret, class Tuple>
            class proxy_member_caller
            {
//          friend class luabind::object;
            public:

                proxy_member_caller(lua_State* L_, const Tuple args)
                    : L(L_)
                    , m_args(args)
                    , m_called(false)
                {
                }

                proxy_member_caller(const proxy_member_caller& rhs)
                    : L(rhs.L)
                    , m_args(rhs.m_args)
                    , m_called(rhs.m_called)
                {
                    rhs.m_called = true;
                }

                ~proxy_member_caller() LUABIND_MAY_THROW
                {
                    if (m_called) return;

                    m_called = true;

                    // don't count the function and self-reference
                    // since those will be popped by pcall
                    int top = lua_gettop(L) - 2;

                    // pcall will pop the function and self reference
                    // and all the parameters

                    push_args_from_tuple<1>::apply(L, m_args);
                    if (pcall(L, boost::tuples::length<Tuple>::value + 1, 0))
                    {
                        assert(lua_gettop(L) == top + 1);
#ifndef LUABIND_NO_EXCEPTIONS
                        throw luabind::error(L);
#else
                        error_callback_fun e = get_error_callback();
                        if (e) e(L);

                        assert(0 && "the lua function threw an error and exceptions are disabled."
                                "If you want to handle this error use luabind::set_error_callback()");
                        std::terminate();
#endif
                    }
                    // pops the return values from the function
                    stack_pop pop(L, lua_gettop(L) - top);
                }

                operator Ret()
                {
                    typename mpl::apply_wrap2<default_policy,Ret,lua_to_cpp>::type converter;

                    m_called = true;

                    // don't count the function and self-reference
                    // since those will be popped by pcall
                    int top = lua_gettop(L) - 2;

                    // pcall will pop the function and self reference
                    // and all the parameters
                    push_args_from_tuple<1>::apply(L, m_args);
                    if (pcall(L, boost::tuples::length<Tuple>::value + 1, 1))
                    {
                        assert(lua_gettop(L) == top + 1);
#ifndef LUABIND_NO_EXCEPTIONS
                        throw luabind::error(L);
#else
                        error_callback_fun e = get_error_callback();
                        if (e) e(L);

                        assert(0 && "the lua function threw an error and exceptions are disabled."
                            "If you want to handle this error use luabind::set_error_callback()");
                        std::terminate();
#endif
                    }

                    // pops the return values from the function
                    stack_pop pop(L, lua_gettop(L) - top);

                    if (converter.match(L, LUABIND_DECORATE_TYPE(Ret), -1) < 0)
                    {
                        assert(lua_gettop(L) == top + 1);
#ifndef LUABIND_NO_EXCEPTIONS
                        throw cast_failed(L, typeid(Ret));
#else
                        cast_failed_callback_fun e = get_cast_failed_callback();
                        if (e) e(L, typeid(Ret));

                        assert(0 && "the lua function's return value could not be converted."
                            "If you want to handle this error use luabind::set_error_callback()");
                        std::terminate();
#endif
                    }

                    return converter.apply(L, LUABIND_DECORATE_TYPE(Ret), -1);
                }

                template<class Policies>
                Ret operator[](const Policies& p)
                {
                    typedef typename find_conversion_policy<0, Policies>::type converter_policy;
                    typename mpl::apply_wrap2<converter_policy,Ret,lua_to_cpp>::type converter;

                    m_called = true;

                    // don't count the function and self-reference
                    // since those will be popped by pcall
                    int top = lua_gettop(L) - 2;

                    // pcall will pop the function and self reference
                    // and all the parameters

                    detail::push_args_from_tuple<1>::apply(L, m_args, p);
                    if (pcall(L, boost::tuples::length<Tuple>::value + 1, 1))
                    {
                        assert(lua_gettop(L) == top + 1);
#ifndef LUABIND_NO_EXCEPTIONS
                        throw error(L);
#else
                        error_callback_fun e = get_error_callback();
                        if (e) e(L);

                        assert(0 && "the lua function threw an error and exceptions are disabled."
                            "If you want to handle this error use luabind::set_error_callback()");
                        std::terminate();
#endif
                    }

                    // pops the return values from the function
                    stack_pop pop(L, lua_gettop(L) - top);

                    if (converter.match(L, LUABIND_DECORATE_TYPE(Ret), -1) < 0)
                    {
                        assert(lua_gettop(L) == top + 1);
#ifndef LUABIND_NO_EXCEPTIONS
                        throw cast_failed(L, typeid(Ret));
#else
                        cast_failed_callback_fun e = get_cast_failed_callback();
                        if (e) e(L, typeid(Ret));

                        assert(0 && "the lua function's return value could not be converted."
                            "If you want to handle this error use luabind::set_error_callback()");
                        std::terminate();
#endif
                    }
                    return converter.apply(L, LUABIND_DECORATE_TYPE(Ret), -1);
                }

            private:

                lua_State* L;
                Tuple m_args;
                mutable bool m_called;

            };

        // if the proxy_member_caller returns void
            template<class Tuple>
            class proxy_member_void_caller
            {
            friend class luabind::object;
            public:

                proxy_member_void_caller(lua_State* L_, const Tuple args)
                    : L(L_)
                    , m_args(args)
                    , m_called(false)
                {
                }

                proxy_member_void_caller(const proxy_member_void_caller& rhs)
                    : L(rhs.L)
                    , m_args(rhs.m_args)
                    , m_called(rhs.m_called)
                {
                    rhs.m_called = true;
                }

                ~proxy_member_void_caller()
                {
                    if (m_called) return;

                    m_called = true;

                    // don't count the function and self-reference
                    // since those will be popped by pcall
                    int top = lua_gettop(L) - 2;

                    // pcall will pop the function and self reference
                    // and all the parameters

                    push_args_from_tuple<1>::apply(L, m_args);
                    if (pcall(L, boost::tuples::length<Tuple>::value + 1, 0))
                    {
                        assert(lua_gettop(L) == top + 1);
#ifndef LUABIND_NO_EXCEPTIONS
                        throw luabind::error(L);
#else
                        error_callback_fun e = get_error_callback();
                        if (e) e(L);

                        assert(0 && "the lua function threw an error and exceptions are disabled."
                            "If you want to handle this error use luabind::set_error_callback()");
                        std::terminate();
#endif
                    }
                    // pops the return values from the function
                    stack_pop pop(L, lua_gettop(L) - top);
                }

                template<class Policies>
                void operator[](const Policies& p)
                {
                    m_called = true;

                    // don't count the function and self-reference
                    // since those will be popped by pcall
                    int top = lua_gettop(L) - 2;

                    // pcall will pop the function and self reference
                    // and all the parameters

                    detail::push_args_from_tuple<1>::apply(L, m_args, p);
                    if (pcall(L, boost::tuples::length<Tuple>::value + 1, 0))
                    {
                        assert(lua_gettop(L) == top + 1);
#ifndef LUABIND_NO_EXCEPTIONS
                        throw error(L);
#else
                        error_callback_fun e = get_error_callback();
                        if (e) e(L);

                        assert(0 && "the lua function threw an error and exceptions are disabled."
                            "If you want to handle this error use luabind::set_error_callback()");
                        std::terminate();
#endif
                    }
                    // pops the return values from the function
                    stack_pop pop(L, lua_gettop(L) - top);
                }

            private:
                lua_State* L;
                Tuple m_args;
                mutable bool m_called;

            };

    } // detail

    #define BOOST_PP_ITERATION_PARAMS_1 (4, (0, LUABIND_MAX_ARITY, <luabind/detail/call_member.hpp>, 1))
    #include BOOST_PP_ITERATE()

}

#endif // LUABIND_CALL_MEMBER_HPP_INCLUDED

#else
#if BOOST_PP_ITERATION_FLAGS() == 1

#define LUABIND_TUPLE_PARAMS(z, n, data) const A##n *
#define LUABIND_OPERATOR_PARAMS(z, n, data) const A##n & a##n

    template<class R BOOST_PP_COMMA_IF(BOOST_PP_ITERATION()) BOOST_PP_ENUM_PARAMS(BOOST_PP_ITERATION(), class A)>
    typename boost::mpl::if_<boost::is_void<R>
            , luabind::detail::proxy_member_void_caller<boost::tuples::tuple<BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_TUPLE_PARAMS, _)> >
            , luabind::detail::proxy_member_caller<R, boost::tuples::tuple<BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_TUPLE_PARAMS, _)> > >::type
    call_member(object const& obj, const char* name BOOST_PP_COMMA_IF(BOOST_PP_ITERATION()) BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_OPERATOR_PARAMS, _))
    {
        typedef boost::tuples::tuple<BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_TUPLE_PARAMS, _)> tuple_t;
#if BOOST_PP_ITERATION() == 0
        tuple_t args;
#else
        tuple_t args(BOOST_PP_ENUM_PARAMS(BOOST_PP_ITERATION(), &a));
#endif

        typedef typename boost::mpl::if_<boost::is_void<R>
            , luabind::detail::proxy_member_void_caller<boost::tuples::tuple<BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_TUPLE_PARAMS, _)> >
            , luabind::detail::proxy_member_caller<R, boost::tuples::tuple<BOOST_PP_ENUM(BOOST_PP_ITERATION(), LUABIND_TUPLE_PARAMS, _)> > >::type proxy_type;

        // this will be cleaned up by the proxy object
        // once the call has been made

        // get the function
        obj.push(obj.interpreter());
        lua_pushstring(obj.interpreter(), name);
        lua_gettable(obj.interpreter(), -2);
        // duplicate the self-object
        lua_pushvalue(obj.interpreter(), -2);
        // remove the bottom self-object
        lua_remove(obj.interpreter(), -3);

        // now the function and self objects
        // are on the stack. These will both
        // be popped by pcall
        return proxy_type(obj.interpreter(), args);
    }

#undef LUABIND_OPERATOR_PARAMS
#undef LUABIND_TUPLE_PARAMS

#endif
#endif
<|endoftext|>


<commit_before>#include "WatchdogProcessView.h"
#include "ui_WatchdogProcessView.h"

WatchdogProcessView::WatchdogProcessView(QWidget *parent) :
    QWidget(parent),
    m_ui(new Ui::WatchdogProcessView)
{
    m_ui->setupUi(this);
}

WatchdogProcessView::~WatchdogProcessView()
{
    delete m_ui;
}

void WatchdogProcessView::changeEvent(QEvent *e)
{
    QWidget::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        m_ui->retranslateUi(this);
        break;
    default:
        break;
    }
}
<commit_msg>Fixed minor compile error<commit_after>#include "WatchdogProcessView.h"
#include "ui_WatchdogProcessView.h"

WatchdogProcessView::WatchdogProcessView(int processid, QWidget *parent) :
    QWidget(parent),
    m_ui(new Ui::WatchdogProcessView)
{
    m_ui->setupUi(this);
}

WatchdogProcessView::~WatchdogProcessView()
{
    delete m_ui;
}

void WatchdogProcessView::changeEvent(QEvent *e)
{
    QWidget::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        m_ui->retranslateUi(this);
        break;
    default:
        break;
    }
}
<|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 "chrome/browser/extensions/browser_extension_window_controller.h"

#include "chrome/browser/extensions/api/tabs/tabs_constants.h"
#include "chrome/browser/extensions/extension_tab_util.h"
#include "chrome/browser/extensions/window_controller_list.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/sessions/session_id.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_tabstrip.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/common/extensions/extension.h"

BrowserExtensionWindowController::BrowserExtensionWindowController(
    Browser* browser)
    : extensions::WindowController(browser->window(), browser->profile()),
      browser_(browser) {
  extensions::WindowControllerList::GetInstance()->AddExtensionWindow(this);
}

BrowserExtensionWindowController::~BrowserExtensionWindowController() {
  extensions::WindowControllerList::GetInstance()->RemoveExtensionWindow(this);
}

int BrowserExtensionWindowController::GetWindowId() const {
  return static_cast<int>(browser_->session_id().id());
}

namespace keys = extensions::tabs_constants;

std::string BrowserExtensionWindowController::GetWindowTypeText() const {
  if (browser_->is_type_popup())
    return keys::kWindowTypeValuePopup;
  if (browser_->is_type_panel())
    return keys::kWindowTypeValuePanel;
  if (browser_->is_app())
    return keys::kWindowTypeValueApp;
  return keys::kWindowTypeValueNormal;
}

base::DictionaryValue*
BrowserExtensionWindowController::CreateWindowValue() const {
  DictionaryValue* result = extensions::WindowController::CreateWindowValue();
  return result;
}

base::DictionaryValue*
BrowserExtensionWindowController::CreateWindowValueWithTabs(
    const extensions::Extension* extension) const {
  DictionaryValue* result = CreateWindowValue();

  result->Set(keys::kTabsKey, ExtensionTabUtil::CreateTabList(browser_,
                                                              extension));

  return result;
}

bool BrowserExtensionWindowController::CanClose(Reason* reason) const {
  // Don't let an extension remove the window if the user is dragging tabs
  // in that window.
  if (!chrome::IsTabStripEditable(browser_)) {
    *reason = extensions::WindowController::REASON_NOT_EDITABLE;
    return false;
  }
  return true;
}

void BrowserExtensionWindowController::SetFullscreenMode(
    bool is_fullscreen,
    const GURL& extension_url) const {
  if (browser_->window()->IsFullscreen() != is_fullscreen)
    browser_->ToggleFullscreenModeWithExtension(extension_url);
}

Browser* BrowserExtensionWindowController::GetBrowser() const {
  return browser_;
}

bool BrowserExtensionWindowController::IsVisibleToExtension(
    const extensions::Extension* extension) const {
  // Platform apps can only see their own windows.
  // TODO(mihaip): what about non-Aura panels?
  return !extension->is_platform_app();
}
<commit_msg>Remove obsolete TODO about browser-based panels.<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 "chrome/browser/extensions/browser_extension_window_controller.h"

#include "chrome/browser/extensions/api/tabs/tabs_constants.h"
#include "chrome/browser/extensions/extension_tab_util.h"
#include "chrome/browser/extensions/window_controller_list.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/sessions/session_id.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_tabstrip.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/common/extensions/extension.h"

BrowserExtensionWindowController::BrowserExtensionWindowController(
    Browser* browser)
    : extensions::WindowController(browser->window(), browser->profile()),
      browser_(browser) {
  extensions::WindowControllerList::GetInstance()->AddExtensionWindow(this);
}

BrowserExtensionWindowController::~BrowserExtensionWindowController() {
  extensions::WindowControllerList::GetInstance()->RemoveExtensionWindow(this);
}

int BrowserExtensionWindowController::GetWindowId() const {
  return static_cast<int>(browser_->session_id().id());
}

namespace keys = extensions::tabs_constants;

std::string BrowserExtensionWindowController::GetWindowTypeText() const {
  if (browser_->is_type_popup())
    return keys::kWindowTypeValuePopup;
  if (browser_->is_type_panel())
    return keys::kWindowTypeValuePanel;
  if (browser_->is_app())
    return keys::kWindowTypeValueApp;
  return keys::kWindowTypeValueNormal;
}

base::DictionaryValue*
BrowserExtensionWindowController::CreateWindowValue() const {
  DictionaryValue* result = extensions::WindowController::CreateWindowValue();
  return result;
}

base::DictionaryValue*
BrowserExtensionWindowController::CreateWindowValueWithTabs(
    const extensions::Extension* extension) const {
  DictionaryValue* result = CreateWindowValue();

  result->Set(keys::kTabsKey, ExtensionTabUtil::CreateTabList(browser_,
                                                              extension));

  return result;
}

bool BrowserExtensionWindowController::CanClose(Reason* reason) const {
  // Don't let an extension remove the window if the user is dragging tabs
  // in that window.
  if (!chrome::IsTabStripEditable(browser_)) {
    *reason = extensions::WindowController::REASON_NOT_EDITABLE;
    return false;
  }
  return true;
}

void BrowserExtensionWindowController::SetFullscreenMode(
    bool is_fullscreen,
    const GURL& extension_url) const {
  if (browser_->window()->IsFullscreen() != is_fullscreen)
    browser_->ToggleFullscreenModeWithExtension(extension_url);
}

Browser* BrowserExtensionWindowController::GetBrowser() const {
  return browser_;
}

bool BrowserExtensionWindowController::IsVisibleToExtension(
    const extensions::Extension* extension) const {
  // Platform apps can only see their own windows.
  return !extension->is_platform_app();
}
<|endoftext|>


<commit_before>#ifdef NL_DATA_CONTAINER_H_

#include "NL_DataContainer.h"

namespace NLE
{
	namespace Core
	{
		template<typename T>
		DataContainer<T>::DataContainer() :
			_sysId(-1),
			_dataPool(),
			_data(_dataPool),
			_updateQueue(),
			_distributor(nullptr)
		{
		}

		template<typename T>
		DataContainer<T>::~DataContainer()
		{
		}

		template<typename T>
		bool DataContainer<T>::initialize(uint_fast8_t sysId, uint_fast8_t initSize)
		{
			_sysId = sysId;
			_data.reserve(initSize);
			return true;
		}

		template<typename T>
		void DataContainer<T>::release()
		{
			_data.clear();
			_dataPool.recycle();
		}

		template<typename T>
		void DataContainer<T>::bindDistributor(DataDistributor<T>* distributor)
		{
			_distributor = distributor;
		}

		template<typename T>
		inline void add(T data)
		{
			_data.push_back(data);
		}

		template<typename T>
		void DataContainer<T>::remove(uint_fast8_t index)
		{
			uint_fast8_t size = _data.size();
			if (index < size)
			{
				uint_fast8_t lastOccupied = size - 1;
				if (index != lastOccupied)
				{
					_data[index] = _data[lastOccupied];
				}
				_data.pop_back();
			}
		}

		template<typename T>
		void DataContainer<T>::modify(uint_fast8_t index, T data)
		{
			_data[index] = data;
			if (_distributor)
			{
				_distributor->queue({ _sysId, index, data });
			}
		}

		template<typename T>
		inline void DataContainer<T>::clear()
		{
			_data.clear();
		}

		template<typename T>
		inline uint_fast8_t DataContainer<T>::size()
		{
			return _data.size();
		}

		template<typename T>
		inline T& DataContainer<T>::get(uint_fast8_t index)
		{
			return _data[index];
		}

		template<typename T>
		inline void DataContainer<T>::queuePacket(DataPacket<T> packet)
		{
			_updateQueue.push(packet);
		}

		template<typename T>
		void DataContainer<T>::applyUpdates()
		{
			DataPacket<T> packet;
			while (_updateQueue.try_pop(packet))
			{
				modify(packet.getItemNumber(), packet.getData());
			}
		}
	}
}

#endif<commit_msg>bug fix: applying container update distributes data<commit_after>#ifdef NL_DATA_CONTAINER_H_

#include "NL_DataContainer.h"

namespace NLE
{
	namespace Core
	{
		template<typename T>
		DataContainer<T>::DataContainer() :
			_sysId(-1),
			_dataPool(),
			_data(_dataPool),
			_updateQueue(),
			_distributor(nullptr)
		{
		}

		template<typename T>
		DataContainer<T>::~DataContainer()
		{
		}

		template<typename T>
		bool DataContainer<T>::initialize(uint_fast8_t sysId, uint_fast8_t initSize)
		{
			_sysId = sysId;
			_data.reserve(initSize);
			return true;
		}

		template<typename T>
		void DataContainer<T>::release()
		{
			_data.clear();
			_dataPool.recycle();
		}

		template<typename T>
		void DataContainer<T>::bindDistributor(DataDistributor<T>* distributor)
		{
			_distributor = distributor;
		}

		template<typename T>
		inline void add(T data)
		{
			_data.push_back(data);
		}

		template<typename T>
		void DataContainer<T>::remove(uint_fast8_t index)
		{
			uint_fast8_t size = _data.size();
			if (index < size)
			{
				uint_fast8_t lastOccupied = size - 1;
				if (index != lastOccupied)
				{
					_data[index] = _data[lastOccupied];
				}
				_data.pop_back();
			}
		}

		template<typename T>
		void DataContainer<T>::modify(uint_fast8_t index, T data)
		{
			_data[index] = data;
			if (_distributor)
			{
				_distributor->queue({ _sysId, index, data });
			}
		}

		template<typename T>
		inline void DataContainer<T>::clear()
		{
			_data.clear();
		}

		template<typename T>
		inline uint_fast8_t DataContainer<T>::size()
		{
			return _data.size();
		}

		template<typename T>
		inline T& DataContainer<T>::get(uint_fast8_t index)
		{
			return _data[index];
		}

		template<typename T>
		inline void DataContainer<T>::queuePacket(DataPacket<T> packet)
		{
			_updateQueue.push(packet);
		}

		template<typename T>
		void DataContainer<T>::applyUpdates()
		{
			DataPacket<T> packet;
			while (_updateQueue.try_pop(packet))
			{
				_data[packet.getItemNumber()] = packet.getData();
			}
		}
	}
}

#endif<|endoftext|>


<commit_before>#include "unit_tests/suite/lumix_unit_tests.h"

#include "engine/log.h"
#ifdef _WIN32
	#include "engine/win/simple_win.h"
#endif
#include <cstdio>

namespace Lumix
{
	namespace UnitTest
	{
		void outputToVS(const char* system, const char* message)
		{
			char tmp[2048];
			copyString(tmp, system);
			catString(tmp, ": ");
			catString(tmp, message);
			catString(tmp, "\r");

			#ifdef _WIN32
				OutputDebugString(tmp);
			#endif
		}

		void outputToConsole(const char* system, const char* message)
		{
			printf("%s: %s\n", system, message);
		}

		void App::init()
		{
			g_log_info.getCallback().bind<outputToVS>();
			g_log_warning.getCallback().bind<outputToVS>();
			g_log_error.getCallback().bind<outputToVS>();

			g_log_info.getCallback().bind<outputToConsole>();
			g_log_warning.getCallback().bind<outputToConsole>();
			g_log_error.getCallback().bind<outputToConsole>();
		}

		void App::run(int argc, const char *argv[])
		{
			Manager::instance().dumpTests();
			Manager::instance().runTests("unit_tests/engine/universe/hierarchy3");
			Manager::instance().dumpResults();
		}

		void App::exit()
		{
			Manager::release();
		}
	} //~UnitTest
} //~UnitTest<commit_msg>fixed unit tests<commit_after>#include "unit_tests/suite/lumix_unit_tests.h"

#include "engine/log.h"
#ifdef _WIN32
	#include "engine/win/simple_win.h"
#endif
#include <cstdio>

namespace Lumix
{
	namespace UnitTest
	{
		void outputToVS(const char* system, const char* message)
		{
			char tmp[2048];
			copyString(tmp, system);
			catString(tmp, ": ");
			catString(tmp, message);
			catString(tmp, "\r");

			#ifdef _WIN32
				OutputDebugString(tmp);
			#endif
		}

		void outputToConsole(const char* system, const char* message)
		{
			printf("%s: %s\n", system, message);
		}

		void App::init()
		{
			g_log_info.getCallback().bind<outputToVS>();
			g_log_warning.getCallback().bind<outputToVS>();
			g_log_error.getCallback().bind<outputToVS>();

			g_log_info.getCallback().bind<outputToConsole>();
			g_log_warning.getCallback().bind<outputToConsole>();
			g_log_error.getCallback().bind<outputToConsole>();
		}

		void App::run(int argc, const char *argv[])
		{
			Manager::instance().dumpTests();
			Manager::instance().runTests("*");
			Manager::instance().dumpResults();
		}

		void App::exit()
		{
			Manager::release();
		}
	} //~UnitTest
} //~UnitTest<|endoftext|>