<commit_before>/*
    yahoochatselectordialog.h

    Copyright (c) 2006 by Andre Duffeck <andre@duffeck.de>
    Kopete    (c) 2002-2006 by the Kopete developers <kopete-devel@kde.org>

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

#include <QDomDocument>
#include <QTreeWidgetItem>
#include <QHeaderView>

#include "ui_yahoochatselectorwidgetbase.h"
#include "yahoochatselectordialog.h"

YahooChatSelectorDialog::YahooChatSelectorDialog( QWidget *parent )
	: KDialog( parent )
{
	setCaption( i18n( "Choose a chat room..." ) );
	setButtons( KDialog::Ok | KDialog::Cancel );
	setDefaultButton( KDialog::Ok );
	showButtonSeparator( true );
	mUi = new Ui_YahooChatSelectorWidgetBase();

	QBoxLayout *layout = new QVBoxLayout(this);
	QWidget *widget = new QWidget(this);
	mUi->setupUi(widget);
	layout->addWidget(widget);
	setMainWidget(widget);

	mUi->treeCategories->header()->hide();
	mUi->treeRooms->header()->hide();

	QTreeWidgetItem *loading = new QTreeWidgetItem(mUi->treeCategories);
	loading->setText( 0, i18n("Loading...") );
	mUi->treeCategories->addTopLevelItem( loading );

 	connect(mUi->treeCategories, SIGNAL(currentItemChanged ( QTreeWidgetItem *, QTreeWidgetItem * )),
		this, SLOT(slotCategorySelectionChanged( QTreeWidgetItem *, QTreeWidgetItem * )));
	connect(mUi->treeRooms, SIGNAL(itemDoubleClicked( QTreeWidgetItem *, int )),
		this, SLOT(slotChatRoomDoubleClicked( QTreeWidgetItem *, int )) );
}

YahooChatSelectorDialog::~YahooChatSelectorDialog()
{
	delete mUi;
}

void YahooChatSelectorDialog::slotCategorySelectionChanged( QTreeWidgetItem *newItem, QTreeWidgetItem *oldItem )
{
	Q_UNUSED( oldItem );
	kDebug(YAHOO_RAW_DEBUG) << k_funcinfo << "Selected Category: " << newItem->text( 0 ) <<  "(" << newItem->data( 0, Qt::UserRole ).toInt() << ")" << endl;

	mUi->treeRooms->clear();

	QTreeWidgetItem *loading = new QTreeWidgetItem(mUi->treeRooms);
	loading->setText( 0, i18n("Loading...") );
	mUi->treeRooms->addTopLevelItem( loading );

	Yahoo::ChatCategory category;
	category.id = newItem->data( 0, Qt::UserRole ).toInt();
	category.name = newItem->text( 0 );

	emit chatCategorySelected( category );
}

void YahooChatSelectorDialog::slotChatRoomDoubleClicked( QTreeWidgetItem * item, int column )
{
	Q_UNUSED( column );
	Q_UNUSED( item );
	QDialog::accept();
}

void YahooChatSelectorDialog::slotSetChatCategories( const QDomDocument &doc )
{
	kDebug(YAHOO_RAW_DEBUG) << k_funcinfo << doc.toString() << endl;
	mUi->treeCategories->takeTopLevelItem(0);

	QTreeWidgetItem *root = new QTreeWidgetItem( mUi->treeCategories );
	root->setText( 0, i18n("Yahoo Chat rooms") );
	QDomNode child = doc.firstChild();
	mUi->treeCategories->setItemExpanded( root, true );
	while( !child.isNull() )
	{
		parseChatCategory(child, root);
		child = child.nextSibling();
	}

}

void YahooChatSelectorDialog::parseChatCategory( const QDomNode &node, QTreeWidgetItem *parentItem )
{
	QTreeWidgetItem *newParent = parentItem;
	if( node.nodeName().startsWith( "category" ) )
	{
		QTreeWidgetItem *item = new QTreeWidgetItem( parentItem );

		item->setText( 0, node.toElement().attribute( "name" ) );
		item->setData( 0, Qt::UserRole, node.toElement().attribute( "id" ) );
		parentItem->addChild( item );
		newParent = item;
	}
	QDomNode child = node.firstChild();
	while( !child.isNull() )
	{
		parseChatCategory(child, newParent);
		child = child.nextSibling();
	}
}

void YahooChatSelectorDialog::slotSetChatRooms( const Yahoo::ChatCategory &category, const QDomDocument &doc )
{
	kDebug(YAHOO_RAW_DEBUG) << k_funcinfo << doc.toString() << endl;
	Q_UNUSED( category );
	mUi->treeRooms->clear();

	QDomNode child = doc.firstChild();
	while( !child.isNull() )
	{
		parseChatRoom( child );
		child = child.nextSibling();
	}

}

void YahooChatSelectorDialog::parseChatRoom( const QDomNode &node )
{
	if( node.nodeName().startsWith( "room" ) )
	{
		QTreeWidgetItem *item = new QTreeWidgetItem( mUi->treeRooms );
		QDomElement elem = node.toElement();
		QString name = elem.attribute( "name" );
		QString id = elem.attribute( "id" );
		item->setText( 0, name );
		item->setData( 0, Qt::ToolTipRole, elem.attribute( "topic" ) );
		item->setData( 0, Qt::UserRole, id );

		QDomNode child;
		for( child = node.firstChild(); !child.isNull(); child = child.nextSibling() )
		{
			if( child.nodeName().startsWith( "lobby" ) )
			{
				QTreeWidgetItem *lobby = new QTreeWidgetItem( item );
				QDomElement e = child.toElement();
				QString voices = e.attribute( "voices" );
				QString users = e.attribute( "users" );
				QString webcams = e.attribute( "webcams" );
				QString count = e.attribute( "count" );
				lobby->setText( 0, name + QString( ": %1 (u:%2, v:%3, w:%4)" )
						.arg( count, users, voices, webcams ) );
				lobby->setData( 0, Qt::UserRole, id );
				item->addChild( lobby );
			}
		}
	}
	else
	{
		QDomNode child = node.firstChild();
		while( !child.isNull() )
		{
			parseChatRoom( child );
			child = child.nextSibling();
		}
	}
}

Yahoo::ChatRoom YahooChatSelectorDialog::selectedRoom()
{
	Yahoo::ChatRoom room;
	QTreeWidgetItem *item = mUi->treeRooms->selectedItems().first();
	room.name =  item->text( 0 );
	room.topic = item->data( 0, Qt::ToolTipRole ).toString();
	room.id = item->data( 0, Qt::UserRole ).toInt();

	return room;
}

#include "yahoochatselectordialog.moc"

<commit_msg>Show users, webcam and voices in tooltip.<commit_after>/*
    yahoochatselectordialog.h

    Copyright (c) 2006 by Andre Duffeck <andre@duffeck.de>
    Kopete    (c) 2002-2006 by the Kopete developers <kopete-devel@kde.org>

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

#include <QDomDocument>
#include <QTreeWidgetItem>
#include <QHeaderView>

#include "ui_yahoochatselectorwidgetbase.h"
#include "yahoochatselectordialog.h"

YahooChatSelectorDialog::YahooChatSelectorDialog( QWidget *parent )
	: KDialog( parent )
{
	setCaption( i18n( "Choose a chat room..." ) );
	setButtons( KDialog::Ok | KDialog::Cancel );
	setDefaultButton( KDialog::Ok );
	showButtonSeparator( true );
	mUi = new Ui_YahooChatSelectorWidgetBase();

	QBoxLayout *layout = new QVBoxLayout(this);
	QWidget *widget = new QWidget(this);
	mUi->setupUi(widget);
	layout->addWidget(widget);
	setMainWidget(widget);

	mUi->treeCategories->header()->hide();
	mUi->treeRooms->header()->hide();

	QTreeWidgetItem *loading = new QTreeWidgetItem(mUi->treeCategories);
	loading->setText( 0, i18n("Loading...") );
	mUi->treeCategories->addTopLevelItem( loading );

 	connect(mUi->treeCategories, SIGNAL(currentItemChanged ( QTreeWidgetItem *, QTreeWidgetItem * )),
		this, SLOT(slotCategorySelectionChanged( QTreeWidgetItem *, QTreeWidgetItem * )));
	connect(mUi->treeRooms, SIGNAL(itemDoubleClicked( QTreeWidgetItem *, int )),
		this, SLOT(slotChatRoomDoubleClicked( QTreeWidgetItem *, int )) );
}

YahooChatSelectorDialog::~YahooChatSelectorDialog()
{
	delete mUi;
}

void YahooChatSelectorDialog::slotCategorySelectionChanged( QTreeWidgetItem *newItem, QTreeWidgetItem *oldItem )
{
	Q_UNUSED( oldItem );
	kDebug(YAHOO_RAW_DEBUG) << k_funcinfo << "Selected Category: " << newItem->text( 0 ) <<  "(" << newItem->data( 0, Qt::UserRole ).toInt() << ")" << endl;

	mUi->treeRooms->clear();

	QTreeWidgetItem *loading = new QTreeWidgetItem(mUi->treeRooms);
	loading->setText( 0, i18n("Loading...") );
	mUi->treeRooms->addTopLevelItem( loading );

	Yahoo::ChatCategory category;
	category.id = newItem->data( 0, Qt::UserRole ).toInt();
	category.name = newItem->text( 0 );

	emit chatCategorySelected( category );
}

void YahooChatSelectorDialog::slotChatRoomDoubleClicked( QTreeWidgetItem * item, int column )
{
	Q_UNUSED( column );
	Q_UNUSED( item );
	QDialog::accept();
}

void YahooChatSelectorDialog::slotSetChatCategories( const QDomDocument &doc )
{
	kDebug(YAHOO_RAW_DEBUG) << k_funcinfo << doc.toString() << endl;
	mUi->treeCategories->takeTopLevelItem(0);

	QTreeWidgetItem *root = new QTreeWidgetItem( mUi->treeCategories );
	root->setText( 0, i18n("Yahoo Chat rooms") );
	QDomNode child = doc.firstChild();
	mUi->treeCategories->setItemExpanded( root, true );
	while( !child.isNull() )
	{
		parseChatCategory(child, root);
		child = child.nextSibling();
	}

}

void YahooChatSelectorDialog::parseChatCategory( const QDomNode &node, QTreeWidgetItem *parentItem )
{
	QTreeWidgetItem *newParent = parentItem;
	if( node.nodeName().startsWith( "category" ) )
	{
		QTreeWidgetItem *item = new QTreeWidgetItem( parentItem );

		item->setText( 0, node.toElement().attribute( "name" ) );
		item->setData( 0, Qt::UserRole, node.toElement().attribute( "id" ) );
		parentItem->addChild( item );
		newParent = item;
	}
	QDomNode child = node.firstChild();
	while( !child.isNull() )
	{
		parseChatCategory(child, newParent);
		child = child.nextSibling();
	}
}

void YahooChatSelectorDialog::slotSetChatRooms( const Yahoo::ChatCategory &category, const QDomDocument &doc )
{
	kDebug(YAHOO_RAW_DEBUG) << k_funcinfo << doc.toString() << endl;
	Q_UNUSED( category );
	mUi->treeRooms->clear();

	QDomNode child = doc.firstChild();
	while( !child.isNull() )
	{
		parseChatRoom( child );
		child = child.nextSibling();
	}

}

void YahooChatSelectorDialog::parseChatRoom( const QDomNode &node )
{
	if( node.nodeName().startsWith( "room" ) )
	{
		QTreeWidgetItem *item = new QTreeWidgetItem( mUi->treeRooms );
		QDomElement elem = node.toElement();
		QString name = elem.attribute( "name" );
		QString id = elem.attribute( "id" );
		item->setText( 0, name );
		item->setData( 0, Qt::ToolTipRole, elem.attribute( "topic" ) );
		item->setData( 0, Qt::UserRole, id );

		QDomNode child;
		for( child = node.firstChild(); !child.isNull(); child = child.nextSibling() )
		{
			if( child.nodeName().startsWith( "lobby" ) )
			{
				QTreeWidgetItem *lobby = new QTreeWidgetItem( item );
				QDomElement e = child.toElement();
				QString voices = e.attribute( "voices" );
				QString users = e.attribute( "users" );
				QString webcams = e.attribute( "webcams" );
				QString count = e.attribute( "count" );
				lobby->setText( 0, name + QString( ":%1" )
						.arg( count ) );
				lobby->setData( 0, Qt::ToolTipRole, QString( "Users: %1 Webcams: %2 Voices: %3" )
						.arg( users, webcams, voices ) );
				lobby->setData( 0, Qt::UserRole, id );
				item->addChild( lobby );
			}
		}
	}
	else
	{
		QDomNode child = node.firstChild();
		while( !child.isNull() )
		{
			parseChatRoom( child );
			child = child.nextSibling();
		}
	}
}

Yahoo::ChatRoom YahooChatSelectorDialog::selectedRoom()
{
	Yahoo::ChatRoom room;
	QTreeWidgetItem *item = mUi->treeRooms->selectedItems().first();
	room.name =  item->text( 0 );
	room.topic = item->data( 0, Qt::ToolTipRole ).toString();
	room.id = item->data( 0, Qt::UserRole ).toInt();

	return room;
}

#include "yahoochatselectordialog.moc"

<|endoftext|>


<commit_before><commit_msg>When run chrome with --no-sandbox, the renderer process calls the dtor of BrokerServicesBase. There some API calls have invalid parameters.<commit_after><|endoftext|>


<commit_before>/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

#include "YogaLayoutableShadowNode.h"

#include <algorithm>
#include <limits>
#include <memory>

#include <react/components/view/conversions.h>
#include <react/core/LayoutConstraints.h>
#include <react/core/LayoutContext.h>
#include <react/debug/DebugStringConvertibleItem.h>
#include <react/debug/SystraceSection.h>
#include <yoga/Yoga.h>

namespace facebook {
namespace react {

YogaLayoutableShadowNode::YogaLayoutableShadowNode()
    : yogaNode_({}), yogaConfig_(nullptr) {
  initializeYogaConfig(yogaConfig_);

  yogaNode_.setConfig(&yogaConfig_);
  yogaNode_.setContext(this);
}

YogaLayoutableShadowNode::YogaLayoutableShadowNode(
    const YogaLayoutableShadowNode &layoutableShadowNode)
    : LayoutableShadowNode(layoutableShadowNode),
      yogaNode_(layoutableShadowNode.yogaNode_),
      yogaConfig_(nullptr) {
  initializeYogaConfig(yogaConfig_);

  yogaNode_.setConfig(&yogaConfig_);
  yogaNode_.setContext(this);
  yogaNode_.setOwner(nullptr);

  // Yoga node must inherit dirty flag.
  assert(layoutableShadowNode.yogaNode_.isDirty() == yogaNode_.isDirty());
}

void YogaLayoutableShadowNode::cleanLayout() {
  yogaNode_.setDirty(false);
}

void YogaLayoutableShadowNode::dirtyLayout() {
  yogaNode_.setDirty(true);
}

bool YogaLayoutableShadowNode::getIsLayoutClean() const {
  return !yogaNode_.isDirty();
}

bool YogaLayoutableShadowNode::getHasNewLayout() const {
  return yogaNode_.getHasNewLayout();
}

void YogaLayoutableShadowNode::setHasNewLayout(bool hasNewLayout) {
  yogaNode_.setHasNewLayout(hasNewLayout);
}

#pragma mark - Mutating Methods

void YogaLayoutableShadowNode::enableMeasurement() {
  ensureUnsealed();

  yogaNode_.setMeasureFunc(
      YogaLayoutableShadowNode::yogaNodeMeasureCallbackConnector);
}

void YogaLayoutableShadowNode::appendChild(YogaLayoutableShadowNode *child) {
  ensureUnsealed();

  yogaNode_.setDirty(true);

  auto yogaNodeRawPtr = &yogaNode_;
  auto childYogaNodeRawPtr = &child->yogaNode_;

  if (childYogaNodeRawPtr->getOwner() != nullptr) {
    child = static_cast<YogaLayoutableShadowNode *>(
        cloneAndReplaceChild(child, yogaNode_.getChildren().size()));
    childYogaNodeRawPtr = &child->yogaNode_;
  }

  // Inserted node must have a clear owner (must not be shared).
  assert(childYogaNodeRawPtr->getOwner() == nullptr);

  child->ensureUnsealed();
  childYogaNodeRawPtr->setOwner(yogaNodeRawPtr);

  yogaNodeRawPtr->insertChild(
      childYogaNodeRawPtr, yogaNodeRawPtr->getChildren().size());
}

void YogaLayoutableShadowNode::setChildren(
    YogaLayoutableShadowNode::UnsharedList children) {
  ensureUnsealed();

  // Optimization:
  // If the new list of child nodes consists of clean nodes, and if their styles
  // are identical to styles of old children, we don't dirty the node.
  bool isClean = !yogaNode_.getDirtied() &&
      children.size() == yogaNode_.getChildren().size();
  auto oldChildren = isClean ? yogaNode_.getChildren() : YGVector{};

  yogaNode_.setChildren({});

  auto i = int{0};
  for (auto const &child : children) {
    appendChild(child);

    isClean = isClean && !child->yogaNode_.isDirty() &&
        child->yogaNode_.getStyle() == oldChildren[i++]->getStyle();
  }

  yogaNode_.setDirty(!isClean);
}

void YogaLayoutableShadowNode::setProps(const YogaStylableProps &props) {
  ensureUnsealed();

  // Resetting `dirty` flag only if `yogaStyle` portion of `Props` was changed.
  if (!yogaNode_.isDirty() && (props.yogaStyle != yogaNode_.getStyle())) {
    yogaNode_.setDirty(true);
  }

  yogaNode_.setStyle(props.yogaStyle);
}

void YogaLayoutableShadowNode::setSize(Size size) const {
  ensureUnsealed();

  auto style = yogaNode_.getStyle();
  style.dimensions()[YGDimensionWidth] = yogaStyleValueFromFloat(size.width);
  style.dimensions()[YGDimensionHeight] = yogaStyleValueFromFloat(size.height);
  yogaNode_.setStyle(style);
  yogaNode_.setDirty(true);
}

void YogaLayoutableShadowNode::setPositionType(
    YGPositionType positionType) const {
  ensureUnsealed();

  auto style = yogaNode_.getStyle();
  style.positionType() = positionType;
  yogaNode_.setStyle(style);
  yogaNode_.setDirty(true);
}

void YogaLayoutableShadowNode::layout(LayoutContext layoutContext) {
  if (!getIsLayoutClean()) {
    ensureUnsealed();

    /*
     * In Yoga, every single Yoga Node has to have a (non-null) pointer to
     * Yoga Config (this config can be shared between many nodes),
     * so every node can be individually configured. This does *not* mean
     * however that Yoga consults with every single Yoga Node Config for every
     * config parameter. Especially in case of `pointScaleFactor`,
     * the only value in the config of the root node is taken into account
     * (and this is by design).
     */
    yogaConfig_.pointScaleFactor = layoutContext.pointScaleFactor;

    {
      SystraceSection s("YogaLayoutableShadowNode::YGNodeCalculateLayout");

      YGNodeCalculateLayout(
          &yogaNode_, YGUndefined, YGUndefined, YGDirectionInherit);
    }
  }

  LayoutableShadowNode::layout(layoutContext);
}

void YogaLayoutableShadowNode::layoutChildren(LayoutContext layoutContext) {
  for (const auto &childYogaNode : yogaNode_.getChildren()) {
    if (!childYogaNode->getHasNewLayout()) {
      continue;
    }

    auto childNode =
        static_cast<YogaLayoutableShadowNode *>(childYogaNode->getContext());

    // Verifying that the Yoga node belongs to the ShadowNode.
    assert(&childNode->yogaNode_ == childYogaNode);

    LayoutMetrics childLayoutMetrics =
        layoutMetricsFromYogaNode(childNode->yogaNode_);
    childLayoutMetrics.pointScaleFactor = layoutContext.pointScaleFactor;

    // We must copy layout metrics from Yoga node only once (when the parent
    // node exclusively ownes the child node).
    assert(childYogaNode->getOwner() == &yogaNode_);

    childNode->ensureUnsealed();
    auto affected = childNode->setLayoutMetrics(childLayoutMetrics);

    if (affected && layoutContext.affectedNodes) {
      layoutContext.affectedNodes->push_back(childNode);
    }
  }
}

LayoutableShadowNode::UnsharedList
YogaLayoutableShadowNode::getLayoutableChildNodes() const {
  LayoutableShadowNode::UnsharedList yogaLayoutableChildNodes;
  yogaLayoutableChildNodes.reserve(yogaNode_.getChildren().size());

  for (const auto &childYogaNode : yogaNode_.getChildren()) {
    auto childNode =
        static_cast<YogaLayoutableShadowNode *>(childYogaNode->getContext());
    yogaLayoutableChildNodes.push_back(childNode);
  }

  return yogaLayoutableChildNodes;
}

#pragma mark - Yoga Connectors

YGNode *YogaLayoutableShadowNode::yogaNodeCloneCallbackConnector(
    YGNode *oldYogaNode,
    YGNode *parentYogaNode,
    int childIndex) {
  SystraceSection s("YogaLayoutableShadowNode::yogaNodeCloneCallbackConnector");

  // At this point it is garanteed that all shadow nodes associated with yoga
  // nodes are `YogaLayoutableShadowNode` subclasses.
  auto parentNode =
      static_cast<YogaLayoutableShadowNode *>(parentYogaNode->getContext());
  auto oldNode =
      static_cast<YogaLayoutableShadowNode *>(oldYogaNode->getContext());
  auto clonedNode = static_cast<YogaLayoutableShadowNode *>(
      parentNode->cloneAndReplaceChild(oldNode, childIndex));
  return &clonedNode->yogaNode_;
}

YGSize YogaLayoutableShadowNode::yogaNodeMeasureCallbackConnector(
    YGNode *yogaNode,
    float width,
    YGMeasureMode widthMode,
    float height,
    YGMeasureMode heightMode) {
  SystraceSection s(
      "YogaLayoutableShadowNode::yogaNodeMeasureCallbackConnector");

  auto shadowNodeRawPtr =
      static_cast<YogaLayoutableShadowNode *>(yogaNode->getContext());

  auto minimumSize = Size{0, 0};
  auto maximumSize = Size{std::numeric_limits<Float>::infinity(),
                          std::numeric_limits<Float>::infinity()};

  switch (widthMode) {
    case YGMeasureModeUndefined:
      break;
    case YGMeasureModeExactly:
      minimumSize.width = floatFromYogaFloat(width);
      maximumSize.width = floatFromYogaFloat(width);
      break;
    case YGMeasureModeAtMost:
      maximumSize.width = floatFromYogaFloat(width);
      break;
  }

  switch (heightMode) {
    case YGMeasureModeUndefined:
      break;
    case YGMeasureModeExactly:
      minimumSize.height = floatFromYogaFloat(height);
      maximumSize.height = floatFromYogaFloat(height);
      break;
    case YGMeasureModeAtMost:
      maximumSize.height = floatFromYogaFloat(height);
      break;
  }

  auto size = shadowNodeRawPtr->measure({minimumSize, maximumSize});

  return YGSize{yogaFloatFromFloat(size.width),
                yogaFloatFromFloat(size.height)};
}

void YogaLayoutableShadowNode::initializeYogaConfig(YGConfig &config) {
  config.setCloneNodeCallback(
      YogaLayoutableShadowNode::yogaNodeCloneCallbackConnector);
}

} // namespace react
} // namespace facebook
<commit_msg>Fabric: Enable `useLegacyStretchBehaviour` for Yoga in Fabric<commit_after>/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

#include "YogaLayoutableShadowNode.h"

#include <algorithm>
#include <limits>
#include <memory>

#include <react/components/view/conversions.h>
#include <react/core/LayoutConstraints.h>
#include <react/core/LayoutContext.h>
#include <react/debug/DebugStringConvertibleItem.h>
#include <react/debug/SystraceSection.h>
#include <yoga/Yoga.h>

namespace facebook {
namespace react {

YogaLayoutableShadowNode::YogaLayoutableShadowNode()
    : yogaNode_({}), yogaConfig_(nullptr) {
  initializeYogaConfig(yogaConfig_);

  yogaNode_.setConfig(&yogaConfig_);
  yogaNode_.setContext(this);
}

YogaLayoutableShadowNode::YogaLayoutableShadowNode(
    const YogaLayoutableShadowNode &layoutableShadowNode)
    : LayoutableShadowNode(layoutableShadowNode),
      yogaNode_(layoutableShadowNode.yogaNode_),
      yogaConfig_(nullptr) {
  initializeYogaConfig(yogaConfig_);

  yogaNode_.setConfig(&yogaConfig_);
  yogaNode_.setContext(this);
  yogaNode_.setOwner(nullptr);

  // Yoga node must inherit dirty flag.
  assert(layoutableShadowNode.yogaNode_.isDirty() == yogaNode_.isDirty());
}

void YogaLayoutableShadowNode::cleanLayout() {
  yogaNode_.setDirty(false);
}

void YogaLayoutableShadowNode::dirtyLayout() {
  yogaNode_.setDirty(true);
}

bool YogaLayoutableShadowNode::getIsLayoutClean() const {
  return !yogaNode_.isDirty();
}

bool YogaLayoutableShadowNode::getHasNewLayout() const {
  return yogaNode_.getHasNewLayout();
}

void YogaLayoutableShadowNode::setHasNewLayout(bool hasNewLayout) {
  yogaNode_.setHasNewLayout(hasNewLayout);
}

#pragma mark - Mutating Methods

void YogaLayoutableShadowNode::enableMeasurement() {
  ensureUnsealed();

  yogaNode_.setMeasureFunc(
      YogaLayoutableShadowNode::yogaNodeMeasureCallbackConnector);
}

void YogaLayoutableShadowNode::appendChild(YogaLayoutableShadowNode *child) {
  ensureUnsealed();

  yogaNode_.setDirty(true);

  auto yogaNodeRawPtr = &yogaNode_;
  auto childYogaNodeRawPtr = &child->yogaNode_;

  if (childYogaNodeRawPtr->getOwner() != nullptr) {
    child = static_cast<YogaLayoutableShadowNode *>(
        cloneAndReplaceChild(child, yogaNode_.getChildren().size()));
    childYogaNodeRawPtr = &child->yogaNode_;
  }

  // Inserted node must have a clear owner (must not be shared).
  assert(childYogaNodeRawPtr->getOwner() == nullptr);

  child->ensureUnsealed();
  childYogaNodeRawPtr->setOwner(yogaNodeRawPtr);

  yogaNodeRawPtr->insertChild(
      childYogaNodeRawPtr, yogaNodeRawPtr->getChildren().size());
}

void YogaLayoutableShadowNode::setChildren(
    YogaLayoutableShadowNode::UnsharedList children) {
  ensureUnsealed();

  // Optimization:
  // If the new list of child nodes consists of clean nodes, and if their styles
  // are identical to styles of old children, we don't dirty the node.
  bool isClean = !yogaNode_.getDirtied() &&
      children.size() == yogaNode_.getChildren().size();
  auto oldChildren = isClean ? yogaNode_.getChildren() : YGVector{};

  yogaNode_.setChildren({});

  auto i = int{0};
  for (auto const &child : children) {
    appendChild(child);

    isClean = isClean && !child->yogaNode_.isDirty() &&
        child->yogaNode_.getStyle() == oldChildren[i++]->getStyle();
  }

  yogaNode_.setDirty(!isClean);
}

void YogaLayoutableShadowNode::setProps(const YogaStylableProps &props) {
  ensureUnsealed();

  // Resetting `dirty` flag only if `yogaStyle` portion of `Props` was changed.
  if (!yogaNode_.isDirty() && (props.yogaStyle != yogaNode_.getStyle())) {
    yogaNode_.setDirty(true);
  }

  yogaNode_.setStyle(props.yogaStyle);
}

void YogaLayoutableShadowNode::setSize(Size size) const {
  ensureUnsealed();

  auto style = yogaNode_.getStyle();
  style.dimensions()[YGDimensionWidth] = yogaStyleValueFromFloat(size.width);
  style.dimensions()[YGDimensionHeight] = yogaStyleValueFromFloat(size.height);
  yogaNode_.setStyle(style);
  yogaNode_.setDirty(true);
}

void YogaLayoutableShadowNode::setPositionType(
    YGPositionType positionType) const {
  ensureUnsealed();

  auto style = yogaNode_.getStyle();
  style.positionType() = positionType;
  yogaNode_.setStyle(style);
  yogaNode_.setDirty(true);
}

void YogaLayoutableShadowNode::layout(LayoutContext layoutContext) {
  if (!getIsLayoutClean()) {
    ensureUnsealed();

    /*
     * In Yoga, every single Yoga Node has to have a (non-null) pointer to
     * Yoga Config (this config can be shared between many nodes),
     * so every node can be individually configured. This does *not* mean
     * however that Yoga consults with every single Yoga Node Config for every
     * config parameter. Especially in case of `pointScaleFactor`,
     * the only value in the config of the root node is taken into account
     * (and this is by design).
     */
    yogaConfig_.pointScaleFactor = layoutContext.pointScaleFactor;

    {
      SystraceSection s("YogaLayoutableShadowNode::YGNodeCalculateLayout");

      YGNodeCalculateLayout(
          &yogaNode_, YGUndefined, YGUndefined, YGDirectionInherit);
    }
  }

  LayoutableShadowNode::layout(layoutContext);
}

void YogaLayoutableShadowNode::layoutChildren(LayoutContext layoutContext) {
  for (const auto &childYogaNode : yogaNode_.getChildren()) {
    if (!childYogaNode->getHasNewLayout()) {
      continue;
    }

    auto childNode =
        static_cast<YogaLayoutableShadowNode *>(childYogaNode->getContext());

    // Verifying that the Yoga node belongs to the ShadowNode.
    assert(&childNode->yogaNode_ == childYogaNode);

    LayoutMetrics childLayoutMetrics =
        layoutMetricsFromYogaNode(childNode->yogaNode_);
    childLayoutMetrics.pointScaleFactor = layoutContext.pointScaleFactor;

    // We must copy layout metrics from Yoga node only once (when the parent
    // node exclusively ownes the child node).
    assert(childYogaNode->getOwner() == &yogaNode_);

    childNode->ensureUnsealed();
    auto affected = childNode->setLayoutMetrics(childLayoutMetrics);

    if (affected && layoutContext.affectedNodes) {
      layoutContext.affectedNodes->push_back(childNode);
    }
  }
}

LayoutableShadowNode::UnsharedList
YogaLayoutableShadowNode::getLayoutableChildNodes() const {
  LayoutableShadowNode::UnsharedList yogaLayoutableChildNodes;
  yogaLayoutableChildNodes.reserve(yogaNode_.getChildren().size());

  for (const auto &childYogaNode : yogaNode_.getChildren()) {
    auto childNode =
        static_cast<YogaLayoutableShadowNode *>(childYogaNode->getContext());
    yogaLayoutableChildNodes.push_back(childNode);
  }

  return yogaLayoutableChildNodes;
}

#pragma mark - Yoga Connectors

YGNode *YogaLayoutableShadowNode::yogaNodeCloneCallbackConnector(
    YGNode *oldYogaNode,
    YGNode *parentYogaNode,
    int childIndex) {
  SystraceSection s("YogaLayoutableShadowNode::yogaNodeCloneCallbackConnector");

  // At this point it is garanteed that all shadow nodes associated with yoga
  // nodes are `YogaLayoutableShadowNode` subclasses.
  auto parentNode =
      static_cast<YogaLayoutableShadowNode *>(parentYogaNode->getContext());
  auto oldNode =
      static_cast<YogaLayoutableShadowNode *>(oldYogaNode->getContext());
  auto clonedNode = static_cast<YogaLayoutableShadowNode *>(
      parentNode->cloneAndReplaceChild(oldNode, childIndex));
  return &clonedNode->yogaNode_;
}

YGSize YogaLayoutableShadowNode::yogaNodeMeasureCallbackConnector(
    YGNode *yogaNode,
    float width,
    YGMeasureMode widthMode,
    float height,
    YGMeasureMode heightMode) {
  SystraceSection s(
      "YogaLayoutableShadowNode::yogaNodeMeasureCallbackConnector");

  auto shadowNodeRawPtr =
      static_cast<YogaLayoutableShadowNode *>(yogaNode->getContext());

  auto minimumSize = Size{0, 0};
  auto maximumSize = Size{std::numeric_limits<Float>::infinity(),
                          std::numeric_limits<Float>::infinity()};

  switch (widthMode) {
    case YGMeasureModeUndefined:
      break;
    case YGMeasureModeExactly:
      minimumSize.width = floatFromYogaFloat(width);
      maximumSize.width = floatFromYogaFloat(width);
      break;
    case YGMeasureModeAtMost:
      maximumSize.width = floatFromYogaFloat(width);
      break;
  }

  switch (heightMode) {
    case YGMeasureModeUndefined:
      break;
    case YGMeasureModeExactly:
      minimumSize.height = floatFromYogaFloat(height);
      maximumSize.height = floatFromYogaFloat(height);
      break;
    case YGMeasureModeAtMost:
      maximumSize.height = floatFromYogaFloat(height);
      break;
  }

  auto size = shadowNodeRawPtr->measure({minimumSize, maximumSize});

  return YGSize{yogaFloatFromFloat(size.width),
                yogaFloatFromFloat(size.height)};
}

void YogaLayoutableShadowNode::initializeYogaConfig(YGConfig &config) {
  config.setCloneNodeCallback(
      YogaLayoutableShadowNode::yogaNodeCloneCallbackConnector);
  config.useLegacyStretchBehaviour = true;
}

} // namespace react
} // namespace facebook
<|endoftext|>


<commit_before>
#include "../../Flare.h"

#include "FlareSpacecraftDockingSystem.h"
#include "../FlareStationDock.h"
#include "../FlareSpacecraft.h"

#define LOCTEXT_NAMESPACE "FlareSpacecraftDockingSystem"

/*----------------------------------------------------
	Constructor
----------------------------------------------------*/

UFlareSpacecraftDockingSystem::UFlareSpacecraftDockingSystem(const class FObjectInitializer& PCIP)
	: Super(PCIP)
	, Spacecraft(NULL)
{
}

/*----------------------------------------------------
	Gameplay events
----------------------------------------------------*/

void UFlareSpacecraftDockingSystem::TickSystem(float DeltaSeconds)
{
}

void UFlareSpacecraftDockingSystem::Initialize(AFlareSpacecraft* OwnerSpacecraft, FFlareSpacecraftSave* OwnerData)
{
	Spacecraft = OwnerSpacecraft;
	Components = Spacecraft->GetComponentsByClass(UFlareSpacecraftComponent::StaticClass());
	Description = Spacecraft->GetDescription();
	Data = OwnerData;

}

void UFlareSpacecraftDockingSystem::Start()
{
	// Dock data
	int32 Count = 0;
	TArray<UActorComponent*> ActorComponents;
	Spacecraft->GetComponents(ActorComponents);

	// Fill all dock slots
	for (TArray<UActorComponent*>::TIterator ComponentIt(ActorComponents); ComponentIt; ++ComponentIt)
	{
		UFlareStationDock* Component = Cast<UFlareStationDock>(*ComponentIt);
		if (Component)
		{
			// Get data
			FVector DockLocation;
			FRotator DockRotation;
			Component->GetSocketWorldLocationAndRotation(FName("dock"), DockLocation, DockRotation);

			// Fill info
			FFlareDockingInfo Info;
			Info.LocalAxis = Spacecraft->Airframe->GetComponentToWorld().Inverse().GetRotation().RotateVector(DockRotation.RotateVector(FVector(1,0,0)));
			Info.LocalLocation = Spacecraft->Airframe->GetComponentToWorld().Inverse().TransformPosition(DockLocation);
			Info.DockId = Count;
			Info.DockSize = Component->DockSize;
			Info.Station = Spacecraft;
			Info.Granted = false;
			Info.Occupied = false;

			// Push this slot
			DockingSlots.Add(Info);
			Count++;
		}
	}
}

bool UFlareSpacecraftDockingSystem::HasCompatibleDock(IFlareSpacecraftInterface* Ship) const
{
	for (int32 i = 0; i < DockingSlots.Num(); i++)
	{
		if (DockingSlots[i].DockSize == Ship->GetSize())
		{
			return true;
		}
	}
	return false;
}

FFlareDockingInfo UFlareSpacecraftDockingSystem::RequestDock(IFlareSpacecraftInterface* Ship, FVector PreferredLocation)
{
	FLOGV("UFlareSpacecraftDockingSystem::RequestDock ('%s')", *Ship->_getUObject()->GetName());

	int32 BestIndex = -1;
	float BestDistance = 0;

	// Looking for nearest available slot
	for (int32 i = 0; i < DockingSlots.Num(); i++)
	{
		if (!DockingSlots[i].Granted && DockingSlots[i].DockSize == Ship->GetSize())
		{
			float DockDistance = (Spacecraft->Airframe->GetComponentToWorld().TransformPosition(DockingSlots[i].LocalLocation) - PreferredLocation).Size();
			if (BestIndex < 0 || DockDistance < BestDistance)
			{
				BestDistance = DockDistance;
				BestIndex = i;
			}
		}
	}

	if (BestIndex >=0)
	{
		FLOGV("UFlareSpacecraftDockingSystem::RequestDock : found valid dock %d", BestIndex);
		DockingSlots[BestIndex].Granted = true;
		DockingSlots[BestIndex].Ship = Ship;
		return DockingSlots[BestIndex];
	}

	// Default values
	FFlareDockingInfo Info;
	Info.Granted = false;
	Info.Station = Spacecraft;
	return Info;
}

void UFlareSpacecraftDockingSystem::ReleaseDock(IFlareSpacecraftInterface* Ship, int32 DockId)
{
	FLOGV("UFlareSpacecraftDockingSystem::ReleaseDock %d ('%s')", DockId, *Ship->_getUObject()->GetName());
	DockingSlots[DockId].Granted = false;
	DockingSlots[DockId].Occupied = false;
	DockingSlots[DockId].Ship = NULL;
}

void UFlareSpacecraftDockingSystem::Dock(IFlareSpacecraftInterface* Ship, int32 DockId)
{
	FLOGV("UFlareSpacecraftDockingSystem::Dock %d ('%s')", DockId, *Ship->_getUObject()->GetName());
	DockingSlots[DockId].Granted = true;
	DockingSlots[DockId].Occupied = true;
	DockingSlots[DockId].Ship = Ship;
}

TArray<IFlareSpacecraftInterface*> UFlareSpacecraftDockingSystem::GetDockedShips()
{
	TArray<IFlareSpacecraftInterface*> Result;

	for (int32 i = 0; i < DockingSlots.Num(); i++)
	{
		if (DockingSlots[i].Granted)
		{
			FLOGV("UFlareSpacecraftDockingSystem::GetDockedShips : found valid dock %d", i);
			Result.AddUnique(DockingSlots[i].Ship);
		}
	}

	return Result;
}

bool UFlareSpacecraftDockingSystem::HasAvailableDock(IFlareSpacecraftInterface* Ship) const
{
	// Looking for slot
	for (int32 i = 0; i < DockingSlots.Num(); i++)
	{
		if (!DockingSlots[i].Granted)
		{
			return true;
		}
	}

	return false;
}

int UFlareSpacecraftDockingSystem::GetDockCount() const
{
	return DockingSlots.Num();
}

FFlareDockingInfo UFlareSpacecraftDockingSystem::GetDockInfo(int32 DockId)
{
	return DockingSlots[DockId];
}

bool UFlareSpacecraftDockingSystem::IsGrantedShip(IFlareSpacecraftInterface* ShipCanditate) const
{
	for (int32 i = 0; i < DockingSlots.Num(); i++)
	{
		if (DockingSlots[i].Granted && DockingSlots[i].Ship == ShipCanditate)
		{
			return true;
		}
	}

	return false;
}

bool UFlareSpacecraftDockingSystem::IsDockedShip(IFlareSpacecraftInterface* ShipCanditate) const
{
	for (int32 i = 0; i < DockingSlots.Num(); i++)
	{
		if (DockingSlots[i].Occupied && DockingSlots[i].Ship == ShipCanditate)
		{
			return true;
		}
	}

	return false;
}

#undef LOCTEXT_NAMESPACE
<commit_msg>Don't show docking ship in docked ship list<commit_after>
#include "../../Flare.h"

#include "FlareSpacecraftDockingSystem.h"
#include "../FlareStationDock.h"
#include "../FlareSpacecraft.h"

#define LOCTEXT_NAMESPACE "FlareSpacecraftDockingSystem"

/*----------------------------------------------------
	Constructor
----------------------------------------------------*/

UFlareSpacecraftDockingSystem::UFlareSpacecraftDockingSystem(const class FObjectInitializer& PCIP)
	: Super(PCIP)
	, Spacecraft(NULL)
{
}

/*----------------------------------------------------
	Gameplay events
----------------------------------------------------*/

void UFlareSpacecraftDockingSystem::TickSystem(float DeltaSeconds)
{
}

void UFlareSpacecraftDockingSystem::Initialize(AFlareSpacecraft* OwnerSpacecraft, FFlareSpacecraftSave* OwnerData)
{
	Spacecraft = OwnerSpacecraft;
	Components = Spacecraft->GetComponentsByClass(UFlareSpacecraftComponent::StaticClass());
	Description = Spacecraft->GetDescription();
	Data = OwnerData;

}

void UFlareSpacecraftDockingSystem::Start()
{
	// Dock data
	int32 Count = 0;
	TArray<UActorComponent*> ActorComponents;
	Spacecraft->GetComponents(ActorComponents);

	// Fill all dock slots
	for (TArray<UActorComponent*>::TIterator ComponentIt(ActorComponents); ComponentIt; ++ComponentIt)
	{
		UFlareStationDock* Component = Cast<UFlareStationDock>(*ComponentIt);
		if (Component)
		{
			// Get data
			FVector DockLocation;
			FRotator DockRotation;
			Component->GetSocketWorldLocationAndRotation(FName("dock"), DockLocation, DockRotation);

			// Fill info
			FFlareDockingInfo Info;
			Info.LocalAxis = Spacecraft->Airframe->GetComponentToWorld().Inverse().GetRotation().RotateVector(DockRotation.RotateVector(FVector(1,0,0)));
			Info.LocalLocation = Spacecraft->Airframe->GetComponentToWorld().Inverse().TransformPosition(DockLocation);
			Info.DockId = Count;
			Info.DockSize = Component->DockSize;
			Info.Station = Spacecraft;
			Info.Granted = false;
			Info.Occupied = false;

			// Push this slot
			DockingSlots.Add(Info);
			Count++;
		}
	}
}

bool UFlareSpacecraftDockingSystem::HasCompatibleDock(IFlareSpacecraftInterface* Ship) const
{
	for (int32 i = 0; i < DockingSlots.Num(); i++)
	{
		if (DockingSlots[i].DockSize == Ship->GetSize())
		{
			return true;
		}
	}
	return false;
}

FFlareDockingInfo UFlareSpacecraftDockingSystem::RequestDock(IFlareSpacecraftInterface* Ship, FVector PreferredLocation)
{
	FLOGV("UFlareSpacecraftDockingSystem::RequestDock ('%s')", *Ship->_getUObject()->GetName());

	int32 BestIndex = -1;
	float BestDistance = 0;

	// Looking for nearest available slot
	for (int32 i = 0; i < DockingSlots.Num(); i++)
	{
		if (!DockingSlots[i].Granted && DockingSlots[i].DockSize == Ship->GetSize())
		{
			float DockDistance = (Spacecraft->Airframe->GetComponentToWorld().TransformPosition(DockingSlots[i].LocalLocation) - PreferredLocation).Size();
			if (BestIndex < 0 || DockDistance < BestDistance)
			{
				BestDistance = DockDistance;
				BestIndex = i;
			}
		}
	}

	if (BestIndex >=0)
	{
		FLOGV("UFlareSpacecraftDockingSystem::RequestDock : found valid dock %d", BestIndex);
		DockingSlots[BestIndex].Granted = true;
		DockingSlots[BestIndex].Ship = Ship;
		return DockingSlots[BestIndex];
	}

	// Default values
	FFlareDockingInfo Info;
	Info.Granted = false;
	Info.Station = Spacecraft;
	return Info;
}

void UFlareSpacecraftDockingSystem::ReleaseDock(IFlareSpacecraftInterface* Ship, int32 DockId)
{
	FLOGV("UFlareSpacecraftDockingSystem::ReleaseDock %d ('%s')", DockId, *Ship->_getUObject()->GetName());
	DockingSlots[DockId].Granted = false;
	DockingSlots[DockId].Occupied = false;
	DockingSlots[DockId].Ship = NULL;
}

void UFlareSpacecraftDockingSystem::Dock(IFlareSpacecraftInterface* Ship, int32 DockId)
{
	FLOGV("UFlareSpacecraftDockingSystem::Dock %d ('%s')", DockId, *Ship->_getUObject()->GetName());
	DockingSlots[DockId].Granted = true;
	DockingSlots[DockId].Occupied = true;
	DockingSlots[DockId].Ship = Ship;
}

TArray<IFlareSpacecraftInterface*> UFlareSpacecraftDockingSystem::GetDockedShips()
{
	TArray<IFlareSpacecraftInterface*> Result;

	for (int32 i = 0; i < DockingSlots.Num(); i++)
	{
		if (DockingSlots[i].Granted && DockingSlots[i].Occupied)
		{
			FLOGV("UFlareSpacecraftDockingSystem::GetDockedShips : found valid dock %d", i);
			Result.AddUnique(DockingSlots[i].Ship);
		}
	}

	return Result;
}

bool UFlareSpacecraftDockingSystem::HasAvailableDock(IFlareSpacecraftInterface* Ship) const
{
	// Looking for slot
	for (int32 i = 0; i < DockingSlots.Num(); i++)
	{
		if (!DockingSlots[i].Granted)
		{
			return true;
		}
	}

	return false;
}

int UFlareSpacecraftDockingSystem::GetDockCount() const
{
	return DockingSlots.Num();
}

FFlareDockingInfo UFlareSpacecraftDockingSystem::GetDockInfo(int32 DockId)
{
	return DockingSlots[DockId];
}

bool UFlareSpacecraftDockingSystem::IsGrantedShip(IFlareSpacecraftInterface* ShipCanditate) const
{
	for (int32 i = 0; i < DockingSlots.Num(); i++)
	{
		if (DockingSlots[i].Granted && DockingSlots[i].Ship == ShipCanditate)
		{
			return true;
		}
	}

	return false;
}

bool UFlareSpacecraftDockingSystem::IsDockedShip(IFlareSpacecraftInterface* ShipCanditate) const
{
	for (int32 i = 0; i < DockingSlots.Num(); i++)
	{
		if (DockingSlots[i].Occupied && DockingSlots[i].Ship == ShipCanditate)
		{
			return true;
		}
	}

	return false;
}

#undef LOCTEXT_NAMESPACE
<|endoftext|>


<commit_before>#include "Event.h"
#include "FightSystem.h"

#include "Components\PowerComponent.h"

#include "Events\FightResolvedEvent.h"
#include "..\Events\ShipDefeatedEvent.h"
#include "..\Events\ShipVictoriousEvent.h"

using namespace PinnedDownGameplay::Events;
using namespace PinnedDownGameplay::Systems;
using namespace PinnedDownNet::Components;
using namespace PinnedDownNet::Events;

FightSystem::FightSystem()
{
}

void FightSystem::InitSystem(Game* game)
{
	GameSystem::InitSystem(game);

	this->game->eventManager->AddListener(this, FightStartedEvent::FightStartedEventType);
}

void FightSystem::OnEvent(Event & newEvent)
{
	CALL_EVENT_HANDLER(FightStartedEvent);
}

EVENT_HANDLER_DEFINITION(FightSystem, FightStartedEvent)
{
	// Compute player power.
	auto playerPowerComponent = this->game->entityManager->GetComponent<PowerComponent>(data.playerShip, PowerComponent::PowerComponentType);
	auto playerPower = playerPowerComponent->power;

	// Compute enemy power.
	auto enemyPower = 0;

	for (auto it = data.enemyShips->begin(); it != data.enemyShips->end(); ++it)
	{
		auto enemyPowerComponent = this->game->entityManager->GetComponent<PowerComponent>(*it, PowerComponent::PowerComponentType);
		enemyPower += enemyPowerComponent->power;
	}

	// Compare power.
	if (playerPower <= enemyPower)
	{
		// Enemy victory.
		for (auto it = data.enemyShips->begin(); it != data.enemyShips->end(); ++it)
		{
			auto shipVictoriousEvent = std::make_shared<ShipVictoriousEvent>(*it);
			this->game->eventManager->QueueEvent(shipVictoriousEvent);
		}

		auto shipDefeatedEvent = std::make_shared<ShipDefeatedEvent>(data.playerShip);
		this->game->eventManager->QueueEvent(shipDefeatedEvent);
	}
	else
	{
		// Player victory.
		auto shipVictoriousEvent = std::make_shared<ShipVictoriousEvent>(data.playerShip);
		this->game->eventManager->QueueEvent(shipVictoriousEvent);

		for (auto it = data.enemyShips->begin(); it != data.enemyShips->end(); ++it)
		{
			auto shipDefeatedEvent = std::make_shared<ShipDefeatedEvent>(*it);
			this->game->eventManager->QueueEvent(shipDefeatedEvent);
		}
	}

	// Notify client.
	auto fightResolvedEvent = std::make_shared<FightResolvedEvent>(data.playerShip);
	this->game->eventManager->QueueEvent(fightResolvedEvent);
}
<commit_msg>CHANGED: Event - Including fight outcome in FightResolved event.<commit_after>#include "Event.h"
#include "FightSystem.h"

#include "Components\PowerComponent.h"

#include "Data\FightOutcome.h"

#include "Events\FightResolvedEvent.h"
#include "..\Events\ShipDefeatedEvent.h"
#include "..\Events\ShipVictoriousEvent.h"

using namespace PinnedDownGameplay::Events;
using namespace PinnedDownGameplay::Systems;
using namespace PinnedDownNet::Components;
using namespace PinnedDownNet::Data;
using namespace PinnedDownNet::Events;

FightSystem::FightSystem()
{
}

void FightSystem::InitSystem(Game* game)
{
	GameSystem::InitSystem(game);

	this->game->eventManager->AddListener(this, FightStartedEvent::FightStartedEventType);
}

void FightSystem::OnEvent(Event & newEvent)
{
	CALL_EVENT_HANDLER(FightStartedEvent);
}

EVENT_HANDLER_DEFINITION(FightSystem, FightStartedEvent)
{
	// Compute player power.
	auto playerPowerComponent = this->game->entityManager->GetComponent<PowerComponent>(data.playerShip, PowerComponent::PowerComponentType);
	auto playerPower = playerPowerComponent->power;

	// Compute enemy power.
	auto enemyPower = 0;

	for (auto it = data.enemyShips->begin(); it != data.enemyShips->end(); ++it)
	{
		auto enemyPowerComponent = this->game->entityManager->GetComponent<PowerComponent>(*it, PowerComponent::PowerComponentType);
		enemyPower += enemyPowerComponent->power;
	}

	// Compare power.
	if (playerPower <= enemyPower)
	{
		// Enemy victory.
		for (auto it = data.enemyShips->begin(); it != data.enemyShips->end(); ++it)
		{
			auto shipVictoriousEvent = std::make_shared<ShipVictoriousEvent>(*it);
			this->game->eventManager->QueueEvent(shipVictoriousEvent);
		}

		auto shipDefeatedEvent = std::make_shared<ShipDefeatedEvent>(data.playerShip);
		this->game->eventManager->QueueEvent(shipDefeatedEvent);

		// Notify client.
		auto fightResolvedEvent = std::make_shared<FightResolvedEvent>(data.playerShip, FightOutcome::EnemyVictory);
		this->game->eventManager->QueueEvent(fightResolvedEvent);
	}
	else
	{
		// Player victory.
		auto shipVictoriousEvent = std::make_shared<ShipVictoriousEvent>(data.playerShip);
		this->game->eventManager->QueueEvent(shipVictoriousEvent);

		for (auto it = data.enemyShips->begin(); it != data.enemyShips->end(); ++it)
		{
			auto shipDefeatedEvent = std::make_shared<ShipDefeatedEvent>(*it);
			this->game->eventManager->QueueEvent(shipDefeatedEvent);
		}

		// Notify client.
		auto fightResolvedEvent = std::make_shared<FightResolvedEvent>(data.playerShip, FightOutcome::PlayerVictory);
		this->game->eventManager->QueueEvent(fightResolvedEvent);
	}
}
<|endoftext|>


<commit_before>//-----------------------------------
// Copyright Pierric Gimmig 2013-2017
//-----------------------------------

#include "Track.h"

#include "Capture.h"
#include "GlCanvas.h"
#include "TimeGraphLayout.h"
#include "absl/strings/str_format.h"

float TEXT_Z = -0.004f;
float TRACK_Z = -0.005f;

//-----------------------------------------------------------------------------
Track::Track() {
  m_ID = 0;
  m_MousePos[0] = m_MousePos[1] = Vec2(0, 0);
  m_Pos = Vec2(0, 0);
  m_Size = Vec2(0, 0);
  m_PickingOffset = Vec2(0, 0);
  m_Picked = false;
  m_Moving = false;
  m_Canvas = nullptr;

  label_display_mode_ = NAME_AND_TID;

  unsigned char alpha = 255;
  unsigned char grey = 60;
  m_Color = Color(grey, grey, grey, alpha);
}

//-----------------------------------------------------------------------------
void Track::Draw(GlCanvas* a_Canvas, bool a_Picking) {
  static volatile unsigned char alpha = 255;
  static volatile unsigned char grey = 60;
  auto col = Color(grey, grey, grey, alpha);
  a_Picking ? PickingManager::SetPickingColor(
                  a_Canvas->GetPickingManager().CreatePickableId(this))
            : glColor4ubv(&m_Color[0]);

  float x0 = m_Pos[0];
  float x1 = x0 + m_Size[0];

  float y0 = m_Pos[1];
  float y1 = y0 - m_Size[1];

  if (m_Picked) {
    glColor4ub(0, 128, 255, 128);
  }

  glBegin(GL_QUADS);
  glVertex3f(x0, y0, TRACK_Z);
  glVertex3f(x1, y0, TRACK_Z);
  glVertex3f(x1, y1, TRACK_Z);
  glVertex3f(x0, y1, TRACK_Z);
  glEnd();

  if (a_Canvas->GetPickingManager().GetPicked() == this)
    glColor4ub(255, 255, 255, 255);
  else
    glColor4ubv(&m_Color[0]);

  glBegin(GL_LINES);
  glVertex3f(x0, y0, TRACK_Z);
  glVertex3f(x1, y0, TRACK_Z);
  glVertex3f(x1, y1, TRACK_Z);
  glVertex3f(x0, y1, TRACK_Z);
  glEnd();

  std::string track_label;
  switch(label_display_mode_) {
    case NAME_AND_TID:
      track_label = absl::StrFormat("%s [%u]", m_Name, m_ID);
      break;
    case TID_ONLY:
      track_label = absl::StrFormat("[%u]", m_ID);
      break;
    case NAME_ONLY:
      track_label = absl::StrFormat("%s", m_Name, m_ID);
      break;
    case EMPTY:
      track_label = "";
  }

  a_Canvas->AddText(track_label.c_str(),
                    x0, y1, TEXT_Z, Color(255, 255, 255, 255));

  m_Canvas = a_Canvas;
}

//-----------------------------------------------------------------------------
void Track::SetPos(float a_X, float a_Y) {
  if (!m_Moving) {
    m_Pos = Vec2(a_X, a_Y);
  }
}

//-----------------------------------------------------------------------------
void Track::SetSize(float a_SizeX, float a_SizeY) {
  m_Size = Vec2(a_SizeX, a_SizeY);
}

//-----------------------------------------------------------------------------
void Track::OnPick(int a_X, int a_Y) {
  Vec2& mousePos = m_MousePos[0];
  m_Canvas->ScreenToWorld(a_X, a_Y, mousePos[0], mousePos[1]);
  m_PickingOffset = mousePos - m_Pos;
  m_MousePos[1] = m_MousePos[0];
  m_Picked = true;
}

//-----------------------------------------------------------------------------
void Track::OnRelease() {
  m_Picked = false;
  m_Moving = false;
  m_TimeGraph->NeedsUpdate();
}

//-----------------------------------------------------------------------------
void Track::OnDrag(int a_X, int a_Y) {
  m_Moving = true;
  float x = 0.f;
  m_Canvas->ScreenToWorld(a_X, a_Y, x, m_Pos[1]);
  m_MousePos[1] = m_Pos;
  m_Pos[1] -= m_PickingOffset[1];
  m_TimeGraph->NeedsUpdate();
}
<commit_msg>Fix build of OrbitGl/Track.cpp<commit_after>//-----------------------------------
// Copyright Pierric Gimmig 2013-2017
//-----------------------------------

#include "Track.h"

#include "Capture.h"
#include "GlCanvas.h"
#include "TimeGraphLayout.h"
#include "absl/strings/str_format.h"

float TEXT_Z = -0.004f;
float TRACK_Z = -0.005f;

//-----------------------------------------------------------------------------
Track::Track() {
  m_ID = 0;
  m_MousePos[0] = m_MousePos[1] = Vec2(0, 0);
  m_Pos = Vec2(0, 0);
  m_Size = Vec2(0, 0);
  m_PickingOffset = Vec2(0, 0);
  m_Picked = false;
  m_Moving = false;
  m_Canvas = nullptr;

  label_display_mode_ = NAME_AND_TID;

  unsigned char alpha = 255;
  unsigned char grey = 60;
  m_Color = Color(grey, grey, grey, alpha);
}

//-----------------------------------------------------------------------------
void Track::Draw(GlCanvas* a_Canvas, bool a_Picking) {
  static volatile unsigned char alpha = 255;
  static volatile unsigned char grey = 60;
  auto col = Color(grey, grey, grey, alpha);
  a_Picking ? PickingManager::SetPickingColor(
                  a_Canvas->GetPickingManager().CreatePickableId(this))
            : glColor4ubv(&m_Color[0]);

  float x0 = m_Pos[0];
  float x1 = x0 + m_Size[0];

  float y0 = m_Pos[1];
  float y1 = y0 - m_Size[1];

  if (m_Picked) {
    glColor4ub(0, 128, 255, 128);
  }

  glBegin(GL_QUADS);
  glVertex3f(x0, y0, TRACK_Z);
  glVertex3f(x1, y0, TRACK_Z);
  glVertex3f(x1, y1, TRACK_Z);
  glVertex3f(x0, y1, TRACK_Z);
  glEnd();

  if (a_Canvas->GetPickingManager().GetPicked() == this)
    glColor4ub(255, 255, 255, 255);
  else
    glColor4ubv(&m_Color[0]);

  glBegin(GL_LINES);
  glVertex3f(x0, y0, TRACK_Z);
  glVertex3f(x1, y0, TRACK_Z);
  glVertex3f(x1, y1, TRACK_Z);
  glVertex3f(x0, y1, TRACK_Z);
  glEnd();

  std::string track_label;
  switch(label_display_mode_) {
    case NAME_AND_TID:
      track_label = absl::StrFormat("%s [%u]", m_Name, m_ID);
      break;
    case TID_ONLY:
      track_label = absl::StrFormat("[%u]", m_ID);
      break;
    case NAME_ONLY:
      track_label = absl::StrFormat("%s", m_Name);
      break;
    case EMPTY:
      track_label = "";
  }

  a_Canvas->AddText(track_label.c_str(),
                    x0, y1, TEXT_Z, Color(255, 255, 255, 255));

  m_Canvas = a_Canvas;
}

//-----------------------------------------------------------------------------
void Track::SetPos(float a_X, float a_Y) {
  if (!m_Moving) {
    m_Pos = Vec2(a_X, a_Y);
  }
}

//-----------------------------------------------------------------------------
void Track::SetSize(float a_SizeX, float a_SizeY) {
  m_Size = Vec2(a_SizeX, a_SizeY);
}

//-----------------------------------------------------------------------------
void Track::OnPick(int a_X, int a_Y) {
  Vec2& mousePos = m_MousePos[0];
  m_Canvas->ScreenToWorld(a_X, a_Y, mousePos[0], mousePos[1]);
  m_PickingOffset = mousePos - m_Pos;
  m_MousePos[1] = m_MousePos[0];
  m_Picked = true;
}

//-----------------------------------------------------------------------------
void Track::OnRelease() {
  m_Picked = false;
  m_Moving = false;
  m_TimeGraph->NeedsUpdate();
}

//-----------------------------------------------------------------------------
void Track::OnDrag(int a_X, int a_Y) {
  m_Moving = true;
  float x = 0.f;
  m_Canvas->ScreenToWorld(a_X, a_Y, x, m_Pos[1]);
  m_MousePos[1] = m_Pos;
  m_Pos[1] -= m_PickingOffset[1];
  m_TimeGraph->NeedsUpdate();
}
<|endoftext|>


<commit_before>/*
 * SessionProjects.hpp
 *
 * Copyright (C) 2009-11 by RStudio, Inc.
 *
 * This program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

#ifndef SESSION_PROJECTS_HPP
#define SESSION_PROJECTS_HPP

#include <string>

namespace core {
   class Error;
   class FilePath;
}

namespace session {
namespace projects {

core::Error startup();

core::Error initialize();

} // namespace projects
} // namesapce session

#endif // SESSION_PROJECTS_HPP
<commit_msg>ammend last commit w/ extra hpp file<commit_after>/*
 * SessionProjects.hpp
 *
 * Copyright (C) 2009-11 by RStudio, Inc.
 *
 * This program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

#ifndef SESSION_PROJECTS_PROJECTS_HPP
#define SESSION_PROJECTS_PROJECTS_HPP

namespace core {
   class FilePath;
}

namespace session {
namespace projects {

bool projectIsActive();
core::FilePath projectFilePath();
core::FilePath projectDirectory();
core::FilePath projectScratchPath();

} // namespace projects
} // namesapce session

#endif // SESSION_PROJECTS_PROJECTS_HPP
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: ScriptingContext.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: dfoster $ $Date: 2003-11-04 17:45:28 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#include <com/sun/star/beans/PropertyAttribute.hpp>
#include <com/sun/star/frame/XModel.hpp>

#include <cppuhelper/implementationentry.hxx>
#include <cppuhelper/factory.hxx>

#include <util/scriptingconstants.hxx>
#include <util/util.hxx>

#include "ScriptingContext.hxx"

using namespace com::sun::star;
using namespace com::sun::star::uno;
#define DOC_REF_PROPID  1
#define DOC_STORAGE_ID_PROPID 2
#define DOC_URI_PROPID   3
#define RESOLVED_STORAGE_ID_PROPID  4
#define SCRIPT_INFO_PROPID  5
#define SCRIPTINGCONTEXT_DEFAULT_ATTRIBS()   beans::PropertyAttribute::TRANSIENT | beans::PropertyAttribute::MAYBEVOID
namespace func_provider
{

//*************************************************************************
// XScriptingContext implementation
//
//*************************************************************************
ScriptingContext::ScriptingContext( const Reference< XComponentContext > & xContext ) : //ScriptingContextImpl_BASE( GetMutex()),
    OPropertyContainer( GetBroadcastHelper() ),
        m_xContext( xContext )
{
    OSL_TRACE( "< ScriptingContext ctor called >\n" );

    validateXRef( m_xContext,
                  "ScriptingContext::ScriptingContext: No context available\n" );

    Any nullAny;

    scripting_constants::ScriptingConstantsPool& scriptingConstantsPool =
        scripting_constants::ScriptingConstantsPool::instance();
    registerPropertyNoMember( scriptingConstantsPool.DOC_REF, DOC_REF_PROPID, SCRIPTINGCONTEXT_DEFAULT_ATTRIBS(),::getCppuType(  (const Reference< css::frame::XModel >* ) NULL ), NULL ) ;
    registerPropertyNoMember( scriptingConstantsPool.DOC_STORAGE_ID, DOC_STORAGE_ID_PROPID, SCRIPTINGCONTEXT_DEFAULT_ATTRIBS(), ::getCppuType(  (const sal_Int32* ) NULL ), NULL ) ;
    registerPropertyNoMember( scriptingConstantsPool.DOC_URI, DOC_URI_PROPID, SCRIPTINGCONTEXT_DEFAULT_ATTRIBS(), ::getCppuType(  (const ::rtl::OUString* ) NULL ), NULL ) ;
    registerPropertyNoMember( scriptingConstantsPool.RESOLVED_STORAGE_ID, RESOLVED_STORAGE_ID_PROPID, SCRIPTINGCONTEXT_DEFAULT_ATTRIBS(), ::getCppuType(  (const sal_Int32* ) NULL ), NULL );
    registerPropertyNoMember( scriptingConstantsPool.SCRIPT_INFO, SCRIPT_INFO_PROPID, SCRIPTINGCONTEXT_DEFAULT_ATTRIBS(), ::getCppuType(  (const sal_Int32* ) NULL ), NULL );
}

ScriptingContext::~ScriptingContext()
{
    OSL_TRACE( "< ScriptingContext dtor called >\n" );
}
// -----------------------------------------------------------------------------
// OPropertySetHelper
// -----------------------------------------------------------------------------

::cppu::IPropertyArrayHelper& ScriptingContext::getInfoHelper(  )
{
    return *getArrayHelper();
}

// -----------------------------------------------------------------------------
// OPropertyArrayUsageHelper
// -----------------------------------------------------------------------------

::cppu::IPropertyArrayHelper* ScriptingContext::createArrayHelper(  ) const
{
    Sequence< beans::Property > aProps;
    describeProperties( aProps );
    return new ::cppu::OPropertyArrayHelper( aProps );
}
// -----------------------------------------------------------------------------
// XPropertySet
// -----------------------------------------------------------------------------

Reference< beans::XPropertySetInfo > ScriptingContext::getPropertySetInfo(  ) throw (RuntimeException)
{
    Reference< beans::XPropertySetInfo > xInfo( createPropertySetInfo( getInfoHelper() ) );
    return xInfo;
}
// -----------------------------------------------------------------------------// XTypeProvider
// -----------------------------------------------------------------------------
IMPLEMENT_GET_IMPLEMENTATION_ID( ScriptingContext )

css::uno::Sequence< css::uno::Type > SAL_CALL ScriptingContext::getTypes(  ) throw (css::uno::RuntimeException)
{
    return OPropertyContainer::getTypes();
}
} // namespace func_provider
<commit_msg>INTEGRATION: CWS ooo19126 (1.6.90); FILE MERGED 2005/09/05 12:05:20 rt 1.6.90.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ScriptingContext.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 02:31:14 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#include <com/sun/star/beans/PropertyAttribute.hpp>
#include <com/sun/star/frame/XModel.hpp>

#include <cppuhelper/implementationentry.hxx>
#include <cppuhelper/factory.hxx>

#include <util/scriptingconstants.hxx>
#include <util/util.hxx>

#include "ScriptingContext.hxx"

using namespace com::sun::star;
using namespace com::sun::star::uno;
#define DOC_REF_PROPID  1
#define DOC_STORAGE_ID_PROPID 2
#define DOC_URI_PROPID   3
#define RESOLVED_STORAGE_ID_PROPID  4
#define SCRIPT_INFO_PROPID  5
#define SCRIPTINGCONTEXT_DEFAULT_ATTRIBS()   beans::PropertyAttribute::TRANSIENT | beans::PropertyAttribute::MAYBEVOID
namespace func_provider
{

//*************************************************************************
// XScriptingContext implementation
//
//*************************************************************************
ScriptingContext::ScriptingContext( const Reference< XComponentContext > & xContext ) : //ScriptingContextImpl_BASE( GetMutex()),
    OPropertyContainer( GetBroadcastHelper() ),
        m_xContext( xContext )
{
    OSL_TRACE( "< ScriptingContext ctor called >\n" );

    validateXRef( m_xContext,
                  "ScriptingContext::ScriptingContext: No context available\n" );

    Any nullAny;

    scripting_constants::ScriptingConstantsPool& scriptingConstantsPool =
        scripting_constants::ScriptingConstantsPool::instance();
    registerPropertyNoMember( scriptingConstantsPool.DOC_REF, DOC_REF_PROPID, SCRIPTINGCONTEXT_DEFAULT_ATTRIBS(),::getCppuType(  (const Reference< css::frame::XModel >* ) NULL ), NULL ) ;
    registerPropertyNoMember( scriptingConstantsPool.DOC_STORAGE_ID, DOC_STORAGE_ID_PROPID, SCRIPTINGCONTEXT_DEFAULT_ATTRIBS(), ::getCppuType(  (const sal_Int32* ) NULL ), NULL ) ;
    registerPropertyNoMember( scriptingConstantsPool.DOC_URI, DOC_URI_PROPID, SCRIPTINGCONTEXT_DEFAULT_ATTRIBS(), ::getCppuType(  (const ::rtl::OUString* ) NULL ), NULL ) ;
    registerPropertyNoMember( scriptingConstantsPool.RESOLVED_STORAGE_ID, RESOLVED_STORAGE_ID_PROPID, SCRIPTINGCONTEXT_DEFAULT_ATTRIBS(), ::getCppuType(  (const sal_Int32* ) NULL ), NULL );
    registerPropertyNoMember( scriptingConstantsPool.SCRIPT_INFO, SCRIPT_INFO_PROPID, SCRIPTINGCONTEXT_DEFAULT_ATTRIBS(), ::getCppuType(  (const sal_Int32* ) NULL ), NULL );
}

ScriptingContext::~ScriptingContext()
{
    OSL_TRACE( "< ScriptingContext dtor called >\n" );
}
// -----------------------------------------------------------------------------
// OPropertySetHelper
// -----------------------------------------------------------------------------

::cppu::IPropertyArrayHelper& ScriptingContext::getInfoHelper(  )
{
    return *getArrayHelper();
}

// -----------------------------------------------------------------------------
// OPropertyArrayUsageHelper
// -----------------------------------------------------------------------------

::cppu::IPropertyArrayHelper* ScriptingContext::createArrayHelper(  ) const
{
    Sequence< beans::Property > aProps;
    describeProperties( aProps );
    return new ::cppu::OPropertyArrayHelper( aProps );
}
// -----------------------------------------------------------------------------
// XPropertySet
// -----------------------------------------------------------------------------

Reference< beans::XPropertySetInfo > ScriptingContext::getPropertySetInfo(  ) throw (RuntimeException)
{
    Reference< beans::XPropertySetInfo > xInfo( createPropertySetInfo( getInfoHelper() ) );
    return xInfo;
}
// -----------------------------------------------------------------------------// XTypeProvider
// -----------------------------------------------------------------------------
IMPLEMENT_GET_IMPLEMENTATION_ID( ScriptingContext )

css::uno::Sequence< css::uno::Type > SAL_CALL ScriptingContext::getTypes(  ) throw (css::uno::RuntimeException)
{
    return OPropertyContainer::getTypes();
}
} // namespace func_provider
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: TaskPaneTreeNode.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 06:02:41 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef SD_TASKPANE_TREE_NODE_HXX
#define SD_TASKPANE_TREE_NODE_HXX

#include "ILayoutableWindow.hxx"
#include <memory>
#include <vector>

#ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLE_HPP_
#include <com/sun/star/accessibility/XAccessible.hpp>
#endif
#include <tools/link.hxx>

namespace sd {
class ObjectBarManager;
};

namespace sd { namespace toolpanel {

class ControlContainer;
class TaskPaneShellManager;

enum TreeNodeStateChangeEventId {
    EID_CHILD_ADDED,
    EID_ALL_CHILDREN_REMOVED,
    EID_EXPANSION_STATE_CHANGED,
    EID_FOCUSED_STATE_CHANGED,
    EID_SHOWING_STATE_CHANGED
};

/** Base class for all members of the object hierarchy that makes up the
    tool panel.  There are usually at least three levels.  At the top level
    is the ToolPanel with one instance: the root of the tree.  At the
    middle level there are SubToolPanels and Window/Control objects.  At the
    lowest level there are only Window or Control objects.

    This class provides the means of communication between objects on
    different levels.
*/
class TreeNode
    : public ILayoutableWindow,
      public ILayouter
{
public:
    TreeNode (TreeNode* pParent);
    virtual ~TreeNode (void);

    /** Returns <TRUE/> if the node has no children, i.e. is a leaf of a
        tree.  In this case mpControlContainer is NULL.
    */
    bool IsLeaf (void);

    /** Returns true if the node has no parent, i.e. is the root of a tree.
    */
    bool IsRoot (void);

    void SetParentNode (TreeNode* pNewParent);
    TreeNode* GetParentNode (void);

    /** Return the Window pointer of a tree node.
    */
    virtual ::Window* GetWindow (void);

    /** Return a const pointer to the window of a tree node.
    */
    virtual const ::Window* GetConstWindow (void) const;

    /** Return the joined minimum width of all children, i.e. the largest of
        the minimum widths.
    */
    virtual sal_Int32 GetMinimumWidth (void);

    /** Give each node access to the object bar manager of the tool panel.

        At least the root node has to overwrite this method since the
        default implementation simply returns the object bar manager of the
        parent.
    */
    virtual ObjectBarManager* GetObjectBarManager (void);

    /** The default implementaion always returns <FALSE/>
    */
    virtual bool IsResizable (void);

    /** Call this method whenever the size of one of the children of the
        called node has to be changed, e.g. when the layout menu shows more
        or less items than before.  As a typical result the node will layout
        and resize its children according to their size requirements.

        Please remember that the size of the children can be changed in the
        first place because scroll bars can give a node the space it needs.

        The default implementation passes this call to its parent.
    */
    virtual void RequestResize (void);

    /** The default implementation shows the window (when it exists) when
        bExpansionState is <TRUE/>.  It hides the window otherwise.
        @return
            Returns <TRUE/> when the expansion state changes.  When an
            expansion state is requested that is already in place then
            <FALSE/> is returned.
    */
    virtual bool Expand (bool bExpansionState);

    /** The default implementation returns whether the window is showing.
        When there is no window then it returns <FALSE/>.
    */
    virtual bool IsExpanded (void) const;

    /** Return whether the node can be expanded or collapsed.  The default
        implementation always returns <TRUE/> when there is window and
        <FALSE/> otherwise.  If <FALSE/> is returned
        then Expand() may be called but it will not change the expansion
        state.
    */
    virtual bool IsExpandable (void) const;

    /** The default implementation calls GetWindow()->Show().
    */
    virtual void Show (bool bVisibilityState);

    /** The default implementation returns GetWindow()->IsVisible().
    */
    virtual bool IsShowing (void) const;

    ControlContainer& GetControlContainer (void);

    /** Give each node access to a shell manage.  This usually is the shell
        manager of the TaskPaneViewShell.

        At least the root node has to overwrite this method since the
        default implementation simply returns the shell manager of its
        parent.
    */
    virtual TaskPaneShellManager* GetShellManager (void);

    /** You will rarely need to overload this method.  To supply your own
        accessible object you should overload CreateAccessible() instead.
    */
    virtual ::com::sun::star::uno::Reference<
        ::com::sun::star::accessibility::XAccessible> GetAccessibleObject (void);

    /** Overload this method in order to supply a class specific accessible
        object.
        The default implementation will return a new instance of
        AccessibleTreeNode.
        @param rxParent
            The accessible parent of the accessible object to create.  It is
            not necessaryly the accessible object of the parent window of
            GetWindow().

    */
    virtual ::com::sun::star::uno::Reference<
        ::com::sun::star::accessibility::XAccessible> CreateAccessibleObject (
            const ::com::sun::star::uno::Reference<
            ::com::sun::star::accessibility::XAccessible>&rxParent);

    /** Add a listener that will be informated in the future about state
        changes of the tree node.  This includes adding and removing
        children as well as focus, visibility, and expansion state.
        Multiple calls are ignored.  Each listener is added only once.
    */
    void AddStateChangeListener (const Link& rListener);

    /** Remove the listener form the list of state change listeners.
        @param rListener
            It is OK to specify a listener that is not currently
            registered.  Only when the listener is registered it is
            removed.  Otherwise the call is ignored.
    */
    void RemoveStateChangeListener (const Link& rListener);

    /** Call the state change listeners and pass a state change event with
        the specified event id.  The source field is set to this.
        @param pChild
            This optional parameter makes sense only with the
            EID_CHILD_ADDED event.
    */
    void FireStateChangeEvent (
        TreeNodeStateChangeEventId eEventId,
        TreeNode* pChild = NULL) const;

protected:
    ::std::auto_ptr<ControlContainer> mpControlContainer;

private:
    TreeNode* mpParent;
    typedef ::std::vector<Link> StateChangeListenerContainer;
    StateChangeListenerContainer maStateChangeListeners;
};

/** Objects of this class are sent to listeners to notify them about state
    changes of a tree node.
*/
class TreeNodeStateChangeEvent
{
public:

    TreeNodeStateChangeEvent (
        const TreeNode& rNode,
        TreeNodeStateChangeEventId eEventId,
        TreeNode* pChild = NULL);

    const TreeNode& mrSource;
    TreeNodeStateChangeEventId meEventId;
    TreeNode* mpChild;
};

} } // end of namespace ::sd::toolpanel

#endif
<commit_msg>INTEGRATION: CWS sdwarningsbegone (1.5.316); FILE MERGED 2006/11/22 12:42:08 cl 1.5.316.1: #i69285# warning free code changes for unxlngi6.pro<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: TaskPaneTreeNode.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: kz $ $Date: 2006-12-12 17:55:25 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef SD_TASKPANE_TREE_NODE_HXX
#define SD_TASKPANE_TREE_NODE_HXX

#include "ILayoutableWindow.hxx"
#include <memory>
#include <vector>

#ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLE_HPP_
#include <com/sun/star/accessibility/XAccessible.hpp>
#endif
#include <tools/link.hxx>

namespace sd {
class ObjectBarManager;
}

namespace sd { namespace toolpanel {

class ControlContainer;
class TaskPaneShellManager;

enum TreeNodeStateChangeEventId {
    EID_CHILD_ADDED,
    EID_ALL_CHILDREN_REMOVED,
    EID_EXPANSION_STATE_CHANGED,
    EID_FOCUSED_STATE_CHANGED,
    EID_SHOWING_STATE_CHANGED
};

/** Base class for all members of the object hierarchy that makes up the
    tool panel.  There are usually at least three levels.  At the top level
    is the ToolPanel with one instance: the root of the tree.  At the
    middle level there are SubToolPanels and Window/Control objects.  At the
    lowest level there are only Window or Control objects.

    This class provides the means of communication between objects on
    different levels.
*/
class TreeNode
    : public ILayoutableWindow,
      public ILayouter
{
public:
    TreeNode (TreeNode* pParent);
    virtual ~TreeNode (void);

    /** Returns <TRUE/> if the node has no children, i.e. is a leaf of a
        tree.  In this case mpControlContainer is NULL.
    */
    bool IsLeaf (void);

    /** Returns true if the node has no parent, i.e. is the root of a tree.
    */
    bool IsRoot (void);

    void SetParentNode (TreeNode* pNewParent);
    TreeNode* GetParentNode (void);

    /** Return the Window pointer of a tree node.
    */
    virtual ::Window* GetWindow (void);

    /** Return a const pointer to the window of a tree node.
    */
    virtual const ::Window* GetConstWindow (void) const;

    /** Return the joined minimum width of all children, i.e. the largest of
        the minimum widths.
    */
    virtual sal_Int32 GetMinimumWidth (void);

    /** Give each node access to the object bar manager of the tool panel.

        At least the root node has to overwrite this method since the
        default implementation simply returns the object bar manager of the
        parent.
    */
    virtual ObjectBarManager* GetObjectBarManager (void);

    /** The default implementaion always returns <FALSE/>
    */
    virtual bool IsResizable (void);

    /** Call this method whenever the size of one of the children of the
        called node has to be changed, e.g. when the layout menu shows more
        or less items than before.  As a typical result the node will layout
        and resize its children according to their size requirements.

        Please remember that the size of the children can be changed in the
        first place because scroll bars can give a node the space it needs.

        The default implementation passes this call to its parent.
    */
    virtual void RequestResize (void);

    /** The default implementation shows the window (when it exists) when
        bExpansionState is <TRUE/>.  It hides the window otherwise.
        @return
            Returns <TRUE/> when the expansion state changes.  When an
            expansion state is requested that is already in place then
            <FALSE/> is returned.
    */
    virtual bool Expand (bool bExpansionState);

    /** The default implementation returns whether the window is showing.
        When there is no window then it returns <FALSE/>.
    */
    virtual bool IsExpanded (void) const;

    /** Return whether the node can be expanded or collapsed.  The default
        implementation always returns <TRUE/> when there is window and
        <FALSE/> otherwise.  If <FALSE/> is returned
        then Expand() may be called but it will not change the expansion
        state.
    */
    virtual bool IsExpandable (void) const;

    /** The default implementation calls GetWindow()->Show().
    */
    virtual void Show (bool bVisibilityState);

    /** The default implementation returns GetWindow()->IsVisible().
    */
    virtual bool IsShowing (void) const;

    ControlContainer& GetControlContainer (void);

    /** Give each node access to a shell manage.  This usually is the shell
        manager of the TaskPaneViewShell.

        At least the root node has to overwrite this method since the
        default implementation simply returns the shell manager of its
        parent.
    */
    virtual TaskPaneShellManager* GetShellManager (void);

    /** You will rarely need to overload this method.  To supply your own
        accessible object you should overload CreateAccessible() instead.
    */
    virtual ::com::sun::star::uno::Reference<
        ::com::sun::star::accessibility::XAccessible> GetAccessibleObject (void);

    /** Overload this method in order to supply a class specific accessible
        object.
        The default implementation will return a new instance of
        AccessibleTreeNode.
        @param rxParent
            The accessible parent of the accessible object to create.  It is
            not necessaryly the accessible object of the parent window of
            GetWindow().

    */
    virtual ::com::sun::star::uno::Reference<
        ::com::sun::star::accessibility::XAccessible> CreateAccessibleObject (
            const ::com::sun::star::uno::Reference<
            ::com::sun::star::accessibility::XAccessible>&rxParent);

    /** Add a listener that will be informated in the future about state
        changes of the tree node.  This includes adding and removing
        children as well as focus, visibility, and expansion state.
        Multiple calls are ignored.  Each listener is added only once.
    */
    void AddStateChangeListener (const Link& rListener);

    /** Remove the listener form the list of state change listeners.
        @param rListener
            It is OK to specify a listener that is not currently
            registered.  Only when the listener is registered it is
            removed.  Otherwise the call is ignored.
    */
    void RemoveStateChangeListener (const Link& rListener);

    /** Call the state change listeners and pass a state change event with
        the specified event id.  The source field is set to this.
        @param pChild
            This optional parameter makes sense only with the
            EID_CHILD_ADDED event.
    */
    void FireStateChangeEvent (
        TreeNodeStateChangeEventId eEventId,
        TreeNode* pChild = NULL) const;

protected:
    ::std::auto_ptr<ControlContainer> mpControlContainer;

private:
    TreeNode* mpParent;
    typedef ::std::vector<Link> StateChangeListenerContainer;
    StateChangeListenerContainer maStateChangeListeners;
};

/** Objects of this class are sent to listeners to notify them about state
    changes of a tree node.
*/
class TreeNodeStateChangeEvent
{
public:

    TreeNodeStateChangeEvent (
        const TreeNode& rNode,
        TreeNodeStateChangeEventId eEventId,
        TreeNode* pChild = NULL);

    const TreeNode& mrSource;
    TreeNodeStateChangeEventId meEventId;
    TreeNode* mpChild;
};

} } // end of namespace ::sd::toolpanel

#endif
<|endoftext|>