text
stringlengths 54
60.6k
|
|---|
<commit_before>#include "PropertyWidgetEx.h"
#include <QMouseEvent>
#include <QApplication>
#include <QMimeData>
#include <QDrag>
#include <QShortcut>
#include <QClipboard>
#include <QAction>
#include <QDebug>
static const QString kTextPlain = "text/plain";
const QString *pTextPlain = &kTextPlain;
QtnPropertyWidgetEx::QtnPropertyWidgetEx(QWidget *parent)
: QtnPropertyWidget(parent)
, dragged_property(nullptr)
, drop_action(Qt::IgnoreAction)
, can_remove(false)
{
for (auto child : children())
{
auto vbox = dynamic_cast<QVBoxLayout *>(child);
if (nullptr != vbox)
{
vbox->setContentsMargins(0, 0, 0, 0);
vbox->setMargin(0);
vbox->setSpacing(0);
}
}
setAcceptDrops(true);
propertyView()->installEventFilter(this);
}
void QtnPropertyWidgetEx::connectRemoveAction(QAction *action, bool connect)
{
internalConnect(action, &QtnPropertyWidgetEx::removeActiveProperty, connect);
}
void QtnPropertyWidgetEx::connectCutAction(QAction *action, bool connect)
{
internalConnect(action, &QtnPropertyWidgetEx::cutToClipboard, connect);
}
void QtnPropertyWidgetEx::connectCopyAction(QAction *action, bool connect)
{
internalConnect(action, &QtnPropertyWidgetEx::copyToClipboard, connect);
}
void QtnPropertyWidgetEx::connectPasteAction(QAction *action, bool connect)
{
internalConnect(action, &QtnPropertyWidgetEx::pasteFromClipboard, connect);
}
bool QtnPropertyWidgetEx::canRemoveActiveProperty()
{
return canRemoveProperty(propertyView()->activeProperty());
}
bool QtnPropertyWidgetEx::canRemoveProperty(QtnPropertyBase *)
{
return false;
}
bool QtnPropertyWidgetEx::canCutToClipboard()
{
return false;
}
bool QtnPropertyWidgetEx::canCopyToClipboard()
{
return (nullptr != propertyView()->activeProperty());
}
bool QtnPropertyWidgetEx::canPasteFromClipboard()
{
return dataHasSupportedFormats(QApplication::clipboard()->mimeData())
&& (nullptr != propertyView()->activeProperty());
}
bool QtnPropertyWidgetEx::dataHasSupportedFormats(const QMimeData *data)
{
return (nullptr != data && data->hasFormat(kTextPlain));
}
void QtnPropertyWidgetEx::removeActiveProperty()
{
removeProperty(propertyView()->activeProperty());
}
void QtnPropertyWidgetEx::cutToClipboard()
{
copyToClipboard();
removeActiveProperty();
}
void QtnPropertyWidgetEx::copyToClipboard()
{
auto property = propertyView()->activeProperty();
if (nullptr != property)
{
auto mime = getPropertyDataForAction(property, Qt::IgnoreAction);
if (nullptr != mime)
QApplication::clipboard()->setMimeData(mime);
}
}
void QtnPropertyWidgetEx::pasteFromClipboard()
{
auto data = QApplication::clipboard()->mimeData();
if (dataHasSupportedFormats(data))
{
applyPropertyData(data,
propertyView()->activeProperty(),
QtnApplyPosition::Over);
}
}
void QtnPropertyWidgetEx::removeProperty(QtnPropertyBase *)
{
// do nothing
}
QMimeData *QtnPropertyWidgetEx::getPropertyDataForAction(QtnPropertyBase *property,
Qt::DropAction)
{
QString str;
if (property->toStr(str))
{
auto mime = new QMimeData;
mime->setText(str);
return mime;
}
return nullptr;
}
bool QtnPropertyWidgetEx::applyPropertyData(const QMimeData *data,
QtnPropertyBase *destination,
QtnApplyPosition)
{
if (nullptr != destination)
{
Q_ASSERT(nullptr != data);
return destination->fromStr(data->text());
}
return false;
}
bool QtnPropertyWidgetEx::eventFilter(QObject *obj, QEvent *event)
{
switch (event->type())
{
case QEvent::MouseButtonPress:
{
auto mevent = static_cast<QMouseEvent *>(event);
if (mevent->button() == Qt::LeftButton)
{
drag_start_pos = mevent->pos();
dragged_property = propertyView()->getPropertyAt(drag_start_pos);
can_remove = canRemoveProperty(dragged_property);
return true;
}
} break;
case QEvent::MouseMove:
{
auto mevent = static_cast<QMouseEvent *>(event);
if (nullptr != dragged_property
&& 0 != (mevent->buttons() & Qt::LeftButton))
{
if ((mevent->pos() - drag_start_pos).manhattanLength()
< QApplication::startDragDistance())
{
drop_action = Qt::IgnoreAction;
if (dragAndDrop())
return true;
}
}
} break;
default:
break;
}
return QtnPropertyWidget::eventFilter(obj, event);
}
void QtnPropertyWidgetEx::dragEnterEvent(QDragEnterEvent *event)
{
if (dataHasSupportedFormats(event->mimeData()))
event->acceptProposedAction();
}
void QtnPropertyWidgetEx::dragMoveEvent(QDragMoveEvent *event)
{
if (Qt::ControlModifier == QApplication::keyboardModifiers()
|| !can_remove)
{
event->setDropAction(Qt::CopyAction);
} else
{
event->setDropAction(Qt::MoveAction);
}
drop_action = event->dropAction();
event->accept();
}
void QtnPropertyWidgetEx::dropEvent(QDropEvent *event)
{
switch (event->dropAction())
{
case Qt::MoveAction:
case Qt::CopyAction:
{
auto view = propertyView();
auto pos = view->mapFrom(this, event->pos());
QRect rect;
auto property = view->getPropertyAt(pos, &rect);
int part_height = view->itemHeight() / 4;
QtnApplyPosition apply_position;
if (QRect(rect.left(), rect.top(),
rect.width(), part_height).contains(pos))
apply_position = QtnApplyPosition::Before;
else if (QRect(rect.left(), rect.bottom() - part_height,
rect.width(), part_height).contains(pos))
apply_position = QtnApplyPosition::After;
else
apply_position = QtnApplyPosition::Over;
auto data = event->mimeData();
if (property != dragged_property
&& dataHasSupportedFormats(data)
&& applyPropertyData(data, property, apply_position))
event->accept();
} break;
default:
break;
}
}
bool QtnPropertyWidgetEx::dragAndDrop()
{
auto data = getPropertyDataForAction(dragged_property, Qt::CopyAction);
if (nullptr != data)
{
auto drag = new QDrag(this);
drag->setMimeData(data);
// TODO generate cursor
drag->exec(Qt::CopyAction | Qt::MoveAction);
if (Qt::MoveAction == drop_action)
removeProperty(dragged_property);
return true;
}
return false;
}
void QtnPropertyWidgetEx::internalConnect(QAction *action,
void (QtnPropertyWidgetEx::*slot)(),
bool connect)
{
if (connect)
QObject::connect(action, &QAction::triggered, this, slot);
else
QObject::disconnect(action, &QAction::triggered, this, slot);
}
<commit_msg>Drag & Drop bug fixes<commit_after>#include "PropertyWidgetEx.h"
#include <QMouseEvent>
#include <QApplication>
#include <QMimeData>
#include <QDrag>
#include <QShortcut>
#include <QClipboard>
#include <QAction>
#include <QDebug>
static const QString kTextPlain = "text/plain";
const QString *pTextPlain = &kTextPlain;
QtnPropertyWidgetEx::QtnPropertyWidgetEx(QWidget *parent)
: QtnPropertyWidget(parent)
, dragged_property(nullptr)
, drop_action(Qt::IgnoreAction)
, can_remove(false)
{
for (auto child : children())
{
auto vbox = dynamic_cast<QVBoxLayout *>(child);
if (nullptr != vbox)
{
vbox->setContentsMargins(0, 0, 0, 0);
vbox->setMargin(0);
vbox->setSpacing(0);
}
}
setAcceptDrops(true);
propertyView()->installEventFilter(this);
}
void QtnPropertyWidgetEx::connectRemoveAction(QAction *action, bool connect)
{
internalConnect(action, &QtnPropertyWidgetEx::removeActiveProperty, connect);
}
void QtnPropertyWidgetEx::connectCutAction(QAction *action, bool connect)
{
internalConnect(action, &QtnPropertyWidgetEx::cutToClipboard, connect);
}
void QtnPropertyWidgetEx::connectCopyAction(QAction *action, bool connect)
{
internalConnect(action, &QtnPropertyWidgetEx::copyToClipboard, connect);
}
void QtnPropertyWidgetEx::connectPasteAction(QAction *action, bool connect)
{
internalConnect(action, &QtnPropertyWidgetEx::pasteFromClipboard, connect);
}
bool QtnPropertyWidgetEx::canRemoveActiveProperty()
{
return canRemoveProperty(propertyView()->activeProperty());
}
bool QtnPropertyWidgetEx::canRemoveProperty(QtnPropertyBase *)
{
return false;
}
bool QtnPropertyWidgetEx::canCutToClipboard()
{
return false;
}
bool QtnPropertyWidgetEx::canCopyToClipboard()
{
return (nullptr != propertyView()->activeProperty());
}
bool QtnPropertyWidgetEx::canPasteFromClipboard()
{
return dataHasSupportedFormats(QApplication::clipboard()->mimeData())
&& (nullptr != propertyView()->activeProperty());
}
bool QtnPropertyWidgetEx::dataHasSupportedFormats(const QMimeData *data)
{
return (nullptr != data && data->hasFormat(kTextPlain));
}
void QtnPropertyWidgetEx::removeActiveProperty()
{
removeProperty(propertyView()->activeProperty());
}
void QtnPropertyWidgetEx::cutToClipboard()
{
copyToClipboard();
removeActiveProperty();
}
void QtnPropertyWidgetEx::copyToClipboard()
{
auto property = propertyView()->activeProperty();
if (nullptr != property)
{
auto mime = getPropertyDataForAction(property, Qt::IgnoreAction);
if (nullptr != mime)
QApplication::clipboard()->setMimeData(mime);
}
}
void QtnPropertyWidgetEx::pasteFromClipboard()
{
auto data = QApplication::clipboard()->mimeData();
if (dataHasSupportedFormats(data))
{
applyPropertyData(data,
propertyView()->activeProperty(),
QtnApplyPosition::Over);
}
}
void QtnPropertyWidgetEx::removeProperty(QtnPropertyBase *)
{
// do nothing
}
QMimeData *QtnPropertyWidgetEx::getPropertyDataForAction(QtnPropertyBase *property,
Qt::DropAction)
{
QString str;
if (property->toStr(str))
{
auto mime = new QMimeData;
mime->setText(str);
return mime;
}
return nullptr;
}
bool QtnPropertyWidgetEx::applyPropertyData(const QMimeData *data,
QtnPropertyBase *destination,
QtnApplyPosition)
{
if (nullptr != destination)
{
Q_ASSERT(nullptr != data);
return destination->fromStr(data->text());
}
return false;
}
bool QtnPropertyWidgetEx::eventFilter(QObject *obj, QEvent *event)
{
switch (event->type())
{
case QEvent::MouseButtonPress:
{
auto mevent = static_cast<QMouseEvent *>(event);
if (mevent->button() == Qt::LeftButton)
{
drag_start_pos = mevent->pos();
dragged_property = propertyView()->getPropertyAt(drag_start_pos);
can_remove = canRemoveProperty(dragged_property);
return true;
}
} break;
case QEvent::MouseMove:
{
auto mevent = static_cast<QMouseEvent *>(event);
if (nullptr != dragged_property
&& 0 != (mevent->buttons() & Qt::LeftButton))
{
if ((mevent->pos() - drag_start_pos).manhattanLength()
< QApplication::startDragDistance())
{
drop_action = Qt::IgnoreAction;
if (dragAndDrop())
return true;
}
}
} break;
default:
break;
}
return QtnPropertyWidget::eventFilter(obj, event);
}
void QtnPropertyWidgetEx::dragEnterEvent(QDragEnterEvent *event)
{
if (dataHasSupportedFormats(event->mimeData()))
event->acceptProposedAction();
}
void QtnPropertyWidgetEx::dragMoveEvent(QDragMoveEvent *event)
{
if (Qt::ControlModifier == QApplication::keyboardModifiers()
|| !can_remove)
{
event->setDropAction(Qt::CopyAction);
drop_action = Qt::CopyAction;
} else
{
event->setDropAction(Qt::MoveAction);
drop_action = Qt::MoveAction;
}
event->accept();
}
void QtnPropertyWidgetEx::dropEvent(QDropEvent *event)
{
switch (event->dropAction())
{
case Qt::MoveAction:
case Qt::CopyAction:
{
auto view = propertyView();
auto pos = view->mapFrom(this, event->pos());
QRect rect;
auto property = view->getPropertyAt(pos, &rect);
int part_height = view->itemHeight() / 4;
QtnApplyPosition apply_position;
if (QRect(rect.left(), rect.top(),
rect.width(), part_height).contains(pos))
apply_position = QtnApplyPosition::Before;
else if (QRect(rect.left(), rect.bottom() - part_height,
rect.width(), part_height).contains(pos))
apply_position = QtnApplyPosition::After;
else
apply_position = QtnApplyPosition::Over;
if (property == dragged_property
|| nullptr == property)
{
dragged_property = nullptr;
}
auto data = event->mimeData();
if (nullptr != dragged_property
&& dataHasSupportedFormats(data)
&& applyPropertyData(data, property, apply_position))
event->accept();
} break;
default:
break;
}
}
bool QtnPropertyWidgetEx::dragAndDrop()
{
auto data = getPropertyDataForAction(dragged_property, Qt::CopyAction);
if (nullptr != data)
{
auto drag = new QDrag(this);
drag->setMimeData(data);
// TODO generate cursor
drag->exec(Qt::CopyAction | Qt::MoveAction);
if (nullptr != dragged_property)
{
if (Qt::MoveAction == drop_action)
removeProperty(dragged_property);
}
return true;
}
return false;
}
void QtnPropertyWidgetEx::internalConnect(QAction *action,
void (QtnPropertyWidgetEx::*slot)(),
bool connect)
{
if (connect)
QObject::connect(action, &QAction::triggered, this, slot);
else
QObject::disconnect(action, &QAction::triggered, this, slot);
}
<|endoftext|>
|
<commit_before>#include "ScriptObject.h"
#include "../Scene.h"
#include "../Application.h"
#include <regex>
namespace fse
{
ScriptObject::ScriptObject(const std::string& scriptName) : FSEObject(), script_name_(scriptName)
{
}
ScriptObject::ScriptObject(const std::string& scriptName, const sf::Vector2f& spawnPos) : FSEObject(spawnPos), script_name_(scriptName)
{
}
void ScriptObject::spawned()
{
try {
auto chai = scene_->getApplication()->getChai();
chai->use(script_name_);
std::smatch match;
std::regex_search(script_name_, match, std::regex(R"((?!.*(?=\/|\\)).*(?=\.chai))"));
const std::string classname = match.str();
chai->set_global(chaiscript::var(std::ref(*scene_)), "scriptObjectScene");
script_child_ = chai->eval(std::string(
classname + "(scriptObjectScene.getObjectWithId("+ std::to_string(getID()) + "));"));
initialized_ = true;
if (spawnedFun != nullptr)
spawnedFun(script_child_);
}
catch (const std::exception& e)
{
std::cerr << e.what() << "\n";
FSEObject::destroy();
}
}
void ScriptObject::onDespawn()
{
try {
if (onDespawnFun != nullptr)
onDespawnFun(script_child_);
}
catch (const std::exception& e)
{
std::cerr << e.what() << "\n";
}
}
void ScriptObject::update(float deltaTime)
{
try {
if (updateFun != nullptr)
updateFun(script_child_, deltaTime);
}
catch (const std::exception& e)
{
std::cerr << e.what() << "\n";
}
}
void ScriptObject::draw(sf::RenderTarget& target)
{
try
{
if (drawFun != nullptr)
drawFun(script_child_, target);
}
catch (const std::exception& e)
{
std::cerr << e.what() << "\n";
}
}
void ScriptObject::drawNormals(sf::RenderTarget& target)
{
try {
if (drawNormalsFun != nullptr)
drawNormalsFun(script_child_, target);
}
catch (const std::exception& e)
{
std::cerr << e.what() << "\n";
}
}
void ScriptObject::drawSpecular(sf::RenderTarget& target)
{
try {
if (drawSpecularFun != nullptr)
drawSpecularFun(script_child_, target);
}
catch (const std::exception& e)
{
std::cerr << e.what() << "\n";
}
}
void ScriptObject::setPosition(const sf::Vector2f position)
{
try {
if (setPositionFun != nullptr)
setPositionFun(script_child_, position);
}
catch (const std::exception& e)
{
std::cerr << e.what() << "\n";
}
}
sf::Vector2f ScriptObject::getPosition()
{
try {
if (getPositionFun != nullptr)
return getPositionFun(script_child_);
}
catch (const std::exception& e)
{
std::cerr << e.what() << "\n";
}
return FSEObject::getPosition();
}
sf::FloatRect ScriptObject::GetAABBs() const
{
try {
if (getAABBsFun != nullptr)
return getAABBsFun(script_child_);
}
catch (const std::exception& e)
{
std::cerr << e.what() << "\n";
}
return FSEObject::GetAABBs();
}
void ScriptObject::BeginContact(FSEObject* otherObject, b2Contact* contact)
{
try {
if (beginContactFun != nullptr)
beginContactFun(script_child_, otherObject, contact);
}
catch (const std::exception& e)
{
std::cerr << e.what() << "\n";
}
}
void ScriptObject::EndContact(FSEObject* otherObject, b2Contact* contact)
{
try {
if (endContactFun != nullptr)
endContactFun(script_child_, otherObject, contact);
}
catch (const std::exception& e)
{
std::cerr << e.what() << "\n";
}
}
void ScriptObject::PreSolve(FSEObject* otherObject, b2Contact* contact, const b2Manifold* oldManifold)
{
try
{
if (preSolveFun != nullptr)
preSolveFun(script_child_, otherObject, contact, oldManifold);
}
catch (const std::exception& e)
{
std::cerr << e.what() << "\n";
}
}
void ScriptObject::PostSolve(FSEObject* otherObject, b2Contact* contact, const b2ContactImpulse* impulse)
{
try {
if (postSolveFun != nullptr)
postSolveFun(script_child_, otherObject, contact, impulse);
}
catch (const std::exception& e)
{
std::cerr << e.what() << "\n";
}
}
bool ScriptObject::destroy()
{
try {
if (destroyFun != nullptr)
return destroyFun(script_child_);
}
catch (const std::exception& e)
{
std::cerr << e.what() << "\n";
}
return FSEObject::destroy();
}
void ScriptObject::BeginContactComponents(FSEObject* otherObject, b2Contact* contact)
{
try {
if (beginContactComponentsFun != nullptr)
beginContactComponentsFun(script_child_, otherObject, contact);
}
catch (const std::exception& e)
{
std::cerr << e.what() << "\n";
}
}
void ScriptObject::EndContactComponents(FSEObject* otherObject, b2Contact* contact)
{
try {
if (endContactComponentsFun != nullptr)
endContactComponentsFun(script_child_, otherObject, contact);
}
catch (const std::exception& e)
{
std::cerr << e.what() << "\n";
}
}
void ScriptObject::PreSolveComponents(FSEObject* otherObject, b2Contact* contact, const b2Manifold* oldManifold)
{
try {
if (preSolveComponentsFun != nullptr)
preSolveComponentsFun(script_child_, otherObject, contact, oldManifold);
}
catch (const std::exception& e)
{
std::cerr << e.what() << "\n";
}
}
void ScriptObject::PostSolveComponents(FSEObject* otherObject, b2Contact* contact, const b2ContactImpulse* impulse)
{
try {
if (postSolveComponentsFun != nullptr)
postSolveComponentsFun(script_child_, otherObject, contact, impulse);
}
catch (const std::exception& e)
{
std::cerr << e.what() << "\n";
}
}
FSE_CHAI_REGISTER(ScriptObject)
{
RegisterChaiUserTypeFromRTTR<ScriptObject>(chai);
chai.add(chaiscript::base_class<fse::FSEObject, ScriptObject>());
chai.add(chaiscript::constructor<ScriptObject(const std::string&)>(), "ScriptObject");
chai.add(chaiscript::fun([](const ScriptObject* object)
{
return object->initialized_;
}), "isInitialized");
chai.add(chaiscript::fun([](const ScriptObject* object)
{
return object->script_name_;
}), "getScriptName");
chai.add(chaiscript::fun([](const ScriptObject* object)
{
return object->script_child_;
}), "_child");
chai.add(chaiscript::fun(&ScriptObject::spawnedFun), "spawnedCallback");
chai.add(chaiscript::fun(&ScriptObject::onDespawnFun), "onDespawnCallback");
chai.add(chaiscript::fun(&ScriptObject::updateFun), "updateCallback");
chai.add(chaiscript::fun(&ScriptObject::drawFun), "drawCallback");
chai.add(chaiscript::fun(&ScriptObject::drawNormalsFun), "drawNormalsCallback");
chai.add(chaiscript::fun(&ScriptObject::drawSpecularFun), "drawSpecularCallback");
chai.add(chaiscript::fun(&ScriptObject::setPositionFun), "setPositionCallback");
chai.add(chaiscript::fun(&ScriptObject::getPositionFun), "getPositionCallback");
chai.add(chaiscript::fun(&ScriptObject::getAABBsFun), "getAABBsCallback");
chai.add(chaiscript::fun(&ScriptObject::beginContactFun), "beginContactCallback");
chai.add(chaiscript::fun(&ScriptObject::endContactFun), "endContactCallback");
chai.add(chaiscript::fun(&ScriptObject::preSolveFun), "preSolveCallback");
chai.add(chaiscript::fun(&ScriptObject::postSolveFun), "postSolveCallback");
chai.add(chaiscript::fun(&ScriptObject::destroyFun), "destroyCallback");
chai.add(chaiscript::fun(&ScriptObject::beginContactComponentsFun), "beginContactComponentsCallback");
chai.add(chaiscript::fun(&ScriptObject::endContactComponentsFun), "endContactComponentsCallback");
chai.add(chaiscript::fun(&ScriptObject::preSolveComponentsFun), "preSolveComponentsCallback");
chai.add(chaiscript::fun(&ScriptObject::postSolveComponentsFun), "postSolveComponentsCallback");
}
}
#include <rttr/registration>
RTTR_REGISTRATION
{
using namespace rttr;
using namespace fse;
registration::class_<ScriptObject>("fse::ScriptObject")
.constructor<const std::string& >()
(
policy::ctor::as_std_shared_ptr,
parameter_names("script name")
)
.constructor<const std::string&, const sf::Vector2f&>()
(
policy::ctor::as_std_shared_ptr,
parameter_names("script name", "spawn position")
)
.property_readonly("script_name_", &ScriptObject::script_name_)
.property_readonly("initialized_", &ScriptObject::initialized_)
.property_readonly("script_child_", &ScriptObject::script_child_)
;
}
<commit_msg>ScriptObject: cleanup<commit_after>#include "ScriptObject.h"
#include "../Scene.h"
#include "../Application.h"
#include <regex>
namespace fse
{
ScriptObject::ScriptObject(const std::string& scriptName) : FSEObject(), script_name_(scriptName)
{
}
ScriptObject::ScriptObject(const std::string& scriptName, const sf::Vector2f& spawnPos) : FSEObject(spawnPos), script_name_(scriptName)
{
}
void ScriptObject::spawned()
{
try {
auto chai = getChai();
chai->use(script_name_);
std::smatch match;
std::regex_search(script_name_, match, std::regex(R"((?!.*(?=\/|\\)).*(?=\.chai))"));
const std::string classname = match.str();
chai->set_global(chaiscript::var(std::ref(*scene_)), "scriptObjectScene");
script_child_ = chai->eval(std::string(
classname + "(scriptObjectScene.getObjectWithId("+ std::to_string(getID()) + "));"));
initialized_ = true;
if (spawnedFun != nullptr)
spawnedFun(script_child_);
}
catch (const std::exception& e)
{
std::cerr << e.what() << "\n";
FSEObject::destroy();
}
}
void ScriptObject::onDespawn()
{
try {
if (onDespawnFun != nullptr)
onDespawnFun(script_child_);
}
catch (const std::exception& e)
{
std::cerr << e.what() << "\n";
}
}
void ScriptObject::update(float deltaTime)
{
try {
if (updateFun != nullptr)
updateFun(script_child_, deltaTime);
}
catch (const std::exception& e)
{
std::cerr << e.what() << "\n";
}
}
void ScriptObject::draw(sf::RenderTarget& target)
{
try
{
if (drawFun != nullptr)
drawFun(script_child_, target);
}
catch (const std::exception& e)
{
std::cerr << e.what() << "\n";
}
}
void ScriptObject::drawNormals(sf::RenderTarget& target)
{
try {
if (drawNormalsFun != nullptr)
drawNormalsFun(script_child_, target);
}
catch (const std::exception& e)
{
std::cerr << e.what() << "\n";
}
}
void ScriptObject::drawSpecular(sf::RenderTarget& target)
{
try {
if (drawSpecularFun != nullptr)
drawSpecularFun(script_child_, target);
}
catch (const std::exception& e)
{
std::cerr << e.what() << "\n";
}
}
void ScriptObject::setPosition(const sf::Vector2f position)
{
try {
if (setPositionFun != nullptr)
setPositionFun(script_child_, position);
}
catch (const std::exception& e)
{
std::cerr << e.what() << "\n";
}
}
sf::Vector2f ScriptObject::getPosition()
{
try {
if (getPositionFun != nullptr)
return getPositionFun(script_child_);
}
catch (const std::exception& e)
{
std::cerr << e.what() << "\n";
}
return FSEObject::getPosition();
}
sf::FloatRect ScriptObject::GetAABBs() const
{
try {
if (getAABBsFun != nullptr)
return getAABBsFun(script_child_);
}
catch (const std::exception& e)
{
std::cerr << e.what() << "\n";
}
return FSEObject::GetAABBs();
}
void ScriptObject::BeginContact(FSEObject* otherObject, b2Contact* contact)
{
try {
if (beginContactFun != nullptr)
beginContactFun(script_child_, otherObject, contact);
}
catch (const std::exception& e)
{
std::cerr << e.what() << "\n";
}
}
void ScriptObject::EndContact(FSEObject* otherObject, b2Contact* contact)
{
try {
if (endContactFun != nullptr)
endContactFun(script_child_, otherObject, contact);
}
catch (const std::exception& e)
{
std::cerr << e.what() << "\n";
}
}
void ScriptObject::PreSolve(FSEObject* otherObject, b2Contact* contact, const b2Manifold* oldManifold)
{
try
{
if (preSolveFun != nullptr)
preSolveFun(script_child_, otherObject, contact, oldManifold);
}
catch (const std::exception& e)
{
std::cerr << e.what() << "\n";
}
}
void ScriptObject::PostSolve(FSEObject* otherObject, b2Contact* contact, const b2ContactImpulse* impulse)
{
try {
if (postSolveFun != nullptr)
postSolveFun(script_child_, otherObject, contact, impulse);
}
catch (const std::exception& e)
{
std::cerr << e.what() << "\n";
}
}
bool ScriptObject::destroy()
{
try {
if (destroyFun != nullptr)
return destroyFun(script_child_);
}
catch (const std::exception& e)
{
std::cerr << e.what() << "\n";
}
return FSEObject::destroy();
}
void ScriptObject::BeginContactComponents(FSEObject* otherObject, b2Contact* contact)
{
try {
if (beginContactComponentsFun != nullptr)
beginContactComponentsFun(script_child_, otherObject, contact);
}
catch (const std::exception& e)
{
std::cerr << e.what() << "\n";
}
}
void ScriptObject::EndContactComponents(FSEObject* otherObject, b2Contact* contact)
{
try {
if (endContactComponentsFun != nullptr)
endContactComponentsFun(script_child_, otherObject, contact);
}
catch (const std::exception& e)
{
std::cerr << e.what() << "\n";
}
}
void ScriptObject::PreSolveComponents(FSEObject* otherObject, b2Contact* contact, const b2Manifold* oldManifold)
{
try {
if (preSolveComponentsFun != nullptr)
preSolveComponentsFun(script_child_, otherObject, contact, oldManifold);
}
catch (const std::exception& e)
{
std::cerr << e.what() << "\n";
}
}
void ScriptObject::PostSolveComponents(FSEObject* otherObject, b2Contact* contact, const b2ContactImpulse* impulse)
{
try {
if (postSolveComponentsFun != nullptr)
postSolveComponentsFun(script_child_, otherObject, contact, impulse);
}
catch (const std::exception& e)
{
std::cerr << e.what() << "\n";
}
}
FSE_CHAI_REGISTER(ScriptObject)
{
RegisterChaiUserTypeFromRTTR<ScriptObject>(chai);
chai.add(chaiscript::base_class<fse::FSEObject, ScriptObject>());
chai.add(chaiscript::constructor<ScriptObject(const std::string&)>(), "ScriptObject");
chai.add(chaiscript::fun([](const ScriptObject* object)
{
return object->initialized_;
}), "isInitialized");
chai.add(chaiscript::fun([](const ScriptObject* object)
{
return object->script_name_;
}), "getScriptName");
chai.add(chaiscript::fun([](const ScriptObject* object)
{
return object->script_child_;
}), "_child");
chai.add(chaiscript::fun(&ScriptObject::spawnedFun), "spawnedCallback");
chai.add(chaiscript::fun(&ScriptObject::onDespawnFun), "onDespawnCallback");
chai.add(chaiscript::fun(&ScriptObject::updateFun), "updateCallback");
chai.add(chaiscript::fun(&ScriptObject::drawFun), "drawCallback");
chai.add(chaiscript::fun(&ScriptObject::drawNormalsFun), "drawNormalsCallback");
chai.add(chaiscript::fun(&ScriptObject::drawSpecularFun), "drawSpecularCallback");
chai.add(chaiscript::fun(&ScriptObject::setPositionFun), "setPositionCallback");
chai.add(chaiscript::fun(&ScriptObject::getPositionFun), "getPositionCallback");
chai.add(chaiscript::fun(&ScriptObject::getAABBsFun), "getAABBsCallback");
chai.add(chaiscript::fun(&ScriptObject::beginContactFun), "beginContactCallback");
chai.add(chaiscript::fun(&ScriptObject::endContactFun), "endContactCallback");
chai.add(chaiscript::fun(&ScriptObject::preSolveFun), "preSolveCallback");
chai.add(chaiscript::fun(&ScriptObject::postSolveFun), "postSolveCallback");
chai.add(chaiscript::fun(&ScriptObject::destroyFun), "destroyCallback");
chai.add(chaiscript::fun(&ScriptObject::beginContactComponentsFun), "beginContactComponentsCallback");
chai.add(chaiscript::fun(&ScriptObject::endContactComponentsFun), "endContactComponentsCallback");
chai.add(chaiscript::fun(&ScriptObject::preSolveComponentsFun), "preSolveComponentsCallback");
chai.add(chaiscript::fun(&ScriptObject::postSolveComponentsFun), "postSolveComponentsCallback");
}
}
#include <rttr/registration>
RTTR_REGISTRATION
{
using namespace rttr;
using namespace fse;
registration::class_<ScriptObject>("fse::ScriptObject")
.constructor<const std::string& >()
(
policy::ctor::as_std_shared_ptr,
parameter_names("script name")
)
.constructor<const std::string&, const sf::Vector2f&>()
(
policy::ctor::as_std_shared_ptr,
parameter_names("script name", "spawn position")
)
.property_readonly("script_name_", &ScriptObject::script_name_)
.property_readonly("initialized_", &ScriptObject::initialized_)
.property_readonly("script_child_", &ScriptObject::script_child_)
;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/gfx/gtk_preserve_window.h"
#include <gdk/gdkwindow.h>
#include <gtk/gtk.h>
#include <gtk/gtkwidget.h>
#include <gtk/gtkfixed.h>
G_BEGIN_DECLS
#define GTK_PRESERVE_WINDOW_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), \
GTK_TYPE_PRESERVE_WINDOW, \
GtkPreserveWindowPrivate))
typedef struct _GtkPreserveWindowPrivate GtkPreserveWindowPrivate;
struct _GtkPreserveWindowPrivate {
// If true, don't create/destroy windows on realize/unrealize.
gboolean preserve_window;
// Whether or not we delegate the resize of the GdkWindow
// to someone else.
gboolean delegate_resize;
};
G_DEFINE_TYPE(GtkPreserveWindow, gtk_preserve_window, GTK_TYPE_FIXED)
static void gtk_preserve_window_destroy(GtkObject* object);
static void gtk_preserve_window_realize(GtkWidget* widget);
static void gtk_preserve_window_unrealize(GtkWidget* widget);
static void gtk_preserve_window_size_allocate(GtkWidget* widget,
GtkAllocation* allocation);
static void gtk_preserve_window_class_init(GtkPreserveWindowClass *klass) {
GtkWidgetClass* widget_class = reinterpret_cast<GtkWidgetClass*>(klass);
widget_class->realize = gtk_preserve_window_realize;
widget_class->unrealize = gtk_preserve_window_unrealize;
widget_class->size_allocate = gtk_preserve_window_size_allocate;
GtkObjectClass* object_class = reinterpret_cast<GtkObjectClass*>(klass);
object_class->destroy = gtk_preserve_window_destroy;
GObjectClass* gobject_class = G_OBJECT_CLASS(klass);
g_type_class_add_private(gobject_class, sizeof(GtkPreserveWindowPrivate));
}
static void gtk_preserve_window_init(GtkPreserveWindow* widget) {
GtkPreserveWindowPrivate* priv = GTK_PRESERVE_WINDOW_GET_PRIVATE(widget);
priv->preserve_window = FALSE;
// These widgets always have their own window.
gtk_fixed_set_has_window(GTK_FIXED(widget), TRUE);
}
GtkWidget* gtk_preserve_window_new() {
return GTK_WIDGET(g_object_new(GTK_TYPE_PRESERVE_WINDOW, NULL));
}
static void gtk_preserve_window_destroy(GtkObject* object) {
GtkWidget* widget = reinterpret_cast<GtkWidget*>(object);
GtkPreserveWindowPrivate* priv = GTK_PRESERVE_WINDOW_GET_PRIVATE(widget);
if (widget->window) {
gdk_window_set_user_data(widget->window, NULL);
// If the window is preserved, someone else must destroy it.
if (!priv->preserve_window)
gdk_window_destroy(widget->window);
widget->window = NULL;
}
GTK_OBJECT_CLASS(gtk_preserve_window_parent_class)->destroy(object);
}
static void gtk_preserve_window_realize(GtkWidget* widget) {
g_return_if_fail(GTK_IS_PRESERVE_WINDOW(widget));
if (widget->window) {
gdk_window_reparent(widget->window,
gtk_widget_get_parent_window(widget),
widget->allocation.x,
widget->allocation.y);
widget->style = gtk_style_attach(widget->style, widget->window);
gtk_style_set_background(widget->style, widget->window, GTK_STATE_NORMAL);
gint event_mask = gtk_widget_get_events(widget);
event_mask |= GDK_EXPOSURE_MASK | GDK_BUTTON_PRESS_MASK;
gdk_window_set_events(widget->window, (GdkEventMask) event_mask);
gdk_window_set_user_data(widget->window, widget);
// Deprecated as of GTK 2.22. Used for compatibility.
// It should be: gtk_widget_set_realized(widget, TRUE)
GTK_WIDGET_SET_FLAGS(widget, GTK_REALIZED);
} else {
GTK_WIDGET_CLASS(gtk_preserve_window_parent_class)->realize(widget);
}
}
static void gtk_preserve_window_unrealize(GtkWidget* widget) {
g_return_if_fail(GTK_IS_PRESERVE_WINDOW(widget));
GtkPreserveWindowPrivate* priv = GTK_PRESERVE_WINDOW_GET_PRIVATE(widget);
if (priv->preserve_window) {
GtkWidgetClass* widget_class =
GTK_WIDGET_CLASS(gtk_preserve_window_parent_class);
GtkContainerClass* container_class =
GTK_CONTAINER_CLASS(gtk_preserve_window_parent_class);
// Deprecated as of GTK 2.22. Used for compatibility.
// It should be: gtk_widget_get_mapped()
if (GTK_WIDGET_MAPPED(widget)) {
widget_class->unmap(widget);
// Deprecated as of GTK 2.22. Used for compatibility.
// It should be: gtk_widget_set_mapped(widget, FALSE)
GTK_WIDGET_UNSET_FLAGS(widget, GTK_MAPPED);
}
// This is the behavior from GtkWidget, inherited by GtkFixed.
// It is unclear why we should not call the potentially overridden
// unrealize method (via the callback), but doing so causes errors.
container_class->forall(
GTK_CONTAINER(widget), FALSE,
reinterpret_cast<GtkCallback>(gtk_widget_unrealize), NULL);
gtk_style_detach(widget->style);
gdk_window_reparent(widget->window, gdk_get_default_root_window(), 0, 0);
gtk_selection_remove_all(widget);
gdk_window_set_user_data(widget->window, NULL);
// Deprecated as of GTK 2.22. Used for compatibility.
// It should be: gtk_widget_set_realized(widget, FALSE)
GTK_WIDGET_UNSET_FLAGS(widget, GTK_REALIZED);
} else {
GTK_WIDGET_CLASS(gtk_preserve_window_parent_class)->unrealize(widget);
}
}
gboolean gtk_preserve_window_get_preserve(GtkPreserveWindow* window) {
g_return_val_if_fail(GTK_IS_PRESERVE_WINDOW(window), FALSE);
GtkPreserveWindowPrivate* priv = GTK_PRESERVE_WINDOW_GET_PRIVATE(window);
return priv->preserve_window;
}
void gtk_preserve_window_set_preserve(GtkPreserveWindow* window,
gboolean value) {
g_return_if_fail(GTK_IS_PRESERVE_WINDOW(window));
GtkPreserveWindowPrivate* priv = GTK_PRESERVE_WINDOW_GET_PRIVATE(window);
priv->preserve_window = value;
GtkWidget* widget = GTK_WIDGET(window);
if (value && !widget->window) {
GdkWindowAttr attributes;
gint attributes_mask;
// We may not know the width and height, so we rely on the fact
// that a size-allocation will resize it later.
attributes.width = 1;
attributes.height = 1;
attributes.window_type = GDK_WINDOW_CHILD;
attributes.wclass = GDK_INPUT_OUTPUT;
attributes.visual = gtk_widget_get_visual(widget);
attributes.colormap = gtk_widget_get_colormap(widget);
attributes_mask = GDK_WA_VISUAL | GDK_WA_COLORMAP;
widget->window = gdk_window_new(
gdk_get_default_root_window(), &attributes, attributes_mask);
} else if (!value && widget->window && !GTK_WIDGET_REALIZED(widget)) {
gdk_window_destroy(widget->window);
widget->window = NULL;
}
}
void gtk_preserve_window_size_allocate(GtkWidget* widget,
GtkAllocation* allocation) {
g_return_if_fail(GTK_IS_PRESERVE_WINDOW(widget));
GtkPreserveWindowPrivate* priv = GTK_PRESERVE_WINDOW_GET_PRIVATE(widget);
if (priv->delegate_resize) {
// Just update the state. Someone else will gdk_window_resize the
// associated GdkWindow.
widget->allocation = *allocation;
} else {
GTK_WIDGET_CLASS(gtk_preserve_window_parent_class)->size_allocate(
widget, allocation);
}
}
void gtk_preserve_window_delegate_resize(GtkPreserveWindow* widget,
gboolean delegate) {
GtkPreserveWindowPrivate* priv = GTK_PRESERVE_WINDOW_GET_PRIVATE(widget);
priv->delegate_resize = delegate;
}
G_END_DECLS
<commit_msg>To prevent damage to the back-buffer, it's only necessary to defer resize.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/gfx/gtk_preserve_window.h"
#include <gdk/gdkwindow.h>
#include <gtk/gtk.h>
#include <gtk/gtkwidget.h>
#include <gtk/gtkfixed.h>
G_BEGIN_DECLS
#define GTK_PRESERVE_WINDOW_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), \
GTK_TYPE_PRESERVE_WINDOW, \
GtkPreserveWindowPrivate))
typedef struct _GtkPreserveWindowPrivate GtkPreserveWindowPrivate;
struct _GtkPreserveWindowPrivate {
// If true, don't create/destroy windows on realize/unrealize.
gboolean preserve_window;
// Whether or not we delegate the resize of the GdkWindow
// to someone else.
gboolean delegate_resize;
};
G_DEFINE_TYPE(GtkPreserveWindow, gtk_preserve_window, GTK_TYPE_FIXED)
static void gtk_preserve_window_destroy(GtkObject* object);
static void gtk_preserve_window_realize(GtkWidget* widget);
static void gtk_preserve_window_unrealize(GtkWidget* widget);
static void gtk_preserve_window_size_allocate(GtkWidget* widget,
GtkAllocation* allocation);
static void gtk_preserve_window_class_init(GtkPreserveWindowClass *klass) {
GtkWidgetClass* widget_class = reinterpret_cast<GtkWidgetClass*>(klass);
widget_class->realize = gtk_preserve_window_realize;
widget_class->unrealize = gtk_preserve_window_unrealize;
widget_class->size_allocate = gtk_preserve_window_size_allocate;
GtkObjectClass* object_class = reinterpret_cast<GtkObjectClass*>(klass);
object_class->destroy = gtk_preserve_window_destroy;
GObjectClass* gobject_class = G_OBJECT_CLASS(klass);
g_type_class_add_private(gobject_class, sizeof(GtkPreserveWindowPrivate));
}
static void gtk_preserve_window_init(GtkPreserveWindow* widget) {
GtkPreserveWindowPrivate* priv = GTK_PRESERVE_WINDOW_GET_PRIVATE(widget);
priv->preserve_window = FALSE;
// These widgets always have their own window.
gtk_fixed_set_has_window(GTK_FIXED(widget), TRUE);
}
GtkWidget* gtk_preserve_window_new() {
return GTK_WIDGET(g_object_new(GTK_TYPE_PRESERVE_WINDOW, NULL));
}
static void gtk_preserve_window_destroy(GtkObject* object) {
GtkWidget* widget = reinterpret_cast<GtkWidget*>(object);
GtkPreserveWindowPrivate* priv = GTK_PRESERVE_WINDOW_GET_PRIVATE(widget);
if (widget->window) {
gdk_window_set_user_data(widget->window, NULL);
// If the window is preserved, someone else must destroy it.
if (!priv->preserve_window)
gdk_window_destroy(widget->window);
widget->window = NULL;
}
GTK_OBJECT_CLASS(gtk_preserve_window_parent_class)->destroy(object);
}
static void gtk_preserve_window_realize(GtkWidget* widget) {
g_return_if_fail(GTK_IS_PRESERVE_WINDOW(widget));
if (widget->window) {
gdk_window_reparent(widget->window,
gtk_widget_get_parent_window(widget),
widget->allocation.x,
widget->allocation.y);
widget->style = gtk_style_attach(widget->style, widget->window);
gtk_style_set_background(widget->style, widget->window, GTK_STATE_NORMAL);
gint event_mask = gtk_widget_get_events(widget);
event_mask |= GDK_EXPOSURE_MASK | GDK_BUTTON_PRESS_MASK;
gdk_window_set_events(widget->window, (GdkEventMask) event_mask);
gdk_window_set_user_data(widget->window, widget);
// Deprecated as of GTK 2.22. Used for compatibility.
// It should be: gtk_widget_set_realized(widget, TRUE)
GTK_WIDGET_SET_FLAGS(widget, GTK_REALIZED);
} else {
GTK_WIDGET_CLASS(gtk_preserve_window_parent_class)->realize(widget);
}
}
static void gtk_preserve_window_unrealize(GtkWidget* widget) {
g_return_if_fail(GTK_IS_PRESERVE_WINDOW(widget));
GtkPreserveWindowPrivate* priv = GTK_PRESERVE_WINDOW_GET_PRIVATE(widget);
if (priv->preserve_window) {
GtkWidgetClass* widget_class =
GTK_WIDGET_CLASS(gtk_preserve_window_parent_class);
GtkContainerClass* container_class =
GTK_CONTAINER_CLASS(gtk_preserve_window_parent_class);
// Deprecated as of GTK 2.22. Used for compatibility.
// It should be: gtk_widget_get_mapped()
if (GTK_WIDGET_MAPPED(widget)) {
widget_class->unmap(widget);
// Deprecated as of GTK 2.22. Used for compatibility.
// It should be: gtk_widget_set_mapped(widget, FALSE)
GTK_WIDGET_UNSET_FLAGS(widget, GTK_MAPPED);
}
// This is the behavior from GtkWidget, inherited by GtkFixed.
// It is unclear why we should not call the potentially overridden
// unrealize method (via the callback), but doing so causes errors.
container_class->forall(
GTK_CONTAINER(widget), FALSE,
reinterpret_cast<GtkCallback>(gtk_widget_unrealize), NULL);
gtk_style_detach(widget->style);
gdk_window_reparent(widget->window, gdk_get_default_root_window(), 0, 0);
gtk_selection_remove_all(widget);
gdk_window_set_user_data(widget->window, NULL);
// Deprecated as of GTK 2.22. Used for compatibility.
// It should be: gtk_widget_set_realized(widget, FALSE)
GTK_WIDGET_UNSET_FLAGS(widget, GTK_REALIZED);
} else {
GTK_WIDGET_CLASS(gtk_preserve_window_parent_class)->unrealize(widget);
}
}
gboolean gtk_preserve_window_get_preserve(GtkPreserveWindow* window) {
g_return_val_if_fail(GTK_IS_PRESERVE_WINDOW(window), FALSE);
GtkPreserveWindowPrivate* priv = GTK_PRESERVE_WINDOW_GET_PRIVATE(window);
return priv->preserve_window;
}
void gtk_preserve_window_set_preserve(GtkPreserveWindow* window,
gboolean value) {
g_return_if_fail(GTK_IS_PRESERVE_WINDOW(window));
GtkPreserveWindowPrivate* priv = GTK_PRESERVE_WINDOW_GET_PRIVATE(window);
priv->preserve_window = value;
GtkWidget* widget = GTK_WIDGET(window);
if (value && !widget->window) {
GdkWindowAttr attributes;
gint attributes_mask;
// We may not know the width and height, so we rely on the fact
// that a size-allocation will resize it later.
attributes.width = 1;
attributes.height = 1;
attributes.window_type = GDK_WINDOW_CHILD;
attributes.wclass = GDK_INPUT_OUTPUT;
attributes.visual = gtk_widget_get_visual(widget);
attributes.colormap = gtk_widget_get_colormap(widget);
attributes_mask = GDK_WA_VISUAL | GDK_WA_COLORMAP;
widget->window = gdk_window_new(
gdk_get_default_root_window(), &attributes, attributes_mask);
} else if (!value && widget->window && !GTK_WIDGET_REALIZED(widget)) {
gdk_window_destroy(widget->window);
widget->window = NULL;
}
}
void gtk_preserve_window_size_allocate(GtkWidget* widget,
GtkAllocation* allocation) {
g_return_if_fail(GTK_IS_PRESERVE_WINDOW(widget));
GtkPreserveWindowPrivate* priv = GTK_PRESERVE_WINDOW_GET_PRIVATE(widget);
if (priv->delegate_resize) {
widget->allocation = *allocation;
// Only update the position. Someone else will call gdk_window_resize.
if (GTK_WIDGET_REALIZED(widget)) {
gdk_window_move(widget->window, allocation->x, allocation->y);
}
} else {
GTK_WIDGET_CLASS(gtk_preserve_window_parent_class)->size_allocate(
widget, allocation);
}
}
void gtk_preserve_window_delegate_resize(GtkPreserveWindow* widget,
gboolean delegate) {
GtkPreserveWindowPrivate* priv = GTK_PRESERVE_WINDOW_GET_PRIVATE(widget);
priv->delegate_resize = delegate;
}
G_END_DECLS
<|endoftext|>
|
<commit_before>// Copyright 2014 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/bookmarks/chrome_bookmark_client.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/logging.h"
#include "base/values.h"
#include "chrome/browser/favicon/favicon_service.h"
#include "chrome/browser/favicon/favicon_service_factory.h"
#include "chrome/browser/history/history_service.h"
#include "chrome/browser/policy/profile_policy_connector.h"
#include "chrome/browser/policy/profile_policy_connector_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "components/bookmarks/browser/bookmark_model.h"
#include "components/bookmarks/browser/bookmark_node.h"
#include "components/bookmarks/browser/bookmark_utils.h"
#include "components/history/core/browser/url_database.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/notification_details.h"
#include "content/public/browser/notification_source.h"
#include "content/public/browser/user_metrics.h"
#include "grit/components_strings.h"
#include "policy/policy_constants.h"
#include "ui/base/l10n/l10n_util.h"
using bookmarks::BookmarkModel;
using bookmarks::BookmarkNode;
using bookmarks::BookmarkPermanentNode;
namespace {
void RunCallbackWithImage(
const favicon_base::FaviconImageCallback& callback,
const favicon_base::FaviconRawBitmapResult& bitmap_result) {
favicon_base::FaviconImageResult result;
if (bitmap_result.is_valid()) {
result.image = gfx::Image::CreateFrom1xPNGBytes(
bitmap_result.bitmap_data->front(), bitmap_result.bitmap_data->size());
result.icon_url = bitmap_result.icon_url;
callback.Run(result);
return;
}
callback.Run(result);
}
void LoadInitialContents(BookmarkPermanentNode* node,
base::ListValue* initial_bookmarks,
int64* next_node_id) {
// Load the initial contents of the |node| now, and assign it an unused ID.
int64 id = *next_node_id;
node->set_id(id);
*next_node_id = policy::ManagedBookmarksTracker::LoadInitial(
node, initial_bookmarks, id + 1);
node->set_visible(!node->empty());
}
} // namespace
ChromeBookmarkClient::ChromeBookmarkClient(Profile* profile)
: profile_(profile),
history_service_(NULL),
model_(NULL),
managed_node_(NULL),
supervised_node_(NULL) {
}
ChromeBookmarkClient::~ChromeBookmarkClient() {
}
void ChromeBookmarkClient::Init(BookmarkModel* model) {
DCHECK(model);
DCHECK(!model_);
model_ = model;
model_->AddObserver(this);
managed_bookmarks_tracker_.reset(new policy::ManagedBookmarksTracker(
model_,
profile_->GetPrefs(),
false,
base::Bind(&ChromeBookmarkClient::GetManagedBookmarksDomain,
base::Unretained(this))));
supervised_bookmarks_tracker_.reset(new policy::ManagedBookmarksTracker(
model_,
profile_->GetPrefs(),
true,
base::Callback<std::string()>()));
}
void ChromeBookmarkClient::Shutdown() {
favicon_changed_subscription_.reset();
if (model_) {
model_->RemoveObserver(this);
model_ = NULL;
}
BookmarkClient::Shutdown();
}
bool ChromeBookmarkClient::PreferTouchIcon() {
#if !defined(OS_IOS)
return false;
#else
return true;
#endif
}
base::CancelableTaskTracker::TaskId
ChromeBookmarkClient::GetFaviconImageForPageURL(
const GURL& page_url,
favicon_base::IconType type,
const favicon_base::FaviconImageCallback& callback,
base::CancelableTaskTracker* tracker) {
FaviconService* favicon_service = FaviconServiceFactory::GetForProfile(
profile_, ServiceAccessType::EXPLICIT_ACCESS);
if (!favicon_service)
return base::CancelableTaskTracker::kBadTaskId;
if (type == favicon_base::FAVICON) {
return favicon_service->GetFaviconImageForPageURL(
page_url, callback, tracker);
} else {
return favicon_service->GetRawFaviconForPageURL(
page_url,
type,
0,
base::Bind(&RunCallbackWithImage, callback),
tracker);
}
}
bool ChromeBookmarkClient::SupportsTypedCountForNodes() {
return true;
}
void ChromeBookmarkClient::GetTypedCountForNodes(
const NodeSet& nodes,
NodeTypedCountPairs* node_typed_count_pairs) {
history::URLDatabase* url_db =
history_service_ ? history_service_->InMemoryDatabase() : NULL;
for (NodeSet::const_iterator i = nodes.begin(); i != nodes.end(); ++i) {
int typed_count = 0;
// If |url_db| is the InMemoryDatabase, it might not cache all URLRows, but
// it guarantees to contain those with |typed_count| > 0. Thus, if we cannot
// fetch the URLRow, it is safe to assume that its |typed_count| is 0.
history::URLRow url;
if (url_db && url_db->GetRowForURL((*i)->url(), &url))
typed_count = url.typed_count();
NodeTypedCountPair pair(*i, typed_count);
node_typed_count_pairs->push_back(pair);
}
}
bool ChromeBookmarkClient::IsPermanentNodeVisible(
const BookmarkPermanentNode* node) {
DCHECK(node->type() == BookmarkNode::BOOKMARK_BAR ||
node->type() == BookmarkNode::OTHER_NODE ||
node->type() == BookmarkNode::MOBILE ||
node == managed_node_ ||
node == supervised_node_);
if (node == managed_node_ || node == supervised_node_)
return false;
#if !defined(OS_IOS)
return node->type() != BookmarkNode::MOBILE;
#else
return node->type() == BookmarkNode::MOBILE;
#endif
}
void ChromeBookmarkClient::RecordAction(const base::UserMetricsAction& action) {
content::RecordAction(action);
}
bookmarks::LoadExtraCallback ChromeBookmarkClient::GetLoadExtraNodesCallback() {
// Create the managed_node_ and supervised_node_ with a temporary ID of 0 now.
// They will be populated (and assigned proper IDs) in the LoadExtraNodes
// callback.
// The ownership of managed_node_ and supervised_node_ is in limbo until
// LoadExtraNodes runs, so we leave them in the care of the closure meanwhile.
scoped_ptr<BookmarkPermanentNode> managed(new BookmarkPermanentNode(0));
managed_node_ = managed.get();
scoped_ptr<BookmarkPermanentNode> supervised(new BookmarkPermanentNode(0));
supervised_node_ = supervised.get();
return base::Bind(
&ChromeBookmarkClient::LoadExtraNodes,
base::Passed(&managed),
base::Passed(managed_bookmarks_tracker_->GetInitialManagedBookmarks()),
base::Passed(&supervised),
base::Passed(
supervised_bookmarks_tracker_->GetInitialManagedBookmarks()));
}
bool ChromeBookmarkClient::CanSetPermanentNodeTitle(
const BookmarkNode* permanent_node) {
// The |managed_node_| can have its title updated if the user signs in or
// out, since the name of the managed domain can appear in it. The
// |supervised_node_| has a fixed title which can never be updated.
return (!bookmarks::IsDescendantOf(permanent_node, managed_node_) &&
!bookmarks::IsDescendantOf(permanent_node, supervised_node_)) ||
permanent_node == managed_node_;
}
bool ChromeBookmarkClient::CanSyncNode(const BookmarkNode* node) {
return !bookmarks::IsDescendantOf(node, managed_node_) &&
!bookmarks::IsDescendantOf(node, supervised_node_);
}
bool ChromeBookmarkClient::CanBeEditedByUser(const BookmarkNode* node) {
return !bookmarks::IsDescendantOf(node, managed_node_) &&
!bookmarks::IsDescendantOf(node, supervised_node_);
}
void ChromeBookmarkClient::SetHistoryService(HistoryService* history_service) {
DCHECK(history_service);
history_service_ = history_service;
favicon_changed_subscription_ = history_service_->AddFaviconChangedCallback(
base::Bind(&BookmarkModel::OnFaviconChanged, base::Unretained(model_)));
}
void ChromeBookmarkClient::BookmarkModelChanged() {
}
void ChromeBookmarkClient::BookmarkNodeRemoved(
BookmarkModel* model,
const BookmarkNode* parent,
int old_index,
const BookmarkNode* node,
const std::set<GURL>& removed_urls) {
if (history_service_)
history_service_->URLsNoLongerBookmarked(removed_urls);
}
void ChromeBookmarkClient::BookmarkAllUserNodesRemoved(
BookmarkModel* model,
const std::set<GURL>& removed_urls) {
if (history_service_)
history_service_->URLsNoLongerBookmarked(removed_urls);
}
void ChromeBookmarkClient::BookmarkModelLoaded(BookmarkModel* model,
bool ids_reassigned) {
// Start tracking the managed and supervised bookmarks. This will detect any
// changes that may have occurred while the initial managed and supervised
// bookmarks were being loaded on the background.
managed_bookmarks_tracker_->Init(managed_node_);
supervised_bookmarks_tracker_->Init(supervised_node_);
}
// static
bookmarks::BookmarkPermanentNodeList ChromeBookmarkClient::LoadExtraNodes(
scoped_ptr<BookmarkPermanentNode> managed_node,
scoped_ptr<base::ListValue> initial_managed_bookmarks,
scoped_ptr<BookmarkPermanentNode> supervised_node,
scoped_ptr<base::ListValue> initial_supervised_bookmarks,
int64* next_node_id) {
LoadInitialContents(
managed_node.get(), initial_managed_bookmarks.get(), next_node_id);
managed_node->SetTitle(l10n_util::GetStringUTF16(
IDS_BOOKMARK_BAR_MANAGED_FOLDER_DEFAULT_NAME));
LoadInitialContents(
supervised_node.get(), initial_supervised_bookmarks.get(), next_node_id);
supervised_node->SetTitle(l10n_util::GetStringUTF16(
IDS_BOOKMARK_BAR_SUPERVISED_FOLDER_DEFAULT_NAME));
bookmarks::BookmarkPermanentNodeList extra_nodes;
// Ownership of the managed and supervised nodes passed to the caller.
extra_nodes.push_back(managed_node.release());
extra_nodes.push_back(supervised_node.release());
return extra_nodes.Pass();
}
std::string ChromeBookmarkClient::GetManagedBookmarksDomain() {
policy::ProfilePolicyConnector* connector =
policy::ProfilePolicyConnectorFactory::GetForBrowserContext(profile_);
if (connector->IsPolicyFromCloudPolicy(policy::key::kManagedBookmarks))
return connector->GetManagementDomain();
return std::string();
}
<commit_msg>Make ChromeBookmarkClient::CanSetPermanentNodeTitle say true for the supervised node.<commit_after>// Copyright 2014 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/bookmarks/chrome_bookmark_client.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/logging.h"
#include "base/values.h"
#include "chrome/browser/favicon/favicon_service.h"
#include "chrome/browser/favicon/favicon_service_factory.h"
#include "chrome/browser/history/history_service.h"
#include "chrome/browser/policy/profile_policy_connector.h"
#include "chrome/browser/policy/profile_policy_connector_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "components/bookmarks/browser/bookmark_model.h"
#include "components/bookmarks/browser/bookmark_node.h"
#include "components/bookmarks/browser/bookmark_utils.h"
#include "components/history/core/browser/url_database.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/notification_details.h"
#include "content/public/browser/notification_source.h"
#include "content/public/browser/user_metrics.h"
#include "grit/components_strings.h"
#include "policy/policy_constants.h"
#include "ui/base/l10n/l10n_util.h"
using bookmarks::BookmarkModel;
using bookmarks::BookmarkNode;
using bookmarks::BookmarkPermanentNode;
namespace {
void RunCallbackWithImage(
const favicon_base::FaviconImageCallback& callback,
const favicon_base::FaviconRawBitmapResult& bitmap_result) {
favicon_base::FaviconImageResult result;
if (bitmap_result.is_valid()) {
result.image = gfx::Image::CreateFrom1xPNGBytes(
bitmap_result.bitmap_data->front(), bitmap_result.bitmap_data->size());
result.icon_url = bitmap_result.icon_url;
callback.Run(result);
return;
}
callback.Run(result);
}
void LoadInitialContents(BookmarkPermanentNode* node,
base::ListValue* initial_bookmarks,
int64* next_node_id) {
// Load the initial contents of the |node| now, and assign it an unused ID.
int64 id = *next_node_id;
node->set_id(id);
*next_node_id = policy::ManagedBookmarksTracker::LoadInitial(
node, initial_bookmarks, id + 1);
node->set_visible(!node->empty());
}
} // namespace
ChromeBookmarkClient::ChromeBookmarkClient(Profile* profile)
: profile_(profile),
history_service_(NULL),
model_(NULL),
managed_node_(NULL),
supervised_node_(NULL) {
}
ChromeBookmarkClient::~ChromeBookmarkClient() {
}
void ChromeBookmarkClient::Init(BookmarkModel* model) {
DCHECK(model);
DCHECK(!model_);
model_ = model;
model_->AddObserver(this);
managed_bookmarks_tracker_.reset(new policy::ManagedBookmarksTracker(
model_,
profile_->GetPrefs(),
false,
base::Bind(&ChromeBookmarkClient::GetManagedBookmarksDomain,
base::Unretained(this))));
supervised_bookmarks_tracker_.reset(new policy::ManagedBookmarksTracker(
model_,
profile_->GetPrefs(),
true,
base::Callback<std::string()>()));
}
void ChromeBookmarkClient::Shutdown() {
favicon_changed_subscription_.reset();
if (model_) {
model_->RemoveObserver(this);
model_ = NULL;
}
BookmarkClient::Shutdown();
}
bool ChromeBookmarkClient::PreferTouchIcon() {
#if !defined(OS_IOS)
return false;
#else
return true;
#endif
}
base::CancelableTaskTracker::TaskId
ChromeBookmarkClient::GetFaviconImageForPageURL(
const GURL& page_url,
favicon_base::IconType type,
const favicon_base::FaviconImageCallback& callback,
base::CancelableTaskTracker* tracker) {
FaviconService* favicon_service = FaviconServiceFactory::GetForProfile(
profile_, ServiceAccessType::EXPLICIT_ACCESS);
if (!favicon_service)
return base::CancelableTaskTracker::kBadTaskId;
if (type == favicon_base::FAVICON) {
return favicon_service->GetFaviconImageForPageURL(
page_url, callback, tracker);
} else {
return favicon_service->GetRawFaviconForPageURL(
page_url,
type,
0,
base::Bind(&RunCallbackWithImage, callback),
tracker);
}
}
bool ChromeBookmarkClient::SupportsTypedCountForNodes() {
return true;
}
void ChromeBookmarkClient::GetTypedCountForNodes(
const NodeSet& nodes,
NodeTypedCountPairs* node_typed_count_pairs) {
history::URLDatabase* url_db =
history_service_ ? history_service_->InMemoryDatabase() : NULL;
for (NodeSet::const_iterator i = nodes.begin(); i != nodes.end(); ++i) {
int typed_count = 0;
// If |url_db| is the InMemoryDatabase, it might not cache all URLRows, but
// it guarantees to contain those with |typed_count| > 0. Thus, if we cannot
// fetch the URLRow, it is safe to assume that its |typed_count| is 0.
history::URLRow url;
if (url_db && url_db->GetRowForURL((*i)->url(), &url))
typed_count = url.typed_count();
NodeTypedCountPair pair(*i, typed_count);
node_typed_count_pairs->push_back(pair);
}
}
bool ChromeBookmarkClient::IsPermanentNodeVisible(
const BookmarkPermanentNode* node) {
DCHECK(node->type() == BookmarkNode::BOOKMARK_BAR ||
node->type() == BookmarkNode::OTHER_NODE ||
node->type() == BookmarkNode::MOBILE ||
node == managed_node_ ||
node == supervised_node_);
if (node == managed_node_ || node == supervised_node_)
return false;
#if !defined(OS_IOS)
return node->type() != BookmarkNode::MOBILE;
#else
return node->type() == BookmarkNode::MOBILE;
#endif
}
void ChromeBookmarkClient::RecordAction(const base::UserMetricsAction& action) {
content::RecordAction(action);
}
bookmarks::LoadExtraCallback ChromeBookmarkClient::GetLoadExtraNodesCallback() {
// Create the managed_node_ and supervised_node_ with a temporary ID of 0 now.
// They will be populated (and assigned proper IDs) in the LoadExtraNodes
// callback.
// The ownership of managed_node_ and supervised_node_ is in limbo until
// LoadExtraNodes runs, so we leave them in the care of the closure meanwhile.
scoped_ptr<BookmarkPermanentNode> managed(new BookmarkPermanentNode(0));
managed_node_ = managed.get();
scoped_ptr<BookmarkPermanentNode> supervised(new BookmarkPermanentNode(0));
supervised_node_ = supervised.get();
return base::Bind(
&ChromeBookmarkClient::LoadExtraNodes,
base::Passed(&managed),
base::Passed(managed_bookmarks_tracker_->GetInitialManagedBookmarks()),
base::Passed(&supervised),
base::Passed(
supervised_bookmarks_tracker_->GetInitialManagedBookmarks()));
}
bool ChromeBookmarkClient::CanSetPermanentNodeTitle(
const BookmarkNode* permanent_node) {
// The |managed_node_| can have its title updated if the user signs in or
// out, since the name of the managed domain can appear in it.
// Also, both |managed_node_| and |supervised_node_| can have their title
// updated on locale changes (crbug.com/459448).
return (!bookmarks::IsDescendantOf(permanent_node, managed_node_) &&
!bookmarks::IsDescendantOf(permanent_node, supervised_node_)) ||
permanent_node == managed_node_ ||
permanent_node == supervised_node_;
}
bool ChromeBookmarkClient::CanSyncNode(const BookmarkNode* node) {
return !bookmarks::IsDescendantOf(node, managed_node_) &&
!bookmarks::IsDescendantOf(node, supervised_node_);
}
bool ChromeBookmarkClient::CanBeEditedByUser(const BookmarkNode* node) {
return !bookmarks::IsDescendantOf(node, managed_node_) &&
!bookmarks::IsDescendantOf(node, supervised_node_);
}
void ChromeBookmarkClient::SetHistoryService(HistoryService* history_service) {
DCHECK(history_service);
history_service_ = history_service;
favicon_changed_subscription_ = history_service_->AddFaviconChangedCallback(
base::Bind(&BookmarkModel::OnFaviconChanged, base::Unretained(model_)));
}
void ChromeBookmarkClient::BookmarkModelChanged() {
}
void ChromeBookmarkClient::BookmarkNodeRemoved(
BookmarkModel* model,
const BookmarkNode* parent,
int old_index,
const BookmarkNode* node,
const std::set<GURL>& removed_urls) {
if (history_service_)
history_service_->URLsNoLongerBookmarked(removed_urls);
}
void ChromeBookmarkClient::BookmarkAllUserNodesRemoved(
BookmarkModel* model,
const std::set<GURL>& removed_urls) {
if (history_service_)
history_service_->URLsNoLongerBookmarked(removed_urls);
}
void ChromeBookmarkClient::BookmarkModelLoaded(BookmarkModel* model,
bool ids_reassigned) {
// Start tracking the managed and supervised bookmarks. This will detect any
// changes that may have occurred while the initial managed and supervised
// bookmarks were being loaded on the background.
managed_bookmarks_tracker_->Init(managed_node_);
supervised_bookmarks_tracker_->Init(supervised_node_);
}
// static
bookmarks::BookmarkPermanentNodeList ChromeBookmarkClient::LoadExtraNodes(
scoped_ptr<BookmarkPermanentNode> managed_node,
scoped_ptr<base::ListValue> initial_managed_bookmarks,
scoped_ptr<BookmarkPermanentNode> supervised_node,
scoped_ptr<base::ListValue> initial_supervised_bookmarks,
int64* next_node_id) {
LoadInitialContents(
managed_node.get(), initial_managed_bookmarks.get(), next_node_id);
managed_node->SetTitle(l10n_util::GetStringUTF16(
IDS_BOOKMARK_BAR_MANAGED_FOLDER_DEFAULT_NAME));
LoadInitialContents(
supervised_node.get(), initial_supervised_bookmarks.get(), next_node_id);
supervised_node->SetTitle(l10n_util::GetStringUTF16(
IDS_BOOKMARK_BAR_SUPERVISED_FOLDER_DEFAULT_NAME));
bookmarks::BookmarkPermanentNodeList extra_nodes;
// Ownership of the managed and supervised nodes passed to the caller.
extra_nodes.push_back(managed_node.release());
extra_nodes.push_back(supervised_node.release());
return extra_nodes.Pass();
}
std::string ChromeBookmarkClient::GetManagedBookmarksDomain() {
policy::ProfilePolicyConnector* connector =
policy::ProfilePolicyConnectorFactory::GetForBrowserContext(profile_);
if (connector->IsPolicyFromCloudPolicy(policy::key::kManagedBookmarks))
return connector->GetManagementDomain();
return std::string();
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/cros/cryptohome_library.h"
#include "base/hash_tables.h"
#include "base/message_loop.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
namespace chromeos {
// This class handles the interaction with the ChromeOS cryptohome library APIs.
class CryptohomeLibraryImpl : public CryptohomeLibrary {
public:
CryptohomeLibraryImpl() {
if (CrosLibrary::Get()->EnsureLoaded())
Init();
}
virtual ~CryptohomeLibraryImpl() {}
bool CheckKey(const std::string& user_email, const std::string& passhash) {
return chromeos::CryptohomeCheckKey(user_email.c_str(), passhash.c_str());
}
bool AsyncCheckKey(const std::string& user_email,
const std::string& passhash,
Delegate* d) {
return CacheCallback(
chromeos::CryptohomeAsyncCheckKey(user_email.c_str(), passhash.c_str()),
d,
"Couldn't initiate async check of user's key.");
}
bool MigrateKey(const std::string& user_email,
const std::string& old_hash,
const std::string& new_hash) {
return chromeos::CryptohomeMigrateKey(user_email.c_str(),
old_hash.c_str(),
new_hash.c_str());
}
bool AsyncMigrateKey(const std::string& user_email,
const std::string& old_hash,
const std::string& new_hash,
Delegate* d) {
return CacheCallback(
chromeos::CryptohomeAsyncMigrateKey(user_email.c_str(),
old_hash.c_str(),
new_hash.c_str()),
d,
"Couldn't initiate aync migration of user's key");
}
bool Mount(const std::string& user_email,
const std::string& passhash,
int* error_code) {
return chromeos::CryptohomeMountAllowFail(user_email.c_str(),
passhash.c_str(),
error_code);
}
bool AsyncMount(const std::string& user_email,
const std::string& passhash,
Delegate* d) {
return CacheCallback(
chromeos::CryptohomeAsyncMount(user_email.c_str(), passhash.c_str()),
d,
"Couldn't initiate async mount of cryptohome.");
}
bool MountForBwsi(int* error_code) {
return chromeos::CryptohomeMountGuest(error_code);
}
bool AsyncMountForBwsi(Delegate* d) {
return CacheCallback(chromeos::CryptohomeAsyncMountGuest(),
d,
"Couldn't initiate async mount of cryptohome.");
}
bool Remove(const std::string& user_email) {
return chromeos::CryptohomeRemove(user_email.c_str());
}
bool AsyncRemove(const std::string& user_email, Delegate* d) {
return CacheCallback(
chromeos::CryptohomeAsyncRemove(user_email.c_str()),
d,
"Couldn't initiate async removal of cryptohome.");
}
bool IsMounted() {
return chromeos::CryptohomeIsMounted();
}
CryptohomeBlob GetSystemSalt() {
return chromeos::CryptohomeGetSystemSalt();
}
private:
static void Handler(const chromeos::CryptohomeAsyncCallStatus& event,
void* cryptohome_library) {
CryptohomeLibraryImpl* library =
reinterpret_cast<CryptohomeLibraryImpl*>(cryptohome_library);
library->Dispatch(event);
}
void Init() {
cryptohome_connection_ = chromeos::CryptohomeMonitorSession(&Handler, this);
}
void Dispatch(const chromeos::CryptohomeAsyncCallStatus& event) {
callback_map_[event.async_id]->OnComplete(event.return_status,
event.return_code);
callback_map_[event.async_id] = NULL;
}
bool CacheCallback(int async_id,
Delegate* d,
const char* error) {
if (async_id == 0) {
LOG(ERROR) << error;
return false;
}
callback_map_[async_id] = d;
return true;
}
typedef base::hash_map<int, Delegate*> CallbackMap;
mutable CallbackMap callback_map_;
void* cryptohome_connection_;
DISALLOW_COPY_AND_ASSIGN(CryptohomeLibraryImpl);
};
class CryptohomeLibraryStubImpl : public CryptohomeLibrary {
public:
CryptohomeLibraryStubImpl() {}
virtual ~CryptohomeLibraryStubImpl() {}
bool CheckKey(const std::string& user_email, const std::string& passhash) {
return true;
}
bool AsyncCheckKey(const std::string& user_email,
const std::string& passhash,
Delegate* callback) {
ChromeThread::PostTask(
ChromeThread::UI, FROM_HERE,
NewRunnableFunction(&DoStubCallback, callback));
return true;
}
bool MigrateKey(const std::string& user_email,
const std::string& old_hash,
const std::string& new_hash) {
return true;
}
bool AsyncMigrateKey(const std::string& user_email,
const std::string& old_hash,
const std::string& new_hash,
Delegate* callback) {
ChromeThread::PostTask(
ChromeThread::UI, FROM_HERE,
NewRunnableFunction(&DoStubCallback, callback));
return true;
}
bool Remove(const std::string& user_email) {
return true;
}
bool AsyncRemove(const std::string& user_email, Delegate* callback) {
ChromeThread::PostTask(
ChromeThread::UI, FROM_HERE,
NewRunnableFunction(&DoStubCallback, callback));
return true;
}
bool Mount(const std::string& user_email,
const std::string& passhash,
int* error_code) {
return true;
}
bool AsyncMount(const std::string& user_email,
const std::string& passhash,
Delegate* callback) {
ChromeThread::PostTask(
ChromeThread::UI, FROM_HERE,
NewRunnableFunction(&DoStubCallback, callback));
return true;
}
bool MountForBwsi(int* error_code) {
return true;
}
bool AsyncMountForBwsi(Delegate* callback) {
ChromeThread::PostTask(
ChromeThread::UI, FROM_HERE,
NewRunnableFunction(&DoStubCallback, callback));
return true;
}
bool IsMounted() {
return true;
}
CryptohomeBlob GetSystemSalt() {
CryptohomeBlob salt = CryptohomeBlob();
salt.push_back(0);
salt.push_back(0);
return salt;
}
private:
static void DoStubCallback(Delegate* callback) {
callback->OnComplete(true, kCryptohomeMountErrorNone);
}
DISALLOW_COPY_AND_ASSIGN(CryptohomeLibraryStubImpl);
};
// static
CryptohomeLibrary* CryptohomeLibrary::GetImpl(bool stub) {
if (stub)
return new CryptohomeLibraryStubImpl();
else
return new CryptohomeLibraryImpl();
}
} // namespace chromeos
<commit_msg>[Chrome OS] Update to use new CryptohomeAsyncMount function signature<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/cros/cryptohome_library.h"
#include "base/hash_tables.h"
#include "base/message_loop.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/chromeos/cros/cros_library.h"
namespace chromeos {
// This class handles the interaction with the ChromeOS cryptohome library APIs.
class CryptohomeLibraryImpl : public CryptohomeLibrary {
public:
CryptohomeLibraryImpl() {
if (CrosLibrary::Get()->EnsureLoaded())
Init();
}
virtual ~CryptohomeLibraryImpl() {}
bool CheckKey(const std::string& user_email, const std::string& passhash) {
return chromeos::CryptohomeCheckKey(user_email.c_str(), passhash.c_str());
}
bool AsyncCheckKey(const std::string& user_email,
const std::string& passhash,
Delegate* d) {
return CacheCallback(
chromeos::CryptohomeAsyncCheckKey(user_email.c_str(), passhash.c_str()),
d,
"Couldn't initiate async check of user's key.");
}
bool MigrateKey(const std::string& user_email,
const std::string& old_hash,
const std::string& new_hash) {
return chromeos::CryptohomeMigrateKey(user_email.c_str(),
old_hash.c_str(),
new_hash.c_str());
}
bool AsyncMigrateKey(const std::string& user_email,
const std::string& old_hash,
const std::string& new_hash,
Delegate* d) {
return CacheCallback(
chromeos::CryptohomeAsyncMigrateKey(user_email.c_str(),
old_hash.c_str(),
new_hash.c_str()),
d,
"Couldn't initiate aync migration of user's key");
}
bool Mount(const std::string& user_email,
const std::string& passhash,
int* error_code) {
return chromeos::CryptohomeMountAllowFail(user_email.c_str(),
passhash.c_str(),
error_code);
}
bool AsyncMount(const std::string& user_email,
const std::string& passhash,
Delegate* d) {
return CacheCallback(
chromeos::CryptohomeAsyncMount(user_email.c_str(),
passhash.c_str(),
true,
"",
std::vector<std::string>()),
d,
"Couldn't initiate async mount of cryptohome.");
}
bool MountForBwsi(int* error_code) {
return chromeos::CryptohomeMountGuest(error_code);
}
bool AsyncMountForBwsi(Delegate* d) {
return CacheCallback(chromeos::CryptohomeAsyncMountGuest(),
d,
"Couldn't initiate async mount of cryptohome.");
}
bool Remove(const std::string& user_email) {
return chromeos::CryptohomeRemove(user_email.c_str());
}
bool AsyncRemove(const std::string& user_email, Delegate* d) {
return CacheCallback(
chromeos::CryptohomeAsyncRemove(user_email.c_str()),
d,
"Couldn't initiate async removal of cryptohome.");
}
bool IsMounted() {
return chromeos::CryptohomeIsMounted();
}
CryptohomeBlob GetSystemSalt() {
return chromeos::CryptohomeGetSystemSalt();
}
private:
static void Handler(const chromeos::CryptohomeAsyncCallStatus& event,
void* cryptohome_library) {
CryptohomeLibraryImpl* library =
reinterpret_cast<CryptohomeLibraryImpl*>(cryptohome_library);
library->Dispatch(event);
}
void Init() {
cryptohome_connection_ = chromeos::CryptohomeMonitorSession(&Handler, this);
}
void Dispatch(const chromeos::CryptohomeAsyncCallStatus& event) {
callback_map_[event.async_id]->OnComplete(event.return_status,
event.return_code);
callback_map_[event.async_id] = NULL;
}
bool CacheCallback(int async_id,
Delegate* d,
const char* error) {
if (async_id == 0) {
LOG(ERROR) << error;
return false;
}
callback_map_[async_id] = d;
return true;
}
typedef base::hash_map<int, Delegate*> CallbackMap;
mutable CallbackMap callback_map_;
void* cryptohome_connection_;
DISALLOW_COPY_AND_ASSIGN(CryptohomeLibraryImpl);
};
class CryptohomeLibraryStubImpl : public CryptohomeLibrary {
public:
CryptohomeLibraryStubImpl() {}
virtual ~CryptohomeLibraryStubImpl() {}
bool CheckKey(const std::string& user_email, const std::string& passhash) {
return true;
}
bool AsyncCheckKey(const std::string& user_email,
const std::string& passhash,
Delegate* callback) {
ChromeThread::PostTask(
ChromeThread::UI, FROM_HERE,
NewRunnableFunction(&DoStubCallback, callback));
return true;
}
bool MigrateKey(const std::string& user_email,
const std::string& old_hash,
const std::string& new_hash) {
return true;
}
bool AsyncMigrateKey(const std::string& user_email,
const std::string& old_hash,
const std::string& new_hash,
Delegate* callback) {
ChromeThread::PostTask(
ChromeThread::UI, FROM_HERE,
NewRunnableFunction(&DoStubCallback, callback));
return true;
}
bool Remove(const std::string& user_email) {
return true;
}
bool AsyncRemove(const std::string& user_email, Delegate* callback) {
ChromeThread::PostTask(
ChromeThread::UI, FROM_HERE,
NewRunnableFunction(&DoStubCallback, callback));
return true;
}
bool Mount(const std::string& user_email,
const std::string& passhash,
int* error_code) {
return true;
}
bool AsyncMount(const std::string& user_email,
const std::string& passhash,
Delegate* callback) {
ChromeThread::PostTask(
ChromeThread::UI, FROM_HERE,
NewRunnableFunction(&DoStubCallback, callback));
return true;
}
bool MountForBwsi(int* error_code) {
return true;
}
bool AsyncMountForBwsi(Delegate* callback) {
ChromeThread::PostTask(
ChromeThread::UI, FROM_HERE,
NewRunnableFunction(&DoStubCallback, callback));
return true;
}
bool IsMounted() {
return true;
}
CryptohomeBlob GetSystemSalt() {
CryptohomeBlob salt = CryptohomeBlob();
salt.push_back(0);
salt.push_back(0);
return salt;
}
private:
static void DoStubCallback(Delegate* callback) {
callback->OnComplete(true, kCryptohomeMountErrorNone);
}
DISALLOW_COPY_AND_ASSIGN(CryptohomeLibraryStubImpl);
};
// static
CryptohomeLibrary* CryptohomeLibrary::GetImpl(bool stub) {
if (stub)
return new CryptohomeLibraryStubImpl();
else
return new CryptohomeLibraryImpl();
}
} // namespace chromeos
<|endoftext|>
|
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/login/oobe_progress_bar.h"
#include "base/logging.h"
#include "base/utf_string_conversions.h"
#include "grit/theme_resources.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/canvas_skia.h"
namespace chromeos {
// static
SkBitmap* OobeProgressBar::dot_current_ = NULL;
SkBitmap* OobeProgressBar::dot_empty_ = NULL;
SkBitmap* OobeProgressBar::dot_filled_ = NULL;
SkBitmap* OobeProgressBar::line_ = NULL;
SkBitmap* OobeProgressBar::line_left_ = NULL;
SkBitmap* OobeProgressBar::line_right_ = NULL;
static const SkColor kCurrentTextColor = SkColorSetRGB(255, 255, 255);
static const SkColor kEmptyTextColor = SkColorSetRGB(112, 115, 118);
static const SkColor kFilledTextColor = SkColorSetRGB(112, 115, 118);
static const int kTextPadding = 5;
OobeProgressBar::OobeProgressBar(const std::vector<int>& steps)
: steps_(steps), progress_(0) {
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
font_ = rb.GetFont(ResourceBundle::BaseFont);
InitClass();
}
OobeProgressBar::~OobeProgressBar() {}
// static
void OobeProgressBar::InitClass() {
static bool initialized = false;
if (!initialized) {
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
// Load images.
dot_current_ = rb.GetBitmapNamed(IDR_OOBE_PROGRESS_DOT_CURRENT);
dot_empty_ = rb.GetBitmapNamed(IDR_OOBE_PROGRESS_DOT_EMPTY);
dot_filled_ = rb.GetBitmapNamed(IDR_OOBE_PROGRESS_DOT_FILLED);
line_ = rb.GetBitmapNamed(IDR_OOBE_PROGRESS_LINE);
line_left_ = rb.GetBitmapNamed(IDR_OOBE_PROGRESS_LINE_LEFT);
line_right_ = rb.GetBitmapNamed(IDR_OOBE_PROGRESS_LINE_RIGHT);
initialized = true;
}
}
void OobeProgressBar::OnPaint(gfx::Canvas* canvas) {
gfx::Rect bounds = GetContentsBounds();
int x = bounds.x();
int y = bounds.y();
double step_width = static_cast<double>(bounds.width()) / steps_.size();
for (size_t i = 0; i < steps_.size(); ++i) {
SkBitmap* dot;
SkColor color;
SkBitmap* line_before = line_;
SkBitmap* line_after = line_;
if (i < progress_) {
dot = dot_filled_;
color = kFilledTextColor;
} else if (i == progress_) {
dot = dot_current_;
color = kCurrentTextColor;
line_before = line_left_;
line_after = line_right_;
} else {
dot = dot_empty_;
color = kEmptyTextColor;
}
// x coordinate for next step.
int next_x = static_cast<int>((i + 1) * step_width);
// Offset of line origin from dot origin.
int line_offset_y = (dot->height() - line_->height()) / 2;
// Current x for painting.
int ix = x;
int line_width = ((next_x - x) -
(line_before->width() + dot->width() + line_after->width())) / 2;
if (i > 0) {
canvas->TileImageInt(*line_, ix, y + line_offset_y,
line_width, line_->height());
}
ix += line_width;
if (i > 0) {
canvas->DrawBitmapInt(*line_before, ix, y + line_offset_y);
}
ix += line_before->width();
canvas->DrawBitmapInt(*dot, ix, y);
ix += dot->width();
if (i != steps_.size() - 1)
canvas->DrawBitmapInt(*line_after, ix, y + line_offset_y);
ix += line_after->width();
if (i != steps_.size() - 1) {
canvas->TileImageInt(*line_, ix, y + line_offset_y,
next_x - ix, line_->height());
}
string16 str = l10n_util::GetStringUTF16(steps_[i]);
canvas->DrawStringInt(str, font_, color,
x + kTextPadding, y + dot->height() + kTextPadding,
(next_x - x - 2 * kTextPadding),
(bounds.height() - dot->height() - 2 * kTextPadding),
gfx::Canvas::MULTI_LINE | gfx::Canvas::TEXT_ALIGN_CENTER |
gfx::Canvas::TEXT_VALIGN_TOP);
x = next_x;
}
}
void OobeProgressBar::OnLocaleChanged() {
font_ = ResourceBundle::GetSharedInstance().GetFont(ResourceBundle::BaseFont);
SchedulePaint();
}
void OobeProgressBar::SetStep(int step) {
for (size_t i = 0; i < steps_.size(); ++i) {
if (steps_[i] == step) {
progress_ = i;
SchedulePaint();
return;
}
}
NOTREACHED();
}
} // namespace chromeos
<commit_msg>Add NO_ELLIPSIS because TEXT_ALIGN_CENTER doesn't work without it<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/login/oobe_progress_bar.h"
#include "base/logging.h"
#include "base/utf_string_conversions.h"
#include "grit/theme_resources.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/canvas_skia.h"
namespace chromeos {
// static
SkBitmap* OobeProgressBar::dot_current_ = NULL;
SkBitmap* OobeProgressBar::dot_empty_ = NULL;
SkBitmap* OobeProgressBar::dot_filled_ = NULL;
SkBitmap* OobeProgressBar::line_ = NULL;
SkBitmap* OobeProgressBar::line_left_ = NULL;
SkBitmap* OobeProgressBar::line_right_ = NULL;
static const SkColor kCurrentTextColor = SkColorSetRGB(255, 255, 255);
static const SkColor kEmptyTextColor = SkColorSetRGB(112, 115, 118);
static const SkColor kFilledTextColor = SkColorSetRGB(112, 115, 118);
static const int kTextPadding = 5;
OobeProgressBar::OobeProgressBar(const std::vector<int>& steps)
: steps_(steps), progress_(0) {
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
font_ = rb.GetFont(ResourceBundle::BaseFont);
InitClass();
}
OobeProgressBar::~OobeProgressBar() {}
// static
void OobeProgressBar::InitClass() {
static bool initialized = false;
if (!initialized) {
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
// Load images.
dot_current_ = rb.GetBitmapNamed(IDR_OOBE_PROGRESS_DOT_CURRENT);
dot_empty_ = rb.GetBitmapNamed(IDR_OOBE_PROGRESS_DOT_EMPTY);
dot_filled_ = rb.GetBitmapNamed(IDR_OOBE_PROGRESS_DOT_FILLED);
line_ = rb.GetBitmapNamed(IDR_OOBE_PROGRESS_LINE);
line_left_ = rb.GetBitmapNamed(IDR_OOBE_PROGRESS_LINE_LEFT);
line_right_ = rb.GetBitmapNamed(IDR_OOBE_PROGRESS_LINE_RIGHT);
initialized = true;
}
}
void OobeProgressBar::OnPaint(gfx::Canvas* canvas) {
gfx::Rect bounds = GetContentsBounds();
int x = bounds.x();
int y = bounds.y();
double step_width = static_cast<double>(bounds.width()) / steps_.size();
for (size_t i = 0; i < steps_.size(); ++i) {
SkBitmap* dot;
SkColor color;
SkBitmap* line_before = line_;
SkBitmap* line_after = line_;
if (i < progress_) {
dot = dot_filled_;
color = kFilledTextColor;
} else if (i == progress_) {
dot = dot_current_;
color = kCurrentTextColor;
line_before = line_left_;
line_after = line_right_;
} else {
dot = dot_empty_;
color = kEmptyTextColor;
}
// x coordinate for next step.
int next_x = static_cast<int>((i + 1) * step_width);
// Offset of line origin from dot origin.
int line_offset_y = (dot->height() - line_->height()) / 2;
// Current x for painting.
int ix = x;
int line_width = ((next_x - x) -
(line_before->width() + dot->width() + line_after->width())) / 2;
if (i > 0) {
canvas->TileImageInt(*line_, ix, y + line_offset_y,
line_width, line_->height());
}
ix += line_width;
if (i > 0) {
canvas->DrawBitmapInt(*line_before, ix, y + line_offset_y);
}
ix += line_before->width();
canvas->DrawBitmapInt(*dot, ix, y);
ix += dot->width();
if (i != steps_.size() - 1)
canvas->DrawBitmapInt(*line_after, ix, y + line_offset_y);
ix += line_after->width();
if (i != steps_.size() - 1) {
canvas->TileImageInt(*line_, ix, y + line_offset_y,
next_x - ix, line_->height());
}
string16 str = l10n_util::GetStringUTF16(steps_[i]);
canvas->DrawStringInt(str, font_, color,
x + kTextPadding, y + dot->height() + kTextPadding,
(next_x - x - 2 * kTextPadding),
(bounds.height() - dot->height() - 2 * kTextPadding),
gfx::Canvas::MULTI_LINE | gfx::Canvas::TEXT_ALIGN_CENTER |
gfx::Canvas::TEXT_VALIGN_TOP | gfx::Canvas::NO_ELLIPSIS);
x = next_x;
}
}
void OobeProgressBar::OnLocaleChanged() {
font_ = ResourceBundle::GetSharedInstance().GetFont(ResourceBundle::BaseFont);
SchedulePaint();
}
void OobeProgressBar::SetStep(int step) {
for (size_t i = 0; i < steps_.size(); ++i) {
if (steps_[i] == step) {
progress_ = i;
SchedulePaint();
return;
}
}
NOTREACHED();
}
} // namespace chromeos
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/notifications/desktop_notification_service.h"
#include "chrome/browser/profile.h"
// Flaky, http://crbug.com/42314.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FLAKY_Notifications) {
#if defined(OS_LINUX) && defined(TOOLKIT_VIEWS)
// Notifications not supported on linux/views yet.
#else
ASSERT_TRUE(RunExtensionTest("notifications/has_not_permission")) << message_;
ASSERT_TRUE(RunExtensionTest("notifications/has_permission_manifest"))
<< message_;
browser()->profile()->GetDesktopNotificationService()
->GrantPermission(GURL(
"chrome-extension://peoadpeiejnhkmpaakpnompolbglelel"));
ASSERT_TRUE(RunExtensionTest("notifications/has_permission_prefs"))
<< message_;
#endif
}
<commit_msg>Disable a flaky test that seems to completely blow up with some frequency on the mac bots and seems to cause a ripple in hosing the bot in general. BUG=42314,50060 TEST=Mac test bots stay greener Review URL: http://codereview.chromium.org/2834069<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/notifications/desktop_notification_service.h"
#include "chrome/browser/profile.h"
// Fails and hoses bot, http://crbug.com/50060.
// Flaky, http://crbug.com/42314.
#if defined(OS_MACOSX)
#define MAYBE_Notifications DISABLED_Notifications
#else
#define MAYBE_Notifications FLAKY_Notifications
#endif
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Notifications) {
#if defined(OS_LINUX) && defined(TOOLKIT_VIEWS)
// Notifications not supported on linux/views yet.
#else
ASSERT_TRUE(RunExtensionTest("notifications/has_not_permission")) << message_;
ASSERT_TRUE(RunExtensionTest("notifications/has_permission_manifest"))
<< message_;
browser()->profile()->GetDesktopNotificationService()
->GrantPermission(GURL(
"chrome-extension://peoadpeiejnhkmpaakpnompolbglelel"));
ASSERT_TRUE(RunExtensionTest("notifications/has_permission_prefs"))
<< message_;
#endif
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/search_engines/search_terms_data.h"
#include "base/logging.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/google/google_url_tracker.h"
#include "googleurl/src/gurl.h"
#if defined(OS_WIN)
#include "chrome/browser/rlz/rlz.h"
#endif
SearchTermsData::SearchTermsData() {
}
SearchTermsData::~SearchTermsData() {
}
std::string SearchTermsData::GoogleBaseSuggestURLValue() const {
// The suggest base URL we want at the end is something like
// "http://clients1.google.TLD/complete/". The key bit we want from the
// original Google base URL is the TLD.
// Start with the Google base URL.
const GURL base_url(GoogleBaseURLValue());
DCHECK(base_url.is_valid());
// Change "www." to "clients1." in the hostname. If no "www." was found, just
// prepend "clients1.".
const std::string base_host(base_url.host());
GURL::Replacements repl;
const std::string suggest_host("clients1." +
(base_host.compare(0, 4, "www.") ? base_host : base_host.substr(4)));
repl.SetHostStr(suggest_host);
// Replace any existing path with "/complete/".
static const std::string suggest_path("/complete/");
repl.SetPathStr(suggest_path);
// Clear the query and ref.
repl.ClearQuery();
repl.ClearRef();
return base_url.ReplaceComponents(repl).spec();
}
// static
std::string* UIThreadSearchTermsData::google_base_url_ = NULL;
UIThreadSearchTermsData::UIThreadSearchTermsData() {
// GoogleURLTracker::GoogleURL() DCHECKs this also, but adding it here helps
// us catch bad behavior at a more common place in this code.
DCHECK(!ChromeThread::IsWellKnownThread(ChromeThread::UI) ||
ChromeThread::CurrentlyOn(ChromeThread::UI));
}
std::string UIThreadSearchTermsData::GoogleBaseURLValue() const {
DCHECK(!ChromeThread::IsWellKnownThread(ChromeThread::UI) ||
ChromeThread::CurrentlyOn(ChromeThread::UI));
return google_base_url_ ?
(*google_base_url_) : GoogleURLTracker::GoogleURL().spec();
}
std::string UIThreadSearchTermsData::GetApplicationLocale() const {
DCHECK(!ChromeThread::IsWellKnownThread(ChromeThread::UI) ||
ChromeThread::CurrentlyOn(ChromeThread::UI));
return g_browser_process->GetApplicationLocale();
}
#if defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD)
std::wstring UIThreadSearchTermsData::GetRlzParameterValue() const {
DCHECK(!ChromeThread::IsWellKnownThread(ChromeThread::UI) ||
ChromeThread::CurrentlyOn(ChromeThread::UI));
std::wstring rlz_string;
RLZTracker::GetAccessPointRlz(rlz_lib::CHROME_OMNIBOX, &rlz_string);
return rlz_string;
}
#endif
// static
void UIThreadSearchTermsData::SetGoogleBaseURL(std::string* google_base_url) {
delete google_base_url_;
google_base_url_ = google_base_url;
}
<commit_msg>Do not include RLZ parameters in search requests for organic installs.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/search_engines/search_terms_data.h"
#include "base/logging.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/google/google_url_tracker.h"
#include "googleurl/src/gurl.h"
#if defined(OS_WIN)
#include "chrome/browser/rlz/rlz.h"
#endif
SearchTermsData::SearchTermsData() {
}
SearchTermsData::~SearchTermsData() {
}
std::string SearchTermsData::GoogleBaseSuggestURLValue() const {
// The suggest base URL we want at the end is something like
// "http://clients1.google.TLD/complete/". The key bit we want from the
// original Google base URL is the TLD.
// Start with the Google base URL.
const GURL base_url(GoogleBaseURLValue());
DCHECK(base_url.is_valid());
// Change "www." to "clients1." in the hostname. If no "www." was found, just
// prepend "clients1.".
const std::string base_host(base_url.host());
GURL::Replacements repl;
const std::string suggest_host("clients1." +
(base_host.compare(0, 4, "www.") ? base_host : base_host.substr(4)));
repl.SetHostStr(suggest_host);
// Replace any existing path with "/complete/".
static const std::string suggest_path("/complete/");
repl.SetPathStr(suggest_path);
// Clear the query and ref.
repl.ClearQuery();
repl.ClearRef();
return base_url.ReplaceComponents(repl).spec();
}
// static
std::string* UIThreadSearchTermsData::google_base_url_ = NULL;
UIThreadSearchTermsData::UIThreadSearchTermsData() {
// GoogleURLTracker::GoogleURL() DCHECKs this also, but adding it here helps
// us catch bad behavior at a more common place in this code.
DCHECK(!ChromeThread::IsWellKnownThread(ChromeThread::UI) ||
ChromeThread::CurrentlyOn(ChromeThread::UI));
}
std::string UIThreadSearchTermsData::GoogleBaseURLValue() const {
DCHECK(!ChromeThread::IsWellKnownThread(ChromeThread::UI) ||
ChromeThread::CurrentlyOn(ChromeThread::UI));
return google_base_url_ ?
(*google_base_url_) : GoogleURLTracker::GoogleURL().spec();
}
std::string UIThreadSearchTermsData::GetApplicationLocale() const {
DCHECK(!ChromeThread::IsWellKnownThread(ChromeThread::UI) ||
ChromeThread::CurrentlyOn(ChromeThread::UI));
return g_browser_process->GetApplicationLocale();
}
#if defined(OS_WIN) && defined(GOOGLE_CHROME_BUILD)
std::wstring UIThreadSearchTermsData::GetRlzParameterValue() const {
DCHECK(!ChromeThread::IsWellKnownThread(ChromeThread::UI) ||
ChromeThread::CurrentlyOn(ChromeThread::UI));
std::wstring rlz_string;
// For organic brandcodes do not use rlz at all. Empty brandcode usually
// means a chromium install. This is ok.
std::wstring brand;
if (GoogleUpdateSettings::GetBrand(&brand) && !brand.empty() &&
!GoogleUpdateSettings::IsOrganic(brand))
RLZTracker::GetAccessPointRlz(rlz_lib::CHROME_OMNIBOX, &rlz_string);
return rlz_string;
}
#endif
// static
void UIThreadSearchTermsData::SetGoogleBaseURL(std::string* google_base_url) {
delete google_base_url_;
google_base_url_ = google_base_url;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/logging.h"
#include "base/task.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/sync/glue/data_type_manager_impl.h"
static const int kStartOrderStart = -1;
namespace {
static const syncable::ModelType kStartOrder[] = {
syncable::BOOKMARKS,
syncable::PREFERENCES
};
} // namespace
namespace browser_sync {
DataTypeManagerImpl::DataTypeManagerImpl(
const DataTypeController::TypeMap& controllers)
: controllers_(controllers),
state_(DataTypeManager::STOPPED),
current_type_(kStartOrderStart) {
DCHECK(arraysize(kStartOrder) > 0);
// Ensure all data type controllers are stopped.
for (DataTypeController::TypeMap::const_iterator it = controllers_.begin();
it != controllers_.end(); ++it) {
DCHECK_EQ(DataTypeController::NOT_RUNNING, (*it).second->state());
}
}
void DataTypeManagerImpl::Start(StartCallback* start_callback) {
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
if (state_ != STOPPED) {
start_callback->Run(BUSY);
delete start_callback;
return;
}
state_ = STARTING;
start_callback_.reset(start_callback);
current_type_ = kStartOrderStart;
StartNextType();
}
void DataTypeManagerImpl::StartNextType() {
// Ensure that the current type has indeed started.
DCHECK(current_type_ == kStartOrderStart ||
controllers_[kStartOrder[current_type_]]->state() ==
DataTypeController::RUNNING);
// Find the next startable type.
while (current_type_ < static_cast<int>(arraysize(kStartOrder)) - 1) {
current_type_++;
syncable::ModelType type = kStartOrder[current_type_];
if (IsEnabled(type)) {
LOG(INFO) << "Starting " << controllers_[type]->name();
controllers_[type]->Start(
true,
NewCallback(this, &DataTypeManagerImpl::TypeStartCallback));
return;
}
}
// No more startable types found, we must be done.
DCHECK_EQ(state_, STARTING);
state_ = STARTED;
start_callback_->Run(OK);
start_callback_.reset();
}
void DataTypeManagerImpl::TypeStartCallback(
DataTypeController::StartResult result) {
// When the data type controller invokes this callback, it must be
// on the UI thread.
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
// If we reach this callback while stopping, this means that the
// current data type was stopped while still starting up. Now that
// the data type is aborted, we can finish stop.
if (state_ == STOPPING) {
FinishStop();
start_callback_->Run(DataTypeManager::ABORTED);
start_callback_.reset();
return;
}
// If the type started normally, continue to the next type.
syncable::ModelType type = kStartOrder[current_type_];
if (result == DataTypeController::OK ||
result == DataTypeController::OK_FIRST_RUN) {
LOG(INFO) << "Started " << controllers_[type]->name();
StartNextType();
return;
}
// Any other result is a fatal error. Shut down any types we've
// managed to start up to this point and pass the result to the
// callback.
LOG(INFO) << "Failed " << controllers_[type]->name();
FinishStop();
StartResult start_result;
switch(result) {
case DataTypeController::ABORTED:
start_result = DataTypeManager::ABORTED;
break;
case DataTypeController::ASSOCIATION_FAILED:
start_result = DataTypeManager::ASSOCIATION_FAILED;
break;
default:
NOTREACHED();
break;
}
start_callback_->Run(start_result);
start_callback_.reset();
}
void DataTypeManagerImpl::Stop() {
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
if (state_ == STOPPED)
return;
// If we are currently starting, then the current type is in a
// partially started state. Abort the startup of the current type
// and continue shutdown when the abort completes.
if (state_ == STARTING) {
state_ = STOPPING;
syncable::ModelType type = kStartOrder[current_type_];
controllers_[type]->Stop();
return;
}
state_ = STOPPING;
FinishStop();
}
void DataTypeManagerImpl::FinishStop() {
DCHECK(state_== STARTING || state_ == STOPPING);
// Simply call the Stop() method on all running data types.
for (unsigned int i = 0; i < arraysize(kStartOrder); ++i) {
syncable::ModelType type = kStartOrder[i];
if (IsRegistered(type) &&
controllers_[type]->state() == DataTypeController::RUNNING) {
controllers_[type]->Stop();
LOG(INFO) << "Stopped " << controllers_[type]->name();
}
}
state_ = STOPPED;
}
bool DataTypeManagerImpl::IsRegistered(syncable::ModelType type) {
return controllers_.count(type) == 1;
}
bool DataTypeManagerImpl::IsEnabled(syncable::ModelType type) {
return IsRegistered(type) && controllers_[type]->enabled();
}
} // namespace browser_sync
<commit_msg>Fix mac build bustage<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/logging.h"
#include "base/task.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/sync/glue/data_type_manager_impl.h"
static const int kStartOrderStart = -1;
namespace {
static const syncable::ModelType kStartOrder[] = {
syncable::BOOKMARKS,
syncable::PREFERENCES
};
} // namespace
namespace browser_sync {
DataTypeManagerImpl::DataTypeManagerImpl(
const DataTypeController::TypeMap& controllers)
: controllers_(controllers),
state_(DataTypeManager::STOPPED),
current_type_(kStartOrderStart) {
DCHECK(arraysize(kStartOrder) > 0);
// Ensure all data type controllers are stopped.
for (DataTypeController::TypeMap::const_iterator it = controllers_.begin();
it != controllers_.end(); ++it) {
DCHECK_EQ(DataTypeController::NOT_RUNNING, (*it).second->state());
}
}
void DataTypeManagerImpl::Start(StartCallback* start_callback) {
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
if (state_ != STOPPED) {
start_callback->Run(BUSY);
delete start_callback;
return;
}
state_ = STARTING;
start_callback_.reset(start_callback);
current_type_ = kStartOrderStart;
StartNextType();
}
void DataTypeManagerImpl::StartNextType() {
// Ensure that the current type has indeed started.
DCHECK(current_type_ == kStartOrderStart ||
controllers_[kStartOrder[current_type_]]->state() ==
DataTypeController::RUNNING);
// Find the next startable type.
while (current_type_ < static_cast<int>(arraysize(kStartOrder)) - 1) {
current_type_++;
syncable::ModelType type = kStartOrder[current_type_];
if (IsEnabled(type)) {
LOG(INFO) << "Starting " << controllers_[type]->name();
controllers_[type]->Start(
true,
NewCallback(this, &DataTypeManagerImpl::TypeStartCallback));
return;
}
}
// No more startable types found, we must be done.
DCHECK_EQ(state_, STARTING);
state_ = STARTED;
start_callback_->Run(OK);
start_callback_.reset();
}
void DataTypeManagerImpl::TypeStartCallback(
DataTypeController::StartResult result) {
// When the data type controller invokes this callback, it must be
// on the UI thread.
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
// If we reach this callback while stopping, this means that the
// current data type was stopped while still starting up. Now that
// the data type is aborted, we can finish stop.
if (state_ == STOPPING) {
FinishStop();
start_callback_->Run(DataTypeManager::ABORTED);
start_callback_.reset();
return;
}
// If the type started normally, continue to the next type.
syncable::ModelType type = kStartOrder[current_type_];
if (result == DataTypeController::OK ||
result == DataTypeController::OK_FIRST_RUN) {
LOG(INFO) << "Started " << controllers_[type]->name();
StartNextType();
return;
}
// Any other result is a fatal error. Shut down any types we've
// managed to start up to this point and pass the result to the
// callback.
LOG(INFO) << "Failed " << controllers_[type]->name();
FinishStop();
StartResult start_result = DataTypeManager::ABORTED;
switch(result) {
case DataTypeController::ABORTED:
start_result = DataTypeManager::ABORTED;
break;
case DataTypeController::ASSOCIATION_FAILED:
start_result = DataTypeManager::ASSOCIATION_FAILED;
break;
default:
NOTREACHED();
break;
}
start_callback_->Run(start_result);
start_callback_.reset();
}
void DataTypeManagerImpl::Stop() {
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
if (state_ == STOPPED)
return;
// If we are currently starting, then the current type is in a
// partially started state. Abort the startup of the current type
// and continue shutdown when the abort completes.
if (state_ == STARTING) {
state_ = STOPPING;
syncable::ModelType type = kStartOrder[current_type_];
controllers_[type]->Stop();
return;
}
state_ = STOPPING;
FinishStop();
}
void DataTypeManagerImpl::FinishStop() {
DCHECK(state_== STARTING || state_ == STOPPING);
// Simply call the Stop() method on all running data types.
for (unsigned int i = 0; i < arraysize(kStartOrder); ++i) {
syncable::ModelType type = kStartOrder[i];
if (IsRegistered(type) &&
controllers_[type]->state() == DataTypeController::RUNNING) {
controllers_[type]->Stop();
LOG(INFO) << "Stopped " << controllers_[type]->name();
}
}
state_ = STOPPED;
}
bool DataTypeManagerImpl::IsRegistered(syncable::ModelType type) {
return controllers_.count(type) == 1;
}
bool DataTypeManagerImpl::IsEnabled(syncable::ModelType type) {
return IsRegistered(type) && controllers_[type]->enabled();
}
} // namespace browser_sync
<|endoftext|>
|
<commit_before>
/*
* Copyright (c) 1999-2008 Mark D. Hill and David A. Wood
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef DATABLOCK_H
#define DATABLOCK_H
#include "mem/ruby/common/Global.hh"
#include "mem/ruby/system/System.hh"
#include "mem/gems_common/Vector.hh"
class DataBlock {
public:
// Constructors
DataBlock() {alloc();}
DataBlock(const DataBlock & cp) {
m_data = new uint8[RubySystem::getBlockSizeBytes()];
memcpy(m_data, cp.m_data, RubySystem::getBlockSizeBytes());
m_alloc = true;
}
// Destructor
~DataBlock() { if(m_alloc) delete [] m_data;}
DataBlock& operator=(const DataBlock& obj);
// Public Methods
void assign(uint8* data);
void clear();
uint8 getByte(int whichByte) const;
const uint8* getData(int offset, int len) const;
void setByte(int whichByte, uint8 data);
void setData(uint8* data, int offset, int len);
void copyPartial(const DataBlock & dblk, int offset, int len);
bool equal(const DataBlock& obj) const;
void print(ostream& out) const;
private:
void alloc();
// Data Members (m_ prefix)
uint8* m_data;
bool m_alloc;
};
// Output operator declaration
ostream& operator<<(ostream& out, const DataBlock& obj);
bool operator==(const DataBlock& obj1, const DataBlock& obj2);
// inline functions for speed
inline
void DataBlock::assign(uint8* data)
{
delete [] m_data;
m_data = data;
m_alloc = false;
}
inline
void DataBlock::alloc()
{
m_data = new uint8[RubySystem::getBlockSizeBytes()];
m_alloc = true;
clear();
}
inline
void DataBlock::clear()
{
memset(m_data, 0, RubySystem::getBlockSizeBytes());
}
inline
bool DataBlock::equal(const DataBlock& obj) const
{
return !memcmp(m_data, obj.m_data, RubySystem::getBlockSizeBytes());
}
inline
void DataBlock::print(ostream& out) const
{
int size = RubySystem::getBlockSizeBytes();
out << "[ ";
for (int i = 0; i < size; i+=4) {
out << hex << *((uint32*)(&(m_data[i]))) << " ";
}
out << dec << "]" << flush;
}
inline
uint8 DataBlock::getByte(int whichByte) const
{
return m_data[whichByte];
}
inline
const uint8* DataBlock::getData(int offset, int len) const
{
assert(offset + len <= RubySystem::getBlockSizeBytes());
return &m_data[offset];
}
inline
void DataBlock::setByte(int whichByte, uint8 data)
{
m_data[whichByte] = data;
}
inline
void DataBlock::setData(uint8* data, int offset, int len)
{
assert(offset + len <= RubySystem::getBlockSizeBytes());
memcpy(&m_data[offset], data, len);
}
inline
void DataBlock::copyPartial(const DataBlock & dblk, int offset, int len)
{
setData(&dblk.m_data[offset], offset, len);
}
// ******************* Definitions *******************
// Output operator definition
extern inline
ostream& operator<<(ostream& out, const DataBlock& obj)
{
obj.print(out);
out << flush;
return out;
}
extern inline
bool operator==(const DataBlock& obj1,const DataBlock& obj2)
{
return (obj1.equal(obj2));
}
#endif //DATABLOCK_H
<commit_msg>ruby: better debug print for DataBlock<commit_after>
/*
* Copyright (c) 1999-2008 Mark D. Hill and David A. Wood
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef DATABLOCK_H
#define DATABLOCK_H
#include "mem/ruby/common/Global.hh"
#include "mem/ruby/system/System.hh"
#include "mem/gems_common/Vector.hh"
class DataBlock {
public:
// Constructors
DataBlock() {alloc();}
DataBlock(const DataBlock & cp) {
m_data = new uint8[RubySystem::getBlockSizeBytes()];
memcpy(m_data, cp.m_data, RubySystem::getBlockSizeBytes());
m_alloc = true;
}
// Destructor
~DataBlock() { if(m_alloc) delete [] m_data;}
DataBlock& operator=(const DataBlock& obj);
// Public Methods
void assign(uint8* data);
void clear();
uint8 getByte(int whichByte) const;
const uint8* getData(int offset, int len) const;
void setByte(int whichByte, uint8 data);
void setData(uint8* data, int offset, int len);
void copyPartial(const DataBlock & dblk, int offset, int len);
bool equal(const DataBlock& obj) const;
void print(ostream& out) const;
private:
void alloc();
// Data Members (m_ prefix)
uint8* m_data;
bool m_alloc;
};
// Output operator declaration
ostream& operator<<(ostream& out, const DataBlock& obj);
bool operator==(const DataBlock& obj1, const DataBlock& obj2);
// inline functions for speed
inline
void DataBlock::assign(uint8* data)
{
delete [] m_data;
m_data = data;
m_alloc = false;
}
inline
void DataBlock::alloc()
{
m_data = new uint8[RubySystem::getBlockSizeBytes()];
m_alloc = true;
clear();
}
inline
void DataBlock::clear()
{
memset(m_data, 0, RubySystem::getBlockSizeBytes());
}
inline
bool DataBlock::equal(const DataBlock& obj) const
{
return !memcmp(m_data, obj.m_data, RubySystem::getBlockSizeBytes());
}
inline
void DataBlock::print(ostream& out) const
{
int size = RubySystem::getBlockSizeBytes();
out << "[ ";
for (int i = 0; i < size; i++) {
out << setw(2) << setfill('0') << hex << "0x" << (int)m_data[i] << " ";
}
out << dec << "]" << flush;
}
inline
uint8 DataBlock::getByte(int whichByte) const
{
return m_data[whichByte];
}
inline
const uint8* DataBlock::getData(int offset, int len) const
{
assert(offset + len <= RubySystem::getBlockSizeBytes());
return &m_data[offset];
}
inline
void DataBlock::setByte(int whichByte, uint8 data)
{
m_data[whichByte] = data;
}
inline
void DataBlock::setData(uint8* data, int offset, int len)
{
assert(offset + len <= RubySystem::getBlockSizeBytes());
memcpy(&m_data[offset], data, len);
}
inline
void DataBlock::copyPartial(const DataBlock & dblk, int offset, int len)
{
setData(&dblk.m_data[offset], offset, len);
}
// ******************* Definitions *******************
// Output operator definition
extern inline
ostream& operator<<(ostream& out, const DataBlock& obj)
{
obj.print(out);
out << flush;
return out;
}
extern inline
bool operator==(const DataBlock& obj1,const DataBlock& obj2)
{
return (obj1.equal(obj2));
}
#endif //DATABLOCK_H
<|endoftext|>
|
<commit_before>// Copyright eeGeo Ltd (2012-2015), All Rights Reserved
#include "TransitionToInteriorPointStage.h"
#include "InteriorsExplorerModel.h"
#include "InteriorsCameraController.h"
#include "InteriorInteractionModel.h"
#include "InteriorSelectionModel.h"
#include "InteriorTransitionModel.h"
namespace ExampleApp
{
namespace CameraTransitions
{
namespace SdkModel
{
TransitionToInteriorPointStage::TransitionToInteriorPointStage(Eegeo::Resources::Interiors::InteriorInteractionModel& interiorInteractionModel,
Eegeo::Resources::Interiors::InteriorSelectionModel& interiorSelectionModel,
const Eegeo::Resources::Interiors::InteriorTransitionModel& interiorTransitionModel,
InteriorsExplorer::SdkModel::InteriorsExplorerModel& interiorsExplorerModel,
Eegeo::Resources::Interiors::InteriorsCameraController& cameraController,
const Eegeo::dv3& newInterestPoint,
float newDistanceToInterest,
const Eegeo::Resources::Interiors::InteriorId &interiorId,
int targetFloorIndex,
bool jumpIfFar)
: m_interiorInteractionModel(interiorInteractionModel)
, m_interiorSelectionModel(interiorSelectionModel)
, m_interiorTransitionModel(interiorTransitionModel)
, m_interiorsExplorerModel(interiorsExplorerModel)
, m_cameraController(cameraController)
, m_newInterestPoint(newInterestPoint)
, m_targetDistanceToInterest(newDistanceToInterest)
, m_transitionDuration(0.5f)
, m_transitionTime(0.0f)
, m_interiorId(interiorId)
, m_targetFloorIndex(targetFloorIndex)
, m_failed(false)
, m_jumpIfFar(jumpIfFar)
, m_startCameraInterestAltitude(0.0f)
, m_endCameraInterestAltitude(0.0f)
, m_initialisedNextInterior(false)
, m_cameraInterestAltitudeStartTime(0.0f)
{
}
void TransitionToInteriorPointStage::Start()
{
Eegeo_ASSERT(m_interiorInteractionModel.HasInteriorModel(), "Must be inside interior to start this transition");
m_startCameraInterestAltitude = m_cameraController.GetFloorOffsetHeight();
m_endCameraInterestAltitude = m_startCameraInterestAltitude;
m_interiorSelectionModel.ClearSelection();
m_interiorSelectionModel.SelectInteriorId(m_interiorId);
m_interiorsExplorerModel.HideInteriorExplorer();
m_transitionTime = 0.0f;
m_startInterestPoint = m_cameraController.GetInterestLocation();
m_startDistanceToInterest = m_cameraController.GetDistanceToInterest();
m_cameraController.SetApplyRestrictions(false);
m_cameraController.SetApplyFloorOffset(false);
m_initialisedNextInterior = false;
m_cameraInterestAltitudeStartTime = 0.0f;
}
void TransitionToInteriorPointStage::Update(float dt)
{
if(m_failed)
{
return;
}
if(!m_initialisedNextInterior && m_interiorInteractionModel.HasInteriorModel())
{
m_interiorInteractionModel.SetSelectedFloorIndex(m_targetFloorIndex);
m_endCameraInterestAltitude = m_cameraController.GetFloorOffsetHeight();
m_cameraInterestAltitudeStartTime = m_transitionTime;
m_initialisedNextInterior = true;
}
if(m_jumpIfFar && ShouldJumpTo(m_newInterestPoint))
{
m_transitionTime = 1.01f;
}
else
{
m_transitionTime += dt/m_transitionDuration;
float t = Eegeo::Math::Clamp01(m_transitionTime);
float smoothT = Eegeo::Math::SmoothStep(t);
Eegeo::dv3 lerpInterestPoint = Eegeo::dv3::Lerp(m_startInterestPoint, m_newInterestPoint, smoothT);
m_cameraController.SetInterestLocation(lerpInterestPoint);
float lerpDistance = Eegeo::Math::Lerp(m_startDistanceToInterest, m_targetDistanceToInterest, smoothT);
m_cameraController.SetDistanceToInterest(lerpDistance);
if(m_initialisedNextInterior)
{
float t2 = m_cameraInterestAltitudeStartTime >= 1.0f ? 1.0f : Eegeo::Math::Clamp01((m_transitionTime - m_cameraInterestAltitudeStartTime)/(1.0f-m_cameraInterestAltitudeStartTime));
float smoothT2 = Eegeo::Math::SmoothStep(t2);
float lerpAltitude = Eegeo::Math::Lerp(m_startCameraInterestAltitude, m_endCameraInterestAltitude, smoothT2);
m_cameraController.SetCameraInterestAltitude(lerpAltitude);
}
}
// Check fail condition and clean up on fail
if(!m_interiorSelectionModel.IsInteriorSelected())
{
m_failed = true;
m_cameraController.SetApplyRestrictions(true);
m_cameraController.SetApplyFloorOffset(true);
}
}
void TransitionToInteriorPointStage::End()
{
m_cameraController.SetInterestLocation(m_newInterestPoint);
m_cameraController.SetDistanceToInterest(m_targetDistanceToInterest);
m_cameraController.SetCameraInterestAltitude(m_endCameraInterestAltitude);
m_cameraController.SetApplyRestrictions(true);
m_cameraController.SetApplyFloorOffset(true);
m_interiorInteractionModel.SetSelectedFloorIndex(m_targetFloorIndex);
m_interiorsExplorerModel.ShowInteriorExplorer(true);
}
const bool TransitionToInteriorPointStage::StageIsComplete() const
{
return m_transitionTime >= 1.0f && m_interiorTransitionModel.InteriorIsVisible();
}
bool TransitionToInteriorPointStage::ShouldJumpTo(Eegeo::dv3& newInterestPoint)
{
const double MAX_CAMERA_TRANSITION_DISTANCE = 500;
const Eegeo::dv3& currentCameraLocation = m_cameraController.GetCameraState().LocationEcef();
double distance = (newInterestPoint - currentCameraLocation).Length();
return distance > MAX_CAMERA_TRANSITION_DISTANCE;
}
const bool TransitionToInteriorPointStage::StageHasFailed() const
{
return m_failed;
}
}
}
}<commit_msg>Build fix - CameraState header had been present on windows via PCH, but wasn't included for Android & iOS. Buddy: Paul Harris<commit_after>// Copyright eeGeo Ltd (2012-2015), All Rights Reserved
#include "TransitionToInteriorPointStage.h"
#include "InteriorsExplorerModel.h"
#include "InteriorsCameraController.h"
#include "InteriorInteractionModel.h"
#include "InteriorSelectionModel.h"
#include "InteriorTransitionModel.h"
#include "CameraState.h"
namespace ExampleApp
{
namespace CameraTransitions
{
namespace SdkModel
{
TransitionToInteriorPointStage::TransitionToInteriorPointStage(Eegeo::Resources::Interiors::InteriorInteractionModel& interiorInteractionModel,
Eegeo::Resources::Interiors::InteriorSelectionModel& interiorSelectionModel,
const Eegeo::Resources::Interiors::InteriorTransitionModel& interiorTransitionModel,
InteriorsExplorer::SdkModel::InteriorsExplorerModel& interiorsExplorerModel,
Eegeo::Resources::Interiors::InteriorsCameraController& cameraController,
const Eegeo::dv3& newInterestPoint,
float newDistanceToInterest,
const Eegeo::Resources::Interiors::InteriorId &interiorId,
int targetFloorIndex,
bool jumpIfFar)
: m_interiorInteractionModel(interiorInteractionModel)
, m_interiorSelectionModel(interiorSelectionModel)
, m_interiorTransitionModel(interiorTransitionModel)
, m_interiorsExplorerModel(interiorsExplorerModel)
, m_cameraController(cameraController)
, m_newInterestPoint(newInterestPoint)
, m_targetDistanceToInterest(newDistanceToInterest)
, m_transitionDuration(0.5f)
, m_transitionTime(0.0f)
, m_interiorId(interiorId)
, m_targetFloorIndex(targetFloorIndex)
, m_failed(false)
, m_jumpIfFar(jumpIfFar)
, m_startCameraInterestAltitude(0.0f)
, m_endCameraInterestAltitude(0.0f)
, m_initialisedNextInterior(false)
, m_cameraInterestAltitudeStartTime(0.0f)
{
}
void TransitionToInteriorPointStage::Start()
{
Eegeo_ASSERT(m_interiorInteractionModel.HasInteriorModel(), "Must be inside interior to start this transition");
m_startCameraInterestAltitude = m_cameraController.GetFloorOffsetHeight();
m_endCameraInterestAltitude = m_startCameraInterestAltitude;
m_interiorSelectionModel.ClearSelection();
m_interiorSelectionModel.SelectInteriorId(m_interiorId);
m_interiorsExplorerModel.HideInteriorExplorer();
m_transitionTime = 0.0f;
m_startInterestPoint = m_cameraController.GetInterestLocation();
m_startDistanceToInterest = m_cameraController.GetDistanceToInterest();
m_cameraController.SetApplyRestrictions(false);
m_cameraController.SetApplyFloorOffset(false);
m_initialisedNextInterior = false;
m_cameraInterestAltitudeStartTime = 0.0f;
}
void TransitionToInteriorPointStage::Update(float dt)
{
if(m_failed)
{
return;
}
if(!m_initialisedNextInterior && m_interiorInteractionModel.HasInteriorModel())
{
m_interiorInteractionModel.SetSelectedFloorIndex(m_targetFloorIndex);
m_endCameraInterestAltitude = m_cameraController.GetFloorOffsetHeight();
m_cameraInterestAltitudeStartTime = m_transitionTime;
m_initialisedNextInterior = true;
}
if(m_jumpIfFar && ShouldJumpTo(m_newInterestPoint))
{
m_transitionTime = 1.01f;
}
else
{
m_transitionTime += dt/m_transitionDuration;
float t = Eegeo::Math::Clamp01(m_transitionTime);
float smoothT = Eegeo::Math::SmoothStep(t);
Eegeo::dv3 lerpInterestPoint = Eegeo::dv3::Lerp(m_startInterestPoint, m_newInterestPoint, smoothT);
m_cameraController.SetInterestLocation(lerpInterestPoint);
float lerpDistance = Eegeo::Math::Lerp(m_startDistanceToInterest, m_targetDistanceToInterest, smoothT);
m_cameraController.SetDistanceToInterest(lerpDistance);
if(m_initialisedNextInterior)
{
float t2 = m_cameraInterestAltitudeStartTime >= 1.0f ? 1.0f : Eegeo::Math::Clamp01((m_transitionTime - m_cameraInterestAltitudeStartTime)/(1.0f-m_cameraInterestAltitudeStartTime));
float smoothT2 = Eegeo::Math::SmoothStep(t2);
float lerpAltitude = Eegeo::Math::Lerp(m_startCameraInterestAltitude, m_endCameraInterestAltitude, smoothT2);
m_cameraController.SetCameraInterestAltitude(lerpAltitude);
}
}
// Check fail condition and clean up on fail
if(!m_interiorSelectionModel.IsInteriorSelected())
{
m_failed = true;
m_cameraController.SetApplyRestrictions(true);
m_cameraController.SetApplyFloorOffset(true);
}
}
void TransitionToInteriorPointStage::End()
{
m_cameraController.SetInterestLocation(m_newInterestPoint);
m_cameraController.SetDistanceToInterest(m_targetDistanceToInterest);
m_cameraController.SetCameraInterestAltitude(m_endCameraInterestAltitude);
m_cameraController.SetApplyRestrictions(true);
m_cameraController.SetApplyFloorOffset(true);
m_interiorInteractionModel.SetSelectedFloorIndex(m_targetFloorIndex);
m_interiorsExplorerModel.ShowInteriorExplorer(true);
}
const bool TransitionToInteriorPointStage::StageIsComplete() const
{
return m_transitionTime >= 1.0f && m_interiorTransitionModel.InteriorIsVisible();
}
bool TransitionToInteriorPointStage::ShouldJumpTo(Eegeo::dv3& newInterestPoint)
{
const double MAX_CAMERA_TRANSITION_DISTANCE = 500;
const Eegeo::dv3& currentCameraLocation = m_cameraController.GetCameraState().LocationEcef();
double distance = (newInterestPoint - currentCameraLocation).Length();
return distance > MAX_CAMERA_TRANSITION_DISTANCE;
}
const bool TransitionToInteriorPointStage::StageHasFailed() const
{
return m_failed;
}
}
}
}<|endoftext|>
|
<commit_before>#define CYBOZU_TEST_DISABLE_AUTO_RUN
#include <cybozu/test.hpp>
#include <cybozu/benchmark.hpp>
#include <cybozu/option.hpp>
#include <cybozu/xorshift.hpp>
#include <mcl/bn384.hpp>
#include <mcl/bn.hpp>
using namespace mcl::bn384;
mcl::fp::Mode g_mode;
#include "bench.hpp"
void testCurve(const mcl::CurveParam& cp)
{
initPairing(cp, g_mode);
G1 P;
G2 Q;
mapToG1(P, 1);
mapToG2(Q, 1);
GT e1, e2;
pairing(e1, P, Q);
cybozu::XorShift rg;
mpz_class a, b;
Fr r;
r.setRand(rg); a = r.getMpz();
r.setRand(rg); b = r.getMpz();
G1 aP;
G2 bQ;
G1::mul(aP, P, a);
G2::mul(bQ, Q, b);
pairing(e2, aP, bQ);
GT::pow(e1, e1, a * b);
CYBOZU_TEST_EQUAL(e1, e2);
testBench(P, Q);
}
CYBOZU_TEST_AUTO(pairing)
{
puts("BN254");
// support 256-bit pairing
testCurve(mcl::BN254);
puts("BN381_1");
testCurve(mcl::BN381_1);
puts("BN381_2");
testCurve(mcl::BN381_2);
puts("BLS12_381");
testCurve(mcl::BLS12_381);
// Q is not on EcT, but bad order
{
const char *s = "1 18d3d8c085a5a5e7553c3a4eb628e88b8465bf4de2612e35a0a4eb018fb0c82e9698896031e62fd7633ffd824a859474 1dc6edfcf33e29575d4791faed8e7203832217423bf7f7fbf1f6b36625b12e7132c15fbc15562ce93362a322fb83dd0d 65836963b1f7b6959030ddfa15ab38ce056097e91dedffd996c1808624fa7e2644a77be606290aa555cda8481cfb3cb 1b77b708d3d4f65aeedf54b58393463a42f0dc5856baadb5ce608036baeca398c5d9e6b169473a8838098fd72fd28b50";
G2 Q;
CYBOZU_TEST_EXCEPTION(Q.setStr(s, 16), std::exception);
}
}
int main(int argc, char *argv[])
try
{
cybozu::Option opt;
std::string mode;
opt.appendOpt(&mode, "auto", "m", ": mode(gmp/gmp_mont/llvm/llvm_mont/xbyak)");
if (!opt.parse(argc, argv)) {
opt.usage();
return 1;
}
g_mode = mcl::fp::StrToMode(mode);
return cybozu::test::autoRun.run(argc, argv);
} catch (std::exception& e) {
printf("ERR %s\n", e.what());
return 1;
}
<commit_msg>add lagrange test<commit_after>#define CYBOZU_TEST_DISABLE_AUTO_RUN
#include <cybozu/test.hpp>
#include <cybozu/benchmark.hpp>
#include <cybozu/option.hpp>
#include <cybozu/xorshift.hpp>
#include <mcl/bn384.hpp>
#include <mcl/bn.hpp>
#include <mcl/lagrange.hpp>
using namespace mcl::bn384;
mcl::fp::Mode g_mode;
#include "bench.hpp"
void testLagrange()
{
puts("testLagrange");
const int k = 7;
Fr c[k], x[k], y[k];
for (size_t i = 0; i < k; i++) {
c[i].setByCSPRNG();
x[i].setByCSPRNG();
}
for (size_t i = 0; i < k; i++) {
mcl::evaluatePolynomial(y[i], c, k, x[i]);
}
Fr s;
mcl::LagrangeInterpolation(s, x, y, k);
CYBOZU_TEST_EQUAL(s, c[0]);
}
void testCurve(const mcl::CurveParam& cp)
{
initPairing(cp, g_mode);
G1 P;
G2 Q;
mapToG1(P, 1);
mapToG2(Q, 1);
GT e1, e2;
pairing(e1, P, Q);
cybozu::XorShift rg;
mpz_class a, b;
Fr r;
r.setRand(rg); a = r.getMpz();
r.setRand(rg); b = r.getMpz();
G1 aP;
G2 bQ;
G1::mul(aP, P, a);
G2::mul(bQ, Q, b);
pairing(e2, aP, bQ);
GT::pow(e1, e1, a * b);
CYBOZU_TEST_EQUAL(e1, e2);
testBench(P, Q);
testLagrange();
}
CYBOZU_TEST_AUTO(pairing)
{
puts("BN254");
// support 256-bit pairing
testCurve(mcl::BN254);
puts("BN381_1");
testCurve(mcl::BN381_1);
puts("BN381_2");
testCurve(mcl::BN381_2);
puts("BLS12_381");
testCurve(mcl::BLS12_381);
// Q is not on EcT, but bad order
{
const char *s = "1 18d3d8c085a5a5e7553c3a4eb628e88b8465bf4de2612e35a0a4eb018fb0c82e9698896031e62fd7633ffd824a859474 1dc6edfcf33e29575d4791faed8e7203832217423bf7f7fbf1f6b36625b12e7132c15fbc15562ce93362a322fb83dd0d 65836963b1f7b6959030ddfa15ab38ce056097e91dedffd996c1808624fa7e2644a77be606290aa555cda8481cfb3cb 1b77b708d3d4f65aeedf54b58393463a42f0dc5856baadb5ce608036baeca398c5d9e6b169473a8838098fd72fd28b50";
G2 Q;
CYBOZU_TEST_EXCEPTION(Q.setStr(s, 16), std::exception);
}
}
int main(int argc, char *argv[])
try
{
cybozu::Option opt;
std::string mode;
opt.appendOpt(&mode, "auto", "m", ": mode(gmp/gmp_mont/llvm/llvm_mont/xbyak)");
if (!opt.parse(argc, argv)) {
opt.usage();
return 1;
}
g_mode = mcl::fp::StrToMode(mode);
return cybozu::test::autoRun.run(argc, argv);
} catch (std::exception& e) {
printf("ERR %s\n", e.what());
return 1;
}
<|endoftext|>
|
<commit_before>#include "Globals.h"
#include "Application.h"
#include "ModulePhysics3D.h"
#include "PhysBody3D.h"
#include "PhysVehicle3D.h"
#include "Primitive.h"
#include "ModuleCamera3D.h"
#include "ModuleInput.h"
#ifdef _DEBUG
#pragma comment (lib, "Bullet/libx86/Debug/BulletDynamics_debug.lib")
#pragma comment (lib, "Bullet/libx86/Debug/BulletCollision_debug.lib")
#pragma comment (lib, "Bullet/libx86/Debug/LinearMath_debug.lib")
#else
#pragma comment (lib, "Bullet/libx86/Release/BulletDynamics.lib")
#pragma comment (lib, "Bullet/libx86/Release/BulletCollision.lib")
#pragma comment (lib, "Bullet/libx86/Release/LinearMath.lib")
#endif
using namespace std;
ModulePhysics3D::ModulePhysics3D(Application* app, const char* name, bool start_enabled) : Module(app, name, start_enabled)
{
debug = true;
collision_conf = new btDefaultCollisionConfiguration();
dispatcher = new btCollisionDispatcher(collision_conf);
broad_phase = new btDbvtBroadphase();
solver = new btSequentialImpulseConstraintSolver();
debug_draw = new DebugDrawer();
}
// Destructor
ModulePhysics3D::~ModulePhysics3D()
{
delete debug_draw;
delete solver;
delete broad_phase;
delete dispatcher;
delete collision_conf;
}
// Render not available yet----------------------------------
bool ModulePhysics3D::Init(cJSON* node)
{
LOG("Creating 3D Physics simulation");
bool ret = true;
return ret;
}
// ---------------------------------------------------------
bool ModulePhysics3D::Start()
{
LOG("Creating Physics environment");
world = new btDiscreteDynamicsWorld(dispatcher, broad_phase, solver, collision_conf);
//world->setDebugDrawer(debug_draw);
world->setGravity(GRAVITY);
vehicle_raycaster = new btDefaultVehicleRaycaster(world);
// Big plane as ground
{
btCollisionShape* colShape = new btStaticPlaneShape(btVector3(0, 1, 0), 0);
btDefaultMotionState* myMotionState = new btDefaultMotionState();
btRigidBody::btRigidBodyConstructionInfo rbInfo(0.0f, myMotionState, colShape);
//btRigidBody* body = new btRigidBody(rbInfo);
//world->addRigidBody(body);
}
return true;
}
// ---------------------------------------------------------
update_status ModulePhysics3D::PreUpdate(float dt)
{
world->stepSimulation(dt, 15);
int numManifolds = world->getDispatcher()->getNumManifolds();
for (int i = 0; i<numManifolds; i++)
{
btPersistentManifold* contactManifold = world->getDispatcher()->getManifoldByIndexInternal(i);
btCollisionObject* obA = (btCollisionObject*)(contactManifold->getBody0());
btCollisionObject* obB = (btCollisionObject*)(contactManifold->getBody1());
int numContacts = contactManifold->getNumContacts();
if (numContacts > 0)
{
PhysBody3D* pbodyA = (PhysBody3D*)obA->getUserPointer();
PhysBody3D* pbodyB = (PhysBody3D*)obB->getUserPointer();
if (pbodyA && pbodyB)
{
list<Module*>::iterator item = pbodyA->collision_listeners.begin();
while (item != pbodyA->collision_listeners.end())
{
(*item)->OnCollision(pbodyA, pbodyB);
item++;
}
item = pbodyB->collision_listeners.begin();
while (item != pbodyB->collision_listeners.end())
{
(*item)->OnCollision(pbodyB, pbodyA);
item++;
}
}
}
}
return UPDATE_CONTINUE;
}
// ---------------------------------------------------------
update_status ModulePhysics3D::Update(float dt)
{
if (App->input->GetKey(SDL_SCANCODE_F1) == KEY_DOWN)
debug = !debug;
if (debug == true)
{
world->debugDrawWorld();
// Render vehicles
list<PhysVehicle3D*>::iterator item = vehicles.begin();
while (item != vehicles.end())
{
(*item)->Render();
item++;
}
if (App->input->GetKey(SDL_SCANCODE_1) == KEY_DOWN)
{
PSphere s(1);
s.SetPos(App->camera->Position.x, App->camera->Position.y, App->camera->Position.z);
float force = 30.0f;
AddBody(s)->Push(-(App->camera->Z.x * force), -(App->camera->Z.y * force), -(App->camera->Z.z * force));
}
}
return UPDATE_CONTINUE;
}
// ---------------------------------------------------------
update_status ModulePhysics3D::PostUpdate(float dt)
{
return UPDATE_CONTINUE;
}
// Called before quitting
bool ModulePhysics3D::CleanUp()
{
LOG("Destroying 3D Physics simulation");
// Remove from the world all collision bodies
for (int i = world->getNumCollisionObjects() - 1; i >= 0; i--)
{
btCollisionObject* obj = world->getCollisionObjectArray()[i];
world->removeCollisionObject(obj);
}
for (list<btTypedConstraint*>::iterator item = constraints.begin(); item != constraints.end(); item++)
{
world->removeConstraint(*item);
delete (*item);
}
constraints.clear();
for (list<btDefaultMotionState*>::iterator item = motions.begin(); item != motions.end(); item++)
delete (*item);
motions.clear();
for (list<btCollisionShape*>::iterator item = shapes.begin(); item != shapes.end(); item++)
delete (*item);
shapes.clear();
for (list<PhysBody3D*>::iterator item = bodies.begin(); item != bodies.end(); item++)
delete (*item);
bodies.clear();
for (list<PhysVehicle3D*>::iterator item = vehicles.begin(); item != vehicles.end(); item++)
delete (*item);
vehicles.clear();
delete vehicle_raycaster;
delete world;
return true;
}
// ---------------------------------------------------------
PhysBody3D* ModulePhysics3D::AddBody(const PSphere& sphere, float mass)
{
btCollisionShape* colShape = new btSphereShape(sphere.radius);
shapes.push_back(colShape);
btTransform startTransform;
startTransform.setFromOpenGLMatrix(&sphere.transform);
btVector3 localInertia(0, 0, 0);
if (mass != 0.f)
colShape->calculateLocalInertia(mass, localInertia);
btDefaultMotionState* myMotionState = new btDefaultMotionState(startTransform);
motions.push_back(myMotionState);
btRigidBody::btRigidBodyConstructionInfo rbInfo(mass, myMotionState, colShape, localInertia);
btRigidBody* body = new btRigidBody(rbInfo);
PhysBody3D* pbody = new PhysBody3D(body);
world->addRigidBody(body);
bodies.push_back(pbody);
return pbody;
}
// ---------------------------------------------------------
PhysBody3D* ModulePhysics3D::AddBody(const PCube& cube, float mass)
{
btCollisionShape* colShape = new btBoxShape(btVector3(cube.size.x*0.5f, cube.size.y*0.5f, cube.size.z*0.5f));
shapes.push_back(colShape);
btTransform startTransform;
startTransform.setFromOpenGLMatrix(&cube.transform);
btVector3 localInertia(0, 0, 0);
if (mass != 0.f)
colShape->calculateLocalInertia(mass, localInertia);
btDefaultMotionState* myMotionState = new btDefaultMotionState(startTransform);
motions.push_back(myMotionState);
btRigidBody::btRigidBodyConstructionInfo rbInfo(mass, myMotionState, colShape, localInertia);
btRigidBody* body = new btRigidBody(rbInfo);
PhysBody3D* pbody = new PhysBody3D(body);
world->addRigidBody(body);
bodies.push_back(pbody);
return pbody;
}
// ---------------------------------------------------------
PhysBody3D* ModulePhysics3D::AddBody(const PCylinder& cylinder, float mass)
{
btCollisionShape* colShape = new btCylinderShapeX(btVector3(cylinder.height*0.5f, cylinder.radius, 0.0f));
shapes.push_back(colShape);
btTransform startTransform;
startTransform.setFromOpenGLMatrix(&cylinder.transform);
btVector3 localInertia(0, 0, 0);
if (mass != 0.f)
colShape->calculateLocalInertia(mass, localInertia);
btDefaultMotionState* myMotionState = new btDefaultMotionState(startTransform);
motions.push_back(myMotionState);
btRigidBody::btRigidBodyConstructionInfo rbInfo(mass, myMotionState, colShape, localInertia);
btRigidBody* body = new btRigidBody(rbInfo);
PhysBody3D* pbody = new PhysBody3D(body);
world->addRigidBody(body);
bodies.push_back(pbody);
return pbody;
}
// ---------------------------------------------------------
PhysVehicle3D* ModulePhysics3D::AddVehicle(const VehicleInfo& info)
{
btCompoundShape* comShape = new btCompoundShape();
shapes.push_back(comShape);
btCollisionShape* colShape = new btBoxShape(btVector3(info.chassis_size.x*0.5f, info.chassis_size.y*0.5f, info.chassis_size.z*0.5f));
shapes.push_back(colShape);
btTransform trans;
trans.setIdentity();
trans.setOrigin(btVector3(info.chassis_offset.x, info.chassis_offset.y, info.chassis_offset.z));
comShape->addChildShape(trans, colShape);
btTransform startTransform;
startTransform.setIdentity();
btVector3 localInertia(0, 0, 0);
comShape->calculateLocalInertia(info.mass, localInertia);
btDefaultMotionState* myMotionState = new btDefaultMotionState(startTransform);
btRigidBody::btRigidBodyConstructionInfo rbInfo(info.mass, myMotionState, comShape, localInertia);
btRigidBody* body = new btRigidBody(rbInfo);
body->setContactProcessingThreshold(BT_LARGE_FLOAT);
body->setActivationState(DISABLE_DEACTIVATION);
world->addRigidBody(body);
btRaycastVehicle::btVehicleTuning tuning;
tuning.m_frictionSlip = info.frictionSlip;
tuning.m_maxSuspensionForce = info.maxSuspensionForce;
tuning.m_maxSuspensionTravelCm = info.maxSuspensionTravelCm;
tuning.m_suspensionCompression = info.suspensionCompression;
tuning.m_suspensionDamping = info.suspensionDamping;
tuning.m_suspensionStiffness = info.suspensionStiffness;
btRaycastVehicle* vehicle = new btRaycastVehicle(tuning, body, vehicle_raycaster);
vehicle->setCoordinateSystem(0, 1, 2);
for (int i = 0; i < info.num_wheels; ++i)
{
btVector3 conn(info.wheels[i].connection.x, info.wheels[i].connection.y, info.wheels[i].connection.z);
btVector3 dir(info.wheels[i].direction.x, info.wheels[i].direction.y, info.wheels[i].direction.z);
btVector3 axis(info.wheels[i].axis.x, info.wheels[i].axis.y, info.wheels[i].axis.z);
vehicle->addWheel(conn, dir, axis, info.wheels[i].suspensionRestLength, info.wheels[i].radius, tuning, info.wheels[i].front);
}
// ---------------------
PhysVehicle3D* pvehicle = new PhysVehicle3D(body, vehicle, info);
world->addVehicle(vehicle);
vehicles.push_back(pvehicle);
return pvehicle;
}
// ---------------------------------------------------------
void ModulePhysics3D::AddConstraintP2P(PhysBody3D& bodyA, PhysBody3D& bodyB, const vec3& anchorA, const vec3& anchorB)
{
btTypedConstraint* p2p = new btPoint2PointConstraint(
*(bodyA.body),
*(bodyB.body),
btVector3(anchorA.x, anchorA.y, anchorA.z),
btVector3(anchorB.x, anchorB.y, anchorB.z));
world->addConstraint(p2p);
constraints.push_back(p2p);
p2p->setDbgDrawSize(2.0f);
}
void ModulePhysics3D::AddConstraintHinge(PhysBody3D& bodyA, PhysBody3D& bodyB, const vec3& anchorA, const vec3& anchorB, const vec3& axisA, const vec3& axisB, bool disable_collision)
{
btHingeConstraint* hinge = new btHingeConstraint(
*(bodyA.body),
*(bodyB.body),
btVector3(anchorA.x, anchorA.y, anchorA.z),
btVector3(anchorB.x, anchorB.y, anchorB.z),
btVector3(axisA.x, axisA.y, axisA.z),
btVector3(axisB.x, axisB.y, axisB.z));
world->addConstraint(hinge, disable_collision);
constraints.push_back(hinge);
hinge->setDbgDrawSize(2.0f);
}
// =============================================
void DebugDrawer::drawLine(const btVector3& from, const btVector3& to, const btVector3& color)
{
line.origin.Set(from.getX(), from.getY(), from.getZ());
line.destination.Set(to.getX(), to.getY(), to.getZ());
line.color.Set(color.getX(), color.getY(), color.getZ());
line.Render();
}
void DebugDrawer::drawContactPoint(const btVector3& PointOnB, const btVector3& normalOnB, btScalar distance, int lifeTime, const btVector3& color)
{
point.transform.translate(PointOnB.getX(), PointOnB.getY(), PointOnB.getZ());
point.color.Set(color.getX(), color.getY(), color.getZ());
point.Render();
}
void DebugDrawer::reportErrorWarning(const char* warningString)
{
LOG("Bullet warning: %s", warningString);
}
void DebugDrawer::draw3dText(const btVector3& location, const char* textString)
{
LOG("Bullet draw text: %s", textString);
}
void DebugDrawer::setDebugMode(int debugMode)
{
mode = (DebugDrawModes)debugMode;
}
int DebugDrawer::getDebugMode() const
{
return mode;
}
<commit_msg>Cleaning leaks<commit_after>#include "Globals.h"
#include "Application.h"
#include "ModulePhysics3D.h"
#include "PhysBody3D.h"
#include "PhysVehicle3D.h"
#include "Primitive.h"
#include "ModuleCamera3D.h"
#include "ModuleInput.h"
#ifdef _DEBUG
#pragma comment (lib, "Bullet/libx86/Debug/BulletDynamics_debug.lib")
#pragma comment (lib, "Bullet/libx86/Debug/BulletCollision_debug.lib")
#pragma comment (lib, "Bullet/libx86/Debug/LinearMath_debug.lib")
#else
#pragma comment (lib, "Bullet/libx86/Release/BulletDynamics.lib")
#pragma comment (lib, "Bullet/libx86/Release/BulletCollision.lib")
#pragma comment (lib, "Bullet/libx86/Release/LinearMath.lib")
#endif
using namespace std;
ModulePhysics3D::ModulePhysics3D(Application* app, const char* name, bool start_enabled) : Module(app, name, start_enabled)
{
debug = true;
collision_conf = new btDefaultCollisionConfiguration();
dispatcher = new btCollisionDispatcher(collision_conf);
broad_phase = new btDbvtBroadphase();
solver = new btSequentialImpulseConstraintSolver();
debug_draw = new DebugDrawer();
}
// Destructor
ModulePhysics3D::~ModulePhysics3D()
{
delete debug_draw;
delete solver;
delete broad_phase;
delete dispatcher;
delete collision_conf;
}
// Render not available yet----------------------------------
bool ModulePhysics3D::Init(cJSON* node)
{
LOG("Creating 3D Physics simulation");
bool ret = true;
return ret;
}
// ---------------------------------------------------------
bool ModulePhysics3D::Start()
{
LOG("Creating Physics environment");
/*
world = new btDiscreteDynamicsWorld(dispatcher, broad_phase, solver, collision_conf);
//world->setDebugDrawer(debug_draw);
world->setGravity(GRAVITY);
vehicle_raycaster = new btDefaultVehicleRaycaster(world);
// Big plane as ground
{
btCollisionShape* colShape = new btStaticPlaneShape(btVector3(0, 1, 0), 0);
btDefaultMotionState* myMotionState = new btDefaultMotionState();
btRigidBody::btRigidBodyConstructionInfo rbInfo(0.0f, myMotionState, colShape);
//btRigidBody* body = new btRigidBody(rbInfo);
//world->addRigidBody(body);
}
*/
return true;
}
// ---------------------------------------------------------
update_status ModulePhysics3D::PreUpdate(float dt)
{
/*world->stepSimulation(dt, 15);
int numManifolds = world->getDispatcher()->getNumManifolds();
for (int i = 0; i<numManifolds; i++)
{
btPersistentManifold* contactManifold = world->getDispatcher()->getManifoldByIndexInternal(i);
btCollisionObject* obA = (btCollisionObject*)(contactManifold->getBody0());
btCollisionObject* obB = (btCollisionObject*)(contactManifold->getBody1());
int numContacts = contactManifold->getNumContacts();
if (numContacts > 0)
{
PhysBody3D* pbodyA = (PhysBody3D*)obA->getUserPointer();
PhysBody3D* pbodyB = (PhysBody3D*)obB->getUserPointer();
if (pbodyA && pbodyB)
{
list<Module*>::iterator item = pbodyA->collision_listeners.begin();
while (item != pbodyA->collision_listeners.end())
{
(*item)->OnCollision(pbodyA, pbodyB);
item++;
}
item = pbodyB->collision_listeners.begin();
while (item != pbodyB->collision_listeners.end())
{
(*item)->OnCollision(pbodyB, pbodyA);
item++;
}
}
}
}*/
return UPDATE_CONTINUE;
}
// ---------------------------------------------------------
update_status ModulePhysics3D::Update(float dt)
{
/*if (App->input->GetKey(SDL_SCANCODE_F1) == KEY_DOWN)
debug = !debug;
if (debug == true)
{
world->debugDrawWorld();
// Render vehicles
list<PhysVehicle3D*>::iterator item = vehicles.begin();
while (item != vehicles.end())
{
(*item)->Render();
item++;
}
if (App->input->GetKey(SDL_SCANCODE_1) == KEY_DOWN)
{
PSphere s(1);
s.SetPos(App->camera->Position.x, App->camera->Position.y, App->camera->Position.z);
float force = 30.0f;
AddBody(s)->Push(-(App->camera->Z.x * force), -(App->camera->Z.y * force), -(App->camera->Z.z * force));
}
}*/
return UPDATE_CONTINUE;
}
// ---------------------------------------------------------
update_status ModulePhysics3D::PostUpdate(float dt)
{
return UPDATE_CONTINUE;
}
// Called before quitting
bool ModulePhysics3D::CleanUp()
{
LOG("Destroying 3D Physics simulation");
// Remove from the world all collision bodies
/*for (int i = world->getNumCollisionObjects() - 1; i >= 0; i--)
{
btCollisionObject* obj = world->getCollisionObjectArray()[i];
world->removeCollisionObject(obj);
}
for (list<btTypedConstraint*>::iterator item = constraints.begin(); item != constraints.end(); item++)
{
world->removeConstraint(*item);
delete (*item);
}
constraints.clear();
for (list<btDefaultMotionState*>::iterator item = motions.begin(); item != motions.end(); item++)
delete (*item);
motions.clear();
for (list<btCollisionShape*>::iterator item = shapes.begin(); item != shapes.end(); item++)
delete (*item);
shapes.clear();
for (list<PhysBody3D*>::iterator item = bodies.begin(); item != bodies.end(); item++)
delete (*item);
bodies.clear();
for (list<PhysVehicle3D*>::iterator item = vehicles.begin(); item != vehicles.end(); item++)
delete (*item);
vehicles.clear();
delete vehicle_raycaster;
delete world;*/
return true;
}
// ---------------------------------------------------------
PhysBody3D* ModulePhysics3D::AddBody(const PSphere& sphere, float mass)
{
btCollisionShape* colShape = new btSphereShape(sphere.radius);
shapes.push_back(colShape);
btTransform startTransform;
startTransform.setFromOpenGLMatrix(&sphere.transform);
btVector3 localInertia(0, 0, 0);
if (mass != 0.f)
colShape->calculateLocalInertia(mass, localInertia);
btDefaultMotionState* myMotionState = new btDefaultMotionState(startTransform);
motions.push_back(myMotionState);
btRigidBody::btRigidBodyConstructionInfo rbInfo(mass, myMotionState, colShape, localInertia);
btRigidBody* body = new btRigidBody(rbInfo);
PhysBody3D* pbody = new PhysBody3D(body);
world->addRigidBody(body);
bodies.push_back(pbody);
return pbody;
}
// ---------------------------------------------------------
PhysBody3D* ModulePhysics3D::AddBody(const PCube& cube, float mass)
{
btCollisionShape* colShape = new btBoxShape(btVector3(cube.size.x*0.5f, cube.size.y*0.5f, cube.size.z*0.5f));
shapes.push_back(colShape);
btTransform startTransform;
startTransform.setFromOpenGLMatrix(&cube.transform);
btVector3 localInertia(0, 0, 0);
if (mass != 0.f)
colShape->calculateLocalInertia(mass, localInertia);
btDefaultMotionState* myMotionState = new btDefaultMotionState(startTransform);
motions.push_back(myMotionState);
btRigidBody::btRigidBodyConstructionInfo rbInfo(mass, myMotionState, colShape, localInertia);
btRigidBody* body = new btRigidBody(rbInfo);
PhysBody3D* pbody = new PhysBody3D(body);
world->addRigidBody(body);
bodies.push_back(pbody);
return pbody;
}
// ---------------------------------------------------------
PhysBody3D* ModulePhysics3D::AddBody(const PCylinder& cylinder, float mass)
{
btCollisionShape* colShape = new btCylinderShapeX(btVector3(cylinder.height*0.5f, cylinder.radius, 0.0f));
shapes.push_back(colShape);
btTransform startTransform;
startTransform.setFromOpenGLMatrix(&cylinder.transform);
btVector3 localInertia(0, 0, 0);
if (mass != 0.f)
colShape->calculateLocalInertia(mass, localInertia);
btDefaultMotionState* myMotionState = new btDefaultMotionState(startTransform);
motions.push_back(myMotionState);
btRigidBody::btRigidBodyConstructionInfo rbInfo(mass, myMotionState, colShape, localInertia);
btRigidBody* body = new btRigidBody(rbInfo);
PhysBody3D* pbody = new PhysBody3D(body);
world->addRigidBody(body);
bodies.push_back(pbody);
return pbody;
}
// ---------------------------------------------------------
PhysVehicle3D* ModulePhysics3D::AddVehicle(const VehicleInfo& info)
{
btCompoundShape* comShape = new btCompoundShape();
shapes.push_back(comShape);
btCollisionShape* colShape = new btBoxShape(btVector3(info.chassis_size.x*0.5f, info.chassis_size.y*0.5f, info.chassis_size.z*0.5f));
shapes.push_back(colShape);
btTransform trans;
trans.setIdentity();
trans.setOrigin(btVector3(info.chassis_offset.x, info.chassis_offset.y, info.chassis_offset.z));
comShape->addChildShape(trans, colShape);
btTransform startTransform;
startTransform.setIdentity();
btVector3 localInertia(0, 0, 0);
comShape->calculateLocalInertia(info.mass, localInertia);
btDefaultMotionState* myMotionState = new btDefaultMotionState(startTransform);
btRigidBody::btRigidBodyConstructionInfo rbInfo(info.mass, myMotionState, comShape, localInertia);
btRigidBody* body = new btRigidBody(rbInfo);
body->setContactProcessingThreshold(BT_LARGE_FLOAT);
body->setActivationState(DISABLE_DEACTIVATION);
world->addRigidBody(body);
btRaycastVehicle::btVehicleTuning tuning;
tuning.m_frictionSlip = info.frictionSlip;
tuning.m_maxSuspensionForce = info.maxSuspensionForce;
tuning.m_maxSuspensionTravelCm = info.maxSuspensionTravelCm;
tuning.m_suspensionCompression = info.suspensionCompression;
tuning.m_suspensionDamping = info.suspensionDamping;
tuning.m_suspensionStiffness = info.suspensionStiffness;
btRaycastVehicle* vehicle = new btRaycastVehicle(tuning, body, vehicle_raycaster);
vehicle->setCoordinateSystem(0, 1, 2);
for (int i = 0; i < info.num_wheels; ++i)
{
btVector3 conn(info.wheels[i].connection.x, info.wheels[i].connection.y, info.wheels[i].connection.z);
btVector3 dir(info.wheels[i].direction.x, info.wheels[i].direction.y, info.wheels[i].direction.z);
btVector3 axis(info.wheels[i].axis.x, info.wheels[i].axis.y, info.wheels[i].axis.z);
vehicle->addWheel(conn, dir, axis, info.wheels[i].suspensionRestLength, info.wheels[i].radius, tuning, info.wheels[i].front);
}
// ---------------------
PhysVehicle3D* pvehicle = new PhysVehicle3D(body, vehicle, info);
world->addVehicle(vehicle);
vehicles.push_back(pvehicle);
return pvehicle;
}
// ---------------------------------------------------------
void ModulePhysics3D::AddConstraintP2P(PhysBody3D& bodyA, PhysBody3D& bodyB, const vec3& anchorA, const vec3& anchorB)
{
btTypedConstraint* p2p = new btPoint2PointConstraint(
*(bodyA.body),
*(bodyB.body),
btVector3(anchorA.x, anchorA.y, anchorA.z),
btVector3(anchorB.x, anchorB.y, anchorB.z));
world->addConstraint(p2p);
constraints.push_back(p2p);
p2p->setDbgDrawSize(2.0f);
}
void ModulePhysics3D::AddConstraintHinge(PhysBody3D& bodyA, PhysBody3D& bodyB, const vec3& anchorA, const vec3& anchorB, const vec3& axisA, const vec3& axisB, bool disable_collision)
{
btHingeConstraint* hinge = new btHingeConstraint(
*(bodyA.body),
*(bodyB.body),
btVector3(anchorA.x, anchorA.y, anchorA.z),
btVector3(anchorB.x, anchorB.y, anchorB.z),
btVector3(axisA.x, axisA.y, axisA.z),
btVector3(axisB.x, axisB.y, axisB.z));
world->addConstraint(hinge, disable_collision);
constraints.push_back(hinge);
hinge->setDbgDrawSize(2.0f);
}
// =============================================
void DebugDrawer::drawLine(const btVector3& from, const btVector3& to, const btVector3& color)
{
line.origin.Set(from.getX(), from.getY(), from.getZ());
line.destination.Set(to.getX(), to.getY(), to.getZ());
line.color.Set(color.getX(), color.getY(), color.getZ());
line.Render();
}
void DebugDrawer::drawContactPoint(const btVector3& PointOnB, const btVector3& normalOnB, btScalar distance, int lifeTime, const btVector3& color)
{
point.transform.translate(PointOnB.getX(), PointOnB.getY(), PointOnB.getZ());
point.color.Set(color.getX(), color.getY(), color.getZ());
point.Render();
}
void DebugDrawer::reportErrorWarning(const char* warningString)
{
LOG("Bullet warning: %s", warningString);
}
void DebugDrawer::draw3dText(const btVector3& location, const char* textString)
{
LOG("Bullet draw text: %s", textString);
}
void DebugDrawer::setDebugMode(int debugMode)
{
mode = (DebugDrawModes)debugMode;
}
int DebugDrawer::getDebugMode() const
{
return mode;
}
<|endoftext|>
|
<commit_before>/**
* @file lars.hpp
* @author Nishant Mehta (niche)
*
* Definition of the LARS class, which performs Least Angle Regression and the
* LASSO.
*/
#ifndef __MLPACK_METHODS_LARS_LARS_HPP
#define __MLPACK_METHODS_LARS_LARS_HPP
#include <armadillo>
#include <mlpack/core.hpp>
#define EPS 1e-16
namespace mlpack {
namespace lars {
// beta is the estimator
// yHat is the prediction from the current estimator
/**
* An implementation of LARS, a stage-wise homotopy-based algorithm for
* l1 regularized linear regression (LASSO) and l1+l2 regularized linear
* regression (Elastic Net).
* Let X be a matrix where each row is a point and each column is a dimension,
* and let y be a vector of targets.
* The Elastic Net problem is to solve
* min_beta ||X beta - y||_2^2 + lambda_1 ||beta||_1 + 0.5 lambda_2 ||beta||_2^2
* If lambda_1 > 0, lambda_2 = 0, the problem is the LASSO.
* If lambda_1 > 0, lambda_2 > 0, the problem is the Elastic Net.
* If lambda_1 = 0, lambda_2 > 0, the problem is Ridge Regression.
* If lambda_1 = 0, lambda_2 = 0, the problem is unregularized linear regression.
*
* Note: This algorithm is not recommended for use (in terms of efficiency)
* when lambda_1 = 0.
*
* Only minor modifications are necessary to handle the constrained version of
* the problem:
* min_beta ||X beta - y||_2^2 + 0.5 lambda_2 ||beta||_2^2
* subject to ||beta||_1 <= tau
* Although this option currently is not implemented, it will be implemented
* very soon.
*
* For more details, see the following papers:
*
* @article{efron2004least,
* title={Least angle regression},
* author={Efron, B. and Hastie, T. and Johnstone, I. and Tibshirani, R.},
* journal={The Annals of statistics},
* volume={32},
* number={2},
* pages={407--499},
* year={2004},
* publisher={Institute of Mathematical Statistics}
* }
*
* @article{zou2005regularization,
* title={Regularization and variable selection via the elastic net},
* author={Zou, H. and Hastie, T.},
* journal={Journal of the Royal Statistical Society Series B},
* volume={67},
* number={2},
* pages={301--320},
* year={2005},
* publisher={Royal Statistical Society}
* }
*/
class LARS {
public:
LARS(const bool useCholesky);
LARS(const bool useCholesky,
const double lambda1);
LARS(const bool useCholesky,
const double lambda1,
const double lambda2);
~LARS() { }
void SetGram(const arma::mat& matGram);
void ComputeGram(const arma::mat& matX);
const std::vector<arma::u32> ActiveSet();
const std::vector<arma::vec> BetaPath();
const std::vector<double> LambdaPath();
const arma::mat MatUtriCholFactor();
void DoLARS(const arma::mat& matX, const arma::vec& y);
void Solution(arma::vec& beta);
private:
arma::mat matGram;
// Upper triangular cholesky factor; initially 0x0 arma::matrix.
arma::mat matUtriCholFactor;
bool useCholesky;
bool lasso;
double lambda1;
bool elasticNet;
double lambda2;
std::vector<arma::vec> betaPath;
std::vector<double> lambdaPath;
arma::u32 nActive;
std::vector<arma::u32> activeSet;
std::vector<bool> isActive;
void Deactivate(arma::u32 activeVarInd);
void Activate(arma::u32 varInd);
void ComputeYHatDirection(const arma::mat& matX,
const arma::vec& betaDirection,
arma::vec& yHatDirection);
void InterpolateBeta();
void CholeskyInsert(const arma::vec& newX, const arma::mat& X);
void CholeskyInsert(const arma::vec& newX, const arma::vec& newGramCol);
void GivensRotate(const arma::vec& x, arma::vec& rotatedX, arma::mat& G);
void CholeskyDelete(arma::u32 colToKill);
};
}; // namespace lars
}; // namespace mlpack
#endif
<commit_msg>added some comments to LARS<commit_after>/**
* @file lars.hpp
* @author Nishant Mehta (niche)
*
* Definition of the LARS class, which performs Least Angle Regression and the
* LASSO.
*/
#ifndef __MLPACK_METHODS_LARS_LARS_HPP
#define __MLPACK_METHODS_LARS_LARS_HPP
#include <armadillo>
#include <mlpack/core.hpp>
#define EPS 1e-16
namespace mlpack {
namespace lars {
// beta is the estimator
// yHat is the prediction from the current estimator
/**
* An implementation of LARS, a stage-wise homotopy-based algorithm for
* l1 regularized linear regression (LASSO) and l1+l2 regularized linear
* regression (Elastic Net).
* Let X be a matrix where each row is a point and each column is a dimension,
* and let y be a vector of targets.
* The Elastic Net problem is to solve
* min_beta ||X beta - y||_2^2 + lambda_1 ||beta||_1 + 0.5 lambda_2 ||beta||_2^2
* If lambda_1 > 0, lambda_2 = 0, the problem is the LASSO.
* If lambda_1 > 0, lambda_2 > 0, the problem is the Elastic Net.
* If lambda_1 = 0, lambda_2 > 0, the problem is Ridge Regression.
* If lambda_1 = 0, lambda_2 = 0, the problem is unregularized linear regression.
*
* Note: This algorithm is not recommended for use (in terms of efficiency)
* when lambda_1 = 0.
*
* Only minor modifications are necessary to handle the constrained version of
* the problem:
* min_beta ||X beta - y||_2^2 + 0.5 lambda_2 ||beta||_2^2
* subject to ||beta||_1 <= tau
* Although this option currently is not implemented, it will be implemented
* very soon.
*
* For more details, see the following papers:
*
* @article{efron2004least,
* title={Least angle regression},
* author={Efron, B. and Hastie, T. and Johnstone, I. and Tibshirani, R.},
* journal={The Annals of statistics},
* volume={32},
* number={2},
* pages={407--499},
* year={2004},
* publisher={Institute of Mathematical Statistics}
* }
*
* @article{zou2005regularization,
* title={Regularization and variable selection via the elastic net},
* author={Zou, H. and Hastie, T.},
* journal={Journal of the Royal Statistical Society Series B},
* volume={67},
* number={2},
* pages={301--320},
* year={2005},
* publisher={Royal Statistical Society}
* }
*/
class LARS {
public:
/**
* Set the parameters to LARS
* Both lambda1 and lambda2 default to 0
*
* @param useCholesky Whether or not to use Cholesky decomposition when
* solving linear system. If no, compute full Gram matrix at beginning.
* @param lambda1 Regularization parameter for l_1-norm penalty
*/
LARS(const bool useCholesky);
/**
* Set the parameters to LARS
* lambda2 defaults to 0
*
* @param useCholesky Whether or not to use Cholesky decomposition when
* solving linear system. If no, compute full Gram matrix at beginning.
* @param lambda1 Regularization parameter for l_1-norm penalty
*/
LARS(const bool useCholesky,
const double lambda1);
/**
* Set the parameters to LARS
*
* @param useCholesky Whether or not to use Cholesky decomposition when
* solving linear system. If no, compute full Gram matrix at beginning.
* @param lambda1 Regularization parameter for l_1-norm penalty
* @param lambda2 Regularization parameter for l_2-norm penalty
*/
LARS(const bool useCholesky,
const double lambda1,
const double lambda2);
~LARS() { }
/*
* Set the Gram matrix (done before calling DoLars)
*
* @param matGram Matrix to which to set Gram matrix
*/
void SetGram(const arma::mat& matGram);
/*
* Compute Gram matrix. If elastic net, add lambda2 * identity to diagonal.
*
* @param matX Data matrix to use for computing Gram matrix
*/
void ComputeGram(const arma::mat& matX);
/*
* Accessor for activeSet
*/
const std::vector<arma::u32> ActiveSet();
/*
* Accessor for betaPath
*/
const std::vector<arma::vec> BetaPath();
/*
* Accessor for lambdaPath
*/
const std::vector<double> LambdaPath();
/*
* Accessor for matUtriCholFactor
*/
const arma::mat MatUtriCholFactor();
/*
* Do LARS
*/
void DoLARS(const arma::mat& matX, const arma::vec& y);
/*
* Load the solution vector, which is the last vector from the solution path
*/
void Solution(arma::vec& beta);
private:
arma::mat matGram;
// Upper triangular cholesky factor; initially 0x0 arma::matrix.
arma::mat matUtriCholFactor;
bool useCholesky;
bool lasso;
double lambda1;
bool elasticNet;
double lambda2;
std::vector<arma::vec> betaPath;
std::vector<double> lambdaPath;
arma::u32 nActive;
std::vector<arma::u32> activeSet;
std::vector<bool> isActive;
void Deactivate(arma::u32 activeVarInd);
void Activate(arma::u32 varInd);
void ComputeYHatDirection(const arma::mat& matX,
const arma::vec& betaDirection,
arma::vec& yHatDirection);
void InterpolateBeta();
void CholeskyInsert(const arma::vec& newX, const arma::mat& X);
void CholeskyInsert(const arma::vec& newX, const arma::vec& newGramCol);
void GivensRotate(const arma::vec& x, arma::vec& rotatedX, arma::mat& G);
void CholeskyDelete(arma::u32 colToKill);
};
}; // namespace lars
}; // namespace mlpack
#endif
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#ifndef INCLUDED_DBACCESS_SOURCE_UI_INC_DIRECTSQL_HXX
#define INCLUDED_DBACCESS_SOURCE_UI_INC_DIRECTSQL_HXX
#include <vcl/dialog.hxx>
#include <svtools/editsyntaxhighlighter.hxx>
#include <vcl/fixed.hxx>
#include <vcl/lstbox.hxx>
#include <vcl/button.hxx>
#include <deque>
#include <com/sun/star/sdbc/XConnection.hpp>
#include <unotools/eventlisteneradapter.hxx>
#include "moduledbu.hxx"
#include <osl/mutex.hxx>
#include <svtools/editbrowsebox.hxx>
namespace dbaui
{
// DirectSQLDialog
class DirectSQLDialog
:public ModalDialog
,public ::utl::OEventListenerAdapter
{
protected:
OModuleClient m_aModuleClient;
::osl::Mutex m_aMutex;
MultiLineEditSyntaxHighlight* m_pSQL;
PushButton* m_pExecute;
ListBox* m_pSQLHistory;
VclMultiLineEdit* m_pStatus;
CheckBox* m_pShowOutput;
VclMultiLineEdit* m_pOutput;
HelpButton* m_pHelp;
PushButton* m_pClose;
typedef ::std::deque< OUString > StringQueue;
StringQueue m_aStatementHistory; // previous statements
StringQueue m_aNormalizedHistory; // previous statements, normalized to be used in the list box
sal_Int32 m_nHistoryLimit;
sal_Int32 m_nStatusCount;
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >
m_xConnection;
public:
DirectSQLDialog(
Window* _pParent,
const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConn);
virtual ~DirectSQLDialog();
/// number of history entries
sal_Int32 getHistorySize() const;
protected:
void executeCurrent();
void switchToHistory(sal_Int32 _nHistoryPos, bool _bUpdateListBox = true);
// OEventListenerAdapter
virtual void _disposing( const ::com::sun::star::lang::EventObject& _rSource ) SAL_OVERRIDE;
protected:
DECL_LINK( OnExecute, void* );
DECL_LINK( OnClose, void* );
DECL_LINK( OnListEntrySelected, void* );
DECL_LINK( OnStatementModified, void* );
private:
/// adds a statement to the statement history
void implAddToStatementHistory(const OUString& _rStatement);
/// ensures that our history has at most m_nHistoryLimit entries
void implEnsureHistoryLimit();
/// executes the statement given, adds the status to the status list
void implExecuteStatement(const OUString& _rStatement);
/// adds a status text to the status list
void addStatusText(const OUString& _rMessage);
/// adds a status text to the output list
void addOutputText(const OUString& _rMessage);
#ifdef DBG_UTIL
const sal_Char* impl_CheckInvariants() const;
#endif
};
#ifdef DBG_UTIL
#define CHECK_INVARIANTS(methodname) \
{ \
const sal_Char* pError = impl_CheckInvariants(); \
if (pError) \
SAL_WARN("dbaccess.ui", methodname << ": " << pError); \
}
#else
#define CHECK_INVARIANTS(methodname)
#endif
} // namespace dbaui
#endif // INCLUDED_DBACCESS_SOURCE_UI_INC_DIRECTSQL_HXX
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>coverity#1210197 Uninitialized pointer field<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#ifndef INCLUDED_DBACCESS_SOURCE_UI_INC_DIRECTSQL_HXX
#define INCLUDED_DBACCESS_SOURCE_UI_INC_DIRECTSQL_HXX
#include <vcl/dialog.hxx>
#include <svtools/editsyntaxhighlighter.hxx>
#include <vcl/fixed.hxx>
#include <vcl/lstbox.hxx>
#include <vcl/button.hxx>
#include <deque>
#include <com/sun/star/sdbc/XConnection.hpp>
#include <unotools/eventlisteneradapter.hxx>
#include "moduledbu.hxx"
#include <osl/mutex.hxx>
#include <svtools/editbrowsebox.hxx>
namespace dbaui
{
// DirectSQLDialog
class DirectSQLDialog
:public ModalDialog
,public ::utl::OEventListenerAdapter
{
protected:
OModuleClient m_aModuleClient;
::osl::Mutex m_aMutex;
MultiLineEditSyntaxHighlight* m_pSQL;
PushButton* m_pExecute;
ListBox* m_pSQLHistory;
VclMultiLineEdit* m_pStatus;
CheckBox* m_pShowOutput;
VclMultiLineEdit* m_pOutput;
PushButton* m_pClose;
typedef ::std::deque< OUString > StringQueue;
StringQueue m_aStatementHistory; // previous statements
StringQueue m_aNormalizedHistory; // previous statements, normalized to be used in the list box
sal_Int32 m_nHistoryLimit;
sal_Int32 m_nStatusCount;
::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >
m_xConnection;
public:
DirectSQLDialog(
Window* _pParent,
const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConn);
virtual ~DirectSQLDialog();
/// number of history entries
sal_Int32 getHistorySize() const;
protected:
void executeCurrent();
void switchToHistory(sal_Int32 _nHistoryPos, bool _bUpdateListBox = true);
// OEventListenerAdapter
virtual void _disposing( const ::com::sun::star::lang::EventObject& _rSource ) SAL_OVERRIDE;
protected:
DECL_LINK( OnExecute, void* );
DECL_LINK( OnClose, void* );
DECL_LINK( OnListEntrySelected, void* );
DECL_LINK( OnStatementModified, void* );
private:
/// adds a statement to the statement history
void implAddToStatementHistory(const OUString& _rStatement);
/// ensures that our history has at most m_nHistoryLimit entries
void implEnsureHistoryLimit();
/// executes the statement given, adds the status to the status list
void implExecuteStatement(const OUString& _rStatement);
/// adds a status text to the status list
void addStatusText(const OUString& _rMessage);
/// adds a status text to the output list
void addOutputText(const OUString& _rMessage);
#ifdef DBG_UTIL
const sal_Char* impl_CheckInvariants() const;
#endif
};
#ifdef DBG_UTIL
#define CHECK_INVARIANTS(methodname) \
{ \
const sal_Char* pError = impl_CheckInvariants(); \
if (pError) \
SAL_WARN("dbaccess.ui", methodname << ": " << pError); \
}
#else
#define CHECK_INVARIANTS(methodname)
#endif
} // namespace dbaui
#endif // INCLUDED_DBACCESS_SOURCE_UI_INC_DIRECTSQL_HXX
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>
|
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved
*/
#include "../../StroikaPreComp.h"
#if qPlatform_Windows
#include <Windows.h>
#endif
#include "../../../Foundation/Characters/CString/Utilities.h"
#include "../../../Foundation/Characters/String_Constant.h"
#include "../../../Foundation/Characters/String2Float.h"
#include "../../../Foundation/Containers/Sequence.h"
#include "../../../Foundation/DataExchange/CharacterDelimitedLines/Reader.h"
#include "../../../Foundation/Debug/Assertions.h"
#include "../../../Foundation/Execution/ProcessRunner.h"
#include "../../../Foundation/IO/FileSystem/BinaryFileInputStream.h"
#include "../../../Foundation/Streams/BasicBinaryInputOutputStream.h"
#include "../../../Foundation/Streams/TextInputStreamBinaryAdapter.h"
#include "../CommonMeasurementTypes.h"
#include "MountedFilesystemUsage.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Containers;
using namespace Stroika::Foundation::DataExchange;
using namespace Stroika::Foundation::Execution;
using namespace Stroika::Foundation::Memory;
using namespace Stroika::Frameworks;
using namespace Stroika::Frameworks::SystemPerformance;
using namespace Stroika::Frameworks::SystemPerformance::Instruments::MountedFilesystemUsage;
using Characters::String_Constant;
#if qPlatform_Windows
namespace {
Sequence<VolumeInfo> capture_Windows_GetVolumeInfo_ ()
{
Sequence<VolumeInfo> result;
TCHAR volumeNameBuf[1024];
for (HANDLE hVol = FindFirstVolume (volumeNameBuf, NEltsOf(volumeNameBuf)); hVol != INVALID_HANDLE_VALUE; ) {
DWORD lpMaximumComponentLength;
DWORD dwSysFlags;
TCHAR FileSysNameBuf[1024];
if (::GetVolumeInformation( volumeNameBuf, NULL, NEltsOf(volumeNameBuf), NULL, &lpMaximumComponentLength, &dwSysFlags, FileSysNameBuf, NEltsOf(FileSysNameBuf))) {
VolumeInfo v;
v.fFileSystemType = String::FromSDKString (FileSysNameBuf);
v.fVolumeID = String::FromSDKString (volumeNameBuf);
{
// @todo - use
// http://msdn.microsoft.com/en-us/library/windows/desktop/cc542456(v=vs.85).aspx
// CharCount = QueryDosDeviceW(&VolumeName[4], DeviceName, ARRAYSIZE(DeviceName));
// to get DEVICENAME
//
TCHAR volPathsBuf[1024];
DWORD retLen = 0;
DWORD x = GetVolumePathNamesForVolumeName (volumeNameBuf, volPathsBuf, NEltsOf(volPathsBuf), &retLen);
if (volPathsBuf[0] == 0) {
v.fMountedOnName.clear ();
result.push_back (v);
}
else {
for (const TCHAR* NameIdx = volPathsBuf; NameIdx[0] != L'\0'; NameIdx += Characters::CString::Length (NameIdx) + 1) {
v.fMountedOnName = String::FromSDKString (NameIdx);
{
ULARGE_INTEGER freeBytesAvailable;
ULARGE_INTEGER totalNumberOfBytes;
ULARGE_INTEGER totalNumberOfFreeBytes;
memset (&freeBytesAvailable, 0, sizeof (freeBytesAvailable));
memset (&totalNumberOfBytes, 0, sizeof (totalNumberOfBytes));
memset (&totalNumberOfFreeBytes, 0, sizeof (totalNumberOfFreeBytes));
DWORD xxx = GetDiskFreeSpaceEx (v.fMountedOnName.AsSDKString ().c_str (), &freeBytesAvailable, &totalNumberOfBytes, &totalNumberOfFreeBytes);
v.fDiskSizeInBytes = static_cast<double> (totalNumberOfBytes.QuadPart);
v.fUsedSizeInBytes = *v.fDiskSizeInBytes - freeBytesAvailable.QuadPart;
}
result.push_back (v);
}
}
}
}
else {
// warning...
}
// find next
if (not ::FindNextVolume (hVol, volumeNameBuf, NEltsOf(volumeNameBuf))) {
FindVolumeClose (hVol);
hVol = INVALID_HANDLE_VALUE;
}
}
return result;
}
}
#endif
#if qPlatform_POSIX
namespace {
Sequence<VolumeInfo> capture_Process_Run_DF_ ()
{
Sequence<VolumeInfo> result;
//
// I looked through the /proc filesystem stuff and didnt see anything obvious to retrive this info...
// run def with ProcessRunner
//
// NEW NOTE - I THINK ITS IN THERE.... RE-EXAMINE proc/filesystems proc/partitions, and http://en.wikipedia.org/wiki/Procfs
// -- LGP 2014-08-01
ProcessRunner pr (L"/bin/df -k -T");
Streams::BasicBinaryInputOutputStream useStdOut;
pr.SetStdOut (useStdOut);
pr.Run ();
String out;
Streams::TextInputStreamBinaryAdapter stdOut = Streams::TextInputStreamBinaryAdapter (useStdOut);
bool skippedHeader = false;
for (String i = stdOut.ReadLine (); not i.empty (); i = stdOut.ReadLine ()) {
if (not skippedHeader) {
skippedHeader = true;
continue;
}
Sequence<String> l = i.Tokenize (Set<Characters::Character> { ' ' });
if (l.size () < 7) {
DbgTrace ("skipping line cuz len=%d", l.size ());
continue;
}
VolumeInfo v;
v.fFileSystemType = l[1].Trim ();
v.fMountedOnName = l[6].Trim ();
{
String d = l[0].Trim ();
if (not d.empty () and d != L"none") {
v.fDeviceOrVolumeName = d;
}
}
v.fDiskSizeInBytes = Characters::String2Float<double> (l[2]) * 1024;
v.fUsedSizeInBytes = Characters::String2Float<double> (l[3]) * 1024;
result.Append (v);
}
return result;
}
}
#endif
#if qPlatform_POSIX
namespace {
struct PerfStats_ {
double fSectorsRead {};
double fTimeSpentReading {};
double fSectorsWritten {};
double fTimeSpentWritingMS {};
};
Mapping<String, PerfStats_> capture_ProcFSDiskStats_ ()
{
using IO::FileSystem::BinaryFileInputStream;
using Characters::String2Float;
Mapping<String, PerfStats_> result;
DataExchange::CharacterDelimitedLines::Reader reader {{' ', '\t' }};
const String_Constant kProcMemInfoFileName_ { L"/proc/diskstats" };
// Note - /procfs files always unseekable
for (Sequence<String> line : reader.ReadMatrix (BinaryFileInputStream::mk (kProcMemInfoFileName_, BinaryFileInputStream::eNotSeekable))) {
#if USE_NOISY_TRACE_IN_THIS_MODULE_
DbgTrace (L"***in Instruments::MountedFilesystemUsage::capture_ProcFSDiskStats_ linesize=%d, line[0]=%s", line.size(), line.empty () ? L"" : line[0].c_str ());
#endif
//
// https://www.kernel.org/doc/Documentation/ABI/testing/procfs-diskstats
//
// 3 - device name
// 6 - sectors read
// 7 - time spent reading (ms)
// 10 - sectors written
// 11 - time spent writing (ms)
//
if (line.size () >= 13) {
String devName = line[3 - 1];
String sectorsRead = line[6 - 1];
String timeSpentReadingMS = line[7 - 1];
String sectorsWritten = line[10 - 1];
String timeSpentWritingMS = line[11 - 1];
result.Add (
devName,
PerfStats_ { String2Float (sectorsRead), String2Float (timeSpentReadingMS) / 1000, String2Float (sectorsWritten), String2Float (timeSpentWritingMS) / 1000 }
);
}
}
return result;
}
}
#endif
namespace {
Sequence<VolumeInfo> capture_ ()
{
Sequence<VolumeInfo> results;
#if qPlatform_Windows
results = capture_Windows_GetVolumeInfo_ ();
#elif qPlatform_POSIX
results = capture_Process_Run_DF_ ();
try {
Mapping<String, PerfStats_> diskStats = capture_ProcFSDiskStats_ ();
Sequence<VolumeInfo> newV;
for (VolumneInfo v : results) {
if (v.fDeviceOrVolumeName.IsPresent ()) {
String devNameLessSlashes = *v.fDeviceOrVolumeName;
size_t i = d.RFind ('/');
if (i != string::npos) {
devNameLessSlashes = devNameLessSlashes.SubString (i + 1);
}
Optional<PerfStats_> o = diskStats.Lookup (devNameLessSlashes);
if (o.IsPresent ()) {
v.fReadIOStats.fBytes = a;
v.fReadIOStats.fTimeTransfering = a;
v.fWriteIOStats.fBytes = a;
v.fWriteIOStats.fTimeTransfering = fTimeTransfering;
v.fIOStats.fBytes = v.fReadIOStats.fBytes + v.fWriteIOStats.fBytes;
v.fIOStats.fTimeTransfering = v.fReadIOStats.fTimeTransfering + v.fWriteIOStats.fTimeTransfering;
}
}
newV.Append (v);
}
results = newV;
}
catch (...) {
}
#endif
return results;
}
}
/*
********************************************************************************
********** Instruments::MountedFilesystemUsage::GetObjectVariantMapper *********
********************************************************************************
*/
ObjectVariantMapper Instruments::MountedFilesystemUsage::GetObjectVariantMapper ()
{
using StructureFieldInfo = ObjectVariantMapper::StructureFieldInfo;
ObjectVariantMapper sMapper_ = [] () -> ObjectVariantMapper {
ObjectVariantMapper mapper;
mapper.AddCommonType<Optional<double>> ();
mapper.AddCommonType<Optional<String>> ();
DISABLE_COMPILER_CLANG_WARNING_START("clang diagnostic ignored \"-Winvalid-offsetof\""); // Really probably an issue, but not to debug here -- LGP 2014-01-04
DISABLE_COMPILER_GCC_WARNING_START("GCC diagnostic ignored \"-Winvalid-offsetof\""); // Really probably an issue, but not to debug here -- LGP 2014-01-04
mapper.AddClass<VolumeInfo::IOStats> (initializer_list<StructureFieldInfo> {
{ Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (VolumeInfo::IOStats, fBytes), String_Constant (L"Bytes"), StructureFieldInfo::NullFieldHandling::eOmit },
{ Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (VolumeInfo::IOStats, fTimeTransfering), String_Constant (L"Time-Transfering"), StructureFieldInfo::NullFieldHandling::eOmit },
});
mapper.AddClass<VolumeInfo> (initializer_list<StructureFieldInfo> {
{ Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (VolumeInfo, fFileSystemType), String_Constant (L"Filesystem-Type"), StructureFieldInfo::NullFieldHandling::eOmit },
{ Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (VolumeInfo, fDeviceOrVolumeName), String_Constant (L"Device-Name"), StructureFieldInfo::NullFieldHandling::eOmit },
{ Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (VolumeInfo, fVolumeID), String_Constant (L"Volume-ID"), StructureFieldInfo::NullFieldHandling::eOmit },
{ Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (VolumeInfo, fMountedOnName), String_Constant (L"Mounted-On") },
{ Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (VolumeInfo, fDiskSizeInBytes), String_Constant (L"Disk-Size"), StructureFieldInfo::NullFieldHandling::eOmit },
{ Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (VolumeInfo, fUsedSizeInBytes), String_Constant (L"Disk-Used-Size"), StructureFieldInfo::NullFieldHandling::eOmit },
{ Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (VolumeInfo, fReadIOStats), String_Constant (L"fReadIOStats") },
{ Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (VolumeInfo, fWriteIOStats), String_Constant (L"fWriteIOStats") },
{ Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (VolumeInfo, fIOStats), String_Constant (L"fIOStats") },
});
DISABLE_COMPILER_GCC_WARNING_END("GCC diagnostic ignored \"-Winvalid-offsetof\"");
DISABLE_COMPILER_CLANG_WARNING_END("clang diagnostic ignored \"-Winvalid-offsetof\"");
mapper.AddCommonType<Collection<VolumeInfo>> ();
mapper.AddCommonType<Sequence<VolumeInfo>> ();
return mapper;
} ();
return sMapper_;
}
/*
********************************************************************************
************* Instruments::MountedFilesystemUsage::GetInstrument ***************
********************************************************************************
*/
Instrument SystemPerformance::Instruments::MountedFilesystemUsage::GetInstrument ()
{
static Instrument kInstrument_ = Instrument (
InstrumentNameType (String_Constant (L"Mounted-Filesystem-Usage")),
[] () -> MeasurementSet {
MeasurementSet results;
DateTime before = DateTime::Now ();
Sequence<VolumeInfo> volumes = capture_ ();
results.fMeasuredAt = DateTimeRange (before, DateTime::Now ());
Measurement m;
m.fValue = MountedFilesystemUsage::GetObjectVariantMapper ().FromObject (volumes);
m.fType = kMountedVolumeUsage;
results.fMeasurements.Add (m);
return results;
},
{kMountedVolumeUsage},
GetObjectVariantMapper ()
);
return kInstrument_;
}
Instrument SystemPerformance::Instruments::GetMountedFilesystemUsage ()
{
return MountedFilesystemUsage::GetInstrument ();
}
<commit_msg>posix mounted filesystem usage iostats fixes<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved
*/
#include "../../StroikaPreComp.h"
#if qPlatform_Windows
#include <Windows.h>
#endif
#include "../../../Foundation/Characters/CString/Utilities.h"
#include "../../../Foundation/Characters/String_Constant.h"
#include "../../../Foundation/Characters/String2Float.h"
#include "../../../Foundation/Containers/Sequence.h"
#include "../../../Foundation/DataExchange/CharacterDelimitedLines/Reader.h"
#include "../../../Foundation/Debug/Assertions.h"
#include "../../../Foundation/Execution/ProcessRunner.h"
#include "../../../Foundation/IO/FileSystem/BinaryFileInputStream.h"
#include "../../../Foundation/Streams/BasicBinaryInputOutputStream.h"
#include "../../../Foundation/Streams/TextInputStreamBinaryAdapter.h"
#include "../CommonMeasurementTypes.h"
#include "MountedFilesystemUsage.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Containers;
using namespace Stroika::Foundation::DataExchange;
using namespace Stroika::Foundation::Execution;
using namespace Stroika::Foundation::Memory;
using namespace Stroika::Frameworks;
using namespace Stroika::Frameworks::SystemPerformance;
using namespace Stroika::Frameworks::SystemPerformance::Instruments::MountedFilesystemUsage;
using Characters::String_Constant;
#if qPlatform_Windows
namespace {
Sequence<VolumeInfo> capture_Windows_GetVolumeInfo_ ()
{
Sequence<VolumeInfo> result;
TCHAR volumeNameBuf[1024];
for (HANDLE hVol = FindFirstVolume (volumeNameBuf, NEltsOf(volumeNameBuf)); hVol != INVALID_HANDLE_VALUE; ) {
DWORD lpMaximumComponentLength;
DWORD dwSysFlags;
TCHAR FileSysNameBuf[1024];
if (::GetVolumeInformation( volumeNameBuf, NULL, NEltsOf(volumeNameBuf), NULL, &lpMaximumComponentLength, &dwSysFlags, FileSysNameBuf, NEltsOf(FileSysNameBuf))) {
VolumeInfo v;
v.fFileSystemType = String::FromSDKString (FileSysNameBuf);
v.fVolumeID = String::FromSDKString (volumeNameBuf);
{
// @todo - use
// http://msdn.microsoft.com/en-us/library/windows/desktop/cc542456(v=vs.85).aspx
// CharCount = QueryDosDeviceW(&VolumeName[4], DeviceName, ARRAYSIZE(DeviceName));
// to get DEVICENAME
//
TCHAR volPathsBuf[1024];
DWORD retLen = 0;
DWORD x = GetVolumePathNamesForVolumeName (volumeNameBuf, volPathsBuf, NEltsOf(volPathsBuf), &retLen);
if (volPathsBuf[0] == 0) {
v.fMountedOnName.clear ();
result.push_back (v);
}
else {
for (const TCHAR* NameIdx = volPathsBuf; NameIdx[0] != L'\0'; NameIdx += Characters::CString::Length (NameIdx) + 1) {
v.fMountedOnName = String::FromSDKString (NameIdx);
{
ULARGE_INTEGER freeBytesAvailable;
ULARGE_INTEGER totalNumberOfBytes;
ULARGE_INTEGER totalNumberOfFreeBytes;
memset (&freeBytesAvailable, 0, sizeof (freeBytesAvailable));
memset (&totalNumberOfBytes, 0, sizeof (totalNumberOfBytes));
memset (&totalNumberOfFreeBytes, 0, sizeof (totalNumberOfFreeBytes));
DWORD xxx = GetDiskFreeSpaceEx (v.fMountedOnName.AsSDKString ().c_str (), &freeBytesAvailable, &totalNumberOfBytes, &totalNumberOfFreeBytes);
v.fDiskSizeInBytes = static_cast<double> (totalNumberOfBytes.QuadPart);
v.fUsedSizeInBytes = *v.fDiskSizeInBytes - freeBytesAvailable.QuadPart;
}
result.push_back (v);
}
}
}
}
else {
// warning...
}
// find next
if (not ::FindNextVolume (hVol, volumeNameBuf, NEltsOf(volumeNameBuf))) {
FindVolumeClose (hVol);
hVol = INVALID_HANDLE_VALUE;
}
}
return result;
}
}
#endif
#if qPlatform_POSIX
namespace {
Sequence<VolumeInfo> capture_Process_Run_DF_ ()
{
Sequence<VolumeInfo> result;
//
// I looked through the /proc filesystem stuff and didnt see anything obvious to retrive this info...
// run def with ProcessRunner
//
// NEW NOTE - I THINK ITS IN THERE.... RE-EXAMINE proc/filesystems proc/partitions, and http://en.wikipedia.org/wiki/Procfs
// -- LGP 2014-08-01
ProcessRunner pr (L"/bin/df -k -T");
Streams::BasicBinaryInputOutputStream useStdOut;
pr.SetStdOut (useStdOut);
pr.Run ();
String out;
Streams::TextInputStreamBinaryAdapter stdOut = Streams::TextInputStreamBinaryAdapter (useStdOut);
bool skippedHeader = false;
for (String i = stdOut.ReadLine (); not i.empty (); i = stdOut.ReadLine ()) {
if (not skippedHeader) {
skippedHeader = true;
continue;
}
Sequence<String> l = i.Tokenize (Set<Characters::Character> { ' ' });
if (l.size () < 7) {
DbgTrace ("skipping line cuz len=%d", l.size ());
continue;
}
VolumeInfo v;
v.fFileSystemType = l[1].Trim ();
v.fMountedOnName = l[6].Trim ();
{
String d = l[0].Trim ();
if (not d.empty () and d != L"none") {
v.fDeviceOrVolumeName = d;
}
}
v.fDiskSizeInBytes = Characters::String2Float<double> (l[2]) * 1024;
v.fUsedSizeInBytes = Characters::String2Float<double> (l[3]) * 1024;
result.Append (v);
}
return result;
}
}
#endif
#if qPlatform_POSIX
namespace {
struct PerfStats_ {
double fSectorsRead;
double fTimeSpentReading;
double fSectorsWritten;
double fTimeSpentWritingMS;
};
Mapping<String, PerfStats_> capture_ProcFSDiskStats_ ()
{
using IO::FileSystem::BinaryFileInputStream;
using Characters::String2Float;
Mapping<String, PerfStats_> result;
DataExchange::CharacterDelimitedLines::Reader reader {{' ', '\t' }};
const String_Constant kProcMemInfoFileName_ { L"/proc/diskstats" };
// Note - /procfs files always unseekable
for (Sequence<String> line : reader.ReadMatrix (BinaryFileInputStream::mk (kProcMemInfoFileName_, BinaryFileInputStream::eNotSeekable))) {
#if USE_NOISY_TRACE_IN_THIS_MODULE_
DbgTrace (L"***in Instruments::MountedFilesystemUsage::capture_ProcFSDiskStats_ linesize=%d, line[0]=%s", line.size(), line.empty () ? L"" : line[0].c_str ());
#endif
//
// https://www.kernel.org/doc/Documentation/ABI/testing/procfs-diskstats
//
// 3 - device name
// 6 - sectors read
// 7 - time spent reading (ms)
// 10 - sectors written
// 11 - time spent writing (ms)
//
if (line.size () >= 13) {
String devName = line[3 - 1];
String sectorsRead = line[6 - 1];
String timeSpentReadingMS = line[7 - 1];
String sectorsWritten = line[10 - 1];
String timeSpentWritingMS = line[11 - 1];
result.Add (
devName,
PerfStats_ { String2Float (sectorsRead), String2Float (timeSpentReadingMS) / 1000, String2Float (sectorsWritten), String2Float (timeSpentWritingMS) / 1000 }
);
}
}
return result;
}
}
#endif
namespace {
Sequence<VolumeInfo> capture_ ()
{
Sequence<VolumeInfo> results;
#if qPlatform_Windows
results = capture_Windows_GetVolumeInfo_ ();
#elif qPlatform_POSIX
results = capture_Process_Run_DF_ ();
try {
Mapping<String, PerfStats_> diskStats = capture_ProcFSDiskStats_ ();
Sequence<VolumeInfo> newV;
for (VolumneInfo v : results) {
if (v.fDeviceOrVolumeName.IsPresent ()) {
String devNameLessSlashes = *v.fDeviceOrVolumeName;
size_t i = devNameLessSlashes.RFind ('/');
if (i != string::npos) {
devNameLessSlashes = devNameLessSlashes.SubString (i + 1);
}
Optional<PerfStats_> o = diskStats.Lookup (devNameLessSlashes);
if (o.IsPresent ()) {
const unsigned int kSectorSizeTmpHack_ = 4 * 1024; // @todo GET from disk stats
v.fReadIOStats.fBytes = o->fSectorsRead * kSectorSizeTmpHack_;
v.fReadIOStats.fTimeTransfering = o->fTimeSpentReading;
v.fWriteIOStats.fBytes = o->fSectorsWritten * kSectorSizeTmpHack_;
v.fWriteIOStats.fTimeTransfering = o->fTimeSpentReading;
v.fIOStats.fBytes = v.fReadIOStats.fBytes + v.fWriteIOStats.fBytes;
v.fIOStats.fTimeTransfering = v.fReadIOStats.fTimeTransfering + v.fWriteIOStats.fTimeTransfering;
}
}
newV.Append (v);
}
results = newV;
}
catch (...) {
}
#endif
return results;
}
}
/*
********************************************************************************
********** Instruments::MountedFilesystemUsage::GetObjectVariantMapper *********
********************************************************************************
*/
ObjectVariantMapper Instruments::MountedFilesystemUsage::GetObjectVariantMapper ()
{
using StructureFieldInfo = ObjectVariantMapper::StructureFieldInfo;
ObjectVariantMapper sMapper_ = [] () -> ObjectVariantMapper {
ObjectVariantMapper mapper;
mapper.AddCommonType<Optional<double>> ();
mapper.AddCommonType<Optional<String>> ();
DISABLE_COMPILER_CLANG_WARNING_START("clang diagnostic ignored \"-Winvalid-offsetof\""); // Really probably an issue, but not to debug here -- LGP 2014-01-04
DISABLE_COMPILER_GCC_WARNING_START("GCC diagnostic ignored \"-Winvalid-offsetof\""); // Really probably an issue, but not to debug here -- LGP 2014-01-04
mapper.AddClass<VolumeInfo::IOStats> (initializer_list<StructureFieldInfo> {
{ Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (VolumeInfo::IOStats, fBytes), String_Constant (L"Bytes"), StructureFieldInfo::NullFieldHandling::eOmit },
{ Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (VolumeInfo::IOStats, fTimeTransfering), String_Constant (L"Time-Transfering"), StructureFieldInfo::NullFieldHandling::eOmit },
});
mapper.AddClass<VolumeInfo> (initializer_list<StructureFieldInfo> {
{ Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (VolumeInfo, fFileSystemType), String_Constant (L"Filesystem-Type"), StructureFieldInfo::NullFieldHandling::eOmit },
{ Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (VolumeInfo, fDeviceOrVolumeName), String_Constant (L"Device-Name"), StructureFieldInfo::NullFieldHandling::eOmit },
{ Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (VolumeInfo, fVolumeID), String_Constant (L"Volume-ID"), StructureFieldInfo::NullFieldHandling::eOmit },
{ Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (VolumeInfo, fMountedOnName), String_Constant (L"Mounted-On") },
{ Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (VolumeInfo, fDiskSizeInBytes), String_Constant (L"Disk-Size"), StructureFieldInfo::NullFieldHandling::eOmit },
{ Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (VolumeInfo, fUsedSizeInBytes), String_Constant (L"Disk-Used-Size"), StructureFieldInfo::NullFieldHandling::eOmit },
{ Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (VolumeInfo, fReadIOStats), String_Constant (L"fReadIOStats") },
{ Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (VolumeInfo, fWriteIOStats), String_Constant (L"fWriteIOStats") },
{ Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (VolumeInfo, fIOStats), String_Constant (L"fIOStats") },
});
DISABLE_COMPILER_GCC_WARNING_END("GCC diagnostic ignored \"-Winvalid-offsetof\"");
DISABLE_COMPILER_CLANG_WARNING_END("clang diagnostic ignored \"-Winvalid-offsetof\"");
mapper.AddCommonType<Collection<VolumeInfo>> ();
mapper.AddCommonType<Sequence<VolumeInfo>> ();
return mapper;
} ();
return sMapper_;
}
/*
********************************************************************************
************* Instruments::MountedFilesystemUsage::GetInstrument ***************
********************************************************************************
*/
Instrument SystemPerformance::Instruments::MountedFilesystemUsage::GetInstrument ()
{
static Instrument kInstrument_ = Instrument (
InstrumentNameType (String_Constant (L"Mounted-Filesystem-Usage")),
[] () -> MeasurementSet {
MeasurementSet results;
DateTime before = DateTime::Now ();
Sequence<VolumeInfo> volumes = capture_ ();
results.fMeasuredAt = DateTimeRange (before, DateTime::Now ());
Measurement m;
m.fValue = MountedFilesystemUsage::GetObjectVariantMapper ().FromObject (volumes);
m.fType = kMountedVolumeUsage;
results.fMeasurements.Add (m);
return results;
},
{kMountedVolumeUsage},
GetObjectVariantMapper ()
);
return kInstrument_;
}
Instrument SystemPerformance::Instruments::GetMountedFilesystemUsage ()
{
return MountedFilesystemUsage::GetInstrument ();
}
<|endoftext|>
|
<commit_before>//===-- SchedInfo.cpp - Generic code to support target schedulers ----------==//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the generic part of a Scheduler description for a
// target. This functionality is defined in the llvm/Target/SchedInfo.h file.
//
//===----------------------------------------------------------------------===//
#include "llvm/Config/alloca.h"
#include "llvm/Target/TargetSchedInfo.h"
#include "llvm/Target/TargetMachine.h"
#include <algorithm>
#include <iostream>
using namespace llvm;
resourceId_t llvm::CPUResource::nextId = 0;
static std::vector<CPUResource*> *CPUResourceMap = 0;
CPUResource::CPUResource(const std::string& resourceName, int maxUsers)
: rname(resourceName), rid(nextId++), maxNumUsers(maxUsers) {
if(!CPUResourceMap)
CPUResourceMap = new std::vector<CPUResource*>;
//Put Resource in the map
CPUResourceMap->push_back(this);
}
///Get CPUResource if you only have the resource ID
CPUResource* CPUResource::getCPUResource(resourceId_t id) {
return (*CPUResourceMap)[id];
}
// Check if fromRVec and toRVec have *any* common entries.
// Assume the vectors are sorted in increasing order.
// Algorithm copied from function set_intersection() for sorted ranges
// (stl_algo.h).
//
inline static bool
RUConflict(const std::vector<resourceId_t>& fromRVec,
const std::vector<resourceId_t>& toRVec)
{
unsigned fN = fromRVec.size(), tN = toRVec.size();
unsigned fi = 0, ti = 0;
while (fi < fN && ti < tN) {
if (fromRVec[fi] < toRVec[ti])
++fi;
else if (toRVec[ti] < fromRVec[fi])
++ti;
else
return true;
}
return false;
}
static cycles_t
ComputeMinGap(const InstrRUsage &fromRU,
const InstrRUsage &toRU)
{
cycles_t minGap = 0;
if (fromRU.numBubbles > 0)
minGap = fromRU.numBubbles;
if (minGap < fromRU.numCycles) {
// only need to check from cycle `minGap' onwards
for (cycles_t gap=minGap; gap <= fromRU.numCycles-1; gap++) {
// check if instr. #2 can start executing `gap' cycles after #1
// by checking for resource conflicts in each overlapping cycle
cycles_t numOverlap =std::min(fromRU.numCycles - gap, toRU.numCycles);
for (cycles_t c = 0; c <= numOverlap-1; c++)
if (RUConflict(fromRU.resourcesByCycle[gap + c],
toRU.resourcesByCycle[c])) {
// conflict found so minGap must be more than `gap'
minGap = gap+1;
break;
}
}
}
return minGap;
}
//---------------------------------------------------------------------------
// class TargetSchedInfo
// Interface to machine description for instruction scheduling
//---------------------------------------------------------------------------
TargetSchedInfo::TargetSchedInfo(const TargetMachine& tgt,
int NumSchedClasses,
const InstrClassRUsage* ClassRUsages,
const InstrRUsageDelta* UsageDeltas,
const InstrIssueDelta* IssueDeltas,
unsigned NumUsageDeltas,
unsigned NumIssueDeltas)
: target(tgt),
numSchedClasses(NumSchedClasses), mii(tgt.getInstrInfo()),
classRUsages(ClassRUsages), usageDeltas(UsageDeltas),
issueDeltas(IssueDeltas), numUsageDeltas(NumUsageDeltas),
numIssueDeltas(NumIssueDeltas)
{}
void
TargetSchedInfo::initializeResources()
{
assert(MAX_NUM_SLOTS >= (int)getMaxNumIssueTotal()
&& "Insufficient slots for static data! Increase MAX_NUM_SLOTS");
// First, compute common resource usage info for each class because
// most instructions will probably behave the same as their class.
// Cannot allocate a vector of InstrRUsage so new each one.
//
std::vector<InstrRUsage> instrRUForClasses;
instrRUForClasses.resize(numSchedClasses);
for (InstrSchedClass sc = 0; sc < numSchedClasses; sc++) {
// instrRUForClasses.push_back(new InstrRUsage);
instrRUForClasses[sc].setMaxSlots(getMaxNumIssueTotal());
instrRUForClasses[sc].setTo(classRUsages[sc]);
}
computeInstrResources(instrRUForClasses);
computeIssueGaps(instrRUForClasses);
}
void
TargetSchedInfo::computeInstrResources(const std::vector<InstrRUsage>&
instrRUForClasses)
{
int numOpCodes = mii->getNumOpcodes();
instrRUsages.resize(numOpCodes);
// First get the resource usage information from the class resource usages.
for (MachineOpCode op = 0; op < numOpCodes; ++op) {
InstrSchedClass sc = getSchedClass(op);
assert(sc < numSchedClasses);
instrRUsages[op] = instrRUForClasses[sc];
}
// Now, modify the resource usages as specified in the deltas.
for (unsigned i = 0; i < numUsageDeltas; ++i) {
MachineOpCode op = usageDeltas[i].opCode;
assert(op < numOpCodes);
instrRUsages[op].addUsageDelta(usageDeltas[i]);
}
// Then modify the issue restrictions as specified in the deltas.
for (unsigned i = 0; i < numIssueDeltas; ++i) {
MachineOpCode op = issueDeltas[i].opCode;
assert(op < numOpCodes);
instrRUsages[issueDeltas[i].opCode].addIssueDelta(issueDeltas[i]);
}
}
void
TargetSchedInfo::computeIssueGaps(const std::vector<InstrRUsage>&
instrRUForClasses)
{
int numOpCodes = mii->getNumOpcodes();
issueGaps.resize(numOpCodes);
conflictLists.resize(numOpCodes);
assert(numOpCodes < (1 << MAX_OPCODE_SIZE) - 1
&& "numOpCodes invalid for implementation of class OpCodePair!");
// First, compute issue gaps between pairs of classes based on common
// resources usages for each class, because most instruction pairs will
// usually behave the same as their class.
//
int* classPairGaps =
static_cast<int*>(alloca(sizeof(int) * numSchedClasses * numSchedClasses));
for (InstrSchedClass fromSC=0; fromSC < numSchedClasses; fromSC++)
for (InstrSchedClass toSC=0; toSC < numSchedClasses; toSC++) {
int classPairGap = ComputeMinGap(instrRUForClasses[fromSC],
instrRUForClasses[toSC]);
classPairGaps[fromSC*numSchedClasses + toSC] = classPairGap;
}
// Now, for each pair of instructions, use the class pair gap if both
// instructions have identical resource usage as their respective classes.
// If not, recompute the gap for the pair from scratch.
longestIssueConflict = 0;
for (MachineOpCode fromOp=0; fromOp < numOpCodes; fromOp++)
for (MachineOpCode toOp=0; toOp < numOpCodes; toOp++) {
int instrPairGap =
(instrRUsages[fromOp].sameAsClass && instrRUsages[toOp].sameAsClass)
? classPairGaps[getSchedClass(fromOp)*numSchedClasses + getSchedClass(toOp)]
: ComputeMinGap(instrRUsages[fromOp], instrRUsages[toOp]);
if (instrPairGap > 0) {
this->setGap(instrPairGap, fromOp, toOp);
conflictLists[fromOp].push_back(toOp);
longestIssueConflict=std::max(longestIssueConflict, instrPairGap);
}
}
}
void InstrRUsage::setTo(const InstrClassRUsage& classRU) {
sameAsClass = true;
isSingleIssue = classRU.isSingleIssue;
breaksGroup = classRU.breaksGroup;
numBubbles = classRU.numBubbles;
for (unsigned i=0; i < classRU.numSlots; i++) {
unsigned slot = classRU.feasibleSlots[i];
assert(slot < feasibleSlots.size() && "Invalid slot specified!");
this->feasibleSlots[slot] = true;
}
numCycles = classRU.totCycles;
resourcesByCycle.resize(this->numCycles);
for (unsigned i=0; i < classRU.numRUEntries; i++)
for (unsigned c=classRU.V[i].startCycle, NC = c + classRU.V[i].numCycles;
c < NC; c++)
this->resourcesByCycle[c].push_back(classRU.V[i].resourceId);
// Sort each resource usage vector by resourceId_t to speed up conflict
// checking
for (unsigned i=0; i < this->resourcesByCycle.size(); i++)
std::sort(resourcesByCycle[i].begin(), resourcesByCycle[i].end());
}
// Add the extra resource usage requirements specified in the delta.
// Note that a negative value of `numCycles' means one entry for that
// resource should be deleted for each cycle.
//
void InstrRUsage::addUsageDelta(const InstrRUsageDelta &delta) {
int NC = delta.numCycles;
sameAsClass = false;
// resize the resources vector if more cycles are specified
unsigned maxCycles = this->numCycles;
maxCycles = std::max(maxCycles, delta.startCycle + abs(NC) - 1);
if (maxCycles > this->numCycles) {
this->resourcesByCycle.resize(maxCycles);
this->numCycles = maxCycles;
}
if (NC >= 0)
for (unsigned c=delta.startCycle, last=c+NC-1; c <= last; c++)
this->resourcesByCycle[c].push_back(delta.resourceId);
else
// Remove the resource from all NC cycles.
for (unsigned c=delta.startCycle, last=(c-NC)-1; c <= last; c++) {
// Look for the resource backwards so we remove the last entry
// for that resource in each cycle.
std::vector<resourceId_t>& rvec = this->resourcesByCycle[c];
int r;
for (r = rvec.size() - 1; r >= 0; r--)
if (rvec[r] == delta.resourceId) {
// found last entry for the resource
rvec.erase(rvec.begin() + r);
break;
}
assert(r >= 0 && "Resource to remove was unused in cycle c!");
}
}
<commit_msg>Remove dead assert<commit_after>//===-- SchedInfo.cpp - Generic code to support target schedulers ----------==//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the generic part of a Scheduler description for a
// target. This functionality is defined in the llvm/Target/SchedInfo.h file.
//
//===----------------------------------------------------------------------===//
#include "llvm/Config/alloca.h"
#include "llvm/Target/TargetSchedInfo.h"
#include "llvm/Target/TargetMachine.h"
#include <algorithm>
#include <iostream>
using namespace llvm;
resourceId_t llvm::CPUResource::nextId = 0;
static std::vector<CPUResource*> *CPUResourceMap = 0;
CPUResource::CPUResource(const std::string& resourceName, int maxUsers)
: rname(resourceName), rid(nextId++), maxNumUsers(maxUsers) {
if(!CPUResourceMap)
CPUResourceMap = new std::vector<CPUResource*>;
//Put Resource in the map
CPUResourceMap->push_back(this);
}
///Get CPUResource if you only have the resource ID
CPUResource* CPUResource::getCPUResource(resourceId_t id) {
return (*CPUResourceMap)[id];
}
// Check if fromRVec and toRVec have *any* common entries.
// Assume the vectors are sorted in increasing order.
// Algorithm copied from function set_intersection() for sorted ranges
// (stl_algo.h).
//
inline static bool
RUConflict(const std::vector<resourceId_t>& fromRVec,
const std::vector<resourceId_t>& toRVec)
{
unsigned fN = fromRVec.size(), tN = toRVec.size();
unsigned fi = 0, ti = 0;
while (fi < fN && ti < tN) {
if (fromRVec[fi] < toRVec[ti])
++fi;
else if (toRVec[ti] < fromRVec[fi])
++ti;
else
return true;
}
return false;
}
static cycles_t
ComputeMinGap(const InstrRUsage &fromRU,
const InstrRUsage &toRU)
{
cycles_t minGap = 0;
if (fromRU.numBubbles > 0)
minGap = fromRU.numBubbles;
if (minGap < fromRU.numCycles) {
// only need to check from cycle `minGap' onwards
for (cycles_t gap=minGap; gap <= fromRU.numCycles-1; gap++) {
// check if instr. #2 can start executing `gap' cycles after #1
// by checking for resource conflicts in each overlapping cycle
cycles_t numOverlap =std::min(fromRU.numCycles - gap, toRU.numCycles);
for (cycles_t c = 0; c <= numOverlap-1; c++)
if (RUConflict(fromRU.resourcesByCycle[gap + c],
toRU.resourcesByCycle[c])) {
// conflict found so minGap must be more than `gap'
minGap = gap+1;
break;
}
}
}
return minGap;
}
//---------------------------------------------------------------------------
// class TargetSchedInfo
// Interface to machine description for instruction scheduling
//---------------------------------------------------------------------------
TargetSchedInfo::TargetSchedInfo(const TargetMachine& tgt,
int NumSchedClasses,
const InstrClassRUsage* ClassRUsages,
const InstrRUsageDelta* UsageDeltas,
const InstrIssueDelta* IssueDeltas,
unsigned NumUsageDeltas,
unsigned NumIssueDeltas)
: target(tgt),
numSchedClasses(NumSchedClasses), mii(tgt.getInstrInfo()),
classRUsages(ClassRUsages), usageDeltas(UsageDeltas),
issueDeltas(IssueDeltas), numUsageDeltas(NumUsageDeltas),
numIssueDeltas(NumIssueDeltas)
{}
void
TargetSchedInfo::initializeResources()
{
assert(MAX_NUM_SLOTS >= (int)getMaxNumIssueTotal()
&& "Insufficient slots for static data! Increase MAX_NUM_SLOTS");
// First, compute common resource usage info for each class because
// most instructions will probably behave the same as their class.
// Cannot allocate a vector of InstrRUsage so new each one.
//
std::vector<InstrRUsage> instrRUForClasses;
instrRUForClasses.resize(numSchedClasses);
for (InstrSchedClass sc = 0; sc < numSchedClasses; sc++) {
// instrRUForClasses.push_back(new InstrRUsage);
instrRUForClasses[sc].setMaxSlots(getMaxNumIssueTotal());
instrRUForClasses[sc].setTo(classRUsages[sc]);
}
computeInstrResources(instrRUForClasses);
computeIssueGaps(instrRUForClasses);
}
void
TargetSchedInfo::computeInstrResources(const std::vector<InstrRUsage>&
instrRUForClasses)
{
int numOpCodes = mii->getNumOpcodes();
instrRUsages.resize(numOpCodes);
// First get the resource usage information from the class resource usages.
for (MachineOpCode op = 0; op < numOpCodes; ++op) {
InstrSchedClass sc = getSchedClass(op);
assert(sc < numSchedClasses);
instrRUsages[op] = instrRUForClasses[sc];
}
// Now, modify the resource usages as specified in the deltas.
for (unsigned i = 0; i < numUsageDeltas; ++i) {
MachineOpCode op = usageDeltas[i].opCode;
assert(op < numOpCodes);
instrRUsages[op].addUsageDelta(usageDeltas[i]);
}
// Then modify the issue restrictions as specified in the deltas.
for (unsigned i = 0; i < numIssueDeltas; ++i) {
MachineOpCode op = issueDeltas[i].opCode;
assert(op < numOpCodes);
instrRUsages[issueDeltas[i].opCode].addIssueDelta(issueDeltas[i]);
}
}
void
TargetSchedInfo::computeIssueGaps(const std::vector<InstrRUsage>&
instrRUForClasses)
{
int numOpCodes = mii->getNumOpcodes();
issueGaps.resize(numOpCodes);
conflictLists.resize(numOpCodes);
// First, compute issue gaps between pairs of classes based on common
// resources usages for each class, because most instruction pairs will
// usually behave the same as their class.
//
int* classPairGaps =
static_cast<int*>(alloca(sizeof(int) * numSchedClasses * numSchedClasses));
for (InstrSchedClass fromSC=0; fromSC < numSchedClasses; fromSC++)
for (InstrSchedClass toSC=0; toSC < numSchedClasses; toSC++) {
int classPairGap = ComputeMinGap(instrRUForClasses[fromSC],
instrRUForClasses[toSC]);
classPairGaps[fromSC*numSchedClasses + toSC] = classPairGap;
}
// Now, for each pair of instructions, use the class pair gap if both
// instructions have identical resource usage as their respective classes.
// If not, recompute the gap for the pair from scratch.
longestIssueConflict = 0;
for (MachineOpCode fromOp=0; fromOp < numOpCodes; fromOp++)
for (MachineOpCode toOp=0; toOp < numOpCodes; toOp++) {
int instrPairGap =
(instrRUsages[fromOp].sameAsClass && instrRUsages[toOp].sameAsClass)
? classPairGaps[getSchedClass(fromOp)*numSchedClasses + getSchedClass(toOp)]
: ComputeMinGap(instrRUsages[fromOp], instrRUsages[toOp]);
if (instrPairGap > 0) {
this->setGap(instrPairGap, fromOp, toOp);
conflictLists[fromOp].push_back(toOp);
longestIssueConflict=std::max(longestIssueConflict, instrPairGap);
}
}
}
void InstrRUsage::setTo(const InstrClassRUsage& classRU) {
sameAsClass = true;
isSingleIssue = classRU.isSingleIssue;
breaksGroup = classRU.breaksGroup;
numBubbles = classRU.numBubbles;
for (unsigned i=0; i < classRU.numSlots; i++) {
unsigned slot = classRU.feasibleSlots[i];
assert(slot < feasibleSlots.size() && "Invalid slot specified!");
this->feasibleSlots[slot] = true;
}
numCycles = classRU.totCycles;
resourcesByCycle.resize(this->numCycles);
for (unsigned i=0; i < classRU.numRUEntries; i++)
for (unsigned c=classRU.V[i].startCycle, NC = c + classRU.V[i].numCycles;
c < NC; c++)
this->resourcesByCycle[c].push_back(classRU.V[i].resourceId);
// Sort each resource usage vector by resourceId_t to speed up conflict
// checking
for (unsigned i=0; i < this->resourcesByCycle.size(); i++)
std::sort(resourcesByCycle[i].begin(), resourcesByCycle[i].end());
}
// Add the extra resource usage requirements specified in the delta.
// Note that a negative value of `numCycles' means one entry for that
// resource should be deleted for each cycle.
//
void InstrRUsage::addUsageDelta(const InstrRUsageDelta &delta) {
int NC = delta.numCycles;
sameAsClass = false;
// resize the resources vector if more cycles are specified
unsigned maxCycles = this->numCycles;
maxCycles = std::max(maxCycles, delta.startCycle + abs(NC) - 1);
if (maxCycles > this->numCycles) {
this->resourcesByCycle.resize(maxCycles);
this->numCycles = maxCycles;
}
if (NC >= 0)
for (unsigned c=delta.startCycle, last=c+NC-1; c <= last; c++)
this->resourcesByCycle[c].push_back(delta.resourceId);
else
// Remove the resource from all NC cycles.
for (unsigned c=delta.startCycle, last=(c-NC)-1; c <= last; c++) {
// Look for the resource backwards so we remove the last entry
// for that resource in each cycle.
std::vector<resourceId_t>& rvec = this->resourcesByCycle[c];
int r;
for (r = rvec.size() - 1; r >= 0; r--)
if (rvec[r] == delta.resourceId) {
// found last entry for the resource
rvec.erase(rvec.begin() + r);
break;
}
assert(r >= 0 && "Resource to remove was unused in cycle c!");
}
}
<|endoftext|>
|
<commit_before>//===-- LiveRegMatrix.cpp - Track register interference -------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the LiveRegMatrix analysis pass.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "regalloc"
#include "llvm/CodeGen/LiveRegMatrix.h"
#include "RegisterCoalescer.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/CodeGen/LiveIntervalAnalysis.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/VirtRegMap.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetRegisterInfo.h"
using namespace llvm;
STATISTIC(NumAssigned , "Number of registers assigned");
STATISTIC(NumUnassigned , "Number of registers unassigned");
char LiveRegMatrix::ID = 0;
INITIALIZE_PASS_BEGIN(LiveRegMatrix, "liveregmatrix",
"Live Register Matrix", false, false)
INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
INITIALIZE_PASS_DEPENDENCY(VirtRegMap)
INITIALIZE_PASS_END(LiveRegMatrix, "liveregmatrix",
"Live Register Matrix", false, false)
LiveRegMatrix::LiveRegMatrix() : MachineFunctionPass(ID),
UserTag(0), RegMaskTag(0), RegMaskVirtReg(0) {}
void LiveRegMatrix::getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesAll();
AU.addRequiredTransitive<LiveIntervals>();
AU.addRequiredTransitive<VirtRegMap>();
MachineFunctionPass::getAnalysisUsage(AU);
}
bool LiveRegMatrix::runOnMachineFunction(MachineFunction &MF) {
TRI = MF.getTarget().getRegisterInfo();
MRI = &MF.getRegInfo();
LIS = &getAnalysis<LiveIntervals>();
VRM = &getAnalysis<VirtRegMap>();
unsigned NumRegUnits = TRI->getNumRegUnits();
if (NumRegUnits != Matrix.size())
Queries.reset(new LiveIntervalUnion::Query[NumRegUnits]);
Matrix.init(LIUAlloc, NumRegUnits);
// Make sure no stale queries get reused.
invalidateVirtRegs();
return false;
}
void LiveRegMatrix::releaseMemory() {
for (unsigned i = 0, e = Matrix.size(); i != e; ++i) {
Matrix[i].clear();
Queries[i].clear();
}
}
void LiveRegMatrix::assign(LiveInterval &VirtReg, unsigned PhysReg) {
DEBUG(dbgs() << "assigning " << PrintReg(VirtReg.reg, TRI)
<< " to " << PrintReg(PhysReg, TRI) << ':');
assert(!VRM->hasPhys(VirtReg.reg) && "Duplicate VirtReg assignment");
VRM->assignVirt2Phys(VirtReg.reg, PhysReg);
MRI->setPhysRegUsed(PhysReg);
for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
DEBUG(dbgs() << ' ' << PrintRegUnit(*Units, TRI));
Matrix[*Units].unify(VirtReg);
}
++NumAssigned;
DEBUG(dbgs() << '\n');
}
void LiveRegMatrix::unassign(LiveInterval &VirtReg) {
unsigned PhysReg = VRM->getPhys(VirtReg.reg);
DEBUG(dbgs() << "unassigning " << PrintReg(VirtReg.reg, TRI)
<< " from " << PrintReg(PhysReg, TRI) << ':');
VRM->clearVirt(VirtReg.reg);
for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
DEBUG(dbgs() << ' ' << PrintRegUnit(*Units, TRI));
Matrix[*Units].extract(VirtReg);
}
++NumUnassigned;
DEBUG(dbgs() << '\n');
}
bool LiveRegMatrix::checkRegMaskInterference(LiveInterval &VirtReg,
unsigned PhysReg) {
// Check if the cached information is valid.
// The same BitVector can be reused for all PhysRegs.
// We could cache multiple VirtRegs if it becomes necessary.
if (RegMaskVirtReg != VirtReg.reg || RegMaskTag != UserTag) {
RegMaskVirtReg = VirtReg.reg;
RegMaskTag = UserTag;
RegMaskUsable.clear();
LIS->checkRegMaskInterference(VirtReg, RegMaskUsable);
}
// The BitVector is indexed by PhysReg, not register unit.
// Regmask interference is more fine grained than regunits.
// For example, a Win64 call can clobber %ymm8 yet preserve %xmm8.
return !RegMaskUsable.empty() && (!PhysReg || !RegMaskUsable.test(PhysReg));
}
bool LiveRegMatrix::checkRegUnitInterference(LiveInterval &VirtReg,
unsigned PhysReg) {
if (VirtReg.empty())
return false;
CoalescerPair CP(VirtReg.reg, PhysReg, *TRI);
for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
const LiveRange &UnitRange = LIS->getRegUnit(*Units);
if (VirtReg.overlaps(UnitRange, CP, *LIS->getSlotIndexes()))
return true;
}
return false;
}
LiveIntervalUnion::Query &LiveRegMatrix::query(LiveInterval &VirtReg,
unsigned RegUnit) {
LiveIntervalUnion::Query &Q = Queries[RegUnit];
Q.init(UserTag, &VirtReg, &Matrix[RegUnit]);
return Q;
}
LiveRegMatrix::InterferenceKind
LiveRegMatrix::checkInterference(LiveInterval &VirtReg, unsigned PhysReg) {
if (VirtReg.empty())
return IK_Free;
// Regmask interference is the fastest check.
if (checkRegMaskInterference(VirtReg, PhysReg))
return IK_RegMask;
// Check for fixed interference.
if (checkRegUnitInterference(VirtReg, PhysReg))
return IK_RegUnit;
// Check the matrix for virtual register interference.
for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units)
if (query(VirtReg, *Units).checkInterference())
return IK_VirtReg;
return IK_Free;
}
<commit_msg>This small change reduces compile time for small programs on targets that have large register files. The omission of Queries.clear() is perfectly safe because LiveIntervalUnion::Query doesn't contain any data that needs freeing and because LiveRegMatrix::runOnFunction happens to reset the OwningArrayPtr holding Queries every time it is run, so there's no need to zero out the queries either. Not having to do this for very large numbers of physregs is a noticeable constant cost reduction in compilation of small programs.<commit_after>//===-- LiveRegMatrix.cpp - Track register interference -------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the LiveRegMatrix analysis pass.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "regalloc"
#include "llvm/CodeGen/LiveRegMatrix.h"
#include "RegisterCoalescer.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/CodeGen/LiveIntervalAnalysis.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/VirtRegMap.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetRegisterInfo.h"
using namespace llvm;
STATISTIC(NumAssigned , "Number of registers assigned");
STATISTIC(NumUnassigned , "Number of registers unassigned");
char LiveRegMatrix::ID = 0;
INITIALIZE_PASS_BEGIN(LiveRegMatrix, "liveregmatrix",
"Live Register Matrix", false, false)
INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
INITIALIZE_PASS_DEPENDENCY(VirtRegMap)
INITIALIZE_PASS_END(LiveRegMatrix, "liveregmatrix",
"Live Register Matrix", false, false)
LiveRegMatrix::LiveRegMatrix() : MachineFunctionPass(ID),
UserTag(0), RegMaskTag(0), RegMaskVirtReg(0) {}
void LiveRegMatrix::getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesAll();
AU.addRequiredTransitive<LiveIntervals>();
AU.addRequiredTransitive<VirtRegMap>();
MachineFunctionPass::getAnalysisUsage(AU);
}
bool LiveRegMatrix::runOnMachineFunction(MachineFunction &MF) {
TRI = MF.getTarget().getRegisterInfo();
MRI = &MF.getRegInfo();
LIS = &getAnalysis<LiveIntervals>();
VRM = &getAnalysis<VirtRegMap>();
unsigned NumRegUnits = TRI->getNumRegUnits();
if (NumRegUnits != Matrix.size())
Queries.reset(new LiveIntervalUnion::Query[NumRegUnits]);
Matrix.init(LIUAlloc, NumRegUnits);
// Make sure no stale queries get reused.
invalidateVirtRegs();
return false;
}
void LiveRegMatrix::releaseMemory() {
for (unsigned i = 0, e = Matrix.size(); i != e; ++i) {
Matrix[i].clear();
// No need to clear Queries here, since LiveIntervalUnion::Query doesn't
// have anything important to clear and LiveRegMatrix's runOnFunction()
// does a OwningPtr::reset anyways.
}
}
void LiveRegMatrix::assign(LiveInterval &VirtReg, unsigned PhysReg) {
DEBUG(dbgs() << "assigning " << PrintReg(VirtReg.reg, TRI)
<< " to " << PrintReg(PhysReg, TRI) << ':');
assert(!VRM->hasPhys(VirtReg.reg) && "Duplicate VirtReg assignment");
VRM->assignVirt2Phys(VirtReg.reg, PhysReg);
MRI->setPhysRegUsed(PhysReg);
for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
DEBUG(dbgs() << ' ' << PrintRegUnit(*Units, TRI));
Matrix[*Units].unify(VirtReg);
}
++NumAssigned;
DEBUG(dbgs() << '\n');
}
void LiveRegMatrix::unassign(LiveInterval &VirtReg) {
unsigned PhysReg = VRM->getPhys(VirtReg.reg);
DEBUG(dbgs() << "unassigning " << PrintReg(VirtReg.reg, TRI)
<< " from " << PrintReg(PhysReg, TRI) << ':');
VRM->clearVirt(VirtReg.reg);
for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
DEBUG(dbgs() << ' ' << PrintRegUnit(*Units, TRI));
Matrix[*Units].extract(VirtReg);
}
++NumUnassigned;
DEBUG(dbgs() << '\n');
}
bool LiveRegMatrix::checkRegMaskInterference(LiveInterval &VirtReg,
unsigned PhysReg) {
// Check if the cached information is valid.
// The same BitVector can be reused for all PhysRegs.
// We could cache multiple VirtRegs if it becomes necessary.
if (RegMaskVirtReg != VirtReg.reg || RegMaskTag != UserTag) {
RegMaskVirtReg = VirtReg.reg;
RegMaskTag = UserTag;
RegMaskUsable.clear();
LIS->checkRegMaskInterference(VirtReg, RegMaskUsable);
}
// The BitVector is indexed by PhysReg, not register unit.
// Regmask interference is more fine grained than regunits.
// For example, a Win64 call can clobber %ymm8 yet preserve %xmm8.
return !RegMaskUsable.empty() && (!PhysReg || !RegMaskUsable.test(PhysReg));
}
bool LiveRegMatrix::checkRegUnitInterference(LiveInterval &VirtReg,
unsigned PhysReg) {
if (VirtReg.empty())
return false;
CoalescerPair CP(VirtReg.reg, PhysReg, *TRI);
for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units) {
const LiveRange &UnitRange = LIS->getRegUnit(*Units);
if (VirtReg.overlaps(UnitRange, CP, *LIS->getSlotIndexes()))
return true;
}
return false;
}
LiveIntervalUnion::Query &LiveRegMatrix::query(LiveInterval &VirtReg,
unsigned RegUnit) {
LiveIntervalUnion::Query &Q = Queries[RegUnit];
Q.init(UserTag, &VirtReg, &Matrix[RegUnit]);
return Q;
}
LiveRegMatrix::InterferenceKind
LiveRegMatrix::checkInterference(LiveInterval &VirtReg, unsigned PhysReg) {
if (VirtReg.empty())
return IK_Free;
// Regmask interference is the fastest check.
if (checkRegMaskInterference(VirtReg, PhysReg))
return IK_RegMask;
// Check for fixed interference.
if (checkRegUnitInterference(VirtReg, PhysReg))
return IK_RegUnit;
// Check the matrix for virtual register interference.
for (MCRegUnitIterator Units(PhysReg, TRI); Units.isValid(); ++Units)
if (query(VirtReg, *Units).checkInterference())
return IK_VirtReg;
return IK_Free;
}
<|endoftext|>
|
<commit_before>//===--- Action.cpp - The LLVM Compiler Driver ------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open
// Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Action class - implementation and auxiliary functions.
//
//===----------------------------------------------------------------------===//
#include "llvm/CompilerDriver/Action.h"
#include "llvm/CompilerDriver/BuiltinOptions.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/SystemUtils.h"
#include "llvm/System/Program.h"
#include "llvm/System/TimeValue.h"
#include <stdexcept>
#include <string>
using namespace llvm;
using namespace llvmc;
namespace llvmc {
extern int Main(int argc, char** argv);
extern const char* ProgramName;
}
namespace {
void PrintString (const std::string& str) {
errs() << str << ' ';
}
void PrintCommand (const std::string& Cmd, const StrVector& Args) {
errs() << Cmd << " ";
std::for_each(Args.begin(), Args.end(), &PrintString);
errs() << '\n';
}
bool IsSegmentationFault (int returnCode) {
#ifdef LLVM_ON_WIN32
return (returnCode >= 0xc0000000UL)
#else
return (returnCode < 0);
#endif
}
int ExecuteProgram (const std::string& name,
const StrVector& args) {
sys::Path prog = sys::Program::FindProgramByName(name);
if (prog.isEmpty()) {
prog = FindExecutable(name, ProgramName, (void *)(intptr_t)&Main);
if (prog.isEmpty())
throw std::runtime_error("Can't find program '" + name + "'");
}
if (!prog.canExecute())
throw std::runtime_error("Program '" + name + "' is not executable.");
// Build the command line vector and the redirects array.
const sys::Path* redirects[3] = {0,0,0};
sys::Path stdout_redirect;
std::vector<const char*> argv;
argv.reserve((args.size()+2));
argv.push_back(name.c_str());
for (StrVector::const_iterator B = args.begin(), E = args.end();
B!=E; ++B) {
if (*B == ">") {
++B;
stdout_redirect.set(*B);
redirects[1] = &stdout_redirect;
}
else {
argv.push_back((*B).c_str());
}
}
argv.push_back(0); // null terminate list.
// Invoke the program.
int ret = sys::Program::ExecuteAndWait(prog, &argv[0], 0, &redirects[0]);
if (IsSegmentationFault(ret)) {
errs() << "Segmentation fault:";
PrintCommand(name, args);
}
return ret;
}
}
namespace llvmc {
void AppendToGlobalTimeLog (const std::string& cmd, double time);
}
int llvmc::Action::Execute () const {
if (DryRun || VerboseMode)
PrintCommand(Command_, Args_);
if (!DryRun) {
if (Time) {
sys::TimeValue now = sys::TimeValue::now();
int ret = ExecuteProgram(Command_, Args_);
sys::TimeValue now2 = sys::TimeValue::now();
now2 -= now;
double elapsed = now2.seconds() + now2.microseconds() / 1000000.0;
AppendToGlobalTimeLog(Command_, elapsed);
return ret;
}
else {
return ExecuteProgram(Command_, Args_);
}
}
return 0;
}
<commit_msg>Print a space after the colon.<commit_after>//===--- Action.cpp - The LLVM Compiler Driver ------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open
// Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Action class - implementation and auxiliary functions.
//
//===----------------------------------------------------------------------===//
#include "llvm/CompilerDriver/Action.h"
#include "llvm/CompilerDriver/BuiltinOptions.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/SystemUtils.h"
#include "llvm/System/Program.h"
#include "llvm/System/TimeValue.h"
#include <stdexcept>
#include <string>
using namespace llvm;
using namespace llvmc;
namespace llvmc {
extern int Main(int argc, char** argv);
extern const char* ProgramName;
}
namespace {
void PrintString (const std::string& str) {
errs() << str << ' ';
}
void PrintCommand (const std::string& Cmd, const StrVector& Args) {
errs() << Cmd << ' ';
std::for_each(Args.begin(), Args.end(), &PrintString);
errs() << '\n';
}
bool IsSegmentationFault (int returnCode) {
#ifdef LLVM_ON_WIN32
return (returnCode >= 0xc0000000UL)
#else
return (returnCode < 0);
#endif
}
int ExecuteProgram (const std::string& name,
const StrVector& args) {
sys::Path prog = sys::Program::FindProgramByName(name);
if (prog.isEmpty()) {
prog = FindExecutable(name, ProgramName, (void *)(intptr_t)&Main);
if (prog.isEmpty())
throw std::runtime_error("Can't find program '" + name + "'");
}
if (!prog.canExecute())
throw std::runtime_error("Program '" + name + "' is not executable.");
// Build the command line vector and the redirects array.
const sys::Path* redirects[3] = {0,0,0};
sys::Path stdout_redirect;
std::vector<const char*> argv;
argv.reserve((args.size()+2));
argv.push_back(name.c_str());
for (StrVector::const_iterator B = args.begin(), E = args.end();
B!=E; ++B) {
if (*B == ">") {
++B;
stdout_redirect.set(*B);
redirects[1] = &stdout_redirect;
}
else {
argv.push_back((*B).c_str());
}
}
argv.push_back(0); // null terminate list.
// Invoke the program.
int ret = sys::Program::ExecuteAndWait(prog, &argv[0], 0, &redirects[0]);
if (IsSegmentationFault(ret)) {
errs() << "Segmentation fault: ";
PrintCommand(name, args);
}
return ret;
}
}
namespace llvmc {
void AppendToGlobalTimeLog (const std::string& cmd, double time);
}
int llvmc::Action::Execute () const {
if (DryRun || VerboseMode)
PrintCommand(Command_, Args_);
if (!DryRun) {
if (Time) {
sys::TimeValue now = sys::TimeValue::now();
int ret = ExecuteProgram(Command_, Args_);
sys::TimeValue now2 = sys::TimeValue::now();
now2 -= now;
double elapsed = now2.seconds() + now2.microseconds() / 1000000.0;
AppendToGlobalTimeLog(Command_, elapsed);
return ret;
}
else {
return ExecuteProgram(Command_, Args_);
}
}
return 0;
}
<|endoftext|>
|
<commit_before>#if !defined(__CINT__) || defined(__MAKECINT__)
#include <TH2F.h>
#include <TGrid.h>
#include <TCanvas.h>
#include <TStopwatch.h>
#include <TStyle.h>
#include "AliRawReaderDate.h"
#include "AliRawReaderRoot.h"
#include "AliITSRawStreamSDD.h"
#include "AliITSRawStreamSDDCompressed.h"
#endif
// Macro to display the SDD Raw Data for 1 DDL
// Origin: F. Prino, prino@to.infn.it
void PlotSDDRawData(Char_t datafil[100], Int_t nDDL, Int_t firstEv=18, Int_t lastEv=20){
const Int_t nHybrids=24;
Bool_t writtenoutput=kFALSE;
TH2F** histo = new TH2F*[nHybrids];
Char_t nome[20];
for(Int_t i=0;i<nHybrids;i++){
sprintf(nome,"histo%d",i);
histo[i]=new TH2F(nome,"",256,-0.5,255.5,256,-0.5,255.5);
histo[i]->SetStats(0);
}
Int_t iev=firstEv;
AliRawReader *rd;
if(strstr(datafil,".root")!=0){
rd=new AliRawReaderRoot(datafil,iev);
}else{
rd=new AliRawReaderDate(datafil,iev);
}
TStopwatch *evtime=new TStopwatch();
TCanvas* c0 = new TCanvas("cd0","c0",900,900);
gStyle->SetPalette(1);
do{
c0->Clear();
c0->Divide(4,6,0.001,0.001);
evtime->Start();
printf("Event # %d\n",iev);
rd->Reset();
for(Int_t i=0;i<nHybrids;i++) histo[i]->Reset();
UChar_t cdhAttr=AliITSRawStreamSDD::ReadBlockAttributes(rd);
UInt_t amSamplFreq=AliITSRawStreamSDD::ReadAMSamplFreqFromCDH(cdhAttr);
AliITSRawStream* s=AliITSRawStreamSDD::CreateRawStreamSDD(rd,cdhAttr);
if(!writtenoutput){
printf("Use %s raw stream, sampling frequency %d MHz\n",s->ClassName(),amSamplFreq);
writtenoutput=kTRUE;
}
Int_t iCountNext=0;
while(s->Next()){
iCountNext++;
if(s->IsCompletedModule()==kFALSE && s->IsCompletedDDL()==kFALSE){
Int_t i=s->GetCarlosId()*2+s->GetChannel();
if(rd->GetDDLID()==nDDL) histo[i]->Fill(s->GetCoord2(),s->GetCoord1(),s->GetSignal());
}
}
evtime->Stop();
printf("**** Event=%d \n",iev);
evtime->Print("u");
evtime->Reset();
iev++;
for(Int_t i=0;i<nHybrids;i++){
c0->cd(i+1);
histo[i]->DrawCopy("colz");
}
c0->Update();
}while(rd->NextEvent()&&iev<=lastEv);
}
void PlotSDDRawData(Int_t nrun, Int_t n2, Int_t year=2009, Char_t* dir="LHC09b_SDD",
Int_t nDDL=0,
Int_t firstEv=18,
Int_t lastEv=20){
TGrid::Connect("alien:",0,0,"t");
Char_t filnam[200];
sprintf(filnam,"alien:///alice/data/%d/%s/%09d/raw/%02d%09d%03d.10.root",year,dir,nrun,year-2000,nrun,n2);
printf("Open file %s\n",filnam);
PlotSDDRawData(filnam,nDDL,firstEv,lastEv);
}
<commit_msg>New feature to plot raw data of single module<commit_after>#if !defined(__CINT__) || defined(__MAKECINT__)
#include <TH2F.h>
#include <TGrid.h>
#include <TCanvas.h>
#include <TStopwatch.h>
#include <TStyle.h>
#include "AliRawReaderDate.h"
#include "AliRawReaderRoot.h"
#include "AliITSRawStreamSDD.h"
#include "AliITSRawStreamSDDCompressed.h"
#endif
// Macro to display the SDD Raw Data for 1 DDL
// Origin: F. Prino, prino@to.infn.it
void PlotSDDRawData(Char_t datafil[100], Int_t nDDL, Int_t firstEv=18, Int_t lastEv=20){
const Int_t nHybrids=24;
Bool_t writtenoutput=kFALSE;
TH2F** histo = new TH2F*[nHybrids];
for(Int_t i=0;i<nHybrids;i++){
histo[i]=new TH2F(Form("histo%d",i),"",256,-0.5,255.5,256,-0.5,255.5);
histo[i]->SetStats(0);
}
Bool_t isSingleMod=kFALSE;
Int_t npx=4;
Int_t npy=6;
Int_t xsiz=900;
Int_t ysiz=900;
Int_t nHybrToPlot=24;
Int_t iMod=-1;
if(nDDL>=240 && nDDL<500){
iMod=nDDL;
AliITSDDLModuleMapSDD* dmap=new AliITSDDLModuleMapSDD();
dmap->SetJun09Map();
Int_t nCarlos;
dmap->FindInDDLMap(iMod,nDDL,nCarlos);
histo[nCarlos*2]->SetTitle(Form("Module %d Side 0",iMod));
histo[nCarlos*2+1]->SetTitle(Form("Module %d Side 0",iMod));
isSingleMod=kTRUE;
npx=2;
npy=1;
xsiz=900;
ysiz=450;
nHybrToPlot=2;
}
Int_t iev=firstEv;
AliRawReader *rd;
if(strstr(datafil,".root")!=0){
rd=new AliRawReaderRoot(datafil,iev);
}else{
rd=new AliRawReaderDate(datafil,iev);
}
TStopwatch *evtime=new TStopwatch();
TCanvas* c0 = new TCanvas("cd0","c0",xsiz,ysiz);
gStyle->SetPalette(1);
do{
c0->Clear();
c0->Divide(npx,npy,0.001,0.001);
evtime->Start();
printf("Event # %d\n",iev);
rd->Reset();
for(Int_t i=0;i<nHybrids;i++) histo[i]->Reset();
UChar_t cdhAttr=AliITSRawStreamSDD::ReadBlockAttributes(rd);
UInt_t amSamplFreq=AliITSRawStreamSDD::ReadAMSamplFreqFromCDH(cdhAttr);
AliITSRawStream* s=AliITSRawStreamSDD::CreateRawStreamSDD(rd,cdhAttr);
if(!writtenoutput){
printf("Use %s raw stream, sampling frequency %d MHz\n",s->ClassName(),amSamplFreq);
writtenoutput=kTRUE;
}
Int_t iCountNext=0;
while(s->Next()){
iCountNext++;
if(s->IsCompletedModule()==kFALSE && s->IsCompletedDDL()==kFALSE){
Int_t i=s->GetCarlosId()*2+s->GetChannel();
if(rd->GetDDLID()==nDDL) histo[i]->Fill(s->GetCoord2(),s->GetCoord1(),s->GetSignal());
}
}
evtime->Stop();
printf("**** Event=%d \n",iev);
evtime->Print("u");
evtime->Reset();
iev++;
for(Int_t i=0;i<nHybrToPlot;i++){
c0->cd(i+1);
if(isSingleMod){
histo[nCarlos*2+i]->DrawCopy("colz");
}else{
histo[i]->DrawCopy("colz");
}
}
c0->Update();
if(histo[nCarlos*2]->GetMaximum()>1) getchar();
}while(rd->NextEvent()&&iev<=lastEv);
}
void PlotSDDRawData(Int_t nrun, Int_t n2, Int_t year=2009, Char_t* dir="LHC09b_SDD",
Int_t nDDL=0,
Int_t firstEv=18,
Int_t lastEv=20){
TGrid::Connect("alien:",0,0,"t");
Char_t filnam[200];
sprintf(filnam,"alien:///alice/data/%d/%s/%09d/raw/%02d%09d%03d.10.root",year,dir,nrun,year-2000,nrun,n2);
printf("Open file %s\n",filnam);
PlotSDDRawData(filnam,nDDL,firstEv,lastEv);
}
<|endoftext|>
|
<commit_before>/**
* @file IntegralImageProvider.cpp
*
* Implementation of class IntegralImageProvider
*
*/
#include "IntegralImageProvider.h"
IntegralImageProvider::IntegralImageProvider()
{
}
IntegralImageProvider::~IntegralImageProvider()
{
}
void IntegralImageProvider::execute(CameraInfo::CameraID id)
{
cameraID = id;
makeIntegralBild(getBallDetectorIntegralImage());
}
void IntegralImageProvider::makeIntegralBild(BallDetectorIntegralImage& integralImage) const
{
const int32_t FACTOR = integralImage.FACTOR;
const uint32_t MAX_COLOR = integralImage.MAX_COLOR;
const uint32_t imgWidth = getImage().width()/FACTOR;
const uint32_t imgHeight = getImage().height()/FACTOR;
integralImage.setDimension(imgWidth, imgHeight);
uint32_t* dataPtr = integralImage.getDataPointer();
uint32_t* prevRowPtr = dataPtr;
uint32_t* curRowPtr = dataPtr + imgWidth*MAX_COLOR;
// NOTE: we use the byte-wise access to the image, so we skipp every 2nd pixel
const Pixel* imgPtr = reinterpret_cast<Pixel*>(getImage().data());
const int32_t FACTOR_HALF = integralImage.FACTOR/2;
// initial offset in the y direction
const uint32_t yImageOffsetInitial = getImage().width() * FACTOR_HALF;
// In each line we iterate over imgWidth-1 pixel. Because the pixel pointer is accumulated,
// we have to subtract it from the subsequent offset in the y-axis
const uint32_t yImageOffsetIteration = yImageOffsetInitial - (imgWidth-1) * FACTOR_HALF;
// initial y-offset
imgPtr += yImageOffsetInitial;
for(uint16_t y = 1; y < imgHeight; ++y)
{
uint32_t akk[MAX_COLOR] = { 0 };
prevRowPtr += MAX_COLOR;
curRowPtr += MAX_COLOR;
for(uint16_t x = 1; x < imgWidth; ++x)
{
imgPtr += FACTOR_HALF;
if(getFieldColorPercept().greenHSISeparator.isColor(*imgPtr)) {
++akk[1];
} else {
akk[0] += (imgPtr->y0);
}
for(uint32_t i = 0; i < MAX_COLOR; ++i) {
curRowPtr[i] = akk[i] + prevRowPtr[i];
}
curRowPtr += MAX_COLOR;
prevRowPtr += MAX_COLOR;
}
// iteration y-offset
imgPtr += yImageOffsetIteration;
}
}<commit_msg>remove tabs<commit_after>/**
* @file IntegralImageProvider.cpp
*
* Implementation of class IntegralImageProvider
*
*/
#include "IntegralImageProvider.h"
IntegralImageProvider::IntegralImageProvider()
{
}
IntegralImageProvider::~IntegralImageProvider()
{
}
void IntegralImageProvider::execute(CameraInfo::CameraID id)
{
cameraID = id;
makeIntegralBild(getBallDetectorIntegralImage());
}
void IntegralImageProvider::makeIntegralBild(BallDetectorIntegralImage& integralImage) const
{
const int32_t FACTOR = integralImage.FACTOR;
const uint32_t MAX_COLOR = integralImage.MAX_COLOR;
const uint32_t imgWidth = getImage().width()/FACTOR;
const uint32_t imgHeight = getImage().height()/FACTOR;
integralImage.setDimension(imgWidth, imgHeight);
uint32_t* dataPtr = integralImage.getDataPointer();
uint32_t* prevRowPtr = dataPtr;
uint32_t* curRowPtr = dataPtr + imgWidth*MAX_COLOR;
// NOTE: we use the byte-wise access to the image, so we skipp every 2nd pixel
const Pixel* imgPtr = reinterpret_cast<Pixel*>(getImage().data());
const int32_t FACTOR_HALF = integralImage.FACTOR/2;
// initial offset in the y direction
const uint32_t yImageOffsetInitial = getImage().width() * FACTOR_HALF;
// In each line we iterate over imgWidth-1 pixel. Because the pixel pointer is accumulated,
// we have to subtract it from the subsequent offset in the y-axis
const uint32_t yImageOffsetIteration = yImageOffsetInitial - (imgWidth-1) * FACTOR_HALF;
// initial y-offset
imgPtr += yImageOffsetInitial;
for(uint16_t y = 1; y < imgHeight; ++y)
{
uint32_t akk[MAX_COLOR] = { 0 };
prevRowPtr += MAX_COLOR;
curRowPtr += MAX_COLOR;
for(uint16_t x = 1; x < imgWidth; ++x)
{
imgPtr += FACTOR_HALF;
if(getFieldColorPercept().greenHSISeparator.isColor(*imgPtr)) {
++akk[1];
} else {
akk[0] += (imgPtr->y0);
}
for(uint32_t i = 0; i < MAX_COLOR; ++i) {
curRowPtr[i] = akk[i] + prevRowPtr[i];
}
curRowPtr += MAX_COLOR;
prevRowPtr += MAX_COLOR;
}
// iteration y-offset
imgPtr += yImageOffsetIteration;
}
}<|endoftext|>
|
<commit_before>/*
* Copyright 2007-2020 CM4all GmbH
* All rights reserved.
*
* author: Max Kellermann <mk@cm4all.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "cgi/Address.hxx"
#include "AllocatorPtr.hxx"
#include "TestPool.hxx"
#include <gtest/gtest.h>
TEST(CgiAddressTest, Uri)
{
TestPool pool;
AllocatorPtr alloc(pool);
CgiAddress a("/usr/bin/cgi");
ASSERT_FALSE(a.IsExpandable());
ASSERT_STREQ(a.GetURI(alloc), "/");
a.script_name = "/";
ASSERT_STREQ(a.GetURI(alloc), "/");
a.path_info = "foo";
ASSERT_STREQ(a.GetURI(alloc), "/foo");
a.query_string = "";
ASSERT_STREQ(a.GetURI(alloc), "/foo?");
a.query_string = "a=b";
ASSERT_STREQ(a.GetURI(alloc), "/foo?a=b");
a.path_info = "";
ASSERT_STREQ(a.GetURI(alloc), "/?a=b");
a.path_info = nullptr;
ASSERT_STREQ(a.GetURI(alloc), "/?a=b");
a.script_name = "/test.cgi";
a.path_info = nullptr;
a.query_string = nullptr;
ASSERT_STREQ(a.GetURI(alloc), "/test.cgi");
a.path_info = "/foo";
ASSERT_STREQ(a.GetURI(alloc), "/test.cgi/foo");
a.script_name = "/bar/";
ASSERT_STREQ(a.GetURI(alloc), "/bar/foo");
a.script_name = "/";
ASSERT_STREQ(a.GetURI(alloc), "/foo");
a.script_name = nullptr;
ASSERT_STREQ(a.GetURI(alloc), "/foo");
}
TEST(CgiAddressTest, Apply)
{
TestPool pool;
AllocatorPtr alloc(pool);
CgiAddress a("/usr/bin/cgi");
a.script_name = "/test.pl";
a.path_info = "/foo";
auto b = a.Apply(alloc, "");
ASSERT_EQ((const CgiAddress *)&a, b);
b = a.Apply(alloc, "bar");
ASSERT_NE(b, nullptr);
ASSERT_NE(b, &a);
ASSERT_FALSE(b->IsValidBase());
ASSERT_STREQ(b->path, a.path);
ASSERT_STREQ(b->script_name, a.script_name);
ASSERT_STREQ(b->path_info, "/bar");
a.path_info = "/foo/";
ASSERT_EQ(true, a.IsValidBase());
b = a.Apply(alloc, "bar");
ASSERT_NE(b, nullptr);
ASSERT_NE(b, &a);
ASSERT_FALSE(b->IsValidBase());
ASSERT_STREQ(b->path, a.path);
ASSERT_STREQ(b->script_name, a.script_name);
ASSERT_STREQ(b->path_info, "/foo/bar");
b = a.Apply(alloc, "/bar");
ASSERT_NE(b, nullptr);
ASSERT_NE(b, &a);
ASSERT_FALSE(b->IsValidBase());
ASSERT_STREQ(b->path, a.path);
ASSERT_STREQ(b->script_name, a.script_name);
ASSERT_STREQ(b->path_info, "/bar");
}
<commit_msg>test/t_cgi_address: add RelativeTo() test<commit_after>/*
* Copyright 2007-2020 CM4all GmbH
* All rights reserved.
*
* author: Max Kellermann <mk@cm4all.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "cgi/Address.hxx"
#include "AllocatorPtr.hxx"
#include "TestPool.hxx"
#include <gtest/gtest.h>
TEST(CgiAddressTest, Uri)
{
TestPool pool;
AllocatorPtr alloc(pool);
CgiAddress a("/usr/bin/cgi");
ASSERT_FALSE(a.IsExpandable());
ASSERT_STREQ(a.GetURI(alloc), "/");
a.script_name = "/";
ASSERT_STREQ(a.GetURI(alloc), "/");
a.path_info = "foo";
ASSERT_STREQ(a.GetURI(alloc), "/foo");
a.query_string = "";
ASSERT_STREQ(a.GetURI(alloc), "/foo?");
a.query_string = "a=b";
ASSERT_STREQ(a.GetURI(alloc), "/foo?a=b");
a.path_info = "";
ASSERT_STREQ(a.GetURI(alloc), "/?a=b");
a.path_info = nullptr;
ASSERT_STREQ(a.GetURI(alloc), "/?a=b");
a.script_name = "/test.cgi";
a.path_info = nullptr;
a.query_string = nullptr;
ASSERT_STREQ(a.GetURI(alloc), "/test.cgi");
a.path_info = "/foo";
ASSERT_STREQ(a.GetURI(alloc), "/test.cgi/foo");
a.script_name = "/bar/";
ASSERT_STREQ(a.GetURI(alloc), "/bar/foo");
a.script_name = "/";
ASSERT_STREQ(a.GetURI(alloc), "/foo");
a.script_name = nullptr;
ASSERT_STREQ(a.GetURI(alloc), "/foo");
}
TEST(CgiAddressTest, Apply)
{
TestPool pool;
AllocatorPtr alloc(pool);
CgiAddress a("/usr/bin/cgi");
a.script_name = "/test.pl";
a.path_info = "/foo";
auto b = a.Apply(alloc, "");
ASSERT_EQ((const CgiAddress *)&a, b);
b = a.Apply(alloc, "bar");
ASSERT_NE(b, nullptr);
ASSERT_NE(b, &a);
ASSERT_FALSE(b->IsValidBase());
ASSERT_STREQ(b->path, a.path);
ASSERT_STREQ(b->script_name, a.script_name);
ASSERT_STREQ(b->path_info, "/bar");
a.path_info = "/foo/";
ASSERT_EQ(true, a.IsValidBase());
b = a.Apply(alloc, "bar");
ASSERT_NE(b, nullptr);
ASSERT_NE(b, &a);
ASSERT_FALSE(b->IsValidBase());
ASSERT_STREQ(b->path, a.path);
ASSERT_STREQ(b->script_name, a.script_name);
ASSERT_STREQ(b->path_info, "/foo/bar");
b = a.Apply(alloc, "/bar");
ASSERT_NE(b, nullptr);
ASSERT_NE(b, &a);
ASSERT_FALSE(b->IsValidBase());
ASSERT_STREQ(b->path, a.path);
ASSERT_STREQ(b->script_name, a.script_name);
ASSERT_STREQ(b->path_info, "/bar");
}
gcc_pure
static auto
MakeCgiAddress(const char *executable_path, const char *script_name,
const char *path_info) noexcept
{
CgiAddress address(executable_path);
address.script_name = script_name;
address.path_info = path_info;
return address;
}
static bool
operator==(const StringView a, const StringView b) noexcept
{
if (a.IsNull() || b.IsNull())
return a.IsNull() && b.IsNull();
if (a.size != b.size)
return false;
return memcmp(a.data, b.data, a.size) == 0;
}
static bool
operator==(const StringView a, const char *b) noexcept
{
return a == StringView(b);
}
static bool
operator==(const StringView a, std::nullptr_t b) noexcept
{
return a == StringView(b);
}
TEST(CgiAddressTest, RelativeTo)
{
TestPool pool;
AllocatorPtr alloc(pool);
const auto base = MakeCgiAddress("/usr/bin/cgi", "/test.pl", "/foo/");
ASSERT_EQ(MakeCgiAddress("/usr/bin/other-cgi", "/test.pl", "/foo/").RelativeTo(base), nullptr);
ASSERT_EQ(MakeCgiAddress("/usr/bin/cgi", "/test.pl", nullptr).RelativeTo(base), nullptr);
ASSERT_EQ(MakeCgiAddress("/usr/bin/cgi", "/test.pl", "/").RelativeTo(base), nullptr);
ASSERT_EQ(MakeCgiAddress("/usr/bin/cgi", "/test.pl", "/foo").RelativeTo(base), nullptr);
ASSERT_EQ(MakeCgiAddress("/usr/bin/cgi", "/test.pl", "/foo/").RelativeTo(base), "");
ASSERT_EQ(MakeCgiAddress("/usr/bin/cgi", "/test.pl", "/foo/bar").RelativeTo(base), "bar");
}
<|endoftext|>
|
<commit_before>// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#define DUNE_STUFF_FUNCTIONS_DISABLE_CHECKS
// This one has to come first (includes the config.h)!
#include <dune/stuff/test/test_common.hh>
#ifdef HAVE_FASP
# undef HAVE_FASP
#endif
#include <dune/common/exceptions.hh>
#if HAVE_ALUGRID_SERIAL_H || HAVE_ALUGRID_PARALLEL_H
# define ENABLE_ALUGRID 1
# include <dune/grid/alugrid.hh>
#else
# error This test requires ALUGrid!
#endif
#include <dune/stuff/common/color.hh>
#include <dune/stuff/common/print.hh>
#include <dune/stuff/common/float_cmp.hh>
#include "elliptic-testcases.hh"
#include "elliptic-cg-discretization.hh"
#include "elliptic-sipdg-discretization.hh"
#include "elliptic-swipdg-discretization.hh"
class errors_are_not_as_expected
: public Dune::Exception
{};
typedef Dune::ALUConformGrid< 2, 2 > AluConform2dGridType;
// change this to toggle output
std::ostream& test_out = std::cout;
//std::ostream& test_out = DSC_LOG.devnull();
typedef testing::Types< EllipticTestCase::ESV07< AluConform2dGridType >
, EllipticTestCase::LocalThermalBlock< AluConform2dGridType >
, EllipticTestCase::ER07< AluConform2dGridType >
, EllipticTestCase::MixedBoundaryTypes< AluConform2dGridType >
// , EllipticTestCase::Spe10Model1< AluConform2dGridType >
> AluConform2dTestCases;
std::vector< double > truncate_vector(const std::vector< double >& in, const size_t size)
{
assert(size <= in.size());
if (size == in.size())
return in;
else {
std::vector< double > out(size);
for (size_t ii = 0; ii < size; ++ii)
out[ii] = in[ii];
return out;
}
} // ... truncate_vector(...)
template< class TestCase >
struct EllipticCGDiscretization
: public ::testing::Test
{
void produces_correct_results() const
{
const TestCase test_case;
test_case.print_header(test_out);
test_out << std::endl;
EllipticCG::EocStudy< TestCase, 1 > eoc_study(test_case);
auto errors = eoc_study.run(test_out);
for (const auto& norm : eoc_study.provided_norms()) {
if (!Dune::Stuff::Common::FloatCmp::lt(errors[norm],
truncate_vector(eoc_study.expected_results(norm), errors[norm].size()))) {
std::stringstream ss;
Dune::Stuff::Common::print(errors[norm], "errors (" + norm + ")", ss);
Dune::Stuff::Common::print(eoc_study.expected_results(norm), " expected results (" + norm + ")", ss);
DUNE_THROW_COLORFULLY(errors_are_not_as_expected, ss.str());
}
}
}
}; // EllipticCGDiscretization
template< class TestCase >
struct EllipticSIPDGDiscretization
: public ::testing::Test
{
void produces_correct_results() const
{
if (std::is_same< TestCase, EllipticTestCase::Spe10Model1< Dune::ALUConformGrid< 2, 2 > > >::value) {
std::cerr
<< Dune::Stuff::Common::colorStringRed("EllipticSIPDGDiscretization does not work for "
"EllipticTestCase::Spe10Model1< Dune::ALUConformGrid< 2, 2 > >!")
<< std::endl;
} else {
const TestCase test_case;
test_case.print_header(test_out);
test_out << std::endl;
EllipticSIPDG::EocStudy< TestCase, 1 > eoc_study_1(test_case);
auto errors_1 = eoc_study_1.run(test_out);
for (const auto& norm : eoc_study_1.provided_norms()) {
if (!Dune::Stuff::Common::FloatCmp::lt(errors_1[norm], eoc_study_1.expected_results(norm))) {
std::stringstream ss;
Dune::Stuff::Common::print(errors_1[norm], "errors (" + norm + ")", ss);
Dune::Stuff::Common::print(eoc_study_1.expected_results(norm), " expected results (" + norm + ")", ss);
DUNE_THROW_COLORFULLY(errors_are_not_as_expected, ss.str());
}
}
test_out << std::endl;
EllipticSIPDG::EocStudy< TestCase, 2 > eoc_study_2(test_case);
auto errors_2 = eoc_study_2.run(test_out);
for (const auto& norm : eoc_study_2.provided_norms())
if (!Dune::Stuff::Common::FloatCmp::lt(errors_2[norm], eoc_study_2.expected_results(norm))) {
std::stringstream ss;
Dune::Stuff::Common::print(errors_2[norm], "errors (" + norm + ")", ss);
Dune::Stuff::Common::print(eoc_study_2.expected_results(norm), " expected results (" + norm + ")", ss);
DUNE_THROW_COLORFULLY(errors_are_not_as_expected, ss.str());
}
}
}
}; // EllipticSIPDGDiscretization
template< class TestCase >
struct EllipticSWIPDGDiscretization
: public ::testing::Test
{
void produces_correct_results() const
{
const TestCase test_case;
test_case.print_header(test_out);
test_out << std::endl;
EllipticSWIPDG::EocStudy< TestCase, 1 > eoc_study_1(test_case);
auto errors_1 = eoc_study_1.run(test_out);
for (const auto& norm : eoc_study_1.provided_norms()) {
if (!Dune::Stuff::Common::FloatCmp::lt(errors_1[norm], eoc_study_1.expected_results(norm))) {
std::stringstream ss;
Dune::Stuff::Common::print(errors_1[norm], "errors (" + norm + ")", ss);
Dune::Stuff::Common::print(eoc_study_1.expected_results(norm), " expected results (" + norm + ")", ss);
DUNE_THROW_COLORFULLY(errors_are_not_as_expected, ss.str());
}
}
test_out << std::endl;
EllipticSWIPDG::EocStudy< TestCase, 2 > eoc_study_2(test_case);
auto errors_2 = eoc_study_2.run(test_out);
for (const auto& norm : eoc_study_2.provided_norms())
if (!Dune::Stuff::Common::FloatCmp::lt(errors_2[norm], eoc_study_2.expected_results(norm))) {
std::stringstream ss;
Dune::Stuff::Common::print(errors_2[norm], "errors (" + norm + ")", ss);
Dune::Stuff::Common::print(eoc_study_2.expected_results(norm), " expected results (" + norm + ")", ss);
DUNE_THROW_COLORFULLY(errors_are_not_as_expected, ss.str());
}
}
};
TYPED_TEST_CASE(EllipticCGDiscretization, AluConform2dTestCases);
TYPED_TEST(EllipticCGDiscretization, produces_correct_results) {
this->produces_correct_results();
}
TYPED_TEST_CASE(EllipticSIPDGDiscretization, AluConform2dTestCases);
TYPED_TEST(EllipticSIPDGDiscretization, produces_correct_results) {
this->produces_correct_results();
}
TYPED_TEST_CASE(EllipticSWIPDGDiscretization, AluConform2dTestCases);
TYPED_TEST(EllipticSWIPDGDiscretization, produces_correct_results) {
this->produces_correct_results();
}
int main(int argc, char** argv)
{
try {
test_init(argc, argv);
return RUN_ALL_TESTS();
} catch (Dune::Exception& e) {
std::cerr << "\nDune reported error: " << e.what() << std::endl;
std::abort();
} catch (std::exception& e) {
std::cerr << "\n" << e.what() << std::endl;
std::abort();
} catch (...) {
std::cerr << "Unknown exception thrown!" << std::endl;
std::abort();
} // try
}
<commit_msg>[tests.elliptic-discretizations] disabled DG for the moment<commit_after>// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#define DUNE_STUFF_FUNCTIONS_DISABLE_CHECKS
// This one has to come first (includes the config.h)!
#include <dune/stuff/test/test_common.hh>
#ifdef HAVE_FASP
# undef HAVE_FASP
#endif
#include <dune/common/exceptions.hh>
#if HAVE_ALUGRID_SERIAL_H || HAVE_ALUGRID_PARALLEL_H
# define ENABLE_ALUGRID 1
# include <dune/grid/alugrid.hh>
#else
# error This test requires ALUGrid!
#endif
#include <dune/stuff/common/color.hh>
#include <dune/stuff/common/print.hh>
#include <dune/stuff/common/float_cmp.hh>
#include "elliptic-testcases.hh"
#include "elliptic-cg-discretization.hh"
//#include "elliptic-sipdg-discretization.hh"
//#include "elliptic-swipdg-discretization.hh"
class errors_are_not_as_expected
: public Dune::Exception
{};
typedef Dune::ALUConformGrid< 2, 2 > AluConform2dGridType;
// change this to toggle output
std::ostream& test_out = std::cout;
//std::ostream& test_out = DSC_LOG.devnull();
typedef testing::Types< EllipticTestCase::ESV07< AluConform2dGridType >
, EllipticTestCase::LocalThermalBlock< AluConform2dGridType >
, EllipticTestCase::ER07< AluConform2dGridType >
, EllipticTestCase::MixedBoundaryTypes< AluConform2dGridType >
, EllipticTestCase::Spe10Model1< AluConform2dGridType >
> AluConform2dTestCases;
std::vector< double > truncate_vector(const std::vector< double >& in, const size_t size)
{
assert(size <= in.size());
if (size == in.size())
return in;
else {
std::vector< double > out(size);
for (size_t ii = 0; ii < size; ++ii)
out[ii] = in[ii];
return out;
}
} // ... truncate_vector(...)
template< class TestCase >
struct EllipticCGDiscretization
: public ::testing::Test
{
void produces_correct_results() const
{
const TestCase test_case;
test_case.print_header(test_out);
test_out << std::endl;
EllipticCG::EocStudy< TestCase, 1 > eoc_study(test_case);
auto errors = eoc_study.run(test_out);
for (const auto& norm : eoc_study.provided_norms()) {
if (!Dune::Stuff::Common::FloatCmp::lt(errors[norm],
truncate_vector(eoc_study.expected_results(norm), errors[norm].size()))) {
std::stringstream ss;
Dune::Stuff::Common::print(errors[norm], "errors (" + norm + ")", ss);
Dune::Stuff::Common::print(eoc_study.expected_results(norm), " expected results (" + norm + ")", ss);
DUNE_THROW_COLORFULLY(errors_are_not_as_expected, ss.str());
}
}
}
}; // EllipticCGDiscretization
//template< class TestCase >
//struct EllipticSIPDGDiscretization
// : public ::testing::Test
//{
// void produces_correct_results() const
// {
// if (std::is_same< TestCase, EllipticTestCase::Spe10Model1< Dune::ALUConformGrid< 2, 2 > > >::value) {
// std::cerr
// << Dune::Stuff::Common::colorStringRed("EllipticSIPDGDiscretization does not work for "
// "EllipticTestCase::Spe10Model1< Dune::ALUConformGrid< 2, 2 > >!")
// << std::endl;
// } else {
// const TestCase test_case;
// test_case.print_header(test_out);
// test_out << std::endl;
// EllipticSIPDG::EocStudy< TestCase, 1 > eoc_study_1(test_case);
// auto errors_1 = eoc_study_1.run(test_out);
// for (const auto& norm : eoc_study_1.provided_norms()) {
// if (!Dune::Stuff::Common::FloatCmp::lt(errors_1[norm], eoc_study_1.expected_results(norm))) {
// std::stringstream ss;
// Dune::Stuff::Common::print(errors_1[norm], "errors (" + norm + ")", ss);
// Dune::Stuff::Common::print(eoc_study_1.expected_results(norm), " expected results (" + norm + ")", ss);
// DUNE_THROW_COLORFULLY(errors_are_not_as_expected, ss.str());
// }
// }
// test_out << std::endl;
// EllipticSIPDG::EocStudy< TestCase, 2 > eoc_study_2(test_case);
// auto errors_2 = eoc_study_2.run(test_out);
// for (const auto& norm : eoc_study_2.provided_norms())
// if (!Dune::Stuff::Common::FloatCmp::lt(errors_2[norm], eoc_study_2.expected_results(norm))) {
// std::stringstream ss;
// Dune::Stuff::Common::print(errors_2[norm], "errors (" + norm + ")", ss);
// Dune::Stuff::Common::print(eoc_study_2.expected_results(norm), " expected results (" + norm + ")", ss);
// DUNE_THROW_COLORFULLY(errors_are_not_as_expected, ss.str());
// }
// }
// }
//}; // EllipticSIPDGDiscretization
//template< class TestCase >
//struct EllipticSWIPDGDiscretization
// : public ::testing::Test
//{
// void produces_correct_results() const
// {
// const TestCase test_case;
// test_case.print_header(test_out);
// test_out << std::endl;
// EllipticSWIPDG::EocStudy< TestCase, 1 > eoc_study_1(test_case);
// auto errors_1 = eoc_study_1.run(test_out);
// for (const auto& norm : eoc_study_1.provided_norms()) {
// if (!Dune::Stuff::Common::FloatCmp::lt(errors_1[norm], eoc_study_1.expected_results(norm))) {
// std::stringstream ss;
// Dune::Stuff::Common::print(errors_1[norm], "errors (" + norm + ")", ss);
// Dune::Stuff::Common::print(eoc_study_1.expected_results(norm), " expected results (" + norm + ")", ss);
// DUNE_THROW_COLORFULLY(errors_are_not_as_expected, ss.str());
// }
// }
// test_out << std::endl;
// EllipticSWIPDG::EocStudy< TestCase, 2 > eoc_study_2(test_case);
// auto errors_2 = eoc_study_2.run(test_out);
// for (const auto& norm : eoc_study_2.provided_norms())
// if (!Dune::Stuff::Common::FloatCmp::lt(errors_2[norm], eoc_study_2.expected_results(norm))) {
// std::stringstream ss;
// Dune::Stuff::Common::print(errors_2[norm], "errors (" + norm + ")", ss);
// Dune::Stuff::Common::print(eoc_study_2.expected_results(norm), " expected results (" + norm + ")", ss);
// DUNE_THROW_COLORFULLY(errors_are_not_as_expected, ss.str());
// }
// }
//};
TYPED_TEST_CASE(EllipticCGDiscretization, AluConform2dTestCases);
TYPED_TEST(EllipticCGDiscretization, produces_correct_results) {
this->produces_correct_results();
}
//TYPED_TEST_CASE(EllipticSIPDGDiscretization, AluConform2dTestCases);
//TYPED_TEST(EllipticSIPDGDiscretization, produces_correct_results) {
// this->produces_correct_results();
//}
//TYPED_TEST_CASE(EllipticSWIPDGDiscretization, AluConform2dTestCases);
//TYPED_TEST(EllipticSWIPDGDiscretization, produces_correct_results) {
// this->produces_correct_results();
//}
int main(int argc, char** argv)
{
try {
test_init(argc, argv);
return RUN_ALL_TESTS();
} catch (Dune::Exception& e) {
std::cerr << "\nDune reported error: " << e.what() << std::endl;
std::abort();
} catch (std::exception& e) {
std::cerr << "\n" << e.what() << std::endl;
std::abort();
} catch (...) {
std::cerr << "Unknown exception thrown!" << std::endl;
std::abort();
} // try
}
<|endoftext|>
|
<commit_before>#include <cstdlib>
#include <SDL2/SDL.h>
#include "KeyListener.h"
KeyListener::KeyListener(){}
KeyListener::~KeyListener(){}
int KeyListener::query(){
// message processing loop
SDL_Event event;
while (SDL_PollEvent(&event))
{
// check for messages
switch (event.type)
{
// exit if the window is closed
case SDL_QUIT:
return 1;
break;
// check for keypresses
case SDL_KEYDOWN:
{
// exit if ESCAPE is pressed
if (event.key.keysym.sym == SDL_SCANCODE_ESCAPE)
return 1;
break;
}
} // end switch
} // end of message processing
return 0;
}
int KeyListener::getKeys(){
const Uint8 *keys = SDL_GetKeyboardState(NULL);
// Handle input
if (keys[SDL_SCANCODE_LEFT] && !keys[SDL_SCANCODE_RIGHT])
return 1;
else if (keys[SDL_SCANCODE_RIGHT] && !keys[SDL_SCANCODE_LEFT])
return 2;
else
return 0;
}
int KeyListener::save(){
SDL_Event event;
if (event.type == SDL_KEYDOWN)
{
if (event.key.keysym.sym == SDL_SCANCODE_S)
return 1;
else if(event.key.keysym.sym == SDL_SCANCODE_L)
return 2;
}
return 0;
}
<commit_msg>Keyboard events are now properly handled.<commit_after>#include <cstdlib>
#include <SDL2/SDL.h>
#include "KeyListener.h"
KeyListener::KeyListener(){}
KeyListener::~KeyListener(){}
int KeyListener::query(){
// message processing loop
SDL_Event event;
const Uint8* keys = SDL_GetKeyboardState(NULL);
while (SDL_PollEvent(&event))
{
// check for messages
switch (event.type)
{
// exit if the window is closed
case SDL_QUIT:
return 1;
break;
// check for keypresses
case SDL_KEYDOWN:
{
// exit if ESCAPE is pressed
if (keys[SDL_SCANCODE_ESCAPE])
return 1;
break;
}
} // end switch
} // end of message processing
return 0;
}
int KeyListener::getKeys(){
const Uint8 *keys = SDL_GetKeyboardState(NULL);
SDL_Event event;
while(SDL_PollEvent(&event)){
// Handle input
if (keys[SDL_SCANCODE_LEFT] && !keys[SDL_SCANCODE_RIGHT])
return 1;
else if (keys[SDL_SCANCODE_RIGHT] && !keys[SDL_SCANCODE_LEFT])
return 2;
else
return 0;
}
}
int KeyListener::save(){
const Uint8 *keys = SDL_GetKeyboardState(NULL);
SDL_Event event;
while(SDL_PollEvent(&event)){
if (event.type == SDL_KEYDOWN)
{
if (keys[SDL_SCANCODE_S])
return 1;
else if(keys[SDL_SCANCODE_L])
return 2;
}
}
return 0;
}
<|endoftext|>
|
<commit_before>//===-- ScalarTest.cpp ------------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "gtest/gtest.h"
#include "lldb/Core/Scalar.h"
#include "lldb/Utility/DataExtractor.h"
#include "lldb/Utility/Endian.h"
#include "lldb/Utility/Status.h"
#include "lldb/Utility/StreamString.h"
using namespace lldb_private;
TEST(ScalarTest, RightShiftOperator) {
int a = 0x00001000;
int b = 0xFFFFFFFF;
int c = 4;
Scalar a_scalar(a);
Scalar b_scalar(b);
Scalar c_scalar(c);
ASSERT_EQ(a >> c, a_scalar >> c_scalar);
ASSERT_EQ(b >> c, b_scalar >> c_scalar);
}
TEST(ScalarTest, GetBytes) {
int a = 0x01020304;
long long b = 0x0102030405060708LL;
float c = 1234567.89e32;
double d = 1234567.89e42;
char e[16] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
char f[32] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32};
Scalar a_scalar(a);
Scalar b_scalar(b);
Scalar c_scalar(c);
Scalar d_scalar(d);
Scalar e_scalar;
Scalar f_scalar;
DataExtractor e_data(e, sizeof(e), endian::InlHostByteOrder(),
sizeof(void *));
Status e_error =
e_scalar.SetValueFromData(e_data, lldb::eEncodingUint, sizeof(e));
DataExtractor f_data(f, sizeof(f), endian::InlHostByteOrder(),
sizeof(void *));
Status f_error =
f_scalar.SetValueFromData(f_data, lldb::eEncodingUint, sizeof(f));
ASSERT_EQ(0, memcmp(&a, a_scalar.GetBytes(), sizeof(a)));
ASSERT_EQ(0, memcmp(&b, b_scalar.GetBytes(), sizeof(b)));
ASSERT_EQ(0, memcmp(&c, c_scalar.GetBytes(), sizeof(c)));
ASSERT_EQ(0, memcmp(&d, d_scalar.GetBytes(), sizeof(d)));
ASSERT_EQ(0, e_error.Fail());
ASSERT_EQ(0, memcmp(e, e_scalar.GetBytes(), sizeof(e)));
ASSERT_EQ(0, f_error.Fail());
ASSERT_EQ(0, memcmp(f, f_scalar.GetBytes(), sizeof(f)));
}
TEST(ScalarTest, CastOperations) {
long long a = 0xf1f2f3f4f5f6f7f8LL;
Scalar a_scalar(a);
ASSERT_EQ((signed char)a, a_scalar.SChar());
ASSERT_EQ((unsigned char)a, a_scalar.UChar());
ASSERT_EQ((signed short)a, a_scalar.SShort());
ASSERT_EQ((unsigned short)a, a_scalar.UShort());
ASSERT_EQ((signed int)a, a_scalar.SInt());
ASSERT_EQ((unsigned int)a, a_scalar.UInt());
ASSERT_EQ((signed long)a, a_scalar.SLong());
ASSERT_EQ((unsigned long)a, a_scalar.ULong());
ASSERT_EQ((signed long long)a, a_scalar.SLongLong());
ASSERT_EQ((unsigned long long)a, a_scalar.ULongLong());
int a2 = 23;
Scalar a2_scalar(a2);
ASSERT_EQ((float)a2, a2_scalar.Float());
ASSERT_EQ((double)a2, a2_scalar.Double());
ASSERT_EQ((long double)a2, a2_scalar.LongDouble());
}
TEST(ScalarTest, ExtractBitfield) {
uint32_t len = sizeof(long long) * 8;
long long a1 = 0xf1f2f3f4f5f6f7f8LL;
long long b1 = 0xff1f2f3f4f5f6f7fLL;
Scalar s_scalar(a1);
ASSERT_TRUE(s_scalar.ExtractBitfield(0, 0));
ASSERT_EQ(0, memcmp(&a1, s_scalar.GetBytes(), sizeof(a1)));
ASSERT_TRUE(s_scalar.ExtractBitfield(len, 0));
ASSERT_EQ(0, memcmp(&a1, s_scalar.GetBytes(), sizeof(a1)));
ASSERT_TRUE(s_scalar.ExtractBitfield(len - 4, 4));
ASSERT_EQ(0, memcmp(&b1, s_scalar.GetBytes(), sizeof(b1)));
unsigned long long a2 = 0xf1f2f3f4f5f6f7f8ULL;
unsigned long long b2 = 0x0f1f2f3f4f5f6f7fULL;
Scalar u_scalar(a2);
ASSERT_TRUE(u_scalar.ExtractBitfield(0, 0));
ASSERT_EQ(0, memcmp(&a2, u_scalar.GetBytes(), sizeof(a2)));
ASSERT_TRUE(u_scalar.ExtractBitfield(len, 0));
ASSERT_EQ(0, memcmp(&a2, u_scalar.GetBytes(), sizeof(a2)));
ASSERT_TRUE(u_scalar.ExtractBitfield(len - 4, 4));
ASSERT_EQ(0, memcmp(&b2, u_scalar.GetBytes(), sizeof(b2)));
}
template <typename T> static std::string ScalarGetValue(T value) {
StreamString stream;
Scalar(value).GetValue(&stream, false);
return stream.GetString();
}
TEST(ScalarTest, GetValue) {
EXPECT_EQ("12345", ScalarGetValue<signed short>(12345));
EXPECT_EQ("-12345", ScalarGetValue<signed short>(-12345));
EXPECT_EQ("12345", ScalarGetValue<unsigned short>(12345));
EXPECT_EQ(std::to_string(std::numeric_limits<unsigned short>::max()),
ScalarGetValue(std::numeric_limits<unsigned short>::max()));
EXPECT_EQ("12345", ScalarGetValue<signed int>(12345));
EXPECT_EQ("-12345", ScalarGetValue<signed int>(-12345));
EXPECT_EQ("12345", ScalarGetValue<unsigned int>(12345));
EXPECT_EQ(std::to_string(std::numeric_limits<unsigned int>::max()),
ScalarGetValue(std::numeric_limits<unsigned int>::max()));
EXPECT_EQ("12345678", ScalarGetValue<signed long>(12345678L));
EXPECT_EQ("-12345678", ScalarGetValue<signed long>(-12345678L));
EXPECT_EQ("12345678", ScalarGetValue<unsigned long>(12345678UL));
EXPECT_EQ(std::to_string(std::numeric_limits<unsigned long>::max()),
ScalarGetValue(std::numeric_limits<unsigned long>::max()));
EXPECT_EQ("1234567890123", ScalarGetValue<signed long long>(1234567890123LL));
EXPECT_EQ("-1234567890123",
ScalarGetValue<signed long long>(-1234567890123LL));
EXPECT_EQ("1234567890123",
ScalarGetValue<unsigned long long>(1234567890123ULL));
EXPECT_EQ(std::to_string(std::numeric_limits<unsigned long long>::max()),
ScalarGetValue(std::numeric_limits<unsigned long long>::max()));
}
TEST(ScalarTest, Division) {
Scalar lhs(5.0);
Scalar rhs(2.0);
Scalar r = lhs / rhs;
EXPECT_TRUE(r.IsValid());
EXPECT_EQ(r, Scalar(2.5));
}
TEST(ScalarTest, Promotion) {
static Scalar::Type int_types[] = {
Scalar::e_sint, Scalar::e_uint, Scalar::e_slong,
Scalar::e_ulong, Scalar::e_slonglong, Scalar::e_ulonglong,
Scalar::e_sint128, Scalar::e_uint128, Scalar::e_sint256,
Scalar::e_uint256,
Scalar::e_void // sentinel
};
static Scalar::Type float_types[] = {
Scalar::e_float, Scalar::e_double, Scalar::e_long_double,
Scalar::e_void // sentinel
};
for (int i = 0; int_types[i] != Scalar::e_void; ++i) {
for (int j = 0; float_types[j] != Scalar::e_void; ++j) {
Scalar lhs(2);
EXPECT_TRUE(lhs.Promote(int_types[i])) << "int promotion #" << i;
Scalar rhs(0.5f);
EXPECT_TRUE(rhs.Promote(float_types[j])) << "float promotion #" << j;
Scalar x(2.5f);
EXPECT_TRUE(x.Promote(float_types[j]));
EXPECT_EQ(lhs + rhs, x);
}
}
for (int i = 0; float_types[i] != Scalar::e_void; ++i) {
for (int j = 0; float_types[j] != Scalar::e_void; ++j) {
Scalar lhs(2);
EXPECT_TRUE(lhs.Promote(float_types[i])) << "float promotion #" << i;
Scalar rhs(0.5f);
EXPECT_TRUE(rhs.Promote(float_types[j])) << "float promotion #" << j;
Scalar x(2.5f);
EXPECT_TRUE(x.Promote(float_types[j]));
EXPECT_EQ(lhs + rhs, x);
}
}
}
<commit_msg>Fix narrowing warning by appending `f` to literal constant.<commit_after>//===-- ScalarTest.cpp ------------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "gtest/gtest.h"
#include "lldb/Core/Scalar.h"
#include "lldb/Utility/DataExtractor.h"
#include "lldb/Utility/Endian.h"
#include "lldb/Utility/Status.h"
#include "lldb/Utility/StreamString.h"
using namespace lldb_private;
TEST(ScalarTest, RightShiftOperator) {
int a = 0x00001000;
int b = 0xFFFFFFFF;
int c = 4;
Scalar a_scalar(a);
Scalar b_scalar(b);
Scalar c_scalar(c);
ASSERT_EQ(a >> c, a_scalar >> c_scalar);
ASSERT_EQ(b >> c, b_scalar >> c_scalar);
}
TEST(ScalarTest, GetBytes) {
int a = 0x01020304;
long long b = 0x0102030405060708LL;
float c = 1234567.89e32f;
double d = 1234567.89e42;
char e[16] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
char f[32] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32};
Scalar a_scalar(a);
Scalar b_scalar(b);
Scalar c_scalar(c);
Scalar d_scalar(d);
Scalar e_scalar;
Scalar f_scalar;
DataExtractor e_data(e, sizeof(e), endian::InlHostByteOrder(),
sizeof(void *));
Status e_error =
e_scalar.SetValueFromData(e_data, lldb::eEncodingUint, sizeof(e));
DataExtractor f_data(f, sizeof(f), endian::InlHostByteOrder(),
sizeof(void *));
Status f_error =
f_scalar.SetValueFromData(f_data, lldb::eEncodingUint, sizeof(f));
ASSERT_EQ(0, memcmp(&a, a_scalar.GetBytes(), sizeof(a)));
ASSERT_EQ(0, memcmp(&b, b_scalar.GetBytes(), sizeof(b)));
ASSERT_EQ(0, memcmp(&c, c_scalar.GetBytes(), sizeof(c)));
ASSERT_EQ(0, memcmp(&d, d_scalar.GetBytes(), sizeof(d)));
ASSERT_EQ(0, e_error.Fail());
ASSERT_EQ(0, memcmp(e, e_scalar.GetBytes(), sizeof(e)));
ASSERT_EQ(0, f_error.Fail());
ASSERT_EQ(0, memcmp(f, f_scalar.GetBytes(), sizeof(f)));
}
TEST(ScalarTest, CastOperations) {
long long a = 0xf1f2f3f4f5f6f7f8LL;
Scalar a_scalar(a);
ASSERT_EQ((signed char)a, a_scalar.SChar());
ASSERT_EQ((unsigned char)a, a_scalar.UChar());
ASSERT_EQ((signed short)a, a_scalar.SShort());
ASSERT_EQ((unsigned short)a, a_scalar.UShort());
ASSERT_EQ((signed int)a, a_scalar.SInt());
ASSERT_EQ((unsigned int)a, a_scalar.UInt());
ASSERT_EQ((signed long)a, a_scalar.SLong());
ASSERT_EQ((unsigned long)a, a_scalar.ULong());
ASSERT_EQ((signed long long)a, a_scalar.SLongLong());
ASSERT_EQ((unsigned long long)a, a_scalar.ULongLong());
int a2 = 23;
Scalar a2_scalar(a2);
ASSERT_EQ((float)a2, a2_scalar.Float());
ASSERT_EQ((double)a2, a2_scalar.Double());
ASSERT_EQ((long double)a2, a2_scalar.LongDouble());
}
TEST(ScalarTest, ExtractBitfield) {
uint32_t len = sizeof(long long) * 8;
long long a1 = 0xf1f2f3f4f5f6f7f8LL;
long long b1 = 0xff1f2f3f4f5f6f7fLL;
Scalar s_scalar(a1);
ASSERT_TRUE(s_scalar.ExtractBitfield(0, 0));
ASSERT_EQ(0, memcmp(&a1, s_scalar.GetBytes(), sizeof(a1)));
ASSERT_TRUE(s_scalar.ExtractBitfield(len, 0));
ASSERT_EQ(0, memcmp(&a1, s_scalar.GetBytes(), sizeof(a1)));
ASSERT_TRUE(s_scalar.ExtractBitfield(len - 4, 4));
ASSERT_EQ(0, memcmp(&b1, s_scalar.GetBytes(), sizeof(b1)));
unsigned long long a2 = 0xf1f2f3f4f5f6f7f8ULL;
unsigned long long b2 = 0x0f1f2f3f4f5f6f7fULL;
Scalar u_scalar(a2);
ASSERT_TRUE(u_scalar.ExtractBitfield(0, 0));
ASSERT_EQ(0, memcmp(&a2, u_scalar.GetBytes(), sizeof(a2)));
ASSERT_TRUE(u_scalar.ExtractBitfield(len, 0));
ASSERT_EQ(0, memcmp(&a2, u_scalar.GetBytes(), sizeof(a2)));
ASSERT_TRUE(u_scalar.ExtractBitfield(len - 4, 4));
ASSERT_EQ(0, memcmp(&b2, u_scalar.GetBytes(), sizeof(b2)));
}
template <typename T> static std::string ScalarGetValue(T value) {
StreamString stream;
Scalar(value).GetValue(&stream, false);
return stream.GetString();
}
TEST(ScalarTest, GetValue) {
EXPECT_EQ("12345", ScalarGetValue<signed short>(12345));
EXPECT_EQ("-12345", ScalarGetValue<signed short>(-12345));
EXPECT_EQ("12345", ScalarGetValue<unsigned short>(12345));
EXPECT_EQ(std::to_string(std::numeric_limits<unsigned short>::max()),
ScalarGetValue(std::numeric_limits<unsigned short>::max()));
EXPECT_EQ("12345", ScalarGetValue<signed int>(12345));
EXPECT_EQ("-12345", ScalarGetValue<signed int>(-12345));
EXPECT_EQ("12345", ScalarGetValue<unsigned int>(12345));
EXPECT_EQ(std::to_string(std::numeric_limits<unsigned int>::max()),
ScalarGetValue(std::numeric_limits<unsigned int>::max()));
EXPECT_EQ("12345678", ScalarGetValue<signed long>(12345678L));
EXPECT_EQ("-12345678", ScalarGetValue<signed long>(-12345678L));
EXPECT_EQ("12345678", ScalarGetValue<unsigned long>(12345678UL));
EXPECT_EQ(std::to_string(std::numeric_limits<unsigned long>::max()),
ScalarGetValue(std::numeric_limits<unsigned long>::max()));
EXPECT_EQ("1234567890123", ScalarGetValue<signed long long>(1234567890123LL));
EXPECT_EQ("-1234567890123",
ScalarGetValue<signed long long>(-1234567890123LL));
EXPECT_EQ("1234567890123",
ScalarGetValue<unsigned long long>(1234567890123ULL));
EXPECT_EQ(std::to_string(std::numeric_limits<unsigned long long>::max()),
ScalarGetValue(std::numeric_limits<unsigned long long>::max()));
}
TEST(ScalarTest, Division) {
Scalar lhs(5.0);
Scalar rhs(2.0);
Scalar r = lhs / rhs;
EXPECT_TRUE(r.IsValid());
EXPECT_EQ(r, Scalar(2.5));
}
TEST(ScalarTest, Promotion) {
static Scalar::Type int_types[] = {
Scalar::e_sint, Scalar::e_uint, Scalar::e_slong,
Scalar::e_ulong, Scalar::e_slonglong, Scalar::e_ulonglong,
Scalar::e_sint128, Scalar::e_uint128, Scalar::e_sint256,
Scalar::e_uint256,
Scalar::e_void // sentinel
};
static Scalar::Type float_types[] = {
Scalar::e_float, Scalar::e_double, Scalar::e_long_double,
Scalar::e_void // sentinel
};
for (int i = 0; int_types[i] != Scalar::e_void; ++i) {
for (int j = 0; float_types[j] != Scalar::e_void; ++j) {
Scalar lhs(2);
EXPECT_TRUE(lhs.Promote(int_types[i])) << "int promotion #" << i;
Scalar rhs(0.5f);
EXPECT_TRUE(rhs.Promote(float_types[j])) << "float promotion #" << j;
Scalar x(2.5f);
EXPECT_TRUE(x.Promote(float_types[j]));
EXPECT_EQ(lhs + rhs, x);
}
}
for (int i = 0; float_types[i] != Scalar::e_void; ++i) {
for (int j = 0; float_types[j] != Scalar::e_void; ++j) {
Scalar lhs(2);
EXPECT_TRUE(lhs.Promote(float_types[i])) << "float promotion #" << i;
Scalar rhs(0.5f);
EXPECT_TRUE(rhs.Promote(float_types[j])) << "float promotion #" << j;
Scalar x(2.5f);
EXPECT_TRUE(x.Promote(float_types[j]));
EXPECT_EQ(lhs + rhs, x);
}
}
}
<|endoftext|>
|
<commit_before>//--------------------------------------------------------------------*- C++ -*-
// CLING - the C++ LLVM-based InterpreterG :)
// author: Baozeng Ding <sploving1@gmail.com>
// author: Vassil Vassilev <vasil.georgiev.vasilev@cern.ch>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
#include "cling/Interpreter/Exception.h"
#include "cling/Interpreter/InterpreterCallbacks.h"
#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/Visibility.h"
#include "cling/Utils/Validation.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Sema/Sema.h"
#include "clang/Sema/SemaDiagnostic.h"
extern "C" {
/// Throw an InvalidDerefException if the Arg pointer is invalid.
///\param Interp: The interpreter that has compiled the code.
///\param Expr: The expression corresponding determining the pointer value.
///\param Arg: The pointer to be checked.
///\returns void*, const-cast from Arg, to reduce the complexity in the
/// calling AST nodes, at the expense of possibly doing a
/// T* -> const void* -> const_cast<void*> -> T* round trip.
CLING_LIB_EXPORT
void* cling_runtime_internal_throwIfInvalidPointer(void* Interp, void* Expr,
const void* Arg) {
const clang::Expr* const E = (const clang::Expr*)Expr;
#if defined(__APPLE__) && defined(__arm64__)
// See https://github.com/root-project/root/issues/7541 and
// https://bugs.llvm.org/show_bug.cgi?id=49692 :
// llvm JIT fails to catch exceptions on M1, so let's throw less.
// This might still better than `terminate`...
(void)Interp;
(void)Expr;
#else
// The isValidAddress function return true even when the pointer is
// null thus the checks have to be done before returning successfully from the
// function in this specific order.
if (!Arg) {
cling::Interpreter* I = (cling::Interpreter*)Interp;
clang::Sema& S = I->getCI()->getSema();
// Print a nice backtrace.
// FIXME: re-enable once we have JIT debug symbols!
//I->getCallbacks()->PrintStackTrace();
throw cling::InvalidDerefException(&S, E,
cling::InvalidDerefException::DerefType::NULL_DEREF);
} else if (!cling::utils::isAddressValid(Arg)) {
cling::Interpreter* I = (cling::Interpreter*)Interp;
clang::Sema& S = I->getCI()->getSema();
// Print a nice backtrace.
// FIXME: re-enable once we have JIT debug symbols!
//I->getCallbacks()->PrintStackTrace();
throw cling::InvalidDerefException(&S, E,
cling::InvalidDerefException::DerefType::INVALID_MEM);
}
#endif
return const_cast<void*>(Arg);
}
}
namespace cling {
InterpreterException::InterpreterException(const std::string& What) :
std::runtime_error(What), m_Sema(nullptr) {}
InterpreterException::InterpreterException(const char* What, clang::Sema* S) :
std::runtime_error(What), m_Sema(S) {}
bool InterpreterException::diagnose() const { return false; }
InterpreterException::~InterpreterException() noexcept {}
InvalidDerefException::InvalidDerefException(clang::Sema* S,
const clang::Expr* E,
DerefType type)
: InterpreterException(type == INVALID_MEM ?
"Trying to access a pointer that points to an invalid memory address." :
"Trying to dereference null pointer or trying to call routine taking "
"non-null arguments", S),
m_Arg(E), m_Type(type) {}
InvalidDerefException::~InvalidDerefException() noexcept {}
bool InvalidDerefException::diagnose() const {
// Construct custom diagnostic: warning for invalid memory address;
// no equivalent in clang.
if (m_Type == cling::InvalidDerefException::DerefType::INVALID_MEM) {
clang::DiagnosticsEngine& Diags = m_Sema->getDiagnostics();
unsigned DiagID =
Diags.getCustomDiagID(clang::DiagnosticsEngine::Warning,
"invalid memory pointer passed to a callee:");
Diags.Report(m_Arg->getBeginLoc(), DiagID) << m_Arg->getSourceRange();
}
else
m_Sema->Diag(m_Arg->getBeginLoc(), clang::diag::warn_null_arg)
<< m_Arg->getSourceRange();
return true;
}
CompilationException::CompilationException(const std::string& Reason) :
InterpreterException(Reason) {}
CompilationException::~CompilationException() noexcept {}
void CompilationException::throwingHandler(void * /*user_data*/,
const std::string& reason,
bool /*gen_crash_diag*/) {
#ifndef _MSC_VER
throw cling::CompilationException(reason);
#endif
}
} // end namespace cling
<commit_msg>Remove unused variables to fix build warnings on `mac11arm`<commit_after>//--------------------------------------------------------------------*- C++ -*-
// CLING - the C++ LLVM-based InterpreterG :)
// author: Baozeng Ding <sploving1@gmail.com>
// author: Vassil Vassilev <vasil.georgiev.vasilev@cern.ch>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
#include "cling/Interpreter/Exception.h"
#include "cling/Interpreter/InterpreterCallbacks.h"
#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/Visibility.h"
#include "cling/Utils/Validation.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Sema/Sema.h"
#include "clang/Sema/SemaDiagnostic.h"
extern "C" {
/// Throw an InvalidDerefException if the Arg pointer is invalid.
///\param Interp: The interpreter that has compiled the code.
///\param Expr: The expression corresponding determining the pointer value.
///\param Arg: The pointer to be checked.
///\returns void*, const-cast from Arg, to reduce the complexity in the
/// calling AST nodes, at the expense of possibly doing a
/// T* -> const void* -> const_cast<void*> -> T* round trip.
CLING_LIB_EXPORT
void* cling_runtime_internal_throwIfInvalidPointer(void* Interp, void* Expr,
const void* Arg) {
#if defined(__APPLE__) && defined(__arm64__)
// See https://github.com/root-project/root/issues/7541 and
// https://bugs.llvm.org/show_bug.cgi?id=49692 :
// llvm JIT fails to catch exceptions on M1, so let's throw less.
// This might still better than `terminate`...
(void)Interp;
(void)Expr;
#else
const clang::Expr* const E = (const clang::Expr*)Expr;
// The isValidAddress function return true even when the pointer is
// null thus the checks have to be done before returning successfully from the
// function in this specific order.
if (!Arg) {
cling::Interpreter* I = (cling::Interpreter*)Interp;
clang::Sema& S = I->getCI()->getSema();
// Print a nice backtrace.
// FIXME: re-enable once we have JIT debug symbols!
//I->getCallbacks()->PrintStackTrace();
throw cling::InvalidDerefException(&S, E,
cling::InvalidDerefException::DerefType::NULL_DEREF);
} else if (!cling::utils::isAddressValid(Arg)) {
cling::Interpreter* I = (cling::Interpreter*)Interp;
clang::Sema& S = I->getCI()->getSema();
// Print a nice backtrace.
// FIXME: re-enable once we have JIT debug symbols!
//I->getCallbacks()->PrintStackTrace();
throw cling::InvalidDerefException(&S, E,
cling::InvalidDerefException::DerefType::INVALID_MEM);
}
#endif
return const_cast<void*>(Arg);
}
}
namespace cling {
InterpreterException::InterpreterException(const std::string& What) :
std::runtime_error(What), m_Sema(nullptr) {}
InterpreterException::InterpreterException(const char* What, clang::Sema* S) :
std::runtime_error(What), m_Sema(S) {}
bool InterpreterException::diagnose() const { return false; }
InterpreterException::~InterpreterException() noexcept {}
InvalidDerefException::InvalidDerefException(clang::Sema* S,
const clang::Expr* E,
DerefType type)
: InterpreterException(type == INVALID_MEM ?
"Trying to access a pointer that points to an invalid memory address." :
"Trying to dereference null pointer or trying to call routine taking "
"non-null arguments", S),
m_Arg(E), m_Type(type) {}
InvalidDerefException::~InvalidDerefException() noexcept {}
bool InvalidDerefException::diagnose() const {
// Construct custom diagnostic: warning for invalid memory address;
// no equivalent in clang.
if (m_Type == cling::InvalidDerefException::DerefType::INVALID_MEM) {
clang::DiagnosticsEngine& Diags = m_Sema->getDiagnostics();
unsigned DiagID =
Diags.getCustomDiagID(clang::DiagnosticsEngine::Warning,
"invalid memory pointer passed to a callee:");
Diags.Report(m_Arg->getBeginLoc(), DiagID) << m_Arg->getSourceRange();
}
else
m_Sema->Diag(m_Arg->getBeginLoc(), clang::diag::warn_null_arg)
<< m_Arg->getSourceRange();
return true;
}
CompilationException::CompilationException(const std::string& Reason) :
InterpreterException(Reason) {}
CompilationException::~CompilationException() noexcept {}
void CompilationException::throwingHandler(void * /*user_data*/,
const std::string& reason,
bool /*gen_crash_diag*/) {
#ifndef _MSC_VER
throw cling::CompilationException(reason);
#endif
}
} // end namespace cling
<|endoftext|>
|
<commit_before>//===-- Local.cpp - Functions to perform local transformations ------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This family of functions perform various local transformations to the
// program.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Utils/Local.h"
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Instructions.h"
#include "llvm/Intrinsics.h"
#include "llvm/Analysis/ConstantFolding.h"
#include "llvm/Support/GetElementPtrTypeIterator.h"
#include "llvm/Support/MathExtras.h"
#include <cerrno>
#include <cmath>
using namespace llvm;
//===----------------------------------------------------------------------===//
// Local constant propagation...
//
/// doConstantPropagation - If an instruction references constants, try to fold
/// them together...
///
bool llvm::doConstantPropagation(BasicBlock::iterator &II) {
if (Constant *C = ConstantFoldInstruction(II)) {
// Replaces all of the uses of a variable with uses of the constant.
II->replaceAllUsesWith(C);
// Remove the instruction from the basic block...
II = II->getParent()->getInstList().erase(II);
return true;
}
return false;
}
/// ConstantFoldInstruction - Attempt to constant fold the specified
/// instruction. If successful, the constant result is returned, if not, null
/// is returned. Note that this function can only fail when attempting to fold
/// instructions like loads and stores, which have no constant expression form.
///
Constant *llvm::ConstantFoldInstruction(Instruction *I) {
if (PHINode *PN = dyn_cast<PHINode>(I)) {
if (PN->getNumIncomingValues() == 0)
return Constant::getNullValue(PN->getType());
Constant *Result = dyn_cast<Constant>(PN->getIncomingValue(0));
if (Result == 0) return 0;
// Handle PHI nodes specially here...
for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
if (PN->getIncomingValue(i) != Result && PN->getIncomingValue(i) != PN)
return 0; // Not all the same incoming constants...
// If we reach here, all incoming values are the same constant.
return Result;
} else if (CallInst *CI = dyn_cast<CallInst>(I)) {
if (Function *F = CI->getCalledFunction())
if (canConstantFoldCallTo(F)) {
std::vector<Constant*> Args;
for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
if (Constant *Op = dyn_cast<Constant>(CI->getOperand(i)))
Args.push_back(Op);
else
return 0;
return ConstantFoldCall(F, Args);
}
return 0;
}
Constant *Op0 = 0, *Op1 = 0;
switch (I->getNumOperands()) {
default:
case 2:
Op1 = dyn_cast<Constant>(I->getOperand(1));
if (Op1 == 0) return 0; // Not a constant?, can't fold
case 1:
Op0 = dyn_cast<Constant>(I->getOperand(0));
if (Op0 == 0) return 0; // Not a constant?, can't fold
break;
case 0: return 0;
}
if (isa<BinaryOperator>(I) || isa<ShiftInst>(I))
return ConstantExpr::get(I->getOpcode(), Op0, Op1);
switch (I->getOpcode()) {
default: return 0;
case Instruction::Cast:
return ConstantExpr::getCast(Op0, I->getType());
case Instruction::Select:
if (Constant *Op2 = dyn_cast<Constant>(I->getOperand(2)))
return ConstantExpr::getSelect(Op0, Op1, Op2);
return 0;
case Instruction::ExtractElement:
return ConstantExpr::getExtractElement(Op0, Op1);
case Instruction::InsertElement:
if (Constant *Op2 = dyn_cast<Constant>(I->getOperand(2)))
return ConstantExpr::getInsertElement(Op0, Op1, Op2);
return 0;
case Instruction::ShuffleVector:
if (Constant *Op2 = dyn_cast<Constant>(I->getOperand(2)))
return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
return 0;
case Instruction::GetElementPtr:
std::vector<Constant*> IdxList;
IdxList.reserve(I->getNumOperands()-1);
if (Op1) IdxList.push_back(Op1);
for (unsigned i = 2, e = I->getNumOperands(); i != e; ++i)
if (Constant *C = dyn_cast<Constant>(I->getOperand(i)))
IdxList.push_back(C);
else
return 0; // Non-constant operand
return ConstantExpr::getGetElementPtr(Op0, IdxList);
}
}
// ConstantFoldTerminator - If a terminator instruction is predicated on a
// constant value, convert it into an unconditional branch to the constant
// destination.
//
bool llvm::ConstantFoldTerminator(BasicBlock *BB) {
TerminatorInst *T = BB->getTerminator();
// Branch - See if we are conditional jumping on constant
if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
if (BI->isUnconditional()) return false; // Can't optimize uncond branch
BasicBlock *Dest1 = cast<BasicBlock>(BI->getOperand(0));
BasicBlock *Dest2 = cast<BasicBlock>(BI->getOperand(1));
if (ConstantBool *Cond = dyn_cast<ConstantBool>(BI->getCondition())) {
// Are we branching on constant?
// YES. Change to unconditional branch...
BasicBlock *Destination = Cond->getValue() ? Dest1 : Dest2;
BasicBlock *OldDest = Cond->getValue() ? Dest2 : Dest1;
//cerr << "Function: " << T->getParent()->getParent()
// << "\nRemoving branch from " << T->getParent()
// << "\n\nTo: " << OldDest << endl;
// Let the basic block know that we are letting go of it. Based on this,
// it will adjust it's PHI nodes.
assert(BI->getParent() && "Terminator not inserted in block!");
OldDest->removePredecessor(BI->getParent());
// Set the unconditional destination, and change the insn to be an
// unconditional branch.
BI->setUnconditionalDest(Destination);
return true;
} else if (Dest2 == Dest1) { // Conditional branch to same location?
// This branch matches something like this:
// br bool %cond, label %Dest, label %Dest
// and changes it into: br label %Dest
// Let the basic block know that we are letting go of one copy of it.
assert(BI->getParent() && "Terminator not inserted in block!");
Dest1->removePredecessor(BI->getParent());
// Change a conditional branch to unconditional.
BI->setUnconditionalDest(Dest1);
return true;
}
} else if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
// If we are switching on a constant, we can convert the switch into a
// single branch instruction!
ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
BasicBlock *TheOnlyDest = SI->getSuccessor(0); // The default dest
BasicBlock *DefaultDest = TheOnlyDest;
assert(TheOnlyDest == SI->getDefaultDest() &&
"Default destination is not successor #0?");
// Figure out which case it goes to...
for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
// Found case matching a constant operand?
if (SI->getSuccessorValue(i) == CI) {
TheOnlyDest = SI->getSuccessor(i);
break;
}
// Check to see if this branch is going to the same place as the default
// dest. If so, eliminate it as an explicit compare.
if (SI->getSuccessor(i) == DefaultDest) {
// Remove this entry...
DefaultDest->removePredecessor(SI->getParent());
SI->removeCase(i);
--i; --e; // Don't skip an entry...
continue;
}
// Otherwise, check to see if the switch only branches to one destination.
// We do this by reseting "TheOnlyDest" to null when we find two non-equal
// destinations.
if (SI->getSuccessor(i) != TheOnlyDest) TheOnlyDest = 0;
}
if (CI && !TheOnlyDest) {
// Branching on a constant, but not any of the cases, go to the default
// successor.
TheOnlyDest = SI->getDefaultDest();
}
// If we found a single destination that we can fold the switch into, do so
// now.
if (TheOnlyDest) {
// Insert the new branch..
new BranchInst(TheOnlyDest, SI);
BasicBlock *BB = SI->getParent();
// Remove entries from PHI nodes which we no longer branch to...
for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
// Found case matching a constant operand?
BasicBlock *Succ = SI->getSuccessor(i);
if (Succ == TheOnlyDest)
TheOnlyDest = 0; // Don't modify the first branch to TheOnlyDest
else
Succ->removePredecessor(BB);
}
// Delete the old switch...
BB->getInstList().erase(SI);
return true;
} else if (SI->getNumSuccessors() == 2) {
// Otherwise, we can fold this switch into a conditional branch
// instruction if it has only one non-default destination.
Value *Cond = new SetCondInst(Instruction::SetEQ, SI->getCondition(),
SI->getSuccessorValue(1), "cond", SI);
// Insert the new branch...
new BranchInst(SI->getSuccessor(1), SI->getSuccessor(0), Cond, SI);
// Delete the old switch...
SI->getParent()->getInstList().erase(SI);
return true;
}
}
return false;
}
/// ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a
/// getelementptr constantexpr, return the constant value being addressed by the
/// constant expression, or null if something is funny and we can't decide.
Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
ConstantExpr *CE) {
if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
return 0; // Do not allow stepping over the value!
// Loop over all of the operands, tracking down which value we are
// addressing...
gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
for (++I; I != E; ++I)
if (const StructType *STy = dyn_cast<StructType>(*I)) {
ConstantUInt *CU = cast<ConstantUInt>(I.getOperand());
assert(CU->getValue() < STy->getNumElements() &&
"Struct index out of range!");
unsigned El = (unsigned)CU->getValue();
if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
C = CS->getOperand(El);
} else if (isa<ConstantAggregateZero>(C)) {
C = Constant::getNullValue(STy->getElementType(El));
} else if (isa<UndefValue>(C)) {
C = UndefValue::get(STy->getElementType(El));
} else {
return 0;
}
} else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
if (const ArrayType *ATy = dyn_cast<ArrayType>(*I)) {
if ((uint64_t)CI->getRawValue() >= ATy->getNumElements())
C = UndefValue::get(ATy->getElementType());
if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
C = CA->getOperand((unsigned)CI->getRawValue());
else if (isa<ConstantAggregateZero>(C))
C = Constant::getNullValue(ATy->getElementType());
else if (isa<UndefValue>(C))
C = UndefValue::get(ATy->getElementType());
else
return 0;
} else if (const PackedType *PTy = dyn_cast<PackedType>(*I)) {
if ((uint64_t)CI->getRawValue() >= PTy->getNumElements())
C = UndefValue::get(PTy->getElementType());
if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C))
C = CP->getOperand((unsigned)CI->getRawValue());
else if (isa<ConstantAggregateZero>(C))
C = Constant::getNullValue(PTy->getElementType());
else if (isa<UndefValue>(C))
C = UndefValue::get(PTy->getElementType());
else
return 0;
} else {
return 0;
}
} else {
return 0;
}
return C;
}
//===----------------------------------------------------------------------===//
// Local dead code elimination...
//
bool llvm::isInstructionTriviallyDead(Instruction *I) {
if (!I->use_empty() || isa<TerminatorInst>(I)) return false;
if (!I->mayWriteToMemory()) return true;
if (CallInst *CI = dyn_cast<CallInst>(I))
if (Function *F = CI->getCalledFunction()) {
unsigned IntrinsicID = F->getIntrinsicID();
#define GET_SIDE_EFFECT_INFO
#include "llvm/Intrinsics.gen"
#undef GET_SIDE_EFFECT_INFO
}
return false;
}
// dceInstruction - Inspect the instruction at *BBI and figure out if it's
// [trivially] dead. If so, remove the instruction and update the iterator
// to point to the instruction that immediately succeeded the original
// instruction.
//
bool llvm::dceInstruction(BasicBlock::iterator &BBI) {
// Look for un"used" definitions...
if (isInstructionTriviallyDead(BBI)) {
BBI = BBI->getParent()->getInstList().erase(BBI); // Bye bye
return true;
}
return false;
}
<commit_msg>Revert a patch that is unsafe, due to out of range array accesses in inner array scopes possibly accessing valid memory in outer subscripts.<commit_after>//===-- Local.cpp - Functions to perform local transformations ------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This family of functions perform various local transformations to the
// program.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Utils/Local.h"
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Instructions.h"
#include "llvm/Intrinsics.h"
#include "llvm/Analysis/ConstantFolding.h"
#include "llvm/Support/GetElementPtrTypeIterator.h"
#include "llvm/Support/MathExtras.h"
#include <cerrno>
#include <cmath>
using namespace llvm;
//===----------------------------------------------------------------------===//
// Local constant propagation...
//
/// doConstantPropagation - If an instruction references constants, try to fold
/// them together...
///
bool llvm::doConstantPropagation(BasicBlock::iterator &II) {
if (Constant *C = ConstantFoldInstruction(II)) {
// Replaces all of the uses of a variable with uses of the constant.
II->replaceAllUsesWith(C);
// Remove the instruction from the basic block...
II = II->getParent()->getInstList().erase(II);
return true;
}
return false;
}
/// ConstantFoldInstruction - Attempt to constant fold the specified
/// instruction. If successful, the constant result is returned, if not, null
/// is returned. Note that this function can only fail when attempting to fold
/// instructions like loads and stores, which have no constant expression form.
///
Constant *llvm::ConstantFoldInstruction(Instruction *I) {
if (PHINode *PN = dyn_cast<PHINode>(I)) {
if (PN->getNumIncomingValues() == 0)
return Constant::getNullValue(PN->getType());
Constant *Result = dyn_cast<Constant>(PN->getIncomingValue(0));
if (Result == 0) return 0;
// Handle PHI nodes specially here...
for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
if (PN->getIncomingValue(i) != Result && PN->getIncomingValue(i) != PN)
return 0; // Not all the same incoming constants...
// If we reach here, all incoming values are the same constant.
return Result;
} else if (CallInst *CI = dyn_cast<CallInst>(I)) {
if (Function *F = CI->getCalledFunction())
if (canConstantFoldCallTo(F)) {
std::vector<Constant*> Args;
for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
if (Constant *Op = dyn_cast<Constant>(CI->getOperand(i)))
Args.push_back(Op);
else
return 0;
return ConstantFoldCall(F, Args);
}
return 0;
}
Constant *Op0 = 0, *Op1 = 0;
switch (I->getNumOperands()) {
default:
case 2:
Op1 = dyn_cast<Constant>(I->getOperand(1));
if (Op1 == 0) return 0; // Not a constant?, can't fold
case 1:
Op0 = dyn_cast<Constant>(I->getOperand(0));
if (Op0 == 0) return 0; // Not a constant?, can't fold
break;
case 0: return 0;
}
if (isa<BinaryOperator>(I) || isa<ShiftInst>(I))
return ConstantExpr::get(I->getOpcode(), Op0, Op1);
switch (I->getOpcode()) {
default: return 0;
case Instruction::Cast:
return ConstantExpr::getCast(Op0, I->getType());
case Instruction::Select:
if (Constant *Op2 = dyn_cast<Constant>(I->getOperand(2)))
return ConstantExpr::getSelect(Op0, Op1, Op2);
return 0;
case Instruction::ExtractElement:
return ConstantExpr::getExtractElement(Op0, Op1);
case Instruction::InsertElement:
if (Constant *Op2 = dyn_cast<Constant>(I->getOperand(2)))
return ConstantExpr::getInsertElement(Op0, Op1, Op2);
return 0;
case Instruction::ShuffleVector:
if (Constant *Op2 = dyn_cast<Constant>(I->getOperand(2)))
return ConstantExpr::getShuffleVector(Op0, Op1, Op2);
return 0;
case Instruction::GetElementPtr:
std::vector<Constant*> IdxList;
IdxList.reserve(I->getNumOperands()-1);
if (Op1) IdxList.push_back(Op1);
for (unsigned i = 2, e = I->getNumOperands(); i != e; ++i)
if (Constant *C = dyn_cast<Constant>(I->getOperand(i)))
IdxList.push_back(C);
else
return 0; // Non-constant operand
return ConstantExpr::getGetElementPtr(Op0, IdxList);
}
}
// ConstantFoldTerminator - If a terminator instruction is predicated on a
// constant value, convert it into an unconditional branch to the constant
// destination.
//
bool llvm::ConstantFoldTerminator(BasicBlock *BB) {
TerminatorInst *T = BB->getTerminator();
// Branch - See if we are conditional jumping on constant
if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
if (BI->isUnconditional()) return false; // Can't optimize uncond branch
BasicBlock *Dest1 = cast<BasicBlock>(BI->getOperand(0));
BasicBlock *Dest2 = cast<BasicBlock>(BI->getOperand(1));
if (ConstantBool *Cond = dyn_cast<ConstantBool>(BI->getCondition())) {
// Are we branching on constant?
// YES. Change to unconditional branch...
BasicBlock *Destination = Cond->getValue() ? Dest1 : Dest2;
BasicBlock *OldDest = Cond->getValue() ? Dest2 : Dest1;
//cerr << "Function: " << T->getParent()->getParent()
// << "\nRemoving branch from " << T->getParent()
// << "\n\nTo: " << OldDest << endl;
// Let the basic block know that we are letting go of it. Based on this,
// it will adjust it's PHI nodes.
assert(BI->getParent() && "Terminator not inserted in block!");
OldDest->removePredecessor(BI->getParent());
// Set the unconditional destination, and change the insn to be an
// unconditional branch.
BI->setUnconditionalDest(Destination);
return true;
} else if (Dest2 == Dest1) { // Conditional branch to same location?
// This branch matches something like this:
// br bool %cond, label %Dest, label %Dest
// and changes it into: br label %Dest
// Let the basic block know that we are letting go of one copy of it.
assert(BI->getParent() && "Terminator not inserted in block!");
Dest1->removePredecessor(BI->getParent());
// Change a conditional branch to unconditional.
BI->setUnconditionalDest(Dest1);
return true;
}
} else if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
// If we are switching on a constant, we can convert the switch into a
// single branch instruction!
ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
BasicBlock *TheOnlyDest = SI->getSuccessor(0); // The default dest
BasicBlock *DefaultDest = TheOnlyDest;
assert(TheOnlyDest == SI->getDefaultDest() &&
"Default destination is not successor #0?");
// Figure out which case it goes to...
for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
// Found case matching a constant operand?
if (SI->getSuccessorValue(i) == CI) {
TheOnlyDest = SI->getSuccessor(i);
break;
}
// Check to see if this branch is going to the same place as the default
// dest. If so, eliminate it as an explicit compare.
if (SI->getSuccessor(i) == DefaultDest) {
// Remove this entry...
DefaultDest->removePredecessor(SI->getParent());
SI->removeCase(i);
--i; --e; // Don't skip an entry...
continue;
}
// Otherwise, check to see if the switch only branches to one destination.
// We do this by reseting "TheOnlyDest" to null when we find two non-equal
// destinations.
if (SI->getSuccessor(i) != TheOnlyDest) TheOnlyDest = 0;
}
if (CI && !TheOnlyDest) {
// Branching on a constant, but not any of the cases, go to the default
// successor.
TheOnlyDest = SI->getDefaultDest();
}
// If we found a single destination that we can fold the switch into, do so
// now.
if (TheOnlyDest) {
// Insert the new branch..
new BranchInst(TheOnlyDest, SI);
BasicBlock *BB = SI->getParent();
// Remove entries from PHI nodes which we no longer branch to...
for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
// Found case matching a constant operand?
BasicBlock *Succ = SI->getSuccessor(i);
if (Succ == TheOnlyDest)
TheOnlyDest = 0; // Don't modify the first branch to TheOnlyDest
else
Succ->removePredecessor(BB);
}
// Delete the old switch...
BB->getInstList().erase(SI);
return true;
} else if (SI->getNumSuccessors() == 2) {
// Otherwise, we can fold this switch into a conditional branch
// instruction if it has only one non-default destination.
Value *Cond = new SetCondInst(Instruction::SetEQ, SI->getCondition(),
SI->getSuccessorValue(1), "cond", SI);
// Insert the new branch...
new BranchInst(SI->getSuccessor(1), SI->getSuccessor(0), Cond, SI);
// Delete the old switch...
SI->getParent()->getInstList().erase(SI);
return true;
}
}
return false;
}
/// ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a
/// getelementptr constantexpr, return the constant value being addressed by the
/// constant expression, or null if something is funny and we can't decide.
Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
ConstantExpr *CE) {
if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
return 0; // Do not allow stepping over the value!
// Loop over all of the operands, tracking down which value we are
// addressing...
gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
for (++I; I != E; ++I)
if (const StructType *STy = dyn_cast<StructType>(*I)) {
ConstantUInt *CU = cast<ConstantUInt>(I.getOperand());
assert(CU->getValue() < STy->getNumElements() &&
"Struct index out of range!");
unsigned El = (unsigned)CU->getValue();
if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
C = CS->getOperand(El);
} else if (isa<ConstantAggregateZero>(C)) {
C = Constant::getNullValue(STy->getElementType(El));
} else if (isa<UndefValue>(C)) {
C = UndefValue::get(STy->getElementType(El));
} else {
return 0;
}
} else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
if (const ArrayType *ATy = dyn_cast<ArrayType>(*I)) {
if ((uint64_t)CI->getRawValue() >= ATy->getNumElements())
return 0;
if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
C = CA->getOperand((unsigned)CI->getRawValue());
else if (isa<ConstantAggregateZero>(C))
C = Constant::getNullValue(ATy->getElementType());
else if (isa<UndefValue>(C))
C = UndefValue::get(ATy->getElementType());
else
return 0;
} else if (const PackedType *PTy = dyn_cast<PackedType>(*I)) {
if ((uint64_t)CI->getRawValue() >= PTy->getNumElements())
return 0;
if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C))
C = CP->getOperand((unsigned)CI->getRawValue());
else if (isa<ConstantAggregateZero>(C))
C = Constant::getNullValue(PTy->getElementType());
else if (isa<UndefValue>(C))
C = UndefValue::get(PTy->getElementType());
else
return 0;
} else {
return 0;
}
} else {
return 0;
}
return C;
}
//===----------------------------------------------------------------------===//
// Local dead code elimination...
//
bool llvm::isInstructionTriviallyDead(Instruction *I) {
if (!I->use_empty() || isa<TerminatorInst>(I)) return false;
if (!I->mayWriteToMemory()) return true;
if (CallInst *CI = dyn_cast<CallInst>(I))
if (Function *F = CI->getCalledFunction()) {
unsigned IntrinsicID = F->getIntrinsicID();
#define GET_SIDE_EFFECT_INFO
#include "llvm/Intrinsics.gen"
#undef GET_SIDE_EFFECT_INFO
}
return false;
}
// dceInstruction - Inspect the instruction at *BBI and figure out if it's
// [trivially] dead. If so, remove the instruction and update the iterator
// to point to the instruction that immediately succeeded the original
// instruction.
//
bool llvm::dceInstruction(BasicBlock::iterator &BBI) {
// Look for un"used" definitions...
if (isInstructionTriviallyDead(BBI)) {
BBI = BBI->getParent()->getInstList().erase(BBI); // Bye bye
return true;
}
return false;
}
<|endoftext|>
|
<commit_before>// This file is part of the dune-stuff project:
// https://github.com/wwu-numerik/dune-stuff
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_STUFF_WALK_HH_INCLUDED
#define DUNE_STUFF_WALK_HH_INCLUDED
#include <dune/stuff/common/disable_warnings.hh>
# include <dune/common/fvector.hh>
#include <dune/stuff/common/reenable_warnings.hh>
#include <dune/common/deprecated.hh>
#include <dune/stuff/aliases.hh>
#include <dune/stuff/common/math.hh>
#include <dune/stuff/common/misc.hh>
#include <dune/stuff/common/ranges.hh>
#include <dune/grid/common/geometry.hh>
#include <dune/stuff/aliases.hh>
#include <vector>
#include <boost/format.hpp>
namespace Dune {
namespace Stuff {
namespace Grid {
/** \brief Useful dummy functor if you don't have anything to do on entities/intersections
**/
struct GridWalkDummyFunctor {
GridWalkDummyFunctor(){}
template < class Entity >
void operator() ( const Entity&, const int) const
{}
template < class Entity, class Intersection >
void operator() ( const Entity&, const Intersection&) const
{}
};
namespace {
/** \brief global \ref GridWalkDummyFunctor instance
**/
const GridWalkDummyFunctor gridWalkDummyFunctor;
}
/** \brief applies Functors on each \ref Entity/\ref Intersection of a given \ref GridView
* \todo allow stacking of functor to save gridwalks?
* \tparam GridViewImp any \ref GridView interface compliant type
* \tparam codim determines the codim of the Entities that are iterated on
**/
template < class GridViewImp, int codim = 0 >
class GridWalk {
typedef Dune::GridView<typename GridViewImp::Traits> GridViewType;
public:
GridWalk ( const GridViewType& gp )
: gridView_( gp )
{}
/** \param entityFunctor is applied on all codim 0 entities presented by \var gridView_
* \param intersectionFunctor is applied on all Intersections of all codim 0 entities
* presented by \var gridView_
* \note only instantiable for codim == 0
*/
template < class EntityFunctor, class IntersectionFunctor >
void operator () ( EntityFunctor& entityFunctor, IntersectionFunctor& intersectionFunctor ) const
{
static_assert( codim == 0, "walking intersections is only possible for codim 0 entities" );
for (const auto& entity : DSC::entityRange(gridView_)) {
const int entityIndex = gridView_.indexSet().index(entity);
entityFunctor( entity, entityIndex);
for (const auto& intersection : DSC::intersectionRange(gridView_, entity)) {
intersectionFunctor( entity, intersection);
}
}
}
/** \param entityFunctor is applied on all codim entities presented by \var gridView_
* \note only instantiable for codim < GridView::dimension
*/
template < class EntityFunctor >
void operator () ( EntityFunctor& entityFunctor ) const
{
static_assert( codim <= GridViewType::dimension, "codim too high to walk" );
for (const auto& entity : DSC::entityRange(gridView_)) {
const int entityIndex = gridView_.indexSet().index(entity);
entityFunctor( entity, entityIndex);
}
}
private:
const GridViewType& gridView_;
};
//!
template <class ViewImp, int codim = 0>
GridWalk< Dune::GridView<ViewImp>, codim > make_gridwalk(const Dune::GridView<ViewImp>& view) {
return GridWalk< Dune::GridView<ViewImp>, codim >(view);
}
} // namespace Grid
} // namespace Stuff
} // namespace Dune
#endif // ifndef DUNE_STUFF_WALK_HH_INCLUDED
<commit_msg>[grid.walk] update include guard<commit_after>// This file is part of the dune-stuff project:
// https://github.com/wwu-numerik/dune-stuff
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_STUFF_GRID_WALK_HH
#define DUNE_STUFF_GRID_WALK_HH
#include <dune/stuff/common/disable_warnings.hh>
# include <dune/common/fvector.hh>
#include <dune/stuff/common/reenable_warnings.hh>
#include <dune/common/deprecated.hh>
#include <dune/stuff/aliases.hh>
#include <dune/stuff/common/math.hh>
#include <dune/stuff/common/misc.hh>
#include <dune/stuff/common/ranges.hh>
#include <dune/grid/common/geometry.hh>
#include <dune/stuff/aliases.hh>
#include <vector>
#include <boost/format.hpp>
namespace Dune {
namespace Stuff {
namespace Grid {
/** \brief Useful dummy functor if you don't have anything to do on entities/intersections
**/
struct GridWalkDummyFunctor {
GridWalkDummyFunctor(){}
template < class Entity >
void operator() ( const Entity&, const int) const
{}
template < class Entity, class Intersection >
void operator() ( const Entity&, const Intersection&) const
{}
};
namespace {
/** \brief global \ref GridWalkDummyFunctor instance
**/
const GridWalkDummyFunctor gridWalkDummyFunctor;
}
/** \brief applies Functors on each \ref Entity/\ref Intersection of a given \ref GridView
* \todo allow stacking of functor to save gridwalks?
* \tparam GridViewImp any \ref GridView interface compliant type
* \tparam codim determines the codim of the Entities that are iterated on
**/
template < class GridViewImp, int codim = 0 >
class GridWalk {
typedef Dune::GridView<typename GridViewImp::Traits> GridViewType;
public:
GridWalk ( const GridViewType& gp )
: gridView_( gp )
{}
/** \param entityFunctor is applied on all codim 0 entities presented by \var gridView_
* \param intersectionFunctor is applied on all Intersections of all codim 0 entities
* presented by \var gridView_
* \note only instantiable for codim == 0
*/
template < class EntityFunctor, class IntersectionFunctor >
void operator () ( EntityFunctor& entityFunctor, IntersectionFunctor& intersectionFunctor ) const
{
static_assert( codim == 0, "walking intersections is only possible for codim 0 entities" );
for (const auto& entity : DSC::entityRange(gridView_)) {
const int entityIndex = gridView_.indexSet().index(entity);
entityFunctor( entity, entityIndex);
for (const auto& intersection : DSC::intersectionRange(gridView_, entity)) {
intersectionFunctor( entity, intersection);
}
}
}
/** \param entityFunctor is applied on all codim entities presented by \var gridView_
* \note only instantiable for codim < GridView::dimension
*/
template < class EntityFunctor >
void operator () ( EntityFunctor& entityFunctor ) const
{
static_assert( codim <= GridViewType::dimension, "codim too high to walk" );
for (const auto& entity : DSC::entityRange(gridView_)) {
const int entityIndex = gridView_.indexSet().index(entity);
entityFunctor( entity, entityIndex);
}
}
private:
const GridViewType& gridView_;
};
//!
template <class ViewImp, int codim = 0>
GridWalk< Dune::GridView<ViewImp>, codim > make_gridwalk(const Dune::GridView<ViewImp>& view) {
return GridWalk< Dune::GridView<ViewImp>, codim >(view);
}
} // namespace Grid
} // namespace Stuff
} // namespace Dune
#endif // DUNE_STUFF_GRID_WALK_HH
<|endoftext|>
|
<commit_before>/*
* Author: Ivan De Cesaris <ivan.de.cesaris@intel.com>
* Copyright (c) 2015 - 2016 Intel Corporation.
*
* 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.
*/
/**
* Demonstrate how to read a digital value from an input pin using the MRAA
* library.
* Suitable ones in the Grove Starter Kit are the Button and Touch Sensor,
* connected to digital pin 4 (Grove Base Shield Port D4).
* For the connection to the Grosse Tête connect the Pin 4 (Grove Base Shield)
* to the Pin 1 on Breakout#1 (Grosse Tête). Futhermore, connect the 3v3 Pin and
* GND Pin (Grove Base Shield) to Pin 40 on Breakout#1 and Pin 1 on Breakout#2
* (Grosse Tête).
*/
#include <mraa.hpp>
#include <iostream>
#include <unistd.h>
int main()
{
// check that we are running on Galileo or Edison
mraa::Platform platform = mraa::getPlatformType();
if ((platform != mraa::INTEL_GALILEO_GEN1) &&
(platform != mraa::INTEL_GALILEO_GEN2) &&
(platform != mraa::INTEL_EDISON_FAB_C) &&
(platform != mraa::INTEL_JOULE_EXPANSION)) {
std::cerr << "Unsupported platform, exiting" << std::endl;
return mraa::ERROR_INVALID_PLATFORM;
}
// create a GPIO object from MRAA using pin 4
mraa::Gpio* d_pin = new mraa::Gpio(4);
if (d_pin == NULL) {
std::cerr << "Can't create mraa::Gpio object, exiting" << std::endl;
return mraa::ERROR_UNSPECIFIED;
}
// set the pin as input
if (d_pin->dir(mraa::DIR_IN) != mraa::SUCCESS) {
std::cerr << "Can't set digital pin as input, exiting" << std::endl;
return mraa::ERROR_UNSPECIFIED;
}
// loop forever printing the digital input value every second
for (;;) {
int pin_value = d_pin->read();
std::cout << "value " << pin_value << std::endl;
sleep(1);
}
return mraa::SUCCESS;
}
<commit_msg>Fix Reference to Intel Joule<commit_after>/*
* Author: Ivan De Cesaris <ivan.de.cesaris@intel.com>
* Copyright (c) 2015 - 2016 Intel Corporation.
*
* 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.
*/
/**
* Demonstrate how to read a digital value from an input pin using the MRAA
* library.
* Suitable ones in the Grove Starter Kit are the Button and Touch Sensor,
* connected to digital pin 4 (Grove Base Shield Port D4).
* For the connection to the Intel Joule connect the Pin 4 (Grove Base Shield)
* to the Pin 1 on Breakout#1 (Intel Joule). Futhermore, connect the 3v3 Pin and
* GND Pin (Grove Base Shield) to Pin 40 on Breakout#1 and Pin 1 on Breakout#2
* (Intel Joule).
*/
#include <mraa.hpp>
#include <iostream>
#include <unistd.h>
int main()
{
// check that we are running on Galileo or Edison
mraa::Platform platform = mraa::getPlatformType();
if ((platform != mraa::INTEL_GALILEO_GEN1) &&
(platform != mraa::INTEL_GALILEO_GEN2) &&
(platform != mraa::INTEL_EDISON_FAB_C) &&
(platform != mraa::INTEL_JOULE_EXPANSION)) {
std::cerr << "Unsupported platform, exiting" << std::endl;
return mraa::ERROR_INVALID_PLATFORM;
}
// create a GPIO object from MRAA using pin 4
mraa::Gpio* d_pin = new mraa::Gpio(4);
if (d_pin == NULL) {
std::cerr << "Can't create mraa::Gpio object, exiting" << std::endl;
return mraa::ERROR_UNSPECIFIED;
}
// set the pin as input
if (d_pin->dir(mraa::DIR_IN) != mraa::SUCCESS) {
std::cerr << "Can't set digital pin as input, exiting" << std::endl;
return mraa::ERROR_UNSPECIFIED;
}
// loop forever printing the digital input value every second
for (;;) {
int pin_value = d_pin->read();
std::cout << "value " << pin_value << std::endl;
sleep(1);
}
return mraa::SUCCESS;
}
<|endoftext|>
|
<commit_before>/******************************************************************************
* Copyright 2019 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/prediction/common/message_process.h"
#include <algorithm>
#include <vector>
#include "cyber/common/file.h"
#include "cyber/record/record_reader.h"
#include "modules/common/adapters/adapter_gflags.h"
#include "modules/prediction/common/feature_output.h"
#include "modules/prediction/common/junction_analyzer.h"
#include "modules/prediction/common/prediction_gflags.h"
#include "modules/prediction/common/prediction_system_gflags.h"
#include "modules/prediction/common/validation_checker.h"
#include "modules/prediction/evaluator/evaluator_manager.h"
#include "modules/prediction/predictor/predictor_manager.h"
#include "modules/prediction/proto/offline_features.pb.h"
#include "modules/prediction/scenario/prioritization/obstacles_prioritizer.h"
#include "modules/prediction/scenario/right_of_way/right_of_way.h"
#include "modules/prediction/scenario/scenario_manager.h"
#include "modules/prediction/util/data_extraction.h"
namespace apollo {
namespace prediction {
using apollo::common::adapter::AdapterConfig;
using apollo::localization::LocalizationEstimate;
using apollo::perception::PerceptionObstacle;
using apollo::perception::PerceptionObstacles;
using apollo::planning::ADCTrajectory;
using cyber::record::RecordMessage;
using cyber::record::RecordReader;
bool MessageProcess::Init() {
// Load prediction conf
PredictionConf prediction_conf;
if (!cyber::common::GetProtoFromFile(FLAGS_prediction_conf_file,
&prediction_conf)) {
AERROR << "Unable to load prediction conf file: "
<< FLAGS_prediction_conf_file;
return false;
}
ADEBUG << "Prediction config file is loaded into: "
<< prediction_conf.ShortDebugString();
common::adapter::AdapterManagerConfig adapter_conf;
if (!cyber::common::GetProtoFromFile(FLAGS_prediction_adapter_config_filename,
&adapter_conf)) {
AERROR << "Unable to load adapter conf file: "
<< FLAGS_prediction_adapter_config_filename;
return false;
}
ADEBUG << "Adapter config file is loaded into: "
<< adapter_conf.ShortDebugString();
// Initialization of all managers
ContainerManager::Instance()->Init(adapter_conf);
EvaluatorManager::Instance()->Init(prediction_conf);
PredictorManager::Instance()->Init(prediction_conf);
if (!FLAGS_use_navigation_mode && !PredictionMap::Ready()) {
AERROR << "Map cannot be loaded.";
return false;
}
return true;
}
void MessageProcess::OnPerception(
const perception::PerceptionObstacles& perception_obstacles,
PredictionObstacles* const prediction_obstacles) {
ADEBUG << "Received a perception message ["
<< perception_obstacles.ShortDebugString() << "].";
// Get obstacles_container
auto ptr_obstacles_container =
ContainerManager::Instance()->GetContainer<ObstaclesContainer>(
AdapterConfig::PERCEPTION_OBSTACLES);
CHECK_NOTNULL(ptr_obstacles_container);
// Get pose_container
auto ptr_ego_pose_container =
ContainerManager::Instance()->GetContainer<PoseContainer>(
AdapterConfig::LOCALIZATION);
CHECK_NOTNULL(ptr_ego_pose_container);
// Get adc_trajectory_container
auto ptr_ego_trajectory_container =
ContainerManager::Instance()->GetContainer<ADCTrajectoryContainer>(
AdapterConfig::PLANNING_TRAJECTORY);
CHECK_NOTNULL(ptr_ego_trajectory_container);
// Insert ADC into the obstacle_container.
const PerceptionObstacle* ptr_ego_vehicle =
ptr_ego_pose_container->ToPerceptionObstacle();
if (ptr_ego_vehicle != nullptr) {
ptr_obstacles_container->InsertPerceptionObstacle(
*ptr_ego_vehicle, ptr_ego_vehicle->timestamp());
double x = ptr_ego_vehicle->position().x();
double y = ptr_ego_vehicle->position().y();
ADEBUG << "Get ADC position [" << std::fixed << std::setprecision(6) << x
<< ", " << std::fixed << std::setprecision(6) << y << "].";
ptr_ego_trajectory_container->SetPosition({x, y});
}
// Insert perception_obstacles
ptr_obstacles_container->Insert(perception_obstacles);
// Ignore some obstacles
ObstaclesPrioritizer::Instance()->AssignIgnoreLevel();
// Scenario analysis
ScenarioManager::Instance()->Run();
// Build junction feature for the obstacles in junction
const Scenario& scenario = ScenarioManager::Instance()->scenario();
if (scenario.type() == Scenario::JUNCTION && scenario.has_junction_id()) {
JunctionAnalyzer::Init(scenario.junction_id());
ptr_obstacles_container->BuildJunctionFeature();
}
// Build lane graph
ptr_obstacles_container->BuildLaneGraph();
// Assign CautionLevel for obstacles
ObstaclesPrioritizer::Instance()->AssignCautionLevel();
// Analyze RightOfWay for the caution obstacles
RightOfWay::Analyze();
// Insert features to FeatureOutput for offline_mode
if (FLAGS_prediction_offline_mode == 1) {
for (const int id :
ptr_obstacles_container->curr_frame_movable_obstacle_ids()) {
Obstacle* obstacle_ptr = ptr_obstacles_container->GetObstacle(id);
if (obstacle_ptr == nullptr) {
AERROR << "Null obstacle found.";
continue;
} else if (!obstacle_ptr->latest_feature().IsInitialized()) {
AERROR << "Obstacle [" << id << "] has no latest feature.";
continue;
}
*obstacle_ptr->mutable_latest_feature()->mutable_adc_trajectory_point() =
ptr_ego_trajectory_container->adc_trajectory().trajectory_point();
FeatureOutput::InsertFeatureProto(obstacle_ptr->latest_feature());
ADEBUG << "Insert feature into feature output";
}
// Not doing evaluation on offline mode
return;
}
// Make evaluations
EvaluatorManager::Instance()->Run();
// Make predictions
PredictorManager::Instance()->Run();
// Get predicted obstacles
*prediction_obstacles = PredictorManager::Instance()->prediction_obstacles();
}
void MessageProcess::OnLocalization(
const localization::LocalizationEstimate& localization) {
auto ptr_ego_pose_container =
ContainerManager::Instance()->GetContainer<PoseContainer>(
AdapterConfig::LOCALIZATION);
CHECK(ptr_ego_pose_container != nullptr);
ptr_ego_pose_container->Insert(localization);
ADEBUG << "Received a localization message ["
<< localization.ShortDebugString() << "].";
}
void MessageProcess::OnPlanning(const planning::ADCTrajectory& adc_trajectory) {
auto ptr_ego_trajectory_container =
ContainerManager::Instance()->GetContainer<ADCTrajectoryContainer>(
AdapterConfig::PLANNING_TRAJECTORY);
CHECK(ptr_ego_trajectory_container != nullptr);
ptr_ego_trajectory_container->Insert(adc_trajectory);
ADEBUG << "Received a planning message [" << adc_trajectory.ShortDebugString()
<< "].";
}
void MessageProcess::ProcessOfflineData(const std::string& record_filename) {
RecordReader reader(record_filename);
RecordMessage message;
while (reader.ReadMessage(&message)) {
if (message.channel_name == FLAGS_perception_obstacle_topic) {
PerceptionObstacles perception_obstacles;
if (perception_obstacles.ParseFromString(message.content)) {
PredictionObstacles prediction_obstacles;
OnPerception(perception_obstacles, &prediction_obstacles);
}
} else if (message.channel_name == FLAGS_localization_topic) {
LocalizationEstimate localization;
if (localization.ParseFromString(message.content)) {
OnLocalization(localization);
}
} else if (message.channel_name == FLAGS_planning_trajectory_topic) {
ADCTrajectory adc_trajectory;
if (adc_trajectory.ParseFromString(message.content)) {
OnPlanning(adc_trajectory);
}
}
}
}
} // namespace prediction
} // namespace apollo
<commit_msg>Prediction: trival logic adjudgement<commit_after>/******************************************************************************
* Copyright 2019 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/prediction/common/message_process.h"
#include <algorithm>
#include <vector>
#include "cyber/common/file.h"
#include "cyber/record/record_reader.h"
#include "modules/common/adapters/adapter_gflags.h"
#include "modules/prediction/common/feature_output.h"
#include "modules/prediction/common/junction_analyzer.h"
#include "modules/prediction/common/prediction_gflags.h"
#include "modules/prediction/common/prediction_system_gflags.h"
#include "modules/prediction/common/validation_checker.h"
#include "modules/prediction/evaluator/evaluator_manager.h"
#include "modules/prediction/predictor/predictor_manager.h"
#include "modules/prediction/proto/offline_features.pb.h"
#include "modules/prediction/scenario/prioritization/obstacles_prioritizer.h"
#include "modules/prediction/scenario/right_of_way/right_of_way.h"
#include "modules/prediction/scenario/scenario_manager.h"
#include "modules/prediction/util/data_extraction.h"
namespace apollo {
namespace prediction {
using apollo::common::adapter::AdapterConfig;
using apollo::localization::LocalizationEstimate;
using apollo::perception::PerceptionObstacle;
using apollo::perception::PerceptionObstacles;
using apollo::planning::ADCTrajectory;
using cyber::record::RecordMessage;
using cyber::record::RecordReader;
bool MessageProcess::Init() {
// Load prediction conf
PredictionConf prediction_conf;
if (!cyber::common::GetProtoFromFile(FLAGS_prediction_conf_file,
&prediction_conf)) {
AERROR << "Unable to load prediction conf file: "
<< FLAGS_prediction_conf_file;
return false;
}
ADEBUG << "Prediction config file is loaded into: "
<< prediction_conf.ShortDebugString();
common::adapter::AdapterManagerConfig adapter_conf;
if (!cyber::common::GetProtoFromFile(FLAGS_prediction_adapter_config_filename,
&adapter_conf)) {
AERROR << "Unable to load adapter conf file: "
<< FLAGS_prediction_adapter_config_filename;
return false;
}
ADEBUG << "Adapter config file is loaded into: "
<< adapter_conf.ShortDebugString();
// Initialization of all managers
ContainerManager::Instance()->Init(adapter_conf);
EvaluatorManager::Instance()->Init(prediction_conf);
PredictorManager::Instance()->Init(prediction_conf);
if (!FLAGS_use_navigation_mode && !PredictionMap::Ready()) {
AERROR << "Map cannot be loaded.";
return false;
}
return true;
}
void MessageProcess::OnPerception(
const perception::PerceptionObstacles& perception_obstacles,
PredictionObstacles* const prediction_obstacles) {
ADEBUG << "Received a perception message ["
<< perception_obstacles.ShortDebugString() << "].";
// Get obstacles_container
auto ptr_obstacles_container =
ContainerManager::Instance()->GetContainer<ObstaclesContainer>(
AdapterConfig::PERCEPTION_OBSTACLES);
CHECK_NOTNULL(ptr_obstacles_container);
// Get pose_container
auto ptr_ego_pose_container =
ContainerManager::Instance()->GetContainer<PoseContainer>(
AdapterConfig::LOCALIZATION);
CHECK_NOTNULL(ptr_ego_pose_container);
// Get adc_trajectory_container
auto ptr_ego_trajectory_container =
ContainerManager::Instance()->GetContainer<ADCTrajectoryContainer>(
AdapterConfig::PLANNING_TRAJECTORY);
CHECK_NOTNULL(ptr_ego_trajectory_container);
// Insert ADC into the obstacle_container.
const PerceptionObstacle* ptr_ego_vehicle =
ptr_ego_pose_container->ToPerceptionObstacle();
if (ptr_ego_vehicle != nullptr) {
ptr_obstacles_container->InsertPerceptionObstacle(
*ptr_ego_vehicle, ptr_ego_vehicle->timestamp());
double x = ptr_ego_vehicle->position().x();
double y = ptr_ego_vehicle->position().y();
ADEBUG << "Get ADC position [" << std::fixed << std::setprecision(6) << x
<< ", " << std::fixed << std::setprecision(6) << y << "].";
ptr_ego_trajectory_container->SetPosition({x, y});
}
// Insert perception_obstacles
ptr_obstacles_container->Insert(perception_obstacles);
// Ignore some obstacles
ObstaclesPrioritizer::Instance()->AssignIgnoreLevel();
// Scenario analysis
ScenarioManager::Instance()->Run();
// Build junction feature for the obstacles in junction
const Scenario& scenario = ScenarioManager::Instance()->scenario();
if (scenario.type() == Scenario::JUNCTION && scenario.has_junction_id()) {
JunctionAnalyzer::Init(scenario.junction_id());
ptr_obstacles_container->BuildJunctionFeature();
}
// Build lane graph
ptr_obstacles_container->BuildLaneGraph();
// Assign CautionLevel for obstacles
ObstaclesPrioritizer::Instance()->AssignCautionLevel();
// Analyze RightOfWay for the caution obstacles
RightOfWay::Analyze();
// Insert features to FeatureOutput for offline_mode
if (FLAGS_prediction_offline_mode == 1) {
for (const int id :
ptr_obstacles_container->curr_frame_movable_obstacle_ids()) {
Obstacle* obstacle_ptr = ptr_obstacles_container->GetObstacle(id);
if (obstacle_ptr == nullptr) {
AERROR << "Null obstacle found.";
continue;
}
if (!obstacle_ptr->latest_feature().IsInitialized()) {
AERROR << "Obstacle [" << id << "] has no latest feature.";
continue;
}
*obstacle_ptr->mutable_latest_feature()->mutable_adc_trajectory_point() =
ptr_ego_trajectory_container->adc_trajectory().trajectory_point();
FeatureOutput::InsertFeatureProto(obstacle_ptr->latest_feature());
ADEBUG << "Insert feature into feature output";
}
// Not doing evaluation on offline mode
return;
}
// Make evaluations
EvaluatorManager::Instance()->Run();
// Make predictions
PredictorManager::Instance()->Run();
// Get predicted obstacles
*prediction_obstacles = PredictorManager::Instance()->prediction_obstacles();
}
void MessageProcess::OnLocalization(
const localization::LocalizationEstimate& localization) {
auto ptr_ego_pose_container =
ContainerManager::Instance()->GetContainer<PoseContainer>(
AdapterConfig::LOCALIZATION);
CHECK(ptr_ego_pose_container != nullptr);
ptr_ego_pose_container->Insert(localization);
ADEBUG << "Received a localization message ["
<< localization.ShortDebugString() << "].";
}
void MessageProcess::OnPlanning(const planning::ADCTrajectory& adc_trajectory) {
auto ptr_ego_trajectory_container =
ContainerManager::Instance()->GetContainer<ADCTrajectoryContainer>(
AdapterConfig::PLANNING_TRAJECTORY);
CHECK(ptr_ego_trajectory_container != nullptr);
ptr_ego_trajectory_container->Insert(adc_trajectory);
ADEBUG << "Received a planning message [" << adc_trajectory.ShortDebugString()
<< "].";
}
void MessageProcess::ProcessOfflineData(const std::string& record_filename) {
RecordReader reader(record_filename);
RecordMessage message;
while (reader.ReadMessage(&message)) {
if (message.channel_name == FLAGS_perception_obstacle_topic) {
PerceptionObstacles perception_obstacles;
if (perception_obstacles.ParseFromString(message.content)) {
PredictionObstacles prediction_obstacles;
OnPerception(perception_obstacles, &prediction_obstacles);
}
} else if (message.channel_name == FLAGS_localization_topic) {
LocalizationEstimate localization;
if (localization.ParseFromString(message.content)) {
OnLocalization(localization);
}
} else if (message.channel_name == FLAGS_planning_trajectory_topic) {
ADCTrajectory adc_trajectory;
if (adc_trajectory.ParseFromString(message.content)) {
OnPlanning(adc_trajectory);
}
}
}
}
} // namespace prediction
} // namespace apollo
<|endoftext|>
|
<commit_before>//===- ViewOpGraph.cpp - View/write op graphviz graphs --------------------===//
//
// Copyright 2019 The MLIR Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
#include "mlir/Transforms/ViewOpGraph.h"
#include "mlir/IR/Block.h"
#include "mlir/IR/Operation.h"
#include "mlir/IR/StandardTypes.h"
#include "mlir/Pass/Pass.h"
#include "mlir/Support/STLExtras.h"
#include "llvm/Support/CommandLine.h"
static llvm::cl::opt<int> elideIfLarger(
"print-op-graph-elide-if-larger",
llvm::cl::desc("Upper limit to emit elements attribute rather than elide"),
llvm::cl::init(16));
namespace llvm {
// Specialize GraphTraits to treat Block as a graph of Operations as nodes and
// uses as edges.
template <> struct GraphTraits<mlir::Block *> {
using GraphType = mlir::Block *;
using NodeRef = mlir::Operation *;
using ChildIteratorType = mlir::UseIterator;
static ChildIteratorType child_begin(NodeRef n) {
return ChildIteratorType(n);
}
static ChildIteratorType child_end(NodeRef n) {
return ChildIteratorType(n, /*end=*/true);
}
// Operation's destructor is private so use Operation* instead and use
// mapped iterator.
static mlir::Operation *AddressOf(mlir::Operation &op) { return &op; }
using nodes_iterator =
mapped_iterator<mlir::Block::iterator, decltype(&AddressOf)>;
static nodes_iterator nodes_begin(mlir::Block *b) {
return nodes_iterator(b->begin(), &AddressOf);
}
static nodes_iterator nodes_end(mlir::Block *b) {
return nodes_iterator(b->end(), &AddressOf);
}
};
// Specialize DOTGraphTraits to produce more readable output.
template <>
struct DOTGraphTraits<mlir::Block *> : public DefaultDOTGraphTraits {
using DefaultDOTGraphTraits::DefaultDOTGraphTraits;
static std::string getNodeLabel(mlir::Operation *op, mlir::Block *);
};
std::string DOTGraphTraits<mlir::Block *>::getNodeLabel(mlir::Operation *op,
mlir::Block *b) {
// Reuse the print output for the node labels.
std::string ostr;
raw_string_ostream os(ostr);
os << op->getName() << "\n";
// Print resultant types
mlir::interleaveComma(op->getResultTypes(), os);
os << "\n";
for (auto attr : op->getAttrs()) {
os << '\n' << attr.first << ": ";
// Always emit splat attributes.
if (attr.second.isa<mlir::SplatElementsAttr>()) {
attr.second.print(os);
continue;
}
// Elide "big" elements attributes.
auto elements = attr.second.dyn_cast<mlir::ElementsAttr>();
if (elements && elements.getNumElements() > elideIfLarger) {
os << std::string(elements.getType().getRank(), '[') << "..."
<< std::string(elements.getType().getRank(), ']') << " : "
<< elements.getType();
continue;
}
// Print all other attributes.
attr.second.print(os);
}
return os.str();
}
} // end namespace llvm
namespace {
// PrintOpPass is simple pass to write graph per function.
// Note: this is a module pass only to avoid interleaving on the same ostream
// due to multi-threading over functions.
struct PrintOpPass : public mlir::ModulePass<PrintOpPass> {
explicit PrintOpPass(llvm::raw_ostream &os = llvm::errs(),
bool short_names = false, const llvm::Twine &title = "")
: os(os), title(title.str()), short_names(short_names) {}
std::string getOpName(mlir::Operation &op) {
auto symbolAttr = op.getAttrOfType<mlir::StringAttr>(
mlir::SymbolTable::getSymbolAttrName());
if (symbolAttr)
return symbolAttr.getValue();
++unnamedOpCtr;
return (op.getName().getStringRef() + llvm::utostr(unnamedOpCtr)).str();
}
// Print all the ops in a module.
void processModule(mlir::ModuleOp module) {
for (mlir::Operation &op : module) {
// Modules may actually be nested, recurse on nesting.
if (auto nestedModule = llvm::dyn_cast<mlir::ModuleOp>(op)) {
processModule(nestedModule);
continue;
}
auto opName = getOpName(op);
for (mlir::Region ®ion : op.getRegions()) {
for (auto indexed_block : llvm::enumerate(region)) {
// Suffix block number if there are more than 1 block.
auto blockName = region.getBlocks().size() == 1
? ""
: ("__" + llvm::utostr(indexed_block.index()));
llvm::WriteGraph(os, &indexed_block.value(), short_names,
llvm::Twine(title) + opName + blockName);
}
}
}
}
void runOnModule() override { processModule(getModule()); }
private:
llvm::raw_ostream &os;
std::string title;
int unnamedOpCtr = 0;
bool short_names;
};
} // namespace
void mlir::viewGraph(mlir::Block &block, const llvm::Twine &name,
bool shortNames, const llvm::Twine &title,
llvm::GraphProgram::Name program) {
llvm::ViewGraph(&block, name, shortNames, title, program);
}
llvm::raw_ostream &mlir::writeGraph(llvm::raw_ostream &os, mlir::Block &block,
bool shortNames, const llvm::Twine &title) {
return llvm::WriteGraph(os, &block, shortNames, title);
}
std::unique_ptr<mlir::OpPassBase<mlir::ModuleOp>>
mlir::createPrintOpGraphPass(llvm::raw_ostream &os, bool shortNames,
const llvm::Twine &title) {
return std::make_unique<PrintOpPass>(os, shortNames, title);
}
static mlir::PassRegistration<PrintOpPass> pass("print-op-graph",
"Print op graph per region");
<commit_msg>Dump op location in createPrintOpGraphPass for easier debugging.<commit_after>//===- ViewOpGraph.cpp - View/write op graphviz graphs --------------------===//
//
// Copyright 2019 The MLIR Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// =============================================================================
#include "mlir/Transforms/ViewOpGraph.h"
#include "mlir/IR/Block.h"
#include "mlir/IR/Operation.h"
#include "mlir/IR/StandardTypes.h"
#include "mlir/Pass/Pass.h"
#include "mlir/Support/STLExtras.h"
#include "llvm/Support/CommandLine.h"
static llvm::cl::opt<int> elideIfLarger(
"print-op-graph-elide-if-larger",
llvm::cl::desc("Upper limit to emit elements attribute rather than elide"),
llvm::cl::init(16));
namespace llvm {
// Specialize GraphTraits to treat Block as a graph of Operations as nodes and
// uses as edges.
template <> struct GraphTraits<mlir::Block *> {
using GraphType = mlir::Block *;
using NodeRef = mlir::Operation *;
using ChildIteratorType = mlir::UseIterator;
static ChildIteratorType child_begin(NodeRef n) {
return ChildIteratorType(n);
}
static ChildIteratorType child_end(NodeRef n) {
return ChildIteratorType(n, /*end=*/true);
}
// Operation's destructor is private so use Operation* instead and use
// mapped iterator.
static mlir::Operation *AddressOf(mlir::Operation &op) { return &op; }
using nodes_iterator =
mapped_iterator<mlir::Block::iterator, decltype(&AddressOf)>;
static nodes_iterator nodes_begin(mlir::Block *b) {
return nodes_iterator(b->begin(), &AddressOf);
}
static nodes_iterator nodes_end(mlir::Block *b) {
return nodes_iterator(b->end(), &AddressOf);
}
};
// Specialize DOTGraphTraits to produce more readable output.
template <>
struct DOTGraphTraits<mlir::Block *> : public DefaultDOTGraphTraits {
using DefaultDOTGraphTraits::DefaultDOTGraphTraits;
static std::string getNodeLabel(mlir::Operation *op, mlir::Block *);
};
std::string DOTGraphTraits<mlir::Block *>::getNodeLabel(mlir::Operation *op,
mlir::Block *b) {
// Reuse the print output for the node labels.
std::string ostr;
raw_string_ostream os(ostr);
os << op->getName() << "\n";
if (!op->getLoc().isa<mlir::UnknownLoc>()) {
os << op->getLoc() << "\n";
}
// Print resultant types
mlir::interleaveComma(op->getResultTypes(), os);
os << "\n";
for (auto attr : op->getAttrs()) {
os << '\n' << attr.first << ": ";
// Always emit splat attributes.
if (attr.second.isa<mlir::SplatElementsAttr>()) {
attr.second.print(os);
continue;
}
// Elide "big" elements attributes.
auto elements = attr.second.dyn_cast<mlir::ElementsAttr>();
if (elements && elements.getNumElements() > elideIfLarger) {
os << std::string(elements.getType().getRank(), '[') << "..."
<< std::string(elements.getType().getRank(), ']') << " : "
<< elements.getType();
continue;
}
// Print all other attributes.
attr.second.print(os);
}
return os.str();
}
} // end namespace llvm
namespace {
// PrintOpPass is simple pass to write graph per function.
// Note: this is a module pass only to avoid interleaving on the same ostream
// due to multi-threading over functions.
struct PrintOpPass : public mlir::ModulePass<PrintOpPass> {
explicit PrintOpPass(llvm::raw_ostream &os = llvm::errs(),
bool short_names = false, const llvm::Twine &title = "")
: os(os), title(title.str()), short_names(short_names) {}
std::string getOpName(mlir::Operation &op) {
auto symbolAttr = op.getAttrOfType<mlir::StringAttr>(
mlir::SymbolTable::getSymbolAttrName());
if (symbolAttr)
return symbolAttr.getValue();
++unnamedOpCtr;
return (op.getName().getStringRef() + llvm::utostr(unnamedOpCtr)).str();
}
// Print all the ops in a module.
void processModule(mlir::ModuleOp module) {
for (mlir::Operation &op : module) {
// Modules may actually be nested, recurse on nesting.
if (auto nestedModule = llvm::dyn_cast<mlir::ModuleOp>(op)) {
processModule(nestedModule);
continue;
}
auto opName = getOpName(op);
for (mlir::Region ®ion : op.getRegions()) {
for (auto indexed_block : llvm::enumerate(region)) {
// Suffix block number if there are more than 1 block.
auto blockName = region.getBlocks().size() == 1
? ""
: ("__" + llvm::utostr(indexed_block.index()));
llvm::WriteGraph(os, &indexed_block.value(), short_names,
llvm::Twine(title) + opName + blockName);
}
}
}
}
void runOnModule() override { processModule(getModule()); }
private:
llvm::raw_ostream &os;
std::string title;
int unnamedOpCtr = 0;
bool short_names;
};
} // namespace
void mlir::viewGraph(mlir::Block &block, const llvm::Twine &name,
bool shortNames, const llvm::Twine &title,
llvm::GraphProgram::Name program) {
llvm::ViewGraph(&block, name, shortNames, title, program);
}
llvm::raw_ostream &mlir::writeGraph(llvm::raw_ostream &os, mlir::Block &block,
bool shortNames, const llvm::Twine &title) {
return llvm::WriteGraph(os, &block, shortNames, title);
}
std::unique_ptr<mlir::OpPassBase<mlir::ModuleOp>>
mlir::createPrintOpGraphPass(llvm::raw_ostream &os, bool shortNames,
const llvm::Twine &title) {
return std::make_unique<PrintOpPass>(os, shortNames, title);
}
static mlir::PassRegistration<PrintOpPass> pass("print-op-graph",
"Print op graph per region");
<|endoftext|>
|
<commit_before>/*
* Copyright 2016 - 2019 gtalent2@gmail.com
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "../gfx.hpp"
namespace nostalgia::core {
ox::Error initGfx(Context*) {
return OxError(1);
}
ox::Error shutdownGfx(Context*) {
}
ox::Error initConsole(Context*) {
return OxError(1);
}
ox::Error loadTileSheet(Context*,
TileSheetSpace,
int,
ox::FileAddress,
ox::FileAddress) {
return OxError(1);
}
void setTile(Context*, int, int, int, uint8_t) {
}
}
<commit_msg>[nostalgia/core/qt] Add missing return nostalgia::core::shutdownGfx<commit_after>/*
* Copyright 2016 - 2019 gtalent2@gmail.com
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "../gfx.hpp"
namespace nostalgia::core {
ox::Error initGfx(Context*) {
return OxError(1);
}
ox::Error shutdownGfx(Context*) {
return OxError(1);
}
ox::Error initConsole(Context*) {
return OxError(1);
}
ox::Error loadTileSheet(Context*,
TileSheetSpace,
int,
ox::FileAddress,
ox::FileAddress) {
return OxError(1);
}
void setTile(Context*, int, int, int, uint8_t) {
}
}
<|endoftext|>
|
<commit_before><commit_msg>Treap added (again)<commit_after>class treap{
struct item{
int x, y, l, r, k;
};
private:
vector<item> t;
public:
void resize(int num) {
t.resize(num);
}
void init(int v, int x) {
t[v].x = x;
t[v].y = rand();
t[v].l = t[v].r = 0;
t[v].k = !!v;
}
void cnt(int v) {
t[v].k = v ? t[t[v].l].k + t[t[v].r].k + 1 : 0;
}
void merge(int &v, int l, int r) {
if (!l || !r) {
v = l ? l : r;
} else if (t[l].y > t[r].y) {
v = l;
merge(t[l].r, t[l].r, r);
} else {
v = r;
merge(t[r].l, l, t[r].l);
}
cnt(v);
}
void split(int v, int &l, int &r, int key) {
if (!v) {
l = r = 0;
return;
}
if (t[t[v].l].k + 1 <= key) {
l = v;
split(t[v].r, t[l].r, r, key - t[t[v].l].k - 1);
} else {
r = v;
split(t[v].l, l, t[r].l, key);
}
cnt(l);
cnt(r);
}
treap(int num) {
resize(num);
init(0, 0);
}
void output(int x) {
if (!x) return;
output(t[x].l);
cout << t[x].x << " ";
output(t[x].r);
}
};<|endoftext|>
|
<commit_before>#include "quering.hh"
unsigned char * read_binary_file(const char * filename, size_t filesize)
{
//Get filesize
int fd;
unsigned char * map;
fd = open(filename, O_RDONLY);
if (fd == -1) {
perror("Error opening file for reading");
exit(EXIT_FAILURE);
}
map = (unsigned char *)mmap(0, filesize, PROT_READ, MAP_SHARED, fd, 0);
if (map == MAP_FAILED) {
close(fd);
perror("Error mmapping the file");
exit(EXIT_FAILURE);
}
return map;
}
QueryEngine::QueryEngine(const char * filepath) : decoder(filepath)
{
//Create filepaths
std::string basepath(filepath);
std::string path_to_hashtable = basepath + "/probing_hash.dat";
std::string path_to_data_bin = basepath + "/binfile.dat";
std::string path_to_source_vocabid = basepath + "/source_vocabids";
///Source phrase vocabids
read_map(&source_vocabids, path_to_source_vocabid.c_str());
//Target phrase vocabIDs
vocabids = decoder.get_target_lookup_map();
//Read config file
std::string line;
std::ifstream config ((basepath + "/config").c_str());
//Check API version:
getline(config, line);
if (atoi(line.c_str()) != API_VERSION) {
std::cerr << "The ProbingPT API has changed, please rebinarize your phrase tables." << std::endl;
exit(EXIT_FAILURE);
}
//Get tablesize.
getline(config, line);
int tablesize = atoi(line.c_str());
//Number of scores
getline(config, line);
num_scores = atoi(line.c_str());
//do we have a reordering table
getline(config, line);
std::transform(line.begin(), line.end(), line.begin(), ::tolower); //Get the boolean in lowercase
is_reordering = false;
if (line == "true") {
is_reordering = true;
std::cerr << "WARNING. REORDERING TABLES NOT SUPPORTED YET." << std::endl;
}
config.close();
//Mmap binary table
struct stat filestatus;
stat(path_to_data_bin.c_str(), &filestatus);
binary_filesize = filestatus.st_size;
binary_mmaped = read_binary_file(path_to_data_bin.c_str(), binary_filesize);
//Read hashtable
size_t table_filesize = Table::Size(tablesize, 1.2);
mem = readTable(path_to_hashtable.c_str(), table_filesize);
Table table_init(mem, table_filesize);
table = table_init;
std::cerr << "Initialized successfully! " << std::endl;
}
QueryEngine::~QueryEngine()
{
//Clear mmap content from memory.
munmap(binary_mmaped, binary_filesize);
munmap(mem, table_filesize);
}
std::pair<bool, std::vector<target_text> > QueryEngine::query(std::vector<uint64_t> source_phrase)
{
bool found;
std::vector<target_text> translation_entries;
const Entry * entry;
//TOO SLOW
//uint64_t key = util::MurmurHashNative(&source_phrase[0], source_phrase.size());
uint64_t key = 0;
for (int i = 0; i < source_phrase.size(); i++) {
key += (source_phrase[i] << i);
}
found = table.Find(key, entry);
if (found) {
//The phrase that was searched for was found! We need to get the translation entries.
//We will read the largest entry in bytes and then filter the unnecesarry with functions
//from line_splitter
uint64_t initial_index = entry -> GetValue();
unsigned int bytes_toread = entry -> bytes_toread;
//ASK HIEU FOR MORE EFFICIENT WAY TO DO THIS!
std::vector<unsigned char> encoded_text; //Assign to the vector the relevant portion of the array.
encoded_text.reserve(bytes_toread);
for (int i = 0; i < bytes_toread; i++) {
encoded_text.push_back(binary_mmaped[i+initial_index]);
}
//Get only the translation entries necessary
translation_entries = decoder.full_decode_line(encoded_text, num_scores);
}
std::pair<bool, std::vector<target_text> > output (found, translation_entries);
return output;
}
std::pair<bool, std::vector<target_text> > QueryEngine::query(StringPiece source_phrase)
{
bool found;
std::vector<target_text> translation_entries;
const Entry * entry;
//Convert source frase to VID
std::vector<uint64_t> source_phrase_vid = getVocabIDs(source_phrase);
//TOO SLOW
//uint64_t key = util::MurmurHashNative(&source_phrase_vid[0], source_phrase_vid.size());
uint64_t key = 0;
for (int i = 0; i < source_phrase_vid.size(); i++) {
key += (source_phrase_vid[i] << i);
}
found = table.Find(key, entry);
if (found) {
//The phrase that was searched for was found! We need to get the translation entries.
//We will read the largest entry in bytes and then filter the unnecesarry with functions
//from line_splitter
uint64_t initial_index = entry -> GetValue();
unsigned int bytes_toread = entry -> bytes_toread;
//At the end of the file we can't readd + largest_entry cause we get a segfault.
std::cerr << "Entry size is bytes is: " << bytes_toread << std::endl;
//ASK HIEU FOR MORE EFFICIENT WAY TO DO THIS!
std::vector<unsigned char> encoded_text; //Assign to the vector the relevant portion of the array.
encoded_text.reserve(bytes_toread);
for (int i = 0; i < bytes_toread; i++) {
encoded_text.push_back(binary_mmaped[i+initial_index]);
}
//Get only the translation entries necessary
translation_entries = decoder.full_decode_line(encoded_text, num_scores);
}
std::pair<bool, std::vector<target_text> > output (found, translation_entries);
return output;
}
void QueryEngine::printTargetInfo(std::vector<target_text> target_phrases)
{
int entries = target_phrases.size();
for (int i = 0; i<entries; i++) {
std::cout << "Entry " << i+1 << " of " << entries << ":" << std::endl;
//Print text
std::cout << getTargetWordsFromIDs(target_phrases[i].target_phrase, &vocabids) << "\t";
//Print probabilities:
for (int j = 0; j<target_phrases[i].prob.size(); j++) {
std::cout << target_phrases[i].prob[j] << " ";
}
std::cout << "\t";
//Print word_all1
for (int j = 0; j<target_phrases[i].word_all1.size(); j++) {
if (j%2 == 0) {
std::cout << (short)target_phrases[i].word_all1[j] << "-";
} else {
std::cout << (short)target_phrases[i].word_all1[j] << " ";
}
}
std::cout << std::endl;
}
}
<commit_msg>local variable masking class variable<commit_after>#include "quering.hh"
unsigned char * read_binary_file(const char * filename, size_t filesize)
{
//Get filesize
int fd;
unsigned char * map;
fd = open(filename, O_RDONLY);
if (fd == -1) {
perror("Error opening file for reading");
exit(EXIT_FAILURE);
}
map = (unsigned char *)mmap(0, filesize, PROT_READ, MAP_SHARED, fd, 0);
if (map == MAP_FAILED) {
close(fd);
perror("Error mmapping the file");
exit(EXIT_FAILURE);
}
return map;
}
QueryEngine::QueryEngine(const char * filepath) : decoder(filepath)
{
//Create filepaths
std::string basepath(filepath);
std::string path_to_hashtable = basepath + "/probing_hash.dat";
std::string path_to_data_bin = basepath + "/binfile.dat";
std::string path_to_source_vocabid = basepath + "/source_vocabids";
///Source phrase vocabids
read_map(&source_vocabids, path_to_source_vocabid.c_str());
//Target phrase vocabIDs
vocabids = decoder.get_target_lookup_map();
//Read config file
std::string line;
std::ifstream config ((basepath + "/config").c_str());
//Check API version:
getline(config, line);
if (atoi(line.c_str()) != API_VERSION) {
std::cerr << "The ProbingPT API has changed, please rebinarize your phrase tables." << std::endl;
exit(EXIT_FAILURE);
}
//Get tablesize.
getline(config, line);
int tablesize = atoi(line.c_str());
//Number of scores
getline(config, line);
num_scores = atoi(line.c_str());
//do we have a reordering table
getline(config, line);
std::transform(line.begin(), line.end(), line.begin(), ::tolower); //Get the boolean in lowercase
is_reordering = false;
if (line == "true") {
is_reordering = true;
std::cerr << "WARNING. REORDERING TABLES NOT SUPPORTED YET." << std::endl;
}
config.close();
//Mmap binary table
struct stat filestatus;
stat(path_to_data_bin.c_str(), &filestatus);
binary_filesize = filestatus.st_size;
binary_mmaped = read_binary_file(path_to_data_bin.c_str(), binary_filesize);
//Read hashtable
table_filesize = Table::Size(tablesize, 1.2);
mem = readTable(path_to_hashtable.c_str(), table_filesize);
Table table_init(mem, table_filesize);
table = table_init;
std::cerr << "Initialized successfully! " << std::endl;
}
QueryEngine::~QueryEngine()
{
//Clear mmap content from memory.
munmap(binary_mmaped, binary_filesize);
munmap(mem, table_filesize);
}
std::pair<bool, std::vector<target_text> > QueryEngine::query(std::vector<uint64_t> source_phrase)
{
bool found;
std::vector<target_text> translation_entries;
const Entry * entry;
//TOO SLOW
//uint64_t key = util::MurmurHashNative(&source_phrase[0], source_phrase.size());
uint64_t key = 0;
for (int i = 0; i < source_phrase.size(); i++) {
key += (source_phrase[i] << i);
}
found = table.Find(key, entry);
if (found) {
//The phrase that was searched for was found! We need to get the translation entries.
//We will read the largest entry in bytes and then filter the unnecesarry with functions
//from line_splitter
uint64_t initial_index = entry -> GetValue();
unsigned int bytes_toread = entry -> bytes_toread;
//ASK HIEU FOR MORE EFFICIENT WAY TO DO THIS!
std::vector<unsigned char> encoded_text; //Assign to the vector the relevant portion of the array.
encoded_text.reserve(bytes_toread);
for (int i = 0; i < bytes_toread; i++) {
encoded_text.push_back(binary_mmaped[i+initial_index]);
}
//Get only the translation entries necessary
translation_entries = decoder.full_decode_line(encoded_text, num_scores);
}
std::pair<bool, std::vector<target_text> > output (found, translation_entries);
return output;
}
std::pair<bool, std::vector<target_text> > QueryEngine::query(StringPiece source_phrase)
{
bool found;
std::vector<target_text> translation_entries;
const Entry * entry;
//Convert source frase to VID
std::vector<uint64_t> source_phrase_vid = getVocabIDs(source_phrase);
//TOO SLOW
//uint64_t key = util::MurmurHashNative(&source_phrase_vid[0], source_phrase_vid.size());
uint64_t key = 0;
for (int i = 0; i < source_phrase_vid.size(); i++) {
key += (source_phrase_vid[i] << i);
}
found = table.Find(key, entry);
if (found) {
//The phrase that was searched for was found! We need to get the translation entries.
//We will read the largest entry in bytes and then filter the unnecesarry with functions
//from line_splitter
uint64_t initial_index = entry -> GetValue();
unsigned int bytes_toread = entry -> bytes_toread;
//At the end of the file we can't readd + largest_entry cause we get a segfault.
std::cerr << "Entry size is bytes is: " << bytes_toread << std::endl;
//ASK HIEU FOR MORE EFFICIENT WAY TO DO THIS!
std::vector<unsigned char> encoded_text; //Assign to the vector the relevant portion of the array.
encoded_text.reserve(bytes_toread);
for (int i = 0; i < bytes_toread; i++) {
encoded_text.push_back(binary_mmaped[i+initial_index]);
}
//Get only the translation entries necessary
translation_entries = decoder.full_decode_line(encoded_text, num_scores);
}
std::pair<bool, std::vector<target_text> > output (found, translation_entries);
return output;
}
void QueryEngine::printTargetInfo(std::vector<target_text> target_phrases)
{
int entries = target_phrases.size();
for (int i = 0; i<entries; i++) {
std::cout << "Entry " << i+1 << " of " << entries << ":" << std::endl;
//Print text
std::cout << getTargetWordsFromIDs(target_phrases[i].target_phrase, &vocabids) << "\t";
//Print probabilities:
for (int j = 0; j<target_phrases[i].prob.size(); j++) {
std::cout << target_phrases[i].prob[j] << " ";
}
std::cout << "\t";
//Print word_all1
for (int j = 0; j<target_phrases[i].word_all1.size(); j++) {
if (j%2 == 0) {
std::cout << (short)target_phrases[i].word_all1[j] << "-";
} else {
std::cout << (short)target_phrases[i].word_all1[j] << " ";
}
}
std::cout << std::endl;
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <fcntl.h>
#include <errno.h>
#include <math.h>
#include <poll.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/select.h>
#include <cutils/log.h>
#include "sensors.h"
#include "LightSensor.h"
#define EVENT_TYPE_LIGHT ABS_MISC
/*****************************************************************************/
enum input_device_name {
LIGHTSENSOR_LEVEL = 0,
CM36283_LS,
SUPPORTED_LSENSOR_COUNT,
};
enum {
TYPE_ADC = 0,
TYPE_LUX,
};
static const char *data_device_name[] = {
[LIGHTSENSOR_LEVEL] = "lightsensor-level",
[CM36283_LS] = "cm36283-ls",
};
static const char *input_sysfs_path_list[] = {
[LIGHTSENSOR_LEVEL] = "/sys/class/input/%s/device/",
[CM36283_LS] = "/sys/class/optical_sensors/lightsensor/",
};
static const char *input_sysfs_enable_list[] = {
[LIGHTSENSOR_LEVEL] = "enable",
[CM36283_LS] = "ls_auto",
};
static const int input_report_type[] = {
[LIGHTSENSOR_LEVEL] = TYPE_ADC,
[CM36283_LS] = TYPE_LUX,
};
LightSensor::LightSensor()
: SensorBase(NULL, NULL),
mEnabled(0),
mInputReader(4),
mHasPendingEvent(false),
sensor_index(-1)
{
int i;
char *tok = NULL;
mPendingEvent.version = sizeof(sensors_event_t);
mPendingEvent.sensor = SENSORS_LIGHT_HANDLE;
mPendingEvent.type = SENSOR_TYPE_LIGHT;
memset(mPendingEvent.data, 0, sizeof(mPendingEvent.data));
for(i = 0; i < SUPPORTED_LSENSOR_COUNT; i++) {
data_name = data_device_name[i];
// data_fd is not initialized if data_name passed
// to SensorBase is NULL.
data_fd = openInput(data_name);
if (data_fd > 0) {
sensor_index = i;
break;
}
}
if (data_fd) {
snprintf(input_sysfs_path, sizeof(input_sysfs_path),
input_sysfs_path_list[i], input_name);
input_sysfs_path_len = strlen(input_sysfs_path);
enable(0, 1);
}
}
LightSensor::~LightSensor() {
if (mEnabled) {
enable(0, 0);
}
}
int LightSensor::setDelay(int32_t handle, int64_t ns)
{
int fd;
strcpy(&input_sysfs_path[input_sysfs_path_len], "poll_delay");
fd = open(input_sysfs_path, O_RDWR);
if (fd >= 0) {
char buf[80];
sprintf(buf, "%lld", ns);
write(fd, buf, strlen(buf)+1);
close(fd);
return 0;
}
return -1;
}
int LightSensor::enable(int32_t handle, int en)
{
int flags = en ? 1 : 0;
if (flags != mEnabled) {
int fd;
if (sensor_index >= 0) {
strlcpy(&input_sysfs_path[input_sysfs_path_len],
input_sysfs_enable_list[sensor_index], sizeof(input_sysfs_path) - input_sysfs_path_len);
}
else
return -1;
fd = open(input_sysfs_path, O_RDWR);
if (fd >= 0) {
char buf[2];
int err;
buf[1] = 0;
if (flags) {
buf[0] = '1';
} else {
buf[0] = '0';
}
err = write(fd, buf, sizeof(buf));
close(fd);
mEnabled = flags;
return 0;
}
return -1;
}
return 0;
}
bool LightSensor::hasPendingEvents() const {
return mHasPendingEvent;
}
int LightSensor::readEvents(sensors_event_t* data, int count)
{
if (count < 1)
return -EINVAL;
if (mHasPendingEvent) {
mHasPendingEvent = false;
mPendingEvent.timestamp = getTimestamp();
*data = mPendingEvent;
return mEnabled ? 1 : 0;
}
ssize_t n = mInputReader.fill(data_fd);
if (n < 0)
return n;
int numEventReceived = 0;
input_event const* event;
while (count && mInputReader.readEvent(&event)) {
int type = event->type;
if (type == EV_ABS) {
if (event->code == EVENT_TYPE_LIGHT) {
mPendingEvent.light = convertEvent(event->value);
}
} else if (type == EV_SYN) {
mPendingEvent.timestamp = timevalToNano(event->time);
if (mEnabled) {
*data++ = mPendingEvent;
count--;
numEventReceived++;
}
} else {
ALOGE("LightSensor: unknown event (type=%d, code=%d)",
type, event->code);
}
mInputReader.next();
}
return numEventReceived;
}
float LightSensor::convertEvent(int value)
{
float lux = 0;
if (sensor_index >= 0) {
if (input_report_type[sensor_index] == TYPE_ADC) {
// Convert adc value to lux assuming:
// I = 10 * log(Ev) uA
// R = 47kOhm
// Max adc value 4095 = 3.3V
// 1/4 of light reaches sensor
lux = powf(10, value * (330.0f / 4095.0f / 47.0f)) * 4;
} else if (input_report_type[sensor_index] == TYPE_LUX) {
lux = value;
} else {
ALOGE("LightSensor: unknown report type\n");
lux = 0;
}
}
return lux;
}
<commit_msg>hardware: sensors: add stk3x1x light sensor support to sensor list<commit_after>/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <fcntl.h>
#include <errno.h>
#include <math.h>
#include <poll.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/select.h>
#include <cutils/log.h>
#include "sensors.h"
#include "LightSensor.h"
#define EVENT_TYPE_LIGHT ABS_MISC
/*****************************************************************************/
enum input_device_name {
LIGHTSENSOR_LEVEL = 0,
CM36283_LS,
STK3x1x_LS,
SUPPORTED_LSENSOR_COUNT,
};
enum {
TYPE_ADC = 0,
TYPE_LUX,
};
static const char *data_device_name[] = {
[LIGHTSENSOR_LEVEL] = "lightsensor-level",
[CM36283_LS] = "cm36283-ls",
[STK3x1x_LS] = "stk3x1x-ls",
};
static const char *input_sysfs_path_list[] = {
[LIGHTSENSOR_LEVEL] = "/sys/class/input/%s/device/",
[CM36283_LS] = "/sys/class/optical_sensors/lightsensor/",
[STK3x1x_LS] = "/sys/class/input/%s/device/",
};
static const char *input_sysfs_enable_list[] = {
[LIGHTSENSOR_LEVEL] = "enable",
[CM36283_LS] = "ls_auto",
[STK3x1x_LS] = "enable",
};
static const int input_report_type[] = {
[LIGHTSENSOR_LEVEL] = TYPE_ADC,
[CM36283_LS] = TYPE_LUX,
[STK3x1x_LS] = TYPE_LUX,
};
LightSensor::LightSensor()
: SensorBase(NULL, NULL),
mEnabled(0),
mInputReader(4),
mHasPendingEvent(false),
sensor_index(-1)
{
int i;
char *tok = NULL;
mPendingEvent.version = sizeof(sensors_event_t);
mPendingEvent.sensor = SENSORS_LIGHT_HANDLE;
mPendingEvent.type = SENSOR_TYPE_LIGHT;
memset(mPendingEvent.data, 0, sizeof(mPendingEvent.data));
for(i = 0; i < SUPPORTED_LSENSOR_COUNT; i++) {
data_name = data_device_name[i];
// data_fd is not initialized if data_name passed
// to SensorBase is NULL.
data_fd = openInput(data_name);
if (data_fd > 0) {
sensor_index = i;
break;
}
}
if (data_fd) {
snprintf(input_sysfs_path, sizeof(input_sysfs_path),
input_sysfs_path_list[i], input_name);
input_sysfs_path_len = strlen(input_sysfs_path);
enable(0, 1);
}
}
LightSensor::~LightSensor() {
if (mEnabled) {
enable(0, 0);
}
}
int LightSensor::setDelay(int32_t handle, int64_t ns)
{
int fd;
strcpy(&input_sysfs_path[input_sysfs_path_len], "poll_delay");
fd = open(input_sysfs_path, O_RDWR);
if (fd >= 0) {
char buf[80];
sprintf(buf, "%lld", ns);
write(fd, buf, strlen(buf)+1);
close(fd);
return 0;
}
return -1;
}
int LightSensor::enable(int32_t handle, int en)
{
int flags = en ? 1 : 0;
if (flags != mEnabled) {
int fd;
if (sensor_index >= 0) {
strlcpy(&input_sysfs_path[input_sysfs_path_len],
input_sysfs_enable_list[sensor_index], sizeof(input_sysfs_path) - input_sysfs_path_len);
}
else
return -1;
fd = open(input_sysfs_path, O_RDWR);
if (fd >= 0) {
char buf[2];
int err;
buf[1] = 0;
if (flags) {
buf[0] = '1';
} else {
buf[0] = '0';
}
err = write(fd, buf, sizeof(buf));
close(fd);
mEnabled = flags;
return 0;
}
return -1;
}
return 0;
}
bool LightSensor::hasPendingEvents() const {
return mHasPendingEvent;
}
int LightSensor::readEvents(sensors_event_t* data, int count)
{
if (count < 1)
return -EINVAL;
if (mHasPendingEvent) {
mHasPendingEvent = false;
mPendingEvent.timestamp = getTimestamp();
*data = mPendingEvent;
return mEnabled ? 1 : 0;
}
ssize_t n = mInputReader.fill(data_fd);
if (n < 0)
return n;
int numEventReceived = 0;
input_event const* event;
while (count && mInputReader.readEvent(&event)) {
int type = event->type;
if (type == EV_ABS) {
if (event->code == EVENT_TYPE_LIGHT) {
mPendingEvent.light = convertEvent(event->value);
}
} else if (type == EV_SYN) {
mPendingEvent.timestamp = timevalToNano(event->time);
if (mEnabled) {
*data++ = mPendingEvent;
count--;
numEventReceived++;
}
} else {
ALOGE("LightSensor: unknown event (type=%d, code=%d)",
type, event->code);
}
mInputReader.next();
}
return numEventReceived;
}
float LightSensor::convertEvent(int value)
{
float lux = 0;
if (sensor_index >= 0) {
if (input_report_type[sensor_index] == TYPE_ADC) {
// Convert adc value to lux assuming:
// I = 10 * log(Ev) uA
// R = 47kOhm
// Max adc value 4095 = 3.3V
// 1/4 of light reaches sensor
lux = powf(10, value * (330.0f / 4095.0f / 47.0f)) * 4;
} else if (input_report_type[sensor_index] == TYPE_LUX) {
lux = value;
} else {
ALOGE("LightSensor: unknown report type\n");
lux = 0;
}
}
return lux;
}
<|endoftext|>
|
<commit_before>/********************************************************************
* AUTHORS: Trevor Hansen
*
* BEGIN DATE: May, 2010
*
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.
********************************************************************/
#include "stp/Printer/printers.h"
#include "stp/Printer/SMTLIBPrinter.h"
// Functions used by both the version1 and version2 STMLIB printers.
namespace printer
{
using namespace BEEV;
using std::pair;
using std::endl;
static string tolower(const char* name)
{
string s(name);
for (size_t i = 0; i < s.size(); ++i)
s[i] = ::tolower(s[i]);
return s;
}
// Map from ASTNodes to LetVars
BEEV::ASTNodeMap NodeLetVarMap;
// This is a vector which stores the Node to LetVars pairs. It
// allows for sorted printing, as opposed to NodeLetVarMap
std::vector<pair<ASTNode, ASTNode>> NodeLetVarVec;
// a partial Map from ASTNodes to LetVars. Needed in order to
// correctly print shared subterms inside the LET itself
BEEV::ASTNodeMap NodeLetVarMap1;
// copied from Presentation Langauge printer.
ostream& SMTLIB_Print(ostream& os, const ASTNode n, const int indentation,
void (*SMTLIB1_Print1)(ostream&, const ASTNode, int,
bool),
bool smtlib1)
{
// Clear the maps
NodeLetVarMap.clear();
NodeLetVarVec.clear();
NodeLetVarMap1.clear();
// pass 1: letize the node
{
ASTNodeSet PLPrintNodeSet;
LetizeNode(n, PLPrintNodeSet, smtlib1);
}
// pass 2:
//
// 2. print all the let variables and their counterpart expressions
// 2. as follows (LET var1 = expr1, var2 = expr2, ...
//
// 3. Then print the Node itself, replacing every occurence of
// 3. expr1 with var1, expr2 with var2, ...
// os << "(";
if (0 < NodeLetVarMap.size())
{
std::vector<pair<ASTNode, ASTNode>>::iterator it = NodeLetVarVec.begin();
const std::vector<pair<ASTNode, ASTNode>>::iterator itend =
NodeLetVarVec.end();
os << "(let (";
if (!smtlib1)
os << "(";
// print the let var first
SMTLIB1_Print1(os, it->first, indentation, false);
os << " ";
// print the expr
SMTLIB1_Print1(os, it->second, indentation, false);
os << " )";
if (!smtlib1)
os << ")";
// update the second map for proper printing of LET
NodeLetVarMap1[it->second] = it->first;
string closing = "";
for (it++; it != itend; it++)
{
os << " " << endl;
os << "(let (";
if (!smtlib1)
os << "(";
// print the let var first
SMTLIB1_Print1(os, it->first, indentation, false);
os << " ";
// print the expr
SMTLIB1_Print1(os, it->second, indentation, false);
os << ")";
if (!smtlib1)
os << ")";
// update the second map for proper printing of LET
NodeLetVarMap1[it->second] = it->first;
closing += ")";
}
os << endl;
SMTLIB1_Print1(os, n, indentation, true);
os << closing;
os << " ) ";
}
else
SMTLIB1_Print1(os, n, indentation, false);
os << endl;
return os;
}
void LetizeNode(const ASTNode& n, ASTNodeSet& PLPrintNodeSet, bool smtlib1)
{
const Kind kind = n.GetKind();
if (kind == SYMBOL || kind == BVCONST || kind == FALSE || kind == TRUE)
return;
const ASTVec& c = n.GetChildren();
for (ASTVec::const_iterator it = c.begin(), itend = c.end(); it != itend;
it++)
{
const ASTNode& ccc = *it;
const Kind k = ccc.GetKind();
if (k == SYMBOL || k == BVCONST || k == FALSE || k == TRUE)
continue;
if (PLPrintNodeSet.find(ccc) == PLPrintNodeSet.end())
{
// If branch: if *it is not in NodeSet then,
//
// 1. add it to NodeSet
//
// 2. Letize its childNodes
PLPrintNodeSet.insert(ccc);
LetizeNode(ccc, PLPrintNodeSet, smtlib1);
}
else
{
// 0. Else branch: Node has been seen before
//
// 1. Check if the node has a corresponding letvar in the
// 1. NodeLetVarMap.
//
// 2. if no, then create a new var and add it to the
// 2. NodeLetVarMap
if ((!smtlib1 || ccc.GetType() == BITVECTOR_TYPE) &&
NodeLetVarMap.find(ccc) == NodeLetVarMap.end())
{
// Create a new symbol. Get some name. if it conflicts with a
// declared name, too bad.
int sz = NodeLetVarMap.size();
std::ostringstream oss;
oss << "?let_k_" << sz;
ASTNode CurrentSymbol = n.GetSTPMgr()->CreateSymbol(
oss.str().c_str(), n.GetIndexWidth(), n.GetValueWidth());
/* If for some reason the variable being created here is
* already declared by the user then the printed output will
* not be a legal input to the system. too bad. I refuse to
* check for this. [Vijay is the author of this comment.]
*/
NodeLetVarMap[ccc] = CurrentSymbol;
std::pair<ASTNode, ASTNode> node_letvar_pair(CurrentSymbol, ccc);
NodeLetVarVec.push_back(node_letvar_pair);
}
}
}
} // end of LetizeNode()
string functionToSMTLIBName(const Kind k, bool smtlib1)
{
switch (k)
{
case IFF:
if (smtlib1)
return "iff";
else
return "=";
case IMPLIES:
if (smtlib1)
return "implies";
else
return "=>";
case AND:
case BVAND:
case BVNAND:
case BVNOR:
case BVOR:
case BVSGE:
case BVSGT:
case BVSLE:
case BVSLT:
case BVSUB:
case BVXOR:
case ITE:
case NAND:
case NOR:
case NOT:
case OR:
case XOR:
{
return tolower(_kind_names[k]);
}
case BVCONCAT:
return "concat";
case BVDIV:
return "bvudiv";
case BVGT:
return "bvugt";
case BVGE:
return "bvuge";
case BVLE:
return "bvule";
case BVLEFTSHIFT:
return "bvshl";
case BVLT:
return "bvult";
case BVMOD:
return "bvurem";
case BVMULT:
return "bvmul";
case BVNEG:
return "bvnot"; // CONFUSSSSINNG. (1/2)
case BVPLUS:
return "bvadd";
case BVRIGHTSHIFT:
return "bvlshr"; // logical
case BVSRSHIFT:
return "bvashr"; // arithmetic.
case BVUMINUS:
return "bvneg"; // CONFUSSSSINNG. (2/2)
case EQ:
return "=";
case READ:
return "select";
case WRITE:
return "store";
case SBVDIV:
return "bvsdiv";
case SBVREM:
return "bvsrem";
case SBVMOD:
return "bvsmod";
default:
{
std::cerr << "Unknown name when outputting:";
FatalError(_kind_names[k]);
return ""; // to quieten compiler/
}
}
}
}
<commit_msg>Remove code copy-paste<commit_after>/********************************************************************
* AUTHORS: Trevor Hansen
*
* BEGIN DATE: May, 2010
*
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.
********************************************************************/
#include "stp/Printer/printers.h"
#include "stp/Printer/SMTLIBPrinter.h"
// Functions used by both the version1 and version2 STMLIB printers.
namespace printer
{
using namespace BEEV;
using std::pair;
using std::endl;
static string tolower(const char* name)
{
string s(name);
for (size_t i = 0; i < s.size(); ++i)
s[i] = ::tolower(s[i]);
return s;
}
// Map from ASTNodes to LetVars
BEEV::ASTNodeMap NodeLetVarMap;
// This is a vector which stores the Node to LetVars pairs. It
// allows for sorted printing, as opposed to NodeLetVarMap
std::vector<pair<ASTNode, ASTNode>> NodeLetVarVec;
// a partial Map from ASTNodes to LetVars. Needed in order to
// correctly print shared subterms inside the LET itself
BEEV::ASTNodeMap NodeLetVarMap1;
// copied from Presentation Langauge printer.
ostream& SMTLIB_Print(ostream& os, const ASTNode n, const int indentation,
void (*SMTLIB1_Print1)(ostream&, const ASTNode, int,
bool),
bool smtlib1)
{
// Clear the maps
NodeLetVarMap.clear();
NodeLetVarVec.clear();
NodeLetVarMap1.clear();
// pass 1: letize the node
{
ASTNodeSet PLPrintNodeSet;
LetizeNode(n, PLPrintNodeSet, smtlib1);
}
// pass 2:
//
// 2. print all the let variables and their counterpart expressions
// 2. as follows (LET var1 = expr1, var2 = expr2, ...
//
// 3. Then print the Node itself, replacing every occurence of
// 3. expr1 with var1, expr2 with var2, ...
// os << "(";
if (0 < NodeLetVarMap.size())
{
std::vector<pair<ASTNode, ASTNode>>::iterator it = NodeLetVarVec.begin();
const std::vector<pair<ASTNode, ASTNode>>::iterator itend =
NodeLetVarVec.end();
os << "(let (";
if (!smtlib1)
os << "(";
// print the let var first
SMTLIB1_Print1(os, it->first, indentation, false);
os << " ";
// print the expr
SMTLIB1_Print1(os, it->second, indentation, false);
os << " )";
if (!smtlib1)
os << ")";
// update the second map for proper printing of LET
NodeLetVarMap1[it->second] = it->first;
string closing = "";
for (it++; it != itend; it++)
{
os << " " << endl;
os << "(let (";
if (!smtlib1)
os << "(";
// print the let var first
SMTLIB1_Print1(os, it->first, indentation, false);
os << " ";
// print the expr
SMTLIB1_Print1(os, it->second, indentation, false);
os << ")";
if (!smtlib1)
os << ")";
// update the second map for proper printing of LET
NodeLetVarMap1[it->second] = it->first;
closing += ")";
}
os << endl;
SMTLIB1_Print1(os, n, indentation, true);
os << closing;
os << " ) ";
}
else
SMTLIB1_Print1(os, n, indentation, false);
os << endl;
return os;
}
void LetizeNode(const ASTNode& n, ASTNodeSet& PLPrintNodeSet, bool smtlib1)
{
if (n.isAtom())
return;
const ASTVec& c = n.GetChildren();
for (ASTVec::const_iterator it = c.begin(), itend = c.end(); it != itend;
it++)
{
const ASTNode& ccc = *it;
if (ccc.isAtom())
continue;
if (PLPrintNodeSet.find(ccc) == PLPrintNodeSet.end())
{
// If branch: if *it is not in NodeSet then,
//
// 1. add it to NodeSet
//
// 2. Letize its childNodes
PLPrintNodeSet.insert(ccc);
LetizeNode(ccc, PLPrintNodeSet, smtlib1);
}
else
{
// 0. Else branch: Node has been seen before
//
// 1. Check if the node has a corresponding letvar in the
// 1. NodeLetVarMap.
//
// 2. if no, then create a new var and add it to the
// 2. NodeLetVarMap
if ((!smtlib1 || ccc.GetType() == BITVECTOR_TYPE) &&
NodeLetVarMap.find(ccc) == NodeLetVarMap.end())
{
// Create a new symbol. Get some name. if it conflicts with a
// declared name, too bad.
int sz = NodeLetVarMap.size();
std::ostringstream oss;
oss << "?let_k_" << sz;
ASTNode CurrentSymbol = n.GetSTPMgr()->CreateSymbol(
oss.str().c_str(), n.GetIndexWidth(), n.GetValueWidth());
/* If for some reason the variable being created here is
* already declared by the user then the printed output will
* not be a legal input to the system. too bad. I refuse to
* check for this. [Vijay is the author of this comment.]
*/
NodeLetVarMap[ccc] = CurrentSymbol;
std::pair<ASTNode, ASTNode> node_letvar_pair(CurrentSymbol, ccc);
NodeLetVarVec.push_back(node_letvar_pair);
}
}
}
} // end of LetizeNode()
string functionToSMTLIBName(const Kind k, bool smtlib1)
{
switch (k)
{
case IFF:
if (smtlib1)
return "iff";
else
return "=";
case IMPLIES:
if (smtlib1)
return "implies";
else
return "=>";
case AND:
case BVAND:
case BVNAND:
case BVNOR:
case BVOR:
case BVSGE:
case BVSGT:
case BVSLE:
case BVSLT:
case BVSUB:
case BVXOR:
case ITE:
case NAND:
case NOR:
case NOT:
case OR:
case XOR:
{
return tolower(_kind_names[k]);
}
case BVCONCAT:
return "concat";
case BVDIV:
return "bvudiv";
case BVGT:
return "bvugt";
case BVGE:
return "bvuge";
case BVLE:
return "bvule";
case BVLEFTSHIFT:
return "bvshl";
case BVLT:
return "bvult";
case BVMOD:
return "bvurem";
case BVMULT:
return "bvmul";
case BVNEG:
return "bvnot"; // CONFUSSSSINNG. (1/2)
case BVPLUS:
return "bvadd";
case BVRIGHTSHIFT:
return "bvlshr"; // logical
case BVSRSHIFT:
return "bvashr"; // arithmetic.
case BVUMINUS:
return "bvneg"; // CONFUSSSSINNG. (2/2)
case EQ:
return "=";
case READ:
return "select";
case WRITE:
return "store";
case SBVDIV:
return "bvsdiv";
case SBVREM:
return "bvsrem";
case SBVMOD:
return "bvsmod";
default:
{
std::cerr << "Unknown name when outputting:";
FatalError(_kind_names[k]);
return ""; // to quieten compiler/
}
}
}
}
<|endoftext|>
|
<commit_before>//===- Signals.cpp - Signal Handling support ------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines some helpful functions for dealing with the possibility of
// Unix signals occuring while your program is running.
//
//===----------------------------------------------------------------------===//
#include "Support/Signals.h"
#include <vector>
#include <algorithm>
#include <cstdlib>
#include <cstdio>
#include "Config/config.h" // Get the signal handler return type
#ifdef HAVE_EXECINFO_H
# include <execinfo.h> // For backtrace().
#endif
#include <signal.h>
#include <unistd.h>
using namespace llvm;
static std::vector<std::string> FilesToRemove;
// IntSigs - Signals that may interrupt the program at any time.
static const int IntSigs[] = {
SIGHUP, SIGINT, SIGQUIT, SIGKILL, SIGPIPE, SIGTERM, SIGUSR1, SIGUSR2
};
static const int *IntSigsEnd = IntSigs + sizeof(IntSigs)/sizeof(IntSigs[0]);
// KillSigs - Signals that are synchronous with the program that will cause it
// to die.
static const int KillSigs[] = {
SIGILL, SIGTRAP, SIGABRT, SIGFPE, SIGBUS, SIGSEGV, SIGSYS, SIGXCPU, SIGXFSZ
#ifdef SIGEMT
, SIGEMT
#endif
};
static const int *KillSigsEnd = KillSigs + sizeof(KillSigs)/sizeof(KillSigs[0]);
static void* StackTrace[256];
// SignalHandler - The signal handler that runs...
static RETSIGTYPE SignalHandler(int Sig) {
while (!FilesToRemove.empty()) {
std::remove(FilesToRemove.back().c_str());
FilesToRemove.pop_back();
}
if (std::find(IntSigs, IntSigsEnd, Sig) != IntSigsEnd)
exit(1); // If this is an interrupt signal, exit the program
// Otherwise if it is a fault (like SEGV) output the stacktrace to
// STDERR (if we can) and reissue the signal to die...
#ifdef HAVE_BACKTRACE
// Use backtrace() to output a backtrace on Linux systems with glibc.
int depth = backtrace(StackTrace, sizeof(StackTrace)/sizeof(StackTrace[0]));
backtrace_symbols_fd(StackTrace, depth, STDERR_FILENO);
#endif
signal(Sig, SIG_DFL);
}
static void RegisterHandler(int Signal) { signal(Signal, SignalHandler); }
// RemoveFileOnSignal - The public API
void llvm::RemoveFileOnSignal(const std::string &Filename) {
FilesToRemove.push_back(Filename);
std::for_each(IntSigs, IntSigsEnd, RegisterHandler);
std::for_each(KillSigs, KillSigsEnd, RegisterHandler);
}
/// PrintStackTraceOnErrorSignal - When an error signal (such as SIBABRT or
/// SIGSEGV) is delivered to the process, print a stack trace and then exit.
void llvm::PrintStackTraceOnErrorSignal() {
std::for_each(KillSigs, KillSigsEnd, RegisterHandler);
}
<commit_msg>When printing a stack trace, demangle it if possible. Since we are potentially in a signal handler, allocating memory or doing other unsafe things is bad, which means we should do it in a different process.<commit_after>//===- Signals.cpp - Signal Handling support ------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines some helpful functions for dealing with the possibility of
// Unix signals occuring while your program is running.
//
//===----------------------------------------------------------------------===//
#include "Support/Signals.h"
#include <vector>
#include <algorithm>
#include <cstdlib>
#include <cstdio>
#include "Config/config.h" // Get the signal handler return type
#ifdef HAVE_EXECINFO_H
# include <execinfo.h> // For backtrace().
#endif
#include <signal.h>
#include <unistd.h>
#include <sys/wait.h>
#include <cerrno>
using namespace llvm;
static std::vector<std::string> FilesToRemove;
// IntSigs - Signals that may interrupt the program at any time.
static const int IntSigs[] = {
SIGHUP, SIGINT, SIGQUIT, SIGKILL, SIGPIPE, SIGTERM, SIGUSR1, SIGUSR2
};
static const int *IntSigsEnd = IntSigs + sizeof(IntSigs)/sizeof(IntSigs[0]);
// KillSigs - Signals that are synchronous with the program that will cause it
// to die.
static const int KillSigs[] = {
SIGILL, SIGTRAP, SIGABRT, SIGFPE, SIGBUS, SIGSEGV, SIGSYS, SIGXCPU, SIGXFSZ
#ifdef SIGEMT
, SIGEMT
#endif
};
static const int *KillSigsEnd = KillSigs + sizeof(KillSigs)/sizeof(KillSigs[0]);
#ifdef HAVE_BACKTRACE
static void* StackTrace[256];
#endif
// PrintStackTrace - In the case of a program crash or fault, print out a stack
// trace so that the user has an indication of why and where we died.
//
// On glibc systems we have the 'backtrace' function, which works nicely, but
// doesn't demangle symbols. In order to backtrace symbols, we fork and exec a
// 'c++filt' process to do the demangling. This seems like the simplest and
// most robust solution when we can't allocate memory (such as in a signal
// handler). If we can't find 'c++filt', we fallback to printing mangled names.
//
static void PrintStackTrace() {
#ifdef HAVE_BACKTRACE
// Use backtrace() to output a backtrace on Linux systems with glibc.
int depth = backtrace(StackTrace, sizeof(StackTrace)/sizeof(StackTrace[0]));
// Create a one-way unix pipe. The backtracing process writes to PipeFDs[1],
// the c++filt process reads from PipeFDs[0].
int PipeFDs[2];
if (pipe(PipeFDs)) {
backtrace_symbols_fd(StackTrace, depth, STDERR_FILENO);
return;
}
switch (pid_t ChildPID = fork()) {
case -1: // Error forking, print mangled stack trace
close(PipeFDs[0]);
close(PipeFDs[1]);
backtrace_symbols_fd(StackTrace, depth, STDERR_FILENO);
return;
default: // backtracing process
close(PipeFDs[0]); // Close the reader side.
// Print the mangled backtrace into the pipe.
backtrace_symbols_fd(StackTrace, depth, PipeFDs[1]);
close(PipeFDs[1]); // We are done writing.
while (waitpid(ChildPID, 0, 0) == -1)
if (errno != EINTR) break;
return;
case 0: // c++filt process
close(PipeFDs[1]); // Close the writer side.
dup2(PipeFDs[0], 0); // Read from standard input
close(PipeFDs[0]); // Close the old descriptor
dup2(2, 1); // Revector stdout -> stderr
// Try to run c++filt or gc++filt. If neither is found, call back on 'cat'
// to print the mangled stack trace. If we can't find cat, just exit.
execlp("c++filt", "c++filt", 0);
execlp("gc++filt", "gc++filt", 0);
execlp("cat", "cat", 0);
execlp("/usr/bin/cat", "cat", 0);
exit(0);
}
#endif
}
// SignalHandler - The signal handler that runs...
static RETSIGTYPE SignalHandler(int Sig) {
while (!FilesToRemove.empty()) {
std::remove(FilesToRemove.back().c_str());
FilesToRemove.pop_back();
}
if (std::find(IntSigs, IntSigsEnd, Sig) != IntSigsEnd)
exit(1); // If this is an interrupt signal, exit the program
// Otherwise if it is a fault (like SEGV) output the stacktrace to
// STDERR (if we can) and reissue the signal to die...
PrintStackTrace();
signal(Sig, SIG_DFL);
}
static void RegisterHandler(int Signal) { signal(Signal, SignalHandler); }
// RemoveFileOnSignal - The public API
void llvm::RemoveFileOnSignal(const std::string &Filename) {
FilesToRemove.push_back(Filename);
std::for_each(IntSigs, IntSigsEnd, RegisterHandler);
std::for_each(KillSigs, KillSigsEnd, RegisterHandler);
}
/// PrintStackTraceOnErrorSignal - When an error signal (such as SIBABRT or
/// SIGSEGV) is delivered to the process, print a stack trace and then exit.
void llvm::PrintStackTraceOnErrorSignal() {
std::for_each(KillSigs, KillSigsEnd, RegisterHandler);
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved.
//
// 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.
#ifndef IOX_POSH_ROUDI_INTROSPECTION_PORT_INTROSPECTION_HPP
#define IOX_POSH_ROUDI_INTROSPECTION_PORT_INTROSPECTION_HPP
#include "fixed_size_container.hpp"
#include "iceoryx_posh/iceoryx_posh_types.hpp"
#include "iceoryx_posh/internal/popo/ports/publisher_port_data.hpp"
#include "iceoryx_posh/internal/popo/ports/publisher_port_user.hpp"
#include "iceoryx_posh/mepoo/chunk_header.hpp"
#include "iceoryx_posh/roudi/introspection_types.hpp"
#include "iceoryx_utils/cxx/helplets.hpp"
#include "iceoryx_utils/platform/pthread.hpp"
#include <atomic>
#include <mutex>
#include <thread>
#include <vector>
#include <map>
namespace iox
{
namespace roudi
{
/**
* @brief This class handles the port intropection for RouDi.
* It is recommended to use the PortIntrospectionType alias which sets
* the intended template parameter required for the actual introspection.
*
* The class manages a thread that periodically updates a field with port
* introspection data to which clients may subscribe.
*/
template <typename PublisherPort, typename SubscriberPort>
class PortIntrospection
{
private:
enum class ConnectionState
{
DEFAULT,
SUB_REQUESTED,
CONNECTED
};
using PortIntrospectionTopic = PortIntrospectionFieldTopic;
using PortThroughputIntrospectionTopic = PortThroughputIntrospectionFieldTopic;
class PortData
{
private:
// internal helper classes
struct ConnectionInfo;
struct PublisherInfo
{
PublisherInfo() = default;
PublisherInfo(typename PublisherPort::MemberType_t* const portData,
const ProcessName_t& name,
const capro::ServiceDescription& service,
const NodeName_t& node)
: portData(portData)
, name(name)
, service(service)
, node(node)
{
}
typename PublisherPort::MemberType_t* portData{nullptr};
ProcessName_t name;
capro::ServiceDescription service;
NodeName_t node;
using TimePointNs_t = mepoo::TimePointNs_t;
using DurationNs_t = mepoo::DurationNs_t;
TimePointNs_t m_sequenceNumberTimestamp {DurationNs_t(0)};
mepoo::SequenceNumber_t m_sequenceNumber{0};
// map from indices to object pointers
std::map<int, ConnectionInfo*> connectionMap;
int index{-1};
};
struct SubscriberInfo
{
SubscriberInfo()
{
}
SubscriberInfo(typename SubscriberPort::MemberType_t* const portData,
const ProcessName_t& name,
const capro::ServiceDescription& service,
const NodeName_t& node)
: portData(portData)
, name(name)
, service(service)
, node(node)
{
}
typename SubscriberPort::MemberType_t* portData{nullptr};
ProcessName_t name;
capro::ServiceDescription service;
NodeName_t node;
};
struct ConnectionInfo
{
ConnectionInfo()
{
}
ConnectionInfo(typename SubscriberPort::MemberType_t* const portData,
const ProcessName_t& name,
const capro::ServiceDescription& service,
const NodeName_t& node)
: subscriberInfo(portData, name, service, node)
, state(ConnectionState::DEFAULT)
{
}
ConnectionInfo(SubscriberInfo& subscriberInfo)
: subscriberInfo(subscriberInfo)
, state(ConnectionState::DEFAULT)
{
}
SubscriberInfo subscriberInfo;
PublisherInfo* publisherInfo{nullptr};
ConnectionState state{ConnectionState::DEFAULT};
bool isConnected()
{
return publisherInfo && state == ConnectionState::CONNECTED;
}
};
public:
PortData();
/*!
* @brief add a publisher port to be tracked by introspection
* there cannot be multiple publisher ports with the same capro id
*
* @param[in] port to be added
* @param[in] name of the port to be added
* @param[in] service capro service description of the port to be added
* @param[in] name of the node the port belongs to
*
* @return returns false if the port could not be added and true otherwise
*/
bool addPublisher(typename PublisherPort::MemberType_t* const port,
const ProcessName_t& name,
const capro::ServiceDescription& service,
const NodeName_t& node);
/*!
* @brief add a subscriber port to be tracked by introspection
* multiple subscribers with the same capro id are possible as long as the names are different
*
* @param[in] portData to be added
* @param[in] name name of the port to be added
* @param[in] service capro service description of the port to be added
* @param[in] name of the node the port belongs to
*
* @return returns false if the port could not be added and true otherwise
*/
bool addSubscriber(typename SubscriberPort::MemberType_t* const portData,
const ProcessName_t& name,
const capro::ServiceDescription& service,
const NodeName_t& node);
/*!
* @brief remove a publisher port from introspection
*
* @param[in] name name of the port to be added
* @param[in] service capro service description of the port to be added
*
* @return returns false if the port could not be removed (since it did not exist)
* and true otherwise
*/
bool removePublisher(const ProcessName_t& name, const capro::ServiceDescription& service);
/*!
* @brief remove a subscriber port from introspection
*
* @param[in] name name of the port to be added
* @param[in] service capro service description of the port to be added
*
* @return returns false if the port could not be removed (since it did not exist)
* and true otherwise
*/
bool removeSubscriber(const ProcessName_t& name, const capro::ServiceDescription& service);
/*!
* @brief update the state of any connection identified by the capro id of a given message
* according to the message type (e.g. capro:SUB for a subscription request)
*
* @param[in] message capro message to be processed
*
* @return returns false there is no corresponding capro service and true otherwise
*/
bool updateConnectionState(const capro::CaproMessage& message);
/*!
* @brief prepare the topic to be send based on the internal connection state of all tracked ports
*
* @param[out] topic data structure to be prepared for sending
*
*/
void prepareTopic(PortIntrospectionTopic& topic);
void prepareTopic(PortThroughputIntrospectionTopic& topic);
void prepareTopic(SubscriberPortChangingIntrospectionFieldTopic& topic);
/*!
* @brief compute the next connection state based on the current connection state and a capro message type
*
* @param[in] currentState current connection state (e.g. CONNECTED)
* @param[in] messageType capro message type
*
* @return returns the new connection state
*/
PortIntrospection::ConnectionState getNextState(ConnectionState currentState,
capro::CaproMessageType messageType);
/*!
* @brief indicates whether the logical object state has changed (i.e. the data is new)
*
* @return returns true if the data is new(e.g. new connections were established), false otherwise
*/
bool isNew();
/*!
* @brief sets the internal flag indicating new data
*
* @param[in] value value to be set
*/
void setNew(bool value);
private:
using PublisherContainer = FixedSizeContainer<PublisherInfo, MAX_PUBLISHERS>;
using ConnectionContainer = FixedSizeContainer<ConnectionInfo, MAX_SUBSCRIBERS>;
// index publisher and connections by capro Ids
std::map<capro::ServiceDescription, typename PublisherContainer::Index_t> m_publisherMap;
// TODO: replace inner map wih more approriate structure if possible
// inner map maps from process names to indices in the ConnectionContainer
std::map<capro::ServiceDescription, std::map<ProcessName_t, typename ConnectionContainer::Index_t>>
m_connectionMap;
// Rationale: we avoid allocating the objects on the heap but can still use a map
// to locate/remove them fast(er)
// max number needs to be a compile time constant
PublisherContainer m_publisherContainer;
ConnectionContainer m_connectionContainer;
std::atomic<bool> m_newData;
std::mutex m_mutex;
};
// end of helper classes
public:
PortIntrospection();
~PortIntrospection();
// delete copy constructor and assignment operator
PortIntrospection(PortIntrospection const&) = delete;
PortIntrospection& operator=(PortIntrospection const&) = delete;
// delete move constructor and assignment operator
PortIntrospection(PortIntrospection&&) = delete;
PortIntrospection& operator=(PortIntrospection&&) = delete;
/*!
* @brief add a publisher port to be tracked by introspection
* there cannot be multiple publisher ports with the same capro id
*
* @param[in] port to be added
* @param[in] name of the port to be added
* @param[in] service capro service description of the port to be added
* @param[in] name of the node the port belongs to
*
* @return returns false if the port could not be added and true otherwise
*/
bool addPublisher(typename PublisherPort::MemberType_t* port,
const ProcessName_t& name,
const capro::ServiceDescription& service,
const NodeName_t& node);
/*!
* @brief add a subscriber port to be tracked by introspection
* multiple subscribers with the same capro id are possible as long as the names are different
*
* @param[in] port to be added
* @param[in] name name of the port to be added
* @param[in] service capro service description of the port to be added
* @param[in] name of the node the port belongs to
*
* @return returns false if the port could not be added and true otherwise
*/
bool addSubscriber(typename SubscriberPort::MemberType_t* port,
const ProcessName_t& name,
const capro::ServiceDescription& service,
const NodeName_t& node);
/*!
* @brief remove a publisher port from introspection
*
* @param[in] name name of the port to be added
* @param[in] service capro service description of the port to be added
*
* @return returns false if the port could not be removed (since it did not exist)
* and true otherwise
*/
bool removePublisher(const ProcessName_t& name, const capro::ServiceDescription& service);
/*!
* @brief remove a subscriber port from introspection
*
* @param[in] name name of the port to be added
* @param[in] service capro service description of the port to be added
*
* @return returns false if the port could not be removed (since it did not exist)
* and true otherwise
*/
bool removeSubscriber(const ProcessName_t& name, const capro::ServiceDescription& service);
/*!
* @brief report a capro message to introspection (since this could change the state of active connections)
*
* @param[in] message capro message to be processed
*
*/
void reportMessage(const capro::CaproMessage& message);
/*!
* @brief register publisher port used to send introspection
*
* @param[in] publisherPort publisher port to be registered
*
* @return true if registration was successful, false otherwise
*/
bool registerPublisherPort(PublisherPort&& publisherPortGeneric,
PublisherPort&& publisherPortThroughput,
PublisherPort&& publisherPortSubscriberPortsData);
/*!
* @brief set the time interval used to send new introspection data
*
* @param[in] sendIntervalMs time interval in ms
*
*/
void setSendInterval(unsigned int sendIntervalMs);
/*!
* @brief start the internal send thread
*
*/
void run();
/*!
* @brief stop the internal send thread
*
*/
void stop();
protected:
/*!
* @brief sends the port data; this is used from the unittests
*
*/
void sendPortData();
/*!
* @brief sends the throughput data; this is used from the unittests
*
*/
void sendThroughputData();
/*!
* @brief sends the subscriberport changing data, this is used from the unittests
*
*/
void sendSubscriberPortsData();
protected:
cxx::optional<PublisherPort> m_publisherPort;
cxx::optional<PublisherPort> m_publisherPortThroughput;
cxx::optional<PublisherPort> m_publisherPortSubscriberPortsData;
private:
PortData m_portData;
std::atomic<bool> m_runThread;
std::thread m_thread;
unsigned int m_sendIntervalCount{10};
const std::chrono::milliseconds m_sendIntervalSleep{100};
};
/**
* @brief typedef for the templated port introspection class that is used by RouDi for the
* actual port introspection functionality.
*/
using PortIntrospectionType = PortIntrospection<PublisherPortUserType, SubscriberPortUserType>;
} // namespace roudi
} // namespace iox
#include "port_introspection.inl"
#endif // IOX_POSH_ROUDI_INTROSPECTION_PORT_INTROSPECTION_HPP
<commit_msg>iox-#14 add `U` postfix to literals<commit_after>// Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved.
//
// 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.
#ifndef IOX_POSH_ROUDI_INTROSPECTION_PORT_INTROSPECTION_HPP
#define IOX_POSH_ROUDI_INTROSPECTION_PORT_INTROSPECTION_HPP
#include "fixed_size_container.hpp"
#include "iceoryx_posh/iceoryx_posh_types.hpp"
#include "iceoryx_posh/internal/popo/ports/publisher_port_data.hpp"
#include "iceoryx_posh/internal/popo/ports/publisher_port_user.hpp"
#include "iceoryx_posh/mepoo/chunk_header.hpp"
#include "iceoryx_posh/roudi/introspection_types.hpp"
#include "iceoryx_utils/cxx/helplets.hpp"
#include "iceoryx_utils/platform/pthread.hpp"
#include <atomic>
#include <mutex>
#include <thread>
#include <vector>
#include <map>
namespace iox
{
namespace roudi
{
/**
* @brief This class handles the port intropection for RouDi.
* It is recommended to use the PortIntrospectionType alias which sets
* the intended template parameter required for the actual introspection.
*
* The class manages a thread that periodically updates a field with port
* introspection data to which clients may subscribe.
*/
template <typename PublisherPort, typename SubscriberPort>
class PortIntrospection
{
private:
enum class ConnectionState
{
DEFAULT,
SUB_REQUESTED,
CONNECTED
};
using PortIntrospectionTopic = PortIntrospectionFieldTopic;
using PortThroughputIntrospectionTopic = PortThroughputIntrospectionFieldTopic;
class PortData
{
private:
// internal helper classes
struct ConnectionInfo;
struct PublisherInfo
{
PublisherInfo() = default;
PublisherInfo(typename PublisherPort::MemberType_t* const portData,
const ProcessName_t& name,
const capro::ServiceDescription& service,
const NodeName_t& node)
: portData(portData)
, name(name)
, service(service)
, node(node)
{
}
typename PublisherPort::MemberType_t* portData{nullptr};
ProcessName_t name;
capro::ServiceDescription service;
NodeName_t node;
using TimePointNs_t = mepoo::TimePointNs_t;
using DurationNs_t = mepoo::DurationNs_t;
TimePointNs_t m_sequenceNumberTimestamp {DurationNs_t(0)};
mepoo::SequenceNumber_t m_sequenceNumber{0U};
// map from indices to object pointers
std::map<int, ConnectionInfo*> connectionMap;
int index{-1};
};
struct SubscriberInfo
{
SubscriberInfo()
{
}
SubscriberInfo(typename SubscriberPort::MemberType_t* const portData,
const ProcessName_t& name,
const capro::ServiceDescription& service,
const NodeName_t& node)
: portData(portData)
, name(name)
, service(service)
, node(node)
{
}
typename SubscriberPort::MemberType_t* portData{nullptr};
ProcessName_t name;
capro::ServiceDescription service;
NodeName_t node;
};
struct ConnectionInfo
{
ConnectionInfo()
{
}
ConnectionInfo(typename SubscriberPort::MemberType_t* const portData,
const ProcessName_t& name,
const capro::ServiceDescription& service,
const NodeName_t& node)
: subscriberInfo(portData, name, service, node)
, state(ConnectionState::DEFAULT)
{
}
ConnectionInfo(SubscriberInfo& subscriberInfo)
: subscriberInfo(subscriberInfo)
, state(ConnectionState::DEFAULT)
{
}
SubscriberInfo subscriberInfo;
PublisherInfo* publisherInfo{nullptr};
ConnectionState state{ConnectionState::DEFAULT};
bool isConnected()
{
return publisherInfo && state == ConnectionState::CONNECTED;
}
};
public:
PortData();
/*!
* @brief add a publisher port to be tracked by introspection
* there cannot be multiple publisher ports with the same capro id
*
* @param[in] port to be added
* @param[in] name of the port to be added
* @param[in] service capro service description of the port to be added
* @param[in] name of the node the port belongs to
*
* @return returns false if the port could not be added and true otherwise
*/
bool addPublisher(typename PublisherPort::MemberType_t* const port,
const ProcessName_t& name,
const capro::ServiceDescription& service,
const NodeName_t& node);
/*!
* @brief add a subscriber port to be tracked by introspection
* multiple subscribers with the same capro id are possible as long as the names are different
*
* @param[in] portData to be added
* @param[in] name name of the port to be added
* @param[in] service capro service description of the port to be added
* @param[in] name of the node the port belongs to
*
* @return returns false if the port could not be added and true otherwise
*/
bool addSubscriber(typename SubscriberPort::MemberType_t* const portData,
const ProcessName_t& name,
const capro::ServiceDescription& service,
const NodeName_t& node);
/*!
* @brief remove a publisher port from introspection
*
* @param[in] name name of the port to be added
* @param[in] service capro service description of the port to be added
*
* @return returns false if the port could not be removed (since it did not exist)
* and true otherwise
*/
bool removePublisher(const ProcessName_t& name, const capro::ServiceDescription& service);
/*!
* @brief remove a subscriber port from introspection
*
* @param[in] name name of the port to be added
* @param[in] service capro service description of the port to be added
*
* @return returns false if the port could not be removed (since it did not exist)
* and true otherwise
*/
bool removeSubscriber(const ProcessName_t& name, const capro::ServiceDescription& service);
/*!
* @brief update the state of any connection identified by the capro id of a given message
* according to the message type (e.g. capro:SUB for a subscription request)
*
* @param[in] message capro message to be processed
*
* @return returns false there is no corresponding capro service and true otherwise
*/
bool updateConnectionState(const capro::CaproMessage& message);
/*!
* @brief prepare the topic to be send based on the internal connection state of all tracked ports
*
* @param[out] topic data structure to be prepared for sending
*
*/
void prepareTopic(PortIntrospectionTopic& topic);
void prepareTopic(PortThroughputIntrospectionTopic& topic);
void prepareTopic(SubscriberPortChangingIntrospectionFieldTopic& topic);
/*!
* @brief compute the next connection state based on the current connection state and a capro message type
*
* @param[in] currentState current connection state (e.g. CONNECTED)
* @param[in] messageType capro message type
*
* @return returns the new connection state
*/
PortIntrospection::ConnectionState getNextState(ConnectionState currentState,
capro::CaproMessageType messageType);
/*!
* @brief indicates whether the logical object state has changed (i.e. the data is new)
*
* @return returns true if the data is new(e.g. new connections were established), false otherwise
*/
bool isNew();
/*!
* @brief sets the internal flag indicating new data
*
* @param[in] value value to be set
*/
void setNew(bool value);
private:
using PublisherContainer = FixedSizeContainer<PublisherInfo, MAX_PUBLISHERS>;
using ConnectionContainer = FixedSizeContainer<ConnectionInfo, MAX_SUBSCRIBERS>;
// index publisher and connections by capro Ids
std::map<capro::ServiceDescription, typename PublisherContainer::Index_t> m_publisherMap;
// TODO: replace inner map wih more approriate structure if possible
// inner map maps from process names to indices in the ConnectionContainer
std::map<capro::ServiceDescription, std::map<ProcessName_t, typename ConnectionContainer::Index_t>>
m_connectionMap;
// Rationale: we avoid allocating the objects on the heap but can still use a map
// to locate/remove them fast(er)
// max number needs to be a compile time constant
PublisherContainer m_publisherContainer;
ConnectionContainer m_connectionContainer;
std::atomic<bool> m_newData;
std::mutex m_mutex;
};
// end of helper classes
public:
PortIntrospection();
~PortIntrospection();
// delete copy constructor and assignment operator
PortIntrospection(PortIntrospection const&) = delete;
PortIntrospection& operator=(PortIntrospection const&) = delete;
// delete move constructor and assignment operator
PortIntrospection(PortIntrospection&&) = delete;
PortIntrospection& operator=(PortIntrospection&&) = delete;
/*!
* @brief add a publisher port to be tracked by introspection
* there cannot be multiple publisher ports with the same capro id
*
* @param[in] port to be added
* @param[in] name of the port to be added
* @param[in] service capro service description of the port to be added
* @param[in] name of the node the port belongs to
*
* @return returns false if the port could not be added and true otherwise
*/
bool addPublisher(typename PublisherPort::MemberType_t* port,
const ProcessName_t& name,
const capro::ServiceDescription& service,
const NodeName_t& node);
/*!
* @brief add a subscriber port to be tracked by introspection
* multiple subscribers with the same capro id are possible as long as the names are different
*
* @param[in] port to be added
* @param[in] name name of the port to be added
* @param[in] service capro service description of the port to be added
* @param[in] name of the node the port belongs to
*
* @return returns false if the port could not be added and true otherwise
*/
bool addSubscriber(typename SubscriberPort::MemberType_t* port,
const ProcessName_t& name,
const capro::ServiceDescription& service,
const NodeName_t& node);
/*!
* @brief remove a publisher port from introspection
*
* @param[in] name name of the port to be added
* @param[in] service capro service description of the port to be added
*
* @return returns false if the port could not be removed (since it did not exist)
* and true otherwise
*/
bool removePublisher(const ProcessName_t& name, const capro::ServiceDescription& service);
/*!
* @brief remove a subscriber port from introspection
*
* @param[in] name name of the port to be added
* @param[in] service capro service description of the port to be added
*
* @return returns false if the port could not be removed (since it did not exist)
* and true otherwise
*/
bool removeSubscriber(const ProcessName_t& name, const capro::ServiceDescription& service);
/*!
* @brief report a capro message to introspection (since this could change the state of active connections)
*
* @param[in] message capro message to be processed
*
*/
void reportMessage(const capro::CaproMessage& message);
/*!
* @brief register publisher port used to send introspection
*
* @param[in] publisherPort publisher port to be registered
*
* @return true if registration was successful, false otherwise
*/
bool registerPublisherPort(PublisherPort&& publisherPortGeneric,
PublisherPort&& publisherPortThroughput,
PublisherPort&& publisherPortSubscriberPortsData);
/*!
* @brief set the time interval used to send new introspection data
*
* @param[in] sendIntervalMs time interval in ms
*
*/
void setSendInterval(unsigned int sendIntervalMs);
/*!
* @brief start the internal send thread
*
*/
void run();
/*!
* @brief stop the internal send thread
*
*/
void stop();
protected:
/*!
* @brief sends the port data; this is used from the unittests
*
*/
void sendPortData();
/*!
* @brief sends the throughput data; this is used from the unittests
*
*/
void sendThroughputData();
/*!
* @brief sends the subscriberport changing data, this is used from the unittests
*
*/
void sendSubscriberPortsData();
protected:
cxx::optional<PublisherPort> m_publisherPort;
cxx::optional<PublisherPort> m_publisherPortThroughput;
cxx::optional<PublisherPort> m_publisherPortSubscriberPortsData;
private:
PortData m_portData;
std::atomic<bool> m_runThread;
std::thread m_thread;
unsigned int m_sendIntervalCount{10};
const std::chrono::milliseconds m_sendIntervalSleep{100};
};
/**
* @brief typedef for the templated port introspection class that is used by RouDi for the
* actual port introspection functionality.
*/
using PortIntrospectionType = PortIntrospection<PublisherPortUserType, SubscriberPortUserType>;
} // namespace roudi
} // namespace iox
#include "port_introspection.inl"
#endif // IOX_POSH_ROUDI_INTROSPECTION_PORT_INTROSPECTION_HPP
<|endoftext|>
|
<commit_before>/*
* This file is part of TelepathyQt4
*
* Copyright (C) 2008-2010 Collabora Ltd. <http://www.collabora.co.uk/>
* Copyright (C) 2008-2010 Nokia Corporation
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <TelepathyQt4/ManagerFile>
#include <QtCore/QDir>
#include <QtCore/QHash>
#include <QtCore/QString>
#include <QtCore/QStringList>
#include <QtDBus/QDBusVariant>
#include <TelepathyQt4/KeyFile>
#include <TelepathyQt4/Constants>
#include "TelepathyQt4/debug-internal.h"
namespace Tp
{
struct TELEPATHY_QT4_NO_EXPORT ManagerFile::Private
{
Private(const QString &cnName);
void init();
bool parse(const QString &fileName);
bool isValid() const;
bool hasParameter(const QString &protocol, const QString ¶mName) const;
ParamSpec *getParameter(const QString &protocol, const QString ¶mName);
QStringList protocols() const;
ParamSpecList parameters(const QString &protocol) const;
QVariant valueForKey(const QString ¶m, const QString &signature);
struct ProtocolInfo
{
ProtocolInfo() {}
ProtocolInfo(const ParamSpecList ¶ms)
: params(params)
{
}
ParamSpecList params;
QString vcardField;
QString englishName;
QString iconName;
RequestableChannelClassList rccs;
};
QString cmName;
KeyFile keyFile;
QHash<QString, ProtocolInfo> protocolsMap;
bool valid;
};
ManagerFile::Private::Private(const QString &cmName)
: cmName(cmName),
valid(false)
{
init();
}
void ManagerFile::Private::init()
{
// TODO: should we cache the configDirs anywhere?
QStringList configDirs;
QString xdgDataHome = QString::fromLocal8Bit(qgetenv("XDG_DATA_HOME"));
if (xdgDataHome.isEmpty()) {
configDirs << QDir::homePath() + QLatin1String("/.local/share/data/telepathy/managers/");
}
else {
configDirs << xdgDataHome + QLatin1String("/telepathy/managers/");
}
QString xdgDataDirsEnv = QString::fromLocal8Bit(qgetenv("XDG_DATA_DIRS"));
if (xdgDataDirsEnv.isEmpty()) {
configDirs << QLatin1String("/usr/local/share/telepathy/managers/");
configDirs << QLatin1String("/usr/share/telepathy/managers/");
}
else {
QStringList xdgDataDirs = xdgDataDirsEnv.split(QLatin1Char(':'));
foreach (const QString xdgDataDir, xdgDataDirs) {
configDirs << xdgDataDir + QLatin1String("/telepathy/managers/");
}
}
foreach (const QString configDir, configDirs) {
QString fileName = configDir + cmName + QLatin1String(".manager");
if (QFile::exists(fileName)) {
debug() << "parsing manager file" << fileName;
protocolsMap.clear();
if (!parse(fileName)) {
warning() << "error parsing manager file" << fileName;
continue;
}
valid = true;
return;
}
}
}
bool ManagerFile::Private::parse(const QString &fileName)
{
keyFile.setFileName(fileName);
if (keyFile.status() != KeyFile::NoError) {
return false;
}
/* read supported protocols and parameters */
QString protocol;
QStringList groups = keyFile.allGroups();
foreach (const QString group, groups) {
if (group.startsWith(QLatin1String("Protocol "))) {
protocol = group.right(group.length() - 9);
keyFile.setGroup(group);
ParamSpecList paramSpecList;
QString param;
QStringList params = keyFile.keys();
foreach (param, params) {
ParamSpec spec;
spec.flags = 0;
if (param.startsWith(QLatin1String("param-"))) {
spec.name = param.right(param.length() - 6);
if (spec.name.endsWith(QLatin1String("password"))) {
spec.flags |= ConnMgrParamFlagSecret;
}
QStringList values = keyFile.value(param).split(QLatin1String(" "));
spec.signature = values[0];
if (values.contains(QLatin1String("secret"))) {
spec.flags |= ConnMgrParamFlagSecret;
}
if (values.contains(QLatin1String("dbus-property"))) {
spec.flags |= ConnMgrParamFlagDBusProperty;
}
if (values.contains(QLatin1String("required"))) {
spec.flags |= ConnMgrParamFlagRequired;
}
if (values.contains(QLatin1String("register"))) {
spec.flags |= ConnMgrParamFlagRegister;
}
paramSpecList.append(spec);
}
}
protocolsMap.insert(protocol, ProtocolInfo(paramSpecList));
/* now that we have all param-* created, let's find their default values */
foreach (param, params) {
if (param.startsWith(QLatin1String("default-"))) {
QString paramName = param.right(param.length() - 8);
if (!hasParameter(protocol, paramName)) {
warning() << "param" << paramName
<< "has default value set, but not a definition";
continue;
}
ParamSpec *spec = getParameter(protocol, paramName);
spec->flags |= ConnMgrParamFlagHasDefault;
/* map based on the param dbus signature, otherwise use
* QString */
QVariant value = valueForKey(param, spec->signature);
if (value.type() == QVariant::Invalid) {
warning() << "param" << paramName
<< "has invalid signature";
protocolsMap.clear();
return false;
}
spec->defaultValue = QDBusVariant(value);
}
}
ProtocolInfo &info = protocolsMap[protocol];
info.vcardField = keyFile.value(QLatin1String("VCardField"));
info.englishName = keyFile.value(QLatin1String("EnglishName"));
info.iconName = keyFile.value(QLatin1String("Icon"));
QStringList rccGroups = keyFile.valueAsStringList(
QLatin1String("RequestableChannelClasses"));
RequestableChannelClass rcc;
foreach (const QString &rccGroup, rccGroups) {
keyFile.setGroup(rccGroup);
foreach (const QString &key, keyFile.keys()) {
int spaceIdx = key.indexOf(QLatin1String(" "));
if (spaceIdx == -1) {
continue;
}
QString propertyName = key.mid(0, spaceIdx);
QString signature = key.mid(spaceIdx + 1);
QString param = keyFile.value(key);
QVariant value = valueForKey(key, signature);
rcc.fixedProperties.insert(propertyName, value);
}
rcc.allowedProperties = keyFile.valueAsStringList(
QLatin1String("allowed"));
info.rccs.append(rcc);
}
}
}
return true;
}
bool ManagerFile::Private::isValid() const
{
return ((keyFile.status() == KeyFile::NoError) && (valid));
}
bool ManagerFile::Private::hasParameter(const QString &protocol,
const QString ¶mName) const
{
ParamSpecList paramSpecList = protocolsMap[protocol].params;
foreach (const ParamSpec ¶mSpec, paramSpecList) {
if (paramSpec.name == paramName) {
return true;
}
}
return false;
}
ParamSpec *ManagerFile::Private::getParameter(const QString &protocol,
const QString ¶mName)
{
ParamSpecList ¶mSpecList = protocolsMap[protocol].params;
for (int i = 0; i < paramSpecList.size(); ++i) {
ParamSpec ¶mSpec = paramSpecList[i];
if (paramSpec.name == paramName) {
return ¶mSpec;
}
}
return NULL;
}
QStringList ManagerFile::Private::protocols() const
{
return protocolsMap.keys();
}
ParamSpecList ManagerFile::Private::parameters(const QString &protocol) const
{
return protocolsMap.value(protocol).params;
}
QVariant ManagerFile::Private::valueForKey(const QString ¶m,
const QString &signature)
{
QVariant::Type type = ManagerFile::variantTypeFromDBusSignature(signature);
if (type == QVariant::Invalid) {
return QVariant(type);
}
switch (type) {
case QVariant::Bool:
{
QString value = keyFile.value(param);
if (value.toLower() == QLatin1String("true") ||
value == QLatin1String("1")) {
return QVariant(true);
}
else {
return QVariant(false);
}
break;
}
case QVariant::Int:
{
QString value = keyFile.value(param);
return QVariant(value.toInt());
}
case QVariant::UInt:
{
QString value = keyFile.value(param);
return QVariant(value.toUInt());
}
case QVariant::LongLong:
{
QString value = keyFile.value(param);
return QVariant(value.toLongLong());
}
case QVariant::ULongLong:
{
QString value = keyFile.value(param);
return QVariant(value.toULongLong());
}
case QVariant::Double:
{
QString value = keyFile.value(param);
return QVariant(value.toDouble());
}
case QVariant::StringList:
{
QStringList value = keyFile.valueAsStringList(param);
return QVariant(value);
}
default:
break;
}
QString value = keyFile.value(param);
return QVariant(value);
}
/**
* \class ManagerFile
* \headerfile TelepathyQt4/manager-file.h <TelepathyQt4/ManagerFile>
*
* \brief The ManagerFile class provides an easy way to read telepathy manager
* files according to http://telepathy.freedesktop.org/spec.html.
*/
/**
* Create a ManagerFile object used to read .manager compliant files.
*
* \param cmName Name of the connection manager to read the file for.
*/
ManagerFile::ManagerFile(const QString &cmName)
: mPriv(new Private(cmName))
{
}
/**
* Class destructor.
*/
ManagerFile::~ManagerFile()
{
delete mPriv;
}
/**
* Check whether or not a ManagerFile object is valid. If the file for the
* specified connection manager cannot be found it will be considered invalid.
*
* \return true if valid, false otherwise.
*/
bool ManagerFile::isValid() const
{
return mPriv->isValid();
}
/**
* Return a list of all protocols defined in the manager file.
*
* \return List of all protocols defined in the file.
*/
QStringList ManagerFile::protocols() const
{
return mPriv->protocols();
}
/**
* Return a list of parameters for the given \a protocol.
*
* \param protocol Name of the protocol to look for.
* \return List of ParamSpec of a specific protocol defined in the file, or an
* empty list if the protocol is not defined.
*/
ParamSpecList ManagerFile::parameters(const QString &protocol) const
{
return mPriv->parameters(protocol);
}
/**
* Return the name of the most common vCard field used for the given \a protocol's
* contact identifiers, normalized to lower case.
*
* \param protocol Name of the protocol to look for.
* \return The most common vCard field used for the given protocol's contact
* identifiers, or an empty string if there is no such field or the
* protocol is not defined.
*/
QString ManagerFile::vcardField(const QString &protocol) const
{
return mPriv->protocolsMap[protocol].vcardField;
}
/**
* Return the name of the given \a protocol in a form suitable for display to
* users, such as "AIM" or "Yahoo!".
*
* \param protocol Name of the protocol to look for.
* \return The name of the given \a protocol in a form suitable for display to
* users or an empty string if none is available or the protocol is not
* defined.
*/
QString ManagerFile::englishName(const QString &protocol) const
{
return mPriv->protocolsMap[protocol].englishName;
}
/**
* Return the name of an icon for the given \a protocol in the system's icon
* theme, such as "im-msn".
*
* \param protocol Name of the protocol to look for.
* \return The name of an icon for the given \a protocol in the system's icon
* theme or an empty string if none is available or the protocol is not
* defined.
*/
QString ManagerFile::iconName(const QString &protocol) const
{
return mPriv->protocolsMap[protocol].iconName;
}
/**
* Return a list of channel classes which might be requestable from a connection
* to the given \a protocol.
*
* \param protocol Name of the protocol to look for.
* \return A list of channel classes which might be requestable from a
* connection to the given \a protocol or a default constructed
* RequestableChannelClassList instance if the protocol is not defined.
*/
RequestableChannelClassList ManagerFile::requestableChannelClasses(
const QString &protocol) const
{
return mPriv->protocolsMap[protocol].rccs;
}
QVariant::Type ManagerFile::variantTypeFromDBusSignature(const QString &signature)
{
QVariant::Type type;
if (signature == QLatin1String("b"))
type = QVariant::Bool;
else if (signature == QLatin1String("n") || signature == QLatin1String("i"))
type = QVariant::Int;
else if (signature == QLatin1String("q") || signature == QLatin1String("u"))
type = QVariant::UInt;
else if (signature == QLatin1String("x"))
type = QVariant::LongLong;
else if (signature == QLatin1String("t"))
type = QVariant::ULongLong;
else if (signature == QLatin1String("d"))
type = QVariant::Double;
else if (signature == QLatin1String("as"))
type = QVariant::StringList;
else if (signature == QLatin1String("s") || signature == QLatin1String("o"))
type = QVariant::String;
else
type = QVariant::Invalid;
return type;
}
} // Tp
<commit_msg>ManagerFile: Always return non-empty englishName and iconName strings.<commit_after>/*
* This file is part of TelepathyQt4
*
* Copyright (C) 2008-2010 Collabora Ltd. <http://www.collabora.co.uk/>
* Copyright (C) 2008-2010 Nokia Corporation
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <TelepathyQt4/ManagerFile>
#include <QtCore/QDir>
#include <QtCore/QHash>
#include <QtCore/QString>
#include <QtCore/QStringList>
#include <QtDBus/QDBusVariant>
#include <TelepathyQt4/KeyFile>
#include <TelepathyQt4/Constants>
#include "TelepathyQt4/debug-internal.h"
namespace Tp
{
struct TELEPATHY_QT4_NO_EXPORT ManagerFile::Private
{
Private(const QString &cnName);
void init();
bool parse(const QString &fileName);
bool isValid() const;
bool hasParameter(const QString &protocol, const QString ¶mName) const;
ParamSpec *getParameter(const QString &protocol, const QString ¶mName);
QStringList protocols() const;
ParamSpecList parameters(const QString &protocol) const;
QVariant valueForKey(const QString ¶m, const QString &signature);
struct ProtocolInfo
{
ProtocolInfo() {}
ProtocolInfo(const ParamSpecList ¶ms)
: params(params)
{
}
ParamSpecList params;
QString vcardField;
QString englishName;
QString iconName;
RequestableChannelClassList rccs;
};
QString cmName;
KeyFile keyFile;
QHash<QString, ProtocolInfo> protocolsMap;
bool valid;
};
ManagerFile::Private::Private(const QString &cmName)
: cmName(cmName),
valid(false)
{
init();
}
void ManagerFile::Private::init()
{
// TODO: should we cache the configDirs anywhere?
QStringList configDirs;
QString xdgDataHome = QString::fromLocal8Bit(qgetenv("XDG_DATA_HOME"));
if (xdgDataHome.isEmpty()) {
configDirs << QDir::homePath() + QLatin1String("/.local/share/data/telepathy/managers/");
}
else {
configDirs << xdgDataHome + QLatin1String("/telepathy/managers/");
}
QString xdgDataDirsEnv = QString::fromLocal8Bit(qgetenv("XDG_DATA_DIRS"));
if (xdgDataDirsEnv.isEmpty()) {
configDirs << QLatin1String("/usr/local/share/telepathy/managers/");
configDirs << QLatin1String("/usr/share/telepathy/managers/");
}
else {
QStringList xdgDataDirs = xdgDataDirsEnv.split(QLatin1Char(':'));
foreach (const QString xdgDataDir, xdgDataDirs) {
configDirs << xdgDataDir + QLatin1String("/telepathy/managers/");
}
}
foreach (const QString configDir, configDirs) {
QString fileName = configDir + cmName + QLatin1String(".manager");
if (QFile::exists(fileName)) {
debug() << "parsing manager file" << fileName;
protocolsMap.clear();
if (!parse(fileName)) {
warning() << "error parsing manager file" << fileName;
continue;
}
valid = true;
return;
}
}
}
bool ManagerFile::Private::parse(const QString &fileName)
{
keyFile.setFileName(fileName);
if (keyFile.status() != KeyFile::NoError) {
return false;
}
/* read supported protocols and parameters */
QString protocol;
QStringList groups = keyFile.allGroups();
foreach (const QString group, groups) {
if (group.startsWith(QLatin1String("Protocol "))) {
protocol = group.right(group.length() - 9);
keyFile.setGroup(group);
ParamSpecList paramSpecList;
QString param;
QStringList params = keyFile.keys();
foreach (param, params) {
ParamSpec spec;
spec.flags = 0;
if (param.startsWith(QLatin1String("param-"))) {
spec.name = param.right(param.length() - 6);
if (spec.name.endsWith(QLatin1String("password"))) {
spec.flags |= ConnMgrParamFlagSecret;
}
QStringList values = keyFile.value(param).split(QLatin1String(" "));
spec.signature = values[0];
if (values.contains(QLatin1String("secret"))) {
spec.flags |= ConnMgrParamFlagSecret;
}
if (values.contains(QLatin1String("dbus-property"))) {
spec.flags |= ConnMgrParamFlagDBusProperty;
}
if (values.contains(QLatin1String("required"))) {
spec.flags |= ConnMgrParamFlagRequired;
}
if (values.contains(QLatin1String("register"))) {
spec.flags |= ConnMgrParamFlagRegister;
}
paramSpecList.append(spec);
}
}
protocolsMap.insert(protocol, ProtocolInfo(paramSpecList));
/* now that we have all param-* created, let's find their default values */
foreach (param, params) {
if (param.startsWith(QLatin1String("default-"))) {
QString paramName = param.right(param.length() - 8);
if (!hasParameter(protocol, paramName)) {
warning() << "param" << paramName
<< "has default value set, but not a definition";
continue;
}
ParamSpec *spec = getParameter(protocol, paramName);
spec->flags |= ConnMgrParamFlagHasDefault;
/* map based on the param dbus signature, otherwise use
* QString */
QVariant value = valueForKey(param, spec->signature);
if (value.type() == QVariant::Invalid) {
warning() << "param" << paramName
<< "has invalid signature";
protocolsMap.clear();
return false;
}
spec->defaultValue = QDBusVariant(value);
}
}
ProtocolInfo &info = protocolsMap[protocol];
info.vcardField = keyFile.value(QLatin1String("VCardField"));
info.englishName = keyFile.value(QLatin1String("EnglishName"));
if (info.englishName.isEmpty()) {
info.englishName = QString("%1").arg(protocol);
}
info.iconName = keyFile.value(QLatin1String("Icon"));
if (info.iconName.isEmpty()) {
info.iconName = QString("im-%1").arg(protocol);
}
QStringList rccGroups = keyFile.valueAsStringList(
QLatin1String("RequestableChannelClasses"));
RequestableChannelClass rcc;
foreach (const QString &rccGroup, rccGroups) {
keyFile.setGroup(rccGroup);
foreach (const QString &key, keyFile.keys()) {
int spaceIdx = key.indexOf(QLatin1String(" "));
if (spaceIdx == -1) {
continue;
}
QString propertyName = key.mid(0, spaceIdx);
QString signature = key.mid(spaceIdx + 1);
QString param = keyFile.value(key);
QVariant value = valueForKey(key, signature);
rcc.fixedProperties.insert(propertyName, value);
}
rcc.allowedProperties = keyFile.valueAsStringList(
QLatin1String("allowed"));
info.rccs.append(rcc);
}
}
}
return true;
}
bool ManagerFile::Private::isValid() const
{
return ((keyFile.status() == KeyFile::NoError) && (valid));
}
bool ManagerFile::Private::hasParameter(const QString &protocol,
const QString ¶mName) const
{
ParamSpecList paramSpecList = protocolsMap[protocol].params;
foreach (const ParamSpec ¶mSpec, paramSpecList) {
if (paramSpec.name == paramName) {
return true;
}
}
return false;
}
ParamSpec *ManagerFile::Private::getParameter(const QString &protocol,
const QString ¶mName)
{
ParamSpecList ¶mSpecList = protocolsMap[protocol].params;
for (int i = 0; i < paramSpecList.size(); ++i) {
ParamSpec ¶mSpec = paramSpecList[i];
if (paramSpec.name == paramName) {
return ¶mSpec;
}
}
return NULL;
}
QStringList ManagerFile::Private::protocols() const
{
return protocolsMap.keys();
}
ParamSpecList ManagerFile::Private::parameters(const QString &protocol) const
{
return protocolsMap.value(protocol).params;
}
QVariant ManagerFile::Private::valueForKey(const QString ¶m,
const QString &signature)
{
QVariant::Type type = ManagerFile::variantTypeFromDBusSignature(signature);
if (type == QVariant::Invalid) {
return QVariant(type);
}
switch (type) {
case QVariant::Bool:
{
QString value = keyFile.value(param);
if (value.toLower() == QLatin1String("true") ||
value == QLatin1String("1")) {
return QVariant(true);
}
else {
return QVariant(false);
}
break;
}
case QVariant::Int:
{
QString value = keyFile.value(param);
return QVariant(value.toInt());
}
case QVariant::UInt:
{
QString value = keyFile.value(param);
return QVariant(value.toUInt());
}
case QVariant::LongLong:
{
QString value = keyFile.value(param);
return QVariant(value.toLongLong());
}
case QVariant::ULongLong:
{
QString value = keyFile.value(param);
return QVariant(value.toULongLong());
}
case QVariant::Double:
{
QString value = keyFile.value(param);
return QVariant(value.toDouble());
}
case QVariant::StringList:
{
QStringList value = keyFile.valueAsStringList(param);
return QVariant(value);
}
default:
break;
}
QString value = keyFile.value(param);
return QVariant(value);
}
/**
* \class ManagerFile
* \headerfile TelepathyQt4/manager-file.h <TelepathyQt4/ManagerFile>
*
* \brief The ManagerFile class provides an easy way to read telepathy manager
* files according to http://telepathy.freedesktop.org/spec.html.
*/
/**
* Create a ManagerFile object used to read .manager compliant files.
*
* \param cmName Name of the connection manager to read the file for.
*/
ManagerFile::ManagerFile(const QString &cmName)
: mPriv(new Private(cmName))
{
}
/**
* Class destructor.
*/
ManagerFile::~ManagerFile()
{
delete mPriv;
}
/**
* Check whether or not a ManagerFile object is valid. If the file for the
* specified connection manager cannot be found it will be considered invalid.
*
* \return true if valid, false otherwise.
*/
bool ManagerFile::isValid() const
{
return mPriv->isValid();
}
/**
* Return a list of all protocols defined in the manager file.
*
* \return List of all protocols defined in the file.
*/
QStringList ManagerFile::protocols() const
{
return mPriv->protocols();
}
/**
* Return a list of parameters for the given \a protocol.
*
* \param protocol Name of the protocol to look for.
* \return List of ParamSpec of a specific protocol defined in the file, or an
* empty list if the protocol is not defined.
*/
ParamSpecList ManagerFile::parameters(const QString &protocol) const
{
return mPriv->parameters(protocol);
}
/**
* Return the name of the most common vCard field used for the given \a protocol's
* contact identifiers, normalized to lower case.
*
* \param protocol Name of the protocol to look for.
* \return The most common vCard field used for the given protocol's contact
* identifiers, or an empty string if there is no such field or the
* protocol is not defined.
*/
QString ManagerFile::vcardField(const QString &protocol) const
{
return mPriv->protocolsMap[protocol].vcardField;
}
/**
* Return the name of the given \a protocol in a form suitable for display to
* users, such as "AIM" or "Yahoo!".
*
* \param protocol Name of the protocol to look for.
* \return The name of the given \a protocol in a form suitable for display to
* users or the \a protocol if the protocol is defined and englishName
* is absent.
*/
QString ManagerFile::englishName(const QString &protocol) const
{
return mPriv->protocolsMap[protocol].englishName;
}
/**
* Return the name of an icon for the given \a protocol in the system's icon
* theme, such as "im-msn".
*
* \param protocol Name of the protocol to look for.
* \return The name of an icon for the given \a protocol in the system's icon
* theme or the string im-\a protocol if the protocol is defined and
* Icon is absent.
*/
QString ManagerFile::iconName(const QString &protocol) const
{
return mPriv->protocolsMap[protocol].iconName;
}
/**
* Return a list of channel classes which might be requestable from a connection
* to the given \a protocol.
*
* \param protocol Name of the protocol to look for.
* \return A list of channel classes which might be requestable from a
* connection to the given \a protocol or a default constructed
* RequestableChannelClassList instance if the protocol is not defined.
*/
RequestableChannelClassList ManagerFile::requestableChannelClasses(
const QString &protocol) const
{
return mPriv->protocolsMap[protocol].rccs;
}
QVariant::Type ManagerFile::variantTypeFromDBusSignature(const QString &signature)
{
QVariant::Type type;
if (signature == QLatin1String("b"))
type = QVariant::Bool;
else if (signature == QLatin1String("n") || signature == QLatin1String("i"))
type = QVariant::Int;
else if (signature == QLatin1String("q") || signature == QLatin1String("u"))
type = QVariant::UInt;
else if (signature == QLatin1String("x"))
type = QVariant::LongLong;
else if (signature == QLatin1String("t"))
type = QVariant::ULongLong;
else if (signature == QLatin1String("d"))
type = QVariant::Double;
else if (signature == QLatin1String("as"))
type = QVariant::StringList;
else if (signature == QLatin1String("s") || signature == QLatin1String("o"))
type = QVariant::String;
else
type = QVariant::Invalid;
return type;
}
} // Tp
<|endoftext|>
|
<commit_before>#include "callback_engine.hpp"
#include "callback_object.hpp"
#include "code/ylikuutio/common/any_value.hpp"
#include "code/ylikuutio/hierarchy/hierarchy_templates.hpp"
// Include standard headers
#include <iostream> // std::cout, std::cin, std::cerr
#include <queue> // std::queue
#include <stdint.h> // uint32_t etc.
#include <string> // std::string
#include <vector> // std::vector
namespace callback_system
{
CallbackEngine::CallbackEngine()
{
// constructor.
this->number_of_callback_objects = 0;
}
CallbackEngine::~CallbackEngine()
{
// destructor.
std::cout << "This callback engine will be destroyed.\n";
// destroy all callback objects of this callback engine.
std::cout << "All callback objects of this callback engine will be destroyed.\n";
hierarchy::delete_children<callback_system::CallbackObject*>(this->callback_object_pointer_vector, &this->number_of_callback_objects);
}
void CallbackEngine::set_callback_object_pointer(const uint32_t childID, callback_system::CallbackObject* const child_pointer)
{
hierarchy::set_child_pointer(childID, child_pointer, this->callback_object_pointer_vector, this->free_callback_objectID_queue, &this->number_of_callback_objects);
}
datatypes::AnyValue* CallbackEngine::execute()
{
datatypes::AnyValue* any_value = new datatypes::AnyValue();
// execute all callbacks.
for (uint32_t child_i = 0; child_i < this->callback_object_pointer_vector.size(); child_i++)
{
callback_system::CallbackObject* callback_object_pointer = static_cast<callback_system::CallbackObject*>(this->callback_object_pointer_vector[child_i]);
any_value = callback_object_pointer->execute();
this->return_values.push_back(any_value);
}
this->return_values.clear();
return any_value;
}
uint32_t CallbackEngine::get_n_of_return_values()
{
return this->return_values.size();
}
datatypes::AnyValue* CallbackEngine::get_nth_return_value(uint32_t n)
{
// note: indexing of `n` begins from 0.
uint32_t n_of_return_values = this->get_n_of_return_values();
if (n_of_return_values <= n)
{
return nullptr;
}
return this->return_values.at(n_of_return_values - 1);
}
datatypes::AnyValue* CallbackEngine::get_previous_return_value()
{
uint32_t n_of_return_values = this->get_n_of_return_values();
if (n_of_return_values == 0)
{
return nullptr;
}
return this->return_values.at(this->return_values.size() - 1);
}
}
<commit_msg>`CallbackEngine::execute()` without `CallbackObject`s returns `nullptr`.<commit_after>#include "callback_engine.hpp"
#include "callback_object.hpp"
#include "code/ylikuutio/common/any_value.hpp"
#include "code/ylikuutio/hierarchy/hierarchy_templates.hpp"
// Include standard headers
#include <iostream> // std::cout, std::cin, std::cerr
#include <queue> // std::queue
#include <stdint.h> // uint32_t etc.
#include <string> // std::string
#include <vector> // std::vector
namespace callback_system
{
CallbackEngine::CallbackEngine()
{
// constructor.
this->number_of_callback_objects = 0;
}
CallbackEngine::~CallbackEngine()
{
// destructor.
std::cout << "This callback engine will be destroyed.\n";
// destroy all callback objects of this callback engine.
std::cout << "All callback objects of this callback engine will be destroyed.\n";
hierarchy::delete_children<callback_system::CallbackObject*>(this->callback_object_pointer_vector, &this->number_of_callback_objects);
}
void CallbackEngine::set_callback_object_pointer(const uint32_t childID, callback_system::CallbackObject* const child_pointer)
{
hierarchy::set_child_pointer(childID, child_pointer, this->callback_object_pointer_vector, this->free_callback_objectID_queue, &this->number_of_callback_objects);
}
datatypes::AnyValue* CallbackEngine::execute()
{
datatypes::AnyValue* any_value = nullptr;
// execute all callbacks.
for (uint32_t child_i = 0; child_i < this->callback_object_pointer_vector.size(); child_i++)
{
callback_system::CallbackObject* callback_object_pointer = static_cast<callback_system::CallbackObject*>(this->callback_object_pointer_vector[child_i]);
any_value = callback_object_pointer->execute();
this->return_values.push_back(any_value);
}
this->return_values.clear();
return any_value;
}
uint32_t CallbackEngine::get_n_of_return_values()
{
return this->return_values.size();
}
datatypes::AnyValue* CallbackEngine::get_nth_return_value(uint32_t n)
{
// note: indexing of `n` begins from 0.
uint32_t n_of_return_values = this->get_n_of_return_values();
if (n_of_return_values <= n)
{
return nullptr;
}
return this->return_values.at(n_of_return_values - 1);
}
datatypes::AnyValue* CallbackEngine::get_previous_return_value()
{
uint32_t n_of_return_values = this->get_n_of_return_values();
if (n_of_return_values == 0)
{
return nullptr;
}
return this->return_values.at(this->return_values.size() - 1);
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
* UrBackup - Client/Server backup system
* Copyright (C) 2011 Martin Raiber
*
* 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 3 of the License, or
* (at your option) any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
**************************************************************************/
#include "os_functions.h"
#include "../stringtools.h"
#include "../Interface/Server.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/statvfs.h>
#include <dirent.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <algorithm>
#include <memory.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <netdb.h>
void getMousePos(int &x, int &y)
{
x=0;
y=0;
}
std::vector<SFile> getFiles(const std::wstring &path)
{
std::string upath=Server->ConvertToUTF8(path);
std::vector<SFile> tmp;
DIR *dp;
struct dirent *dirp;
if((dp = opendir(upath.c_str())) == NULL)
{
Server->Log("No permission to access \""+upath+"\"", LL_ERROR);
return tmp;
}
upath+=os_file_sepn();
while ((dirp = readdir(dp)) != NULL)
{
SFile f;
f.name=widen(dirp->d_name);
if(f.name==L"." || f.name==L".." )
continue;
f.isdir=(dirp->d_type==DT_DIR);
if(!f.isdir || dirp->d_type==DT_UNKNOWN)
{
struct stat64 f_info;
int rc=stat64((upath+dirp->d_name).c_str(), &f_info);
if(rc==0)
{
if(dirp->d_type==DT_UNKNOWN)
{
f.isdir=S_ISDIR(f_info.st_mode);
if(!f.isdir)
{
f.last_modified=f_info.st_mtime;
f.size=f_info.st_size;
}
}
else
{
f.last_modified=f_info.st_mtime;
f.size=f_info.st_size;
}
}
else
{
Server->Log("No permission to stat \""+upath+dirp->d_name+"\"", LL_ERROR);
f.last_modified=0;
f.size=0;
}
}
else
{
f.last_modified=0;
f.size=0;
}
tmp.push_back(f);
}
closedir(dp);
std::sort(tmp.begin(), tmp.end());
return tmp;
}
void removeFile(const std::wstring &path)
{
unlink(wnarrow(path).c_str());
}
void moveFile(const std::wstring &src, const std::wstring &dst)
{
rename(wnarrow(src).c_str(), wnarrow(dst).c_str() );
}
bool isDirectory(const std::wstring &path)
{
struct stat64 f_info;
int rc=stat64(Server->ConvertToUTF8(path).c_str(), &f_info);
if(rc!=0)
{
Server->Log(L"No permission to access \""+path+L"\"", LL_ERROR);
return false;
}
if ( S_ISDIR(f_info.st_mode) )
{
return true;
}
else
{
return false;
}
}
int64 os_atoi64(const std::string &str)
{
return strtoll(str.c_str(), NULL, 10);
}
bool os_create_dir(const std::wstring &dir)
{
int rc=mkdir(Server->ConvertToUTF8(dir).c_str(), S_IRWXU | S_IRWXG );
return rc==0;
}
bool os_create_hardlink(const std::wstring &linkname, const std::wstring &fname)
{
int rc=link(Server->ConvertToUTF8(fname).c_str(), Server->ConvertToUTF8(linkname).c_str());
return rc==0;
}
int64 os_free_space(const std::wstring &path)
{
std::wstring cp=path;
if(path.size()==0)
return -1;
if(cp[cp.size()-1]=='/')
cp.erase(cp.size()-1, 1);
if(cp[cp.size()-1]!='/')
cp+='/';
struct statvfs64 buf;
int rc=statvfs64(Server->ConvertToUTF8(path).c_str(), &buf);
if(rc==0)
return buf.f_bsize*buf.f_bavail;
else
return -1;
}
bool os_directory_exists(const std::wstring &path)
{
//std::string upath=Server->ConvertToUTF8(path);
//DIR *dp=opendir(upath.c_str());
//closedir(dp);
//return dp!=NULL;
return isDirectory(path);
}
bool os_remove_nonempty_dir(const std::wstring &path)
{
std::string upath=Server->ConvertToUTF8(path);
std::vector<SFile> tmp;
DIR *dp;
struct dirent *dirp;
if((dp = opendir(upath.c_str())) == NULL)
{
Server->Log("No permission to access \""+upath+"\"", LL_ERROR);
return false;
}
bool ok=true;
std::vector<std::wstring> subdirs;
while ((dirp = readdir(dp)) != NULL)
{
if( (std::string)dirp->d_name!="." && (std::string)dirp->d_name!=".." )
{
if(dirp->d_type==DT_UNKNOWN)
{
struct stat f_info;
int rc=stat((upath+"/"+(std::string)dirp->d_name).c_str(), &f_info);
if(rc==0)
{
if(S_ISDIR(f_info.st_mode) )
{
subdirs.push_back(Server->ConvertToUnicode(dirp->d_name));
}
else
{
if(unlink((upath+"/"+(std::string)dirp->d_name).c_str())!=0)
{
Server->Log("Error deleting file \""+upath+"/"+(std::string)dirp->d_name+"\"", LL_ERROR);
}
}
}
else
{
Server->Log("No permission to stat \""+upath+dirp->d_name+"\"", LL_ERROR);
}
}
else if(dirp->d_type==DT_DIR )
{
subdirs.push_back(Server->ConvertToUnicode(dirp->d_name));
}
else
{
if(unlink((upath+"/"+(std::string)dirp->d_name).c_str())!=0)
{
Server->Log("Error deleting file \""+upath+"/"+(std::string)dirp->d_name+"\"", LL_ERROR);
}
}
}
}
closedir(dp);
for(size_t i=0;i<subdirs.size();++i)
{
bool b=os_remove_nonempty_dir(path+L"/"+subdirs[i]);
if(!b)
ok=false;
}
if(rmdir(upath.c_str())!=0)
{
Server->Log("Error deleting directory \""+upath+"\"", LL_ERROR);
}
return ok;
}
std::wstring os_file_sep(void)
{
return L"/";
}
std::string os_file_sepn(void)
{
return "/";
}
bool os_link_symbolic(const std::wstring &target, const std::wstring &lname)
{
return symlink(Server->ConvertToUTF8(target).c_str(), Server->ConvertToUTF8(lname).c_str())==0;
}
bool os_lookuphostname(std::string pServer, unsigned int *dest)
{
const char* host=pServer.c_str();
unsigned int addr = inet_addr(host);
if (addr != INADDR_NONE)
{
*dest = addr;
}
else
{
hostent* hp = gethostbyname(host);
if (hp != 0)
{
in_addr tmp;
memcpy(&tmp, hp->h_addr, hp->h_length );
*dest=tmp.s_addr;
}
else
{
return false;
}
}
return true;
}<commit_msg>Added Logging to directory removal<commit_after>/*************************************************************************
* UrBackup - Client/Server backup system
* Copyright (C) 2011 Martin Raiber
*
* 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 3 of the License, or
* (at your option) any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
**************************************************************************/
#include "os_functions.h"
#include "../stringtools.h"
#include "../Interface/Server.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/statvfs.h>
#include <dirent.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <algorithm>
#include <memory.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <errno.h>
void getMousePos(int &x, int &y)
{
x=0;
y=0;
}
std::vector<SFile> getFiles(const std::wstring &path)
{
std::string upath=Server->ConvertToUTF8(path);
std::vector<SFile> tmp;
DIR *dp;
struct dirent *dirp;
if((dp = opendir(upath.c_str())) == NULL)
{
Server->Log("No permission to access \""+upath+"\"", LL_ERROR);
return tmp;
}
upath+=os_file_sepn();
while ((dirp = readdir(dp)) != NULL)
{
SFile f;
f.name=widen(dirp->d_name);
if(f.name==L"." || f.name==L".." )
continue;
f.isdir=(dirp->d_type==DT_DIR);
if(!f.isdir || dirp->d_type==DT_UNKNOWN)
{
struct stat64 f_info;
int rc=stat64((upath+dirp->d_name).c_str(), &f_info);
if(rc==0)
{
if(dirp->d_type==DT_UNKNOWN)
{
f.isdir=S_ISDIR(f_info.st_mode);
if(!f.isdir)
{
f.last_modified=f_info.st_mtime;
f.size=f_info.st_size;
}
}
else
{
f.last_modified=f_info.st_mtime;
f.size=f_info.st_size;
}
}
else
{
Server->Log("No permission to stat \""+upath+dirp->d_name+"\"", LL_ERROR);
f.last_modified=0;
f.size=0;
}
}
else
{
f.last_modified=0;
f.size=0;
}
tmp.push_back(f);
}
closedir(dp);
std::sort(tmp.begin(), tmp.end());
return tmp;
}
void removeFile(const std::wstring &path)
{
unlink(wnarrow(path).c_str());
}
void moveFile(const std::wstring &src, const std::wstring &dst)
{
rename(wnarrow(src).c_str(), wnarrow(dst).c_str() );
}
bool isDirectory(const std::wstring &path)
{
struct stat64 f_info;
int rc=stat64(Server->ConvertToUTF8(path).c_str(), &f_info);
if(rc!=0)
{
Server->Log(L"No permission to access \""+path+L"\" (isdir)", LL_DEBUG);
return false;
}
if ( S_ISDIR(f_info.st_mode) )
{
return true;
}
else
{
return false;
}
}
int64 os_atoi64(const std::string &str)
{
return strtoll(str.c_str(), NULL, 10);
}
bool os_create_dir(const std::wstring &dir)
{
int rc=mkdir(Server->ConvertToUTF8(dir).c_str(), S_IRWXU | S_IRWXG );
return rc==0;
}
bool os_create_hardlink(const std::wstring &linkname, const std::wstring &fname)
{
int rc=link(Server->ConvertToUTF8(fname).c_str(), Server->ConvertToUTF8(linkname).c_str());
return rc==0;
}
int64 os_free_space(const std::wstring &path)
{
std::wstring cp=path;
if(path.size()==0)
return -1;
if(cp[cp.size()-1]=='/')
cp.erase(cp.size()-1, 1);
if(cp[cp.size()-1]!='/')
cp+='/';
struct statvfs64 buf;
int rc=statvfs64(Server->ConvertToUTF8(path).c_str(), &buf);
if(rc==0)
return buf.f_bsize*buf.f_bavail;
else
return -1;
}
bool os_directory_exists(const std::wstring &path)
{
//std::string upath=Server->ConvertToUTF8(path);
//DIR *dp=opendir(upath.c_str());
//closedir(dp);
//return dp!=NULL;
return isDirectory(path);
}
bool os_remove_nonempty_dir(const std::wstring &path)
{
std::string upath=Server->ConvertToUTF8(path);
std::vector<SFile> tmp;
DIR *dp;
struct dirent *dirp;
if((dp = opendir(upath.c_str())) == NULL)
{
Server->Log("No permission to access \""+upath+"\"", LL_ERROR);
return false;
}
bool ok=true;
std::vector<std::wstring> subdirs;
while ((dirp = readdir(dp)) != NULL)
{
if( (std::string)dirp->d_name!="." && (std::string)dirp->d_name!=".." )
{
if(dirp->d_type==DT_UNKNOWN)
{
struct stat64 f_info;
int rc=stat64((upath+"/"+(std::string)dirp->d_name).c_str(), &f_info);
if(rc==0)
{
if(S_ISDIR(f_info.st_mode) )
{
subdirs.push_back(Server->ConvertToUnicode(dirp->d_name));
}
else
{
if(unlink((upath+"/"+(std::string)dirp->d_name).c_str())!=0)
{
Server->Log("Error deleting file \""+upath+"/"+(std::string)dirp->d_name+"\"", LL_ERROR);
}
}
}
else
{
std::string e=nconvert(errno);
switch(errno)
{
case EACCES: e="EACCES"; break;
case EBADF: e="EBADF"; break;
case EFAULT: e="EFAULT"; break;
case ELOOP: e="ELOOP"; break;
case ENAMETOOLONG: e="ENAMETOOLONG"; break;
case ENOENT: e="ENOENT"; break;
case ENOMEM: e="ENOMEM"; break;
case ENOTDIR: e="ENOTDIR"; break;
}
Server->Log("No permission to stat \""+upath+"/"+dirp->d_name+"\" error: "+e, LL_ERROR);
}
}
else if(dirp->d_type==DT_DIR )
{
subdirs.push_back(Server->ConvertToUnicode(dirp->d_name));
}
else
{
if(unlink((upath+"/"+(std::string)dirp->d_name).c_str())!=0)
{
Server->Log("Error deleting file \""+upath+"/"+(std::string)dirp->d_name+"\"", LL_ERROR);
}
}
}
}
closedir(dp);
for(size_t i=0;i<subdirs.size();++i)
{
bool b=os_remove_nonempty_dir(path+L"/"+subdirs[i]);
if(!b)
ok=false;
}
if(rmdir(upath.c_str())!=0)
{
Server->Log("Error deleting directory \""+upath+"\"", LL_ERROR);
}
return ok;
}
std::wstring os_file_sep(void)
{
return L"/";
}
std::string os_file_sepn(void)
{
return "/";
}
bool os_link_symbolic(const std::wstring &target, const std::wstring &lname)
{
return symlink(Server->ConvertToUTF8(target).c_str(), Server->ConvertToUTF8(lname).c_str())==0;
}
bool os_lookuphostname(std::string pServer, unsigned int *dest)
{
const char* host=pServer.c_str();
unsigned int addr = inet_addr(host);
if (addr != INADDR_NONE)
{
*dest = addr;
}
else
{
hostent* hp = gethostbyname(host);
if (hp != 0)
{
in_addr tmp;
memcpy(&tmp, hp->h_addr, hp->h_length );
*dest=tmp.s_addr;
}
else
{
return false;
}
}
return true;
}<|endoftext|>
|
<commit_before><commit_msg>Removing second SetState from main, was just using it for testing.<commit_after><|endoftext|>
|
<commit_before>#include <iostream>
#include "Dominio.h"
#include "Entidades.h"
#include "TestesDominio.h"
#include "TestesEntidades.h"
using namespace std;
int main()
{
cout << "Testes de Dominios" << endl;
TUNome testeNome;
switch(testeNome.run()){
case TUNome::SUCESSO: cout << "Nome - SUCESSO" << endl;
break;
case TUNome::FALHA : cout << "Nome - FALHA" << endl;
break;
}
TUTelefone testeTelefone;
switch(testeTelefone.run()){
case TUTelefone::SUCESSO: cout << "Telefone - SUCESSO" << endl;
break;
case TUTelefone::FALHA : cout << "Telefone - FALHA" << endl;
break;
}
TUTitulo testeTitulo;
switch(testeTitulo.run()){
case TUTitulo::SUCESSO: cout << "Titulo - SUCESSO" << endl;
break;
case TUTitulo::FALHA : cout << "Titulo - FALHA" << endl;
break;
}
TUCodigo testeCodigo;
switch(testeCodigo.run()){
case TUCodigo::SUCESSO: cout << "Codigo - SUCESSO" << endl;
break;
case TUCodigo::FALHA : cout << "Codigo - FALHA" << endl;
break;
}
TUGeneroLiterario testeGeneroLiterario;
switch(testeGeneroLiterario.run()){
case TUGeneroLiterario::SUCESSO: cout << "Genero Literario - SUCESSO" << endl;
break;
case TUGeneroLiterario::FALHA : cout << "Genero Literario - FALHA" << endl;
break;
}
TUApelido testeApelido;
switch(testeApelido.run()){
case TUApelido::SUCESSO: cout << "Apelido - SUCESSO" << endl;
break;
case TUApelido::FALHA : cout << "Apelido - FALHA" << endl;
break;
}
TUSenha testeSenha;
switch(testeSenha.run()){
case TUSenha::SUCESSO: cout << "Senha - SUCESSO" << endl;
break;
case TUSenha::FALHA : cout << "Senha - FALHA" << endl;
break;
}
TUData testeData;
switch(testeData.run()){
case TUData::SUCESSO: cout << "Data - SUCESSO" << endl;
break;
case TUData::FALHA : cout << "Data - FALHA" << endl;
break;
}
TUTexto testeTexto;
switch(testeTexto.run()){
case TUTexto::SUCESSO: cout << "Texto - SUCESSO" << endl;
break;
case TUTexto::FALHA : cout << "Texto - FALHA" << endl;
break;
}
cout << "Testes de Entidades" << endl;
TUUsuario testeUsuario;
switch(testeUsuario.run()){
case TUUsuario::SUCESSO: cout << "Usuario - SUCESSO" << endl;
break;
case TUUsuario::FALHA : cout << "Usuario - FALHA" << endl;
break;
}
TUResenha testeResenha;
switch(testeResenha.run()){
case TUResenha::SUCESSO: cout << "Resenha - SUCESSO" << endl;
break;
case TUResenha::FALHA : cout << "Resenha - FALHA" << endl;
break;
}
TULivro testeLivro;
switch(testeLivro.run()){
case TULivro::SUCESSO: cout << "Livro - SUCESSO" << endl;
break;
case TULivro::FALHA : cout << "Livro - FALHA" << endl;
break;
}
return 0;
}
<commit_msg>adicionada uma quebra de linha no print dos testes<commit_after>#include <iostream>
#include "Dominio.h"
#include "Entidades.h"
#include "TestesDominio.h"
#include "TestesEntidades.h"
using namespace std;
int main()
{
cout << "Testes de Dominios" << endl;
TUNome testeNome;
switch(testeNome.run()){
case TUNome::SUCESSO: cout << "Nome - SUCESSO" << endl;
break;
case TUNome::FALHA : cout << "Nome - FALHA" << endl;
break;
}
TUTelefone testeTelefone;
switch(testeTelefone.run()){
case TUTelefone::SUCESSO: cout << "Telefone - SUCESSO" << endl;
break;
case TUTelefone::FALHA : cout << "Telefone - FALHA" << endl;
break;
}
TUTitulo testeTitulo;
switch(testeTitulo.run()){
case TUTitulo::SUCESSO: cout << "Titulo - SUCESSO" << endl;
break;
case TUTitulo::FALHA : cout << "Titulo - FALHA" << endl;
break;
}
TUCodigo testeCodigo;
switch(testeCodigo.run()){
case TUCodigo::SUCESSO: cout << "Codigo - SUCESSO" << endl;
break;
case TUCodigo::FALHA : cout << "Codigo - FALHA" << endl;
break;
}
TUGeneroLiterario testeGeneroLiterario;
switch(testeGeneroLiterario.run()){
case TUGeneroLiterario::SUCESSO: cout << "Genero Literario - SUCESSO" << endl;
break;
case TUGeneroLiterario::FALHA : cout << "Genero Literario - FALHA" << endl;
break;
}
TUApelido testeApelido;
switch(testeApelido.run()){
case TUApelido::SUCESSO: cout << "Apelido - SUCESSO" << endl;
break;
case TUApelido::FALHA : cout << "Apelido - FALHA" << endl;
break;
}
TUSenha testeSenha;
switch(testeSenha.run()){
case TUSenha::SUCESSO: cout << "Senha - SUCESSO" << endl;
break;
case TUSenha::FALHA : cout << "Senha - FALHA" << endl;
break;
}
TUData testeData;
switch(testeData.run()){
case TUData::SUCESSO: cout << "Data - SUCESSO" << endl;
break;
case TUData::FALHA : cout << "Data - FALHA" << endl;
break;
}
TUTexto testeTexto;
switch(testeTexto.run()){
case TUTexto::SUCESSO: cout << "Texto - SUCESSO" << endl;
break;
case TUTexto::FALHA : cout << "Texto - FALHA" << endl;
break;
}
cout << endl;
cout << "Testes de Entidades" << endl;
TUUsuario testeUsuario;
switch(testeUsuario.run()){
case TUUsuario::SUCESSO: cout << "Usuario - SUCESSO" << endl;
break;
case TUUsuario::FALHA : cout << "Usuario - FALHA" << endl;
break;
}
TUResenha testeResenha;
switch(testeResenha.run()){
case TUResenha::SUCESSO: cout << "Resenha - SUCESSO" << endl;
break;
case TUResenha::FALHA : cout << "Resenha - FALHA" << endl;
break;
}
TULivro testeLivro;
switch(testeLivro.run()){
case TULivro::SUCESSO: cout << "Livro - SUCESSO" << endl;
break;
case TULivro::FALHA : cout << "Livro - FALHA" << endl;
break;
}
return 0;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org 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 version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include "sal/config.h"
#include "sal/macros.h"
#include <cstddef>
#include <functional>
#include <memory>
#include <new>
#include <boost/unordered_map.hpp>
#include "com/sun/star/lang/XMain.hpp"
#include "com/sun/star/lang/XMultiComponentFactory.hpp"
#include "com/sun/star/uno/Exception.hpp"
#include "com/sun/star/uno/Reference.hxx"
#include "com/sun/star/uno/RuntimeException.hpp"
#include "com/sun/star/uno/Sequence.hxx"
#include "com/sun/star/uno/XComponentContext.hpp"
#include "com/sun/star/uno/XInterface.hpp"
#include "cppuhelper/factory.hxx"
#include "cppuhelper/implbase1.hxx"
#include "cppuhelper/implementationentry.hxx"
#include "cppuhelper/interfacecontainer.hxx"
#include "cppuhelper/unourl.hxx"
#include "cppuhelper/weak.hxx"
#include "osl/mutex.hxx"
#include "osl/thread.h"
#include "rtl/malformeduriexception.hxx"
#include "rtl/string.h"
#include "rtl/ustrbuf.hxx"
#include "rtl/ustring.h"
#include "rtl/ustring.hxx"
#include "sal/types.h"
#include "salhelper/simplereferenceobject.hxx"
#include "uno/current_context.hxx"
#include "uno/environment.h"
#include "uno/lbnames.h"
#include "test/types/CppTest.hpp"
#include "test/types/JavaTest.hpp"
#include "test/types/TestException.hpp"
#include "test/types/XTest.hpp"
namespace css = ::com::sun::star;
namespace {
class Service: public ::cppu::WeakImplHelper1< ::css::lang::XMain > {
public:
explicit Service(
::css::uno::Reference< ::css::uno::XComponentContext > const & context):
context_(context) {}
virtual ::sal_Int32 SAL_CALL run(
::css::uno::Sequence< ::rtl::OUString > const &)
throw (::css::uno::RuntimeException);
private:
Service(Service &); // not defined
void operator =(Service &); // not defined
virtual ~Service() {}
void test(
::css::uno::Reference< test::types::XTest > const & test,
::rtl::OUString const & name);
::css::uno::Reference< ::css::uno::XComponentContext > context_;
};
::sal_Int32 Service::run(::css::uno::Sequence< ::rtl::OUString > const &)
throw (::css::uno::RuntimeException)
{
osl_getThreadIdentifier(0); // check for sal
(new salhelper::SimpleReferenceObject)->release(); // check for salhelper
css::uno::getCurrentContext(); // check for cppu
try { // check for cppuhelper
std::auto_ptr< cppu::UnoUrl > dummy(new cppu::UnoUrl(rtl::OUString()));
} catch (rtl::MalformedUriException &) {}
{ // check for stlport
osl::Mutex m;
std::auto_ptr< cppu::OMultiTypeInterfaceContainerHelperVar<
int, std::hash< int >, std::equal_to< int > > > dummy(
new cppu::OMultiTypeInterfaceContainerHelperVar<
int, std::hash< int >, std::equal_to< int > >(m));
}
static char const * const services[] = {
"com.sun.star.beans.Introspection",
"com.sun.star.bridge.Bridge",
"com.sun.star.bridge.BridgeFactory",
"com.sun.star.bridge.IiopBridge",
"com.sun.star.bridge.UnoUrlResolver",
"com.sun.star.bridge.UrpBridge",
"com.sun.star.connection.Acceptor",
"com.sun.star.connection.Connector",
"com.sun.star.io.DataInputStream",
"com.sun.star.io.DataOutputStream",
"com.sun.star.io.MarkableInputStream",
"com.sun.star.io.MarkableOutputStream",
"com.sun.star.io.ObjectInputStream",
"com.sun.star.io.ObjectOutputStream",
"com.sun.star.io.Pipe",
"com.sun.star.io.Pump",
"com.sun.star.io.TextInputStream",
"com.sun.star.io.TextOutputStream",
"com.sun.star.java.JavaVirtualMachine",
"com.sun.star.lang.MultiServiceFactory",
"com.sun.star.lang.RegistryServiceManager",
"com.sun.star.lang.ServiceManager",
"com.sun.star.loader.Java",
"com.sun.star.loader.Java2",
"com.sun.star.loader.SharedLibrary",
"com.sun.star.reflection.CoreReflection",
"com.sun.star.reflection.ProxyFactory",
"com.sun.star.reflection.TypeDescriptionManager",
"com.sun.star.reflection.TypeDescriptionProvider",
"com.sun.star.registry.ImplementationRegistration",
"com.sun.star.registry.NestedRegistry",
"com.sun.star.registry.SimpleRegistry",
"com.sun.star.script.Converter",
"com.sun.star.script.Invocation",
"com.sun.star.script.InvocationAdapterFactory",
"com.sun.star.security.AccessController",
"com.sun.star.security.Policy",
"com.sun.star.uno.NamingService",
"com.sun.star.uri.ExternalUriReferenceTranslator",
"com.sun.star.uri.UriReferenceFactory",
"com.sun.star.uri.UriSchemeParser_vndDOTsunDOTstarDOTscript",
"com.sun.star.uri.VndSunStarPkgUrlReferenceFactory"
};
::css::uno::Reference< ::css::lang::XMultiComponentFactory > manager(
context_->getServiceManager());
if (!manager.is()) {
throw ::css::uno::RuntimeException(
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("no service manager")),
static_cast< ::cppu::OWeakObject * >(this));
}
for (::std::size_t i = 0; i < SAL_N_ELEMENTS(services); ++i) {
::css::uno::Reference< ::css::uno::XInterface > instance;
try {
instance = manager->createInstanceWithContext(
::rtl::OUString::createFromAscii(services[i]), context_);
} catch (::css::uno::RuntimeException &) {
throw;
} catch (::css::uno::Exception &) {
throw ::css::uno::RuntimeException(
::rtl::OUString(
RTL_CONSTASCII_USTRINGPARAM("error creating instance")),
static_cast< ::cppu::OWeakObject * >(this));
}
if (!instance.is()) {
throw ::css::uno::RuntimeException(
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("no instance")),
static_cast< ::cppu::OWeakObject * >(this));
}
}
static char const * const singletons[] = {
"com.sun.star.util.theMacroExpander" };
for (::std::size_t i = 0; i < SAL_N_ELEMENTS(singletons); ++i)
{
::rtl::OUStringBuffer b;
b.appendAscii(RTL_CONSTASCII_STRINGPARAM("/singletons/"));
b.appendAscii(singletons[i]);
::css::uno::Reference< ::css::uno::XInterface > instance(
context_->getValueByName(b.makeStringAndClear()),
::css::uno::UNO_QUERY_THROW);
}
test(
::test::types::CppTest::create(context_),
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("test.types.CppTest")));
test(
::test::types::JavaTest::create(context_),
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("test.types.JavaTest")));
return 0;
}
void Service::test(
::css::uno::Reference< test::types::XTest > const & test,
::rtl::OUString const & name)
{
bool ok = false;
try {
test->throwException();
} catch (::test::types::TestException &) {
ok = true;
}
if (!ok) {
throw ::css::uno::RuntimeException(
(name
+ ::rtl::OUString(
RTL_CONSTASCII_USTRINGPARAM(".throwException failed"))),
static_cast< ::cppu::OWeakObject * >(this));
}
}
namespace CppMain {
::css::uno::Reference< ::css::uno::XInterface > create(
::css::uno::Reference< ::css::uno::XComponentContext > const & context)
SAL_THROW((::css::uno::Exception))
{
try {
return static_cast< ::cppu::OWeakObject * >(new Service(context));
} catch (::std::bad_alloc &) {
throw ::css::uno::RuntimeException(
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("std::bad_alloc")),
::css::uno::Reference< ::css::uno::XInterface >());
}
}
::rtl::OUString getImplementationName() {
return ::rtl::OUString(
RTL_CONSTASCII_USTRINGPARAM("test.cpp.cppmain.Component"));
}
::css::uno::Sequence< ::rtl::OUString > getSupportedServiceNames() {
return ::css::uno::Sequence< ::rtl::OUString >();
}
}
::cppu::ImplementationEntry entries[] = {
{ CppMain::create, CppMain::getImplementationName,
CppMain::getSupportedServiceNames, ::cppu::createSingleComponentFactory,
0, 0 },
{ 0, 0, 0, 0, 0, 0 } };
}
extern "C" ::sal_Bool SAL_CALL component_writeInfo(
void * serviceManager, void * registryKey)
{
return ::cppu::component_writeInfoHelper(
serviceManager, registryKey, entries);
}
extern "C" void * SAL_CALL component_getFactory(
char const * implName, void * serviceManager, void * registryKey)
{
return ::cppu::component_getFactoryHelper(
implName, serviceManager, registryKey, entries);
}
extern "C" void SAL_CALL component_getImplementationEnvironment(
char const ** envTypeName, ::uno_Environment **)
{
*envTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
}
<commit_msg>std::hash -> boost::hash<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org 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 version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include "sal/config.h"
#include "sal/macros.h"
#include <cstddef>
#include <functional>
#include <memory>
#include <new>
#include <boost/unordered_map.hpp>
#include "com/sun/star/lang/XMain.hpp"
#include "com/sun/star/lang/XMultiComponentFactory.hpp"
#include "com/sun/star/uno/Exception.hpp"
#include "com/sun/star/uno/Reference.hxx"
#include "com/sun/star/uno/RuntimeException.hpp"
#include "com/sun/star/uno/Sequence.hxx"
#include "com/sun/star/uno/XComponentContext.hpp"
#include "com/sun/star/uno/XInterface.hpp"
#include "cppuhelper/factory.hxx"
#include "cppuhelper/implbase1.hxx"
#include "cppuhelper/implementationentry.hxx"
#include "cppuhelper/interfacecontainer.hxx"
#include "cppuhelper/unourl.hxx"
#include "cppuhelper/weak.hxx"
#include "osl/mutex.hxx"
#include "osl/thread.h"
#include "rtl/malformeduriexception.hxx"
#include "rtl/string.h"
#include "rtl/ustrbuf.hxx"
#include "rtl/ustring.h"
#include "rtl/ustring.hxx"
#include "sal/types.h"
#include "salhelper/simplereferenceobject.hxx"
#include "uno/current_context.hxx"
#include "uno/environment.h"
#include "uno/lbnames.h"
#include "test/types/CppTest.hpp"
#include "test/types/JavaTest.hpp"
#include "test/types/TestException.hpp"
#include "test/types/XTest.hpp"
namespace css = ::com::sun::star;
namespace {
class Service: public ::cppu::WeakImplHelper1< ::css::lang::XMain > {
public:
explicit Service(
::css::uno::Reference< ::css::uno::XComponentContext > const & context):
context_(context) {}
virtual ::sal_Int32 SAL_CALL run(
::css::uno::Sequence< ::rtl::OUString > const &)
throw (::css::uno::RuntimeException);
private:
Service(Service &); // not defined
void operator =(Service &); // not defined
virtual ~Service() {}
void test(
::css::uno::Reference< test::types::XTest > const & test,
::rtl::OUString const & name);
::css::uno::Reference< ::css::uno::XComponentContext > context_;
};
::sal_Int32 Service::run(::css::uno::Sequence< ::rtl::OUString > const &)
throw (::css::uno::RuntimeException)
{
osl_getThreadIdentifier(0); // check for sal
(new salhelper::SimpleReferenceObject)->release(); // check for salhelper
css::uno::getCurrentContext(); // check for cppu
try { // check for cppuhelper
std::auto_ptr< cppu::UnoUrl > dummy(new cppu::UnoUrl(rtl::OUString()));
} catch (rtl::MalformedUriException &) {}
{ // check for stlport
osl::Mutex m;
std::auto_ptr< cppu::OMultiTypeInterfaceContainerHelperVar<
int, boost::hash< int >, std::equal_to< int > > > dummy(
new cppu::OMultiTypeInterfaceContainerHelperVar<
int, boost::hash< int >, std::equal_to< int > >(m));
}
static char const * const services[] = {
"com.sun.star.beans.Introspection",
"com.sun.star.bridge.Bridge",
"com.sun.star.bridge.BridgeFactory",
"com.sun.star.bridge.IiopBridge",
"com.sun.star.bridge.UnoUrlResolver",
"com.sun.star.bridge.UrpBridge",
"com.sun.star.connection.Acceptor",
"com.sun.star.connection.Connector",
"com.sun.star.io.DataInputStream",
"com.sun.star.io.DataOutputStream",
"com.sun.star.io.MarkableInputStream",
"com.sun.star.io.MarkableOutputStream",
"com.sun.star.io.ObjectInputStream",
"com.sun.star.io.ObjectOutputStream",
"com.sun.star.io.Pipe",
"com.sun.star.io.Pump",
"com.sun.star.io.TextInputStream",
"com.sun.star.io.TextOutputStream",
"com.sun.star.java.JavaVirtualMachine",
"com.sun.star.lang.MultiServiceFactory",
"com.sun.star.lang.RegistryServiceManager",
"com.sun.star.lang.ServiceManager",
"com.sun.star.loader.Java",
"com.sun.star.loader.Java2",
"com.sun.star.loader.SharedLibrary",
"com.sun.star.reflection.CoreReflection",
"com.sun.star.reflection.ProxyFactory",
"com.sun.star.reflection.TypeDescriptionManager",
"com.sun.star.reflection.TypeDescriptionProvider",
"com.sun.star.registry.ImplementationRegistration",
"com.sun.star.registry.NestedRegistry",
"com.sun.star.registry.SimpleRegistry",
"com.sun.star.script.Converter",
"com.sun.star.script.Invocation",
"com.sun.star.script.InvocationAdapterFactory",
"com.sun.star.security.AccessController",
"com.sun.star.security.Policy",
"com.sun.star.uno.NamingService",
"com.sun.star.uri.ExternalUriReferenceTranslator",
"com.sun.star.uri.UriReferenceFactory",
"com.sun.star.uri.UriSchemeParser_vndDOTsunDOTstarDOTscript",
"com.sun.star.uri.VndSunStarPkgUrlReferenceFactory"
};
::css::uno::Reference< ::css::lang::XMultiComponentFactory > manager(
context_->getServiceManager());
if (!manager.is()) {
throw ::css::uno::RuntimeException(
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("no service manager")),
static_cast< ::cppu::OWeakObject * >(this));
}
for (::std::size_t i = 0; i < SAL_N_ELEMENTS(services); ++i) {
::css::uno::Reference< ::css::uno::XInterface > instance;
try {
instance = manager->createInstanceWithContext(
::rtl::OUString::createFromAscii(services[i]), context_);
} catch (::css::uno::RuntimeException &) {
throw;
} catch (::css::uno::Exception &) {
throw ::css::uno::RuntimeException(
::rtl::OUString(
RTL_CONSTASCII_USTRINGPARAM("error creating instance")),
static_cast< ::cppu::OWeakObject * >(this));
}
if (!instance.is()) {
throw ::css::uno::RuntimeException(
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("no instance")),
static_cast< ::cppu::OWeakObject * >(this));
}
}
static char const * const singletons[] = {
"com.sun.star.util.theMacroExpander" };
for (::std::size_t i = 0; i < SAL_N_ELEMENTS(singletons); ++i)
{
::rtl::OUStringBuffer b;
b.appendAscii(RTL_CONSTASCII_STRINGPARAM("/singletons/"));
b.appendAscii(singletons[i]);
::css::uno::Reference< ::css::uno::XInterface > instance(
context_->getValueByName(b.makeStringAndClear()),
::css::uno::UNO_QUERY_THROW);
}
test(
::test::types::CppTest::create(context_),
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("test.types.CppTest")));
test(
::test::types::JavaTest::create(context_),
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("test.types.JavaTest")));
return 0;
}
void Service::test(
::css::uno::Reference< test::types::XTest > const & test,
::rtl::OUString const & name)
{
bool ok = false;
try {
test->throwException();
} catch (::test::types::TestException &) {
ok = true;
}
if (!ok) {
throw ::css::uno::RuntimeException(
(name
+ ::rtl::OUString(
RTL_CONSTASCII_USTRINGPARAM(".throwException failed"))),
static_cast< ::cppu::OWeakObject * >(this));
}
}
namespace CppMain {
::css::uno::Reference< ::css::uno::XInterface > create(
::css::uno::Reference< ::css::uno::XComponentContext > const & context)
SAL_THROW((::css::uno::Exception))
{
try {
return static_cast< ::cppu::OWeakObject * >(new Service(context));
} catch (::std::bad_alloc &) {
throw ::css::uno::RuntimeException(
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("std::bad_alloc")),
::css::uno::Reference< ::css::uno::XInterface >());
}
}
::rtl::OUString getImplementationName() {
return ::rtl::OUString(
RTL_CONSTASCII_USTRINGPARAM("test.cpp.cppmain.Component"));
}
::css::uno::Sequence< ::rtl::OUString > getSupportedServiceNames() {
return ::css::uno::Sequence< ::rtl::OUString >();
}
}
::cppu::ImplementationEntry entries[] = {
{ CppMain::create, CppMain::getImplementationName,
CppMain::getSupportedServiceNames, ::cppu::createSingleComponentFactory,
0, 0 },
{ 0, 0, 0, 0, 0, 0 } };
}
extern "C" ::sal_Bool SAL_CALL component_writeInfo(
void * serviceManager, void * registryKey)
{
return ::cppu::component_writeInfoHelper(
serviceManager, registryKey, entries);
}
extern "C" void * SAL_CALL component_getFactory(
char const * implName, void * serviceManager, void * registryKey)
{
return ::cppu::component_getFactoryHelper(
implName, serviceManager, registryKey, entries);
}
extern "C" void SAL_CALL component_getImplementationEnvironment(
char const ** envTypeName, ::uno_Environment **)
{
*envTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/plugin_service_impl.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/command_line.h"
#include "base/path_service.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/testing_profile.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/resource_context.h"
#include "content/public/common/content_switches.h"
#include "content/test/test_browser_thread.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "webkit/plugins/npapi/plugin_list.h"
using content::BrowserThread;
namespace {
const char kNPAPITestPluginMimeType[] = "application/vnd.npapi-test";
void OpenChannel(PluginProcessHost::Client* client) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
// Start opening the channel
PluginServiceImpl::GetInstance()->OpenChannelToNpapiPlugin(
0, 0, GURL(), GURL(), kNPAPITestPluginMimeType, client);
}
// Mock up of the Client and the Listener classes that would supply the
// communication channel with the plugin.
class MockPluginProcessHostClient : public PluginProcessHost::Client,
public IPC::Channel::Listener {
public:
MockPluginProcessHostClient(content::ResourceContext* context)
: context_(context),
channel_(NULL),
set_plugin_info_called_(false) {
}
virtual ~MockPluginProcessHostClient() {
if (channel_)
BrowserThread::DeleteSoon(BrowserThread::IO, FROM_HERE, channel_);
}
// Client implementation.
virtual int ID() OVERRIDE { return 42; }
virtual bool OffTheRecord() OVERRIDE { return false; }
virtual content::ResourceContext* GetResourceContext() OVERRIDE {
return context_;
}
virtual void OnFoundPluginProcessHost(PluginProcessHost* host) OVERRIDE {}
virtual void OnSentPluginChannelRequest() OVERRIDE {}
virtual void OnChannelOpened(const IPC::ChannelHandle& handle) OVERRIDE {
ASSERT_TRUE(BrowserThread::CurrentlyOn(BrowserThread::IO));
ASSERT_TRUE(set_plugin_info_called_);
ASSERT_TRUE(!channel_);
channel_ = new IPC::Channel(handle, IPC::Channel::MODE_CLIENT, this);
ASSERT_TRUE(channel_->Connect());
}
void SetPluginInfo(const webkit::WebPluginInfo& info) OVERRIDE {
ASSERT_TRUE(info.mime_types.size());
ASSERT_EQ(kNPAPITestPluginMimeType, info.mime_types[0].mime_type);
set_plugin_info_called_ = true;
}
MOCK_METHOD0(OnError, void());
// Listener implementation.
MOCK_METHOD1(OnMessageReceived, bool(const IPC::Message& message));
void OnChannelConnected(int32 peer_pid) OVERRIDE {
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
MessageLoop::QuitClosure());
}
MOCK_METHOD0(OnChannelError, void());
MOCK_METHOD0(OnChannelDenied, void());
MOCK_METHOD0(OnChannelListenError, void());
private:
content::ResourceContext* context_;
IPC::Channel* channel_;
bool set_plugin_info_called_;
DISALLOW_COPY_AND_ASSIGN(MockPluginProcessHostClient);
};
class PluginServiceTest : public InProcessBrowserTest {
public:
PluginServiceTest() : InProcessBrowserTest() { }
virtual void SetUpCommandLine(CommandLine* command_line) {
#ifdef OS_MACOSX
FilePath browser_directory;
PathService::Get(base::DIR_MODULE, &browser_directory);
command_line->AppendSwitchPath(switches::kExtraPluginDir,
browser_directory.AppendASCII("plugins"));
#endif
}
};
// Try to open a channel to the test plugin. Minimal plugin process spawning
// test for the PluginService interface.
IN_PROC_BROWSER_TEST_F(PluginServiceTest, OpenChannelToPlugin) {
::testing::StrictMock<MockPluginProcessHostClient> mock_client(
browser()->profile()->GetResourceContext());
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::Bind(&OpenChannel, &mock_client));
ui_test_utils::RunMessageLoop();
}
// A strict mock that fails if any of the methods are called. They shouldn't be
// called since the request should get canceled before then.
class MockCanceledPluginServiceClient : public PluginProcessHost::Client {
public:
MockCanceledPluginServiceClient(content::ResourceContext* context)
: context_(context),
get_resource_context_called_(false) {
}
virtual ~MockCanceledPluginServiceClient() {}
// Client implementation.
MOCK_METHOD0(ID, int());
virtual content::ResourceContext* GetResourceContext() OVERRIDE {
get_resource_context_called_ = true;
return context_;
}
MOCK_METHOD0(OffTheRecord, bool());
MOCK_METHOD1(OnFoundPluginProcessHost, void(PluginProcessHost* host));
MOCK_METHOD0(OnSentPluginChannelRequest, void());
MOCK_METHOD1(OnChannelOpened, void(const IPC::ChannelHandle& handle));
MOCK_METHOD1(SetPluginInfo, void(const webkit::WebPluginInfo& info));
MOCK_METHOD0(OnError, void());
bool get_resource_context_called() const {
return get_resource_context_called_;
}
private:
content::ResourceContext* context_;
bool get_resource_context_called_;
DISALLOW_COPY_AND_ASSIGN(MockCanceledPluginServiceClient);
};
void QuitUIMessageLoopFromIOThread() {
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
MessageLoop::QuitClosure());
}
void OpenChannelAndThenCancel(PluginProcessHost::Client* client) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
// Start opening the channel
PluginServiceImpl::GetInstance()->OpenChannelToNpapiPlugin(
0, 0, GURL(), GURL(), kNPAPITestPluginMimeType, client);
// Immediately cancel it. This is guaranteed to work since PluginService needs
// to consult its filter on the FILE thread.
PluginServiceImpl::GetInstance()->CancelOpenChannelToNpapiPlugin(client);
// Before we terminate the test, add a roundtrip through the FILE thread to
// make sure that it's had a chance to post back to the IO thread. Then signal
// the UI thread to stop and exit the test.
BrowserThread::PostTaskAndReply(
BrowserThread::FILE, FROM_HERE,
base::Bind(&base::DoNothing),
base::Bind(&QuitUIMessageLoopFromIOThread));
}
// Should not attempt to open a channel, since it should be canceled early on.
IN_PROC_BROWSER_TEST_F(PluginServiceTest, CancelOpenChannelToPluginService) {
::testing::StrictMock<MockCanceledPluginServiceClient> mock_client(
browser()->profile()->GetResourceContext());
BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
base::Bind(OpenChannelAndThenCancel, &mock_client));
ui_test_utils::RunMessageLoop();
EXPECT_TRUE(mock_client.get_resource_context_called());
}
class MockCanceledBeforeSentPluginProcessHostClient
: public MockCanceledPluginServiceClient {
public:
MockCanceledBeforeSentPluginProcessHostClient(
content::ResourceContext* context)
: MockCanceledPluginServiceClient(context),
set_plugin_info_called_(false),
on_found_plugin_process_host_called_(false),
host_(NULL) {}
virtual ~MockCanceledBeforeSentPluginProcessHostClient() {}
// Client implementation.
virtual void SetPluginInfo(const webkit::WebPluginInfo& info) OVERRIDE {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
ASSERT_TRUE(info.mime_types.size());
ASSERT_EQ(kNPAPITestPluginMimeType, info.mime_types[0].mime_type);
set_plugin_info_called_ = true;
}
virtual void OnFoundPluginProcessHost(PluginProcessHost* host) OVERRIDE {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
set_on_found_plugin_process_host_called();
set_host(host);
// This gets called right before we request the plugin<=>renderer channel,
// so we have to post a task to cancel it.
MessageLoop::current()->PostTask(
FROM_HERE,
base::Bind(&PluginProcessHost::CancelPendingRequest,
base::Unretained(host), this));
MessageLoop::current()->PostTask(
FROM_HERE,
base::Bind(&QuitUIMessageLoopFromIOThread));
}
bool set_plugin_info_called() const {
return set_plugin_info_called_;
}
bool on_found_plugin_process_host_called() const {
return on_found_plugin_process_host_called_;
}
protected:
void set_on_found_plugin_process_host_called() {
on_found_plugin_process_host_called_ = true;
}
void set_host(PluginProcessHost* host) {
host_ = host;
}
PluginProcessHost* host() const { return host_; }
private:
bool set_plugin_info_called_;
bool on_found_plugin_process_host_called_;
PluginProcessHost* host_;
DISALLOW_COPY_AND_ASSIGN(MockCanceledBeforeSentPluginProcessHostClient);
};
IN_PROC_BROWSER_TEST_F(
PluginServiceTest, CancelBeforeSentOpenChannelToPluginProcessHost) {
::testing::StrictMock<MockCanceledBeforeSentPluginProcessHostClient>
mock_client(browser()->profile()->GetResourceContext());
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::Bind(&OpenChannel, &mock_client));
ui_test_utils::RunMessageLoop();
EXPECT_TRUE(mock_client.get_resource_context_called());
EXPECT_TRUE(mock_client.set_plugin_info_called());
EXPECT_TRUE(mock_client.on_found_plugin_process_host_called());
}
class MockCanceledAfterSentPluginProcessHostClient
: public MockCanceledBeforeSentPluginProcessHostClient {
public:
MockCanceledAfterSentPluginProcessHostClient(
content::ResourceContext* context)
: MockCanceledBeforeSentPluginProcessHostClient(context),
on_sent_plugin_channel_request_called_(false) {}
virtual ~MockCanceledAfterSentPluginProcessHostClient() {}
// Client implementation.
virtual int ID() OVERRIDE { return 42; }
virtual bool OffTheRecord() OVERRIDE { return false; }
// We override this guy again since we don't want to cancel yet.
virtual void OnFoundPluginProcessHost(PluginProcessHost* host) OVERRIDE {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
set_on_found_plugin_process_host_called();
set_host(host);
}
virtual void OnSentPluginChannelRequest() OVERRIDE {
on_sent_plugin_channel_request_called_ = true;
host()->CancelSentRequest(this);
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
MessageLoop::QuitClosure());
}
bool on_sent_plugin_channel_request_called() const {
return on_sent_plugin_channel_request_called_;
}
private:
bool on_sent_plugin_channel_request_called_;
DISALLOW_COPY_AND_ASSIGN(MockCanceledAfterSentPluginProcessHostClient);
};
// Should not attempt to open a channel, since it should be canceled early on.
IN_PROC_BROWSER_TEST_F(
PluginServiceTest, CancelAfterSentOpenChannelToPluginProcessHost) {
::testing::StrictMock<MockCanceledAfterSentPluginProcessHostClient>
mock_client(browser()->profile()->GetResourceContext());
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::Bind(&OpenChannel, &mock_client));
ui_test_utils::RunMessageLoop();
EXPECT_TRUE(mock_client.get_resource_context_called());
EXPECT_TRUE(mock_client.set_plugin_info_called());
EXPECT_TRUE(mock_client.on_found_plugin_process_host_called());
EXPECT_TRUE(mock_client.on_sent_plugin_channel_request_called());
}
} // namespace
<commit_msg>Quit message loop on error in PluginServiceTest, to avoid a timeout.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/plugin_service_impl.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/command_line.h"
#include "base/path_service.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/testing_profile.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/resource_context.h"
#include "content/public/common/content_switches.h"
#include "content/test/test_browser_thread.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "webkit/plugins/npapi/plugin_list.h"
using content::BrowserThread;
namespace {
const char kNPAPITestPluginMimeType[] = "application/vnd.npapi-test";
void OpenChannel(PluginProcessHost::Client* client) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
// Start opening the channel
PluginServiceImpl::GetInstance()->OpenChannelToNpapiPlugin(
0, 0, GURL(), GURL(), kNPAPITestPluginMimeType, client);
}
// Mock up of the Client and the Listener classes that would supply the
// communication channel with the plugin.
class MockPluginProcessHostClient : public PluginProcessHost::Client,
public IPC::Channel::Listener {
public:
MockPluginProcessHostClient(content::ResourceContext* context)
: context_(context),
channel_(NULL),
set_plugin_info_called_(false) {
}
virtual ~MockPluginProcessHostClient() {
if (channel_)
BrowserThread::DeleteSoon(BrowserThread::IO, FROM_HERE, channel_);
}
// PluginProcessHost::Client implementation.
virtual int ID() OVERRIDE { return 42; }
virtual bool OffTheRecord() OVERRIDE { return false; }
virtual content::ResourceContext* GetResourceContext() OVERRIDE {
return context_;
}
virtual void OnFoundPluginProcessHost(PluginProcessHost* host) OVERRIDE {}
virtual void OnSentPluginChannelRequest() OVERRIDE {}
virtual void OnChannelOpened(const IPC::ChannelHandle& handle) OVERRIDE {
ASSERT_TRUE(BrowserThread::CurrentlyOn(BrowserThread::IO));
ASSERT_TRUE(set_plugin_info_called_);
ASSERT_TRUE(!channel_);
channel_ = new IPC::Channel(handle, IPC::Channel::MODE_CLIENT, this);
ASSERT_TRUE(channel_->Connect());
}
virtual void SetPluginInfo(const webkit::WebPluginInfo& info) OVERRIDE {
ASSERT_TRUE(info.mime_types.size());
ASSERT_EQ(kNPAPITestPluginMimeType, info.mime_types[0].mime_type);
set_plugin_info_called_ = true;
}
virtual void OnError() OVERRIDE {
Fail();
}
// IPC::Channel::Listener implementation.
virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE {
Fail();
return false;
}
virtual void OnChannelConnected(int32 peer_pid) OVERRIDE {
QuitMessageLoop();
}
virtual void OnChannelError() OVERRIDE {
Fail();
}
#if defined(OS_POSIX)
virtual void OnChannelDenied() OVERRIDE {
Fail();
}
virtual void OnChannelListenError() OVERRIDE {
Fail();
}
#endif
private:
void Fail() {
FAIL();
QuitMessageLoop();
}
void QuitMessageLoop() {
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
MessageLoop::QuitClosure());
}
content::ResourceContext* context_;
IPC::Channel* channel_;
bool set_plugin_info_called_;
DISALLOW_COPY_AND_ASSIGN(MockPluginProcessHostClient);
};
class PluginServiceTest : public InProcessBrowserTest {
public:
PluginServiceTest() : InProcessBrowserTest() { }
virtual void SetUpCommandLine(CommandLine* command_line) {
#ifdef OS_MACOSX
FilePath browser_directory;
PathService::Get(base::DIR_MODULE, &browser_directory);
command_line->AppendSwitchPath(switches::kExtraPluginDir,
browser_directory.AppendASCII("plugins"));
#endif
}
};
// Try to open a channel to the test plugin. Minimal plugin process spawning
// test for the PluginService interface.
IN_PROC_BROWSER_TEST_F(PluginServiceTest, OpenChannelToPlugin) {
MockPluginProcessHostClient mock_client(
browser()->profile()->GetResourceContext());
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::Bind(&OpenChannel, &mock_client));
ui_test_utils::RunMessageLoop();
}
// A strict mock that fails if any of the methods are called. They shouldn't be
// called since the request should get canceled before then.
class MockCanceledPluginServiceClient : public PluginProcessHost::Client {
public:
MockCanceledPluginServiceClient(content::ResourceContext* context)
: context_(context),
get_resource_context_called_(false) {
}
virtual ~MockCanceledPluginServiceClient() {}
// Client implementation.
MOCK_METHOD0(ID, int());
virtual content::ResourceContext* GetResourceContext() OVERRIDE {
get_resource_context_called_ = true;
return context_;
}
MOCK_METHOD0(OffTheRecord, bool());
MOCK_METHOD1(OnFoundPluginProcessHost, void(PluginProcessHost* host));
MOCK_METHOD0(OnSentPluginChannelRequest, void());
MOCK_METHOD1(OnChannelOpened, void(const IPC::ChannelHandle& handle));
MOCK_METHOD1(SetPluginInfo, void(const webkit::WebPluginInfo& info));
MOCK_METHOD0(OnError, void());
bool get_resource_context_called() const {
return get_resource_context_called_;
}
private:
content::ResourceContext* context_;
bool get_resource_context_called_;
DISALLOW_COPY_AND_ASSIGN(MockCanceledPluginServiceClient);
};
void QuitUIMessageLoopFromIOThread() {
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
MessageLoop::QuitClosure());
}
void OpenChannelAndThenCancel(PluginProcessHost::Client* client) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
// Start opening the channel
PluginServiceImpl::GetInstance()->OpenChannelToNpapiPlugin(
0, 0, GURL(), GURL(), kNPAPITestPluginMimeType, client);
// Immediately cancel it. This is guaranteed to work since PluginService needs
// to consult its filter on the FILE thread.
PluginServiceImpl::GetInstance()->CancelOpenChannelToNpapiPlugin(client);
// Before we terminate the test, add a roundtrip through the FILE thread to
// make sure that it's had a chance to post back to the IO thread. Then signal
// the UI thread to stop and exit the test.
BrowserThread::PostTaskAndReply(
BrowserThread::FILE, FROM_HERE,
base::Bind(&base::DoNothing),
base::Bind(&QuitUIMessageLoopFromIOThread));
}
// Should not attempt to open a channel, since it should be canceled early on.
IN_PROC_BROWSER_TEST_F(PluginServiceTest, CancelOpenChannelToPluginService) {
::testing::StrictMock<MockCanceledPluginServiceClient> mock_client(
browser()->profile()->GetResourceContext());
BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
base::Bind(OpenChannelAndThenCancel, &mock_client));
ui_test_utils::RunMessageLoop();
EXPECT_TRUE(mock_client.get_resource_context_called());
}
class MockCanceledBeforeSentPluginProcessHostClient
: public MockCanceledPluginServiceClient {
public:
MockCanceledBeforeSentPluginProcessHostClient(
content::ResourceContext* context)
: MockCanceledPluginServiceClient(context),
set_plugin_info_called_(false),
on_found_plugin_process_host_called_(false),
host_(NULL) {}
virtual ~MockCanceledBeforeSentPluginProcessHostClient() {}
// Client implementation.
virtual void SetPluginInfo(const webkit::WebPluginInfo& info) OVERRIDE {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
ASSERT_TRUE(info.mime_types.size());
ASSERT_EQ(kNPAPITestPluginMimeType, info.mime_types[0].mime_type);
set_plugin_info_called_ = true;
}
virtual void OnFoundPluginProcessHost(PluginProcessHost* host) OVERRIDE {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
set_on_found_plugin_process_host_called();
set_host(host);
// This gets called right before we request the plugin<=>renderer channel,
// so we have to post a task to cancel it.
MessageLoop::current()->PostTask(
FROM_HERE,
base::Bind(&PluginProcessHost::CancelPendingRequest,
base::Unretained(host), this));
MessageLoop::current()->PostTask(
FROM_HERE,
base::Bind(&QuitUIMessageLoopFromIOThread));
}
bool set_plugin_info_called() const {
return set_plugin_info_called_;
}
bool on_found_plugin_process_host_called() const {
return on_found_plugin_process_host_called_;
}
protected:
void set_on_found_plugin_process_host_called() {
on_found_plugin_process_host_called_ = true;
}
void set_host(PluginProcessHost* host) {
host_ = host;
}
PluginProcessHost* host() const { return host_; }
private:
bool set_plugin_info_called_;
bool on_found_plugin_process_host_called_;
PluginProcessHost* host_;
DISALLOW_COPY_AND_ASSIGN(MockCanceledBeforeSentPluginProcessHostClient);
};
IN_PROC_BROWSER_TEST_F(
PluginServiceTest, CancelBeforeSentOpenChannelToPluginProcessHost) {
::testing::StrictMock<MockCanceledBeforeSentPluginProcessHostClient>
mock_client(browser()->profile()->GetResourceContext());
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::Bind(&OpenChannel, &mock_client));
ui_test_utils::RunMessageLoop();
EXPECT_TRUE(mock_client.get_resource_context_called());
EXPECT_TRUE(mock_client.set_plugin_info_called());
EXPECT_TRUE(mock_client.on_found_plugin_process_host_called());
}
class MockCanceledAfterSentPluginProcessHostClient
: public MockCanceledBeforeSentPluginProcessHostClient {
public:
MockCanceledAfterSentPluginProcessHostClient(
content::ResourceContext* context)
: MockCanceledBeforeSentPluginProcessHostClient(context),
on_sent_plugin_channel_request_called_(false) {}
virtual ~MockCanceledAfterSentPluginProcessHostClient() {}
// Client implementation.
virtual int ID() OVERRIDE { return 42; }
virtual bool OffTheRecord() OVERRIDE { return false; }
// We override this guy again since we don't want to cancel yet.
virtual void OnFoundPluginProcessHost(PluginProcessHost* host) OVERRIDE {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
set_on_found_plugin_process_host_called();
set_host(host);
}
virtual void OnSentPluginChannelRequest() OVERRIDE {
on_sent_plugin_channel_request_called_ = true;
host()->CancelSentRequest(this);
BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
MessageLoop::QuitClosure());
}
bool on_sent_plugin_channel_request_called() const {
return on_sent_plugin_channel_request_called_;
}
private:
bool on_sent_plugin_channel_request_called_;
DISALLOW_COPY_AND_ASSIGN(MockCanceledAfterSentPluginProcessHostClient);
};
// Should not attempt to open a channel, since it should be canceled early on.
IN_PROC_BROWSER_TEST_F(
PluginServiceTest, CancelAfterSentOpenChannelToPluginProcessHost) {
::testing::StrictMock<MockCanceledAfterSentPluginProcessHostClient>
mock_client(browser()->profile()->GetResourceContext());
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::Bind(&OpenChannel, &mock_client));
ui_test_utils::RunMessageLoop();
EXPECT_TRUE(mock_client.get_resource_context_called());
EXPECT_TRUE(mock_client.set_plugin_info_called());
EXPECT_TRUE(mock_client.on_found_plugin_process_host_called());
EXPECT_TRUE(mock_client.on_sent_plugin_channel_request_called());
}
} // namespace
<|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.
// Portions based heavily on:
// third_party/WebKit/Source/WebKit/chromium/public/gtk/WebInputEventFactory.cpp
//
/*
* Copyright (C) 2006-2011 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "content/browser/renderer_host/web_input_event_aura.h"
#include <cstdlib>
#include <X11/Xlib.h>
#include "base/event_types.h"
#include "base/logging.h"
#include "ui/aura/event.h"
#include "ui/base/events.h"
#include "ui/base/keycodes/keyboard_codes.h"
#include "ui/base/keycodes/keyboard_code_conversion_x.h"
namespace content {
// chromium WebKit does not provide a WebInputEventFactory for X11, so we have
// to do the work here ourselves.
namespace {
// This matches Firefox behavior.
const int kPixelsPerTick = 53;
int EventFlagsToWebEventModifiers(int flags) {
int modifiers = 0;
if (flags & ui::EF_SHIFT_DOWN)
modifiers |= WebKit::WebInputEvent::ShiftKey;
if (flags & ui::EF_CONTROL_DOWN)
modifiers |= WebKit::WebInputEvent::ControlKey;
if (flags & ui::EF_ALT_DOWN)
modifiers |= WebKit::WebInputEvent::AltKey;
// TODO(beng): MetaKey/META_MASK
if (flags & ui::EF_LEFT_MOUSE_BUTTON)
modifiers |= WebKit::WebInputEvent::LeftButtonDown;
if (flags & ui::EF_MIDDLE_MOUSE_BUTTON)
modifiers |= WebKit::WebInputEvent::MiddleButtonDown;
if (flags & ui::EF_RIGHT_MOUSE_BUTTON)
modifiers |= WebKit::WebInputEvent::RightButtonDown;
if (flags & ui::EF_CAPS_LOCK_DOWN)
modifiers |= WebKit::WebInputEvent::CapsLockOn;
return modifiers;
}
int XStateToWebEventModifiers(unsigned int state) {
int modifiers = 0;
if (state & ShiftMask)
modifiers |= WebKit::WebInputEvent::ShiftKey;
if (state & ControlMask)
modifiers |= WebKit::WebInputEvent::ControlKey;
if (state & Mod1Mask)
modifiers |= WebKit::WebInputEvent::AltKey;
// TODO(beng): MetaKey/META_MASK
if (state & Button1Mask)
modifiers |= WebKit::WebInputEvent::LeftButtonDown;
if (state & Button2Mask)
modifiers |= WebKit::WebInputEvent::MiddleButtonDown;
if (state & Button3Mask)
modifiers |= WebKit::WebInputEvent::RightButtonDown;
if (state & LockMask)
modifiers |= WebKit::WebInputEvent::CapsLockOn;
if (state & Mod2Mask)
modifiers |= WebKit::WebInputEvent::NumLockOn;
return modifiers;
}
int XKeyEventToWindowsKeyCode(XKeyEvent* event) {
return ui::KeyboardCodeFromXKeyEvent((XEvent*)event);
}
// From
// third_party/WebKit/Source/WebKit/chromium/src/gtk/WebInputEventFactory.cpp:
WebKit::WebUChar GetControlCharacter(int windows_key_code, bool shift) {
if (windows_key_code >= ui::VKEY_A &&
windows_key_code <= ui::VKEY_Z) {
// ctrl-A ~ ctrl-Z map to \x01 ~ \x1A
return windows_key_code - ui::VKEY_A + 1;
}
if (shift) {
// following graphics chars require shift key to input.
switch (windows_key_code) {
// ctrl-@ maps to \x00 (Null byte)
case ui::VKEY_2:
return 0;
// ctrl-^ maps to \x1E (Record separator, Information separator two)
case ui::VKEY_6:
return 0x1E;
// ctrl-_ maps to \x1F (Unit separator, Information separator one)
case ui::VKEY_OEM_MINUS:
return 0x1F;
// Returns 0 for all other keys to avoid inputting unexpected chars.
default:
break;
}
} else {
switch (windows_key_code) {
// ctrl-[ maps to \x1B (Escape)
case ui::VKEY_OEM_4:
return 0x1B;
// ctrl-\ maps to \x1C (File separator, Information separator four)
case ui::VKEY_OEM_5:
return 0x1C;
// ctrl-] maps to \x1D (Group separator, Information separator three)
case ui::VKEY_OEM_6:
return 0x1D;
// ctrl-Enter maps to \x0A (Line feed)
case ui::VKEY_RETURN:
return 0x0A;
// Returns 0 for all other keys to avoid inputting unexpected chars.
default:
break;
}
}
return 0;
}
WebKit::WebTouchPoint::State TouchPointStateFromEvent(
const aura::TouchEvent* event) {
switch (event->type()) {
case ui::ET_TOUCH_PRESSED:
return WebKit::WebTouchPoint::StatePressed;
case ui::ET_TOUCH_RELEASED:
return WebKit::WebTouchPoint::StateReleased;
case ui::ET_TOUCH_MOVED:
return WebKit::WebTouchPoint::StateMoved;
case ui::ET_TOUCH_CANCELLED:
return WebKit::WebTouchPoint::StateCancelled;
default:
return WebKit::WebTouchPoint::StateUndefined;
}
}
WebKit::WebInputEvent::Type TouchEventTypeFromEvent(
const aura::TouchEvent* event) {
switch (event->type()) {
case ui::ET_TOUCH_PRESSED:
return WebKit::WebInputEvent::TouchStart;
case ui::ET_TOUCH_RELEASED:
return WebKit::WebInputEvent::TouchEnd;
case ui::ET_TOUCH_MOVED:
return WebKit::WebInputEvent::TouchMove;
case ui::ET_TOUCH_CANCELLED:
return WebKit::WebInputEvent::TouchCancel;
default:
return WebKit::WebInputEvent::Undefined;
}
}
} // namespace
WebKit::WebMouseEvent MakeWebMouseEventFromAuraEvent(aura::MouseEvent* event) {
WebKit::WebMouseEvent webkit_event;
webkit_event.modifiers = EventFlagsToWebEventModifiers(event->flags());
webkit_event.timeStampSeconds = event->time_stamp().InSecondsF();
webkit_event.button = WebKit::WebMouseEvent::ButtonNone;
if (event->flags() & ui::EF_LEFT_MOUSE_BUTTON)
webkit_event.button = WebKit::WebMouseEvent::ButtonLeft;
if (event->flags() & ui::EF_MIDDLE_MOUSE_BUTTON)
webkit_event.button = WebKit::WebMouseEvent::ButtonMiddle;
if (event->flags() & ui::EF_RIGHT_MOUSE_BUTTON)
webkit_event.button = WebKit::WebMouseEvent::ButtonRight;
switch (event->type()) {
case ui::ET_MOUSE_PRESSED:
webkit_event.type = WebKit::WebInputEvent::MouseDown;
webkit_event.clickCount = event->GetClickCount();
break;
case ui::ET_MOUSE_RELEASED:
webkit_event.type = WebKit::WebInputEvent::MouseUp;
break;
case ui::ET_MOUSE_ENTERED:
case ui::ET_MOUSE_EXITED:
case ui::ET_MOUSE_MOVED:
case ui::ET_MOUSE_DRAGGED:
webkit_event.type = WebKit::WebInputEvent::MouseMove;
break;
default:
NOTIMPLEMENTED() << "Received unexpected event: " << event->type();
break;
}
return webkit_event;
}
WebKit::WebMouseWheelEvent MakeWebMouseWheelEventFromAuraEvent(
aura::MouseEvent* event) {
WebKit::WebMouseWheelEvent webkit_event;
webkit_event.type = WebKit::WebInputEvent::MouseWheel;
webkit_event.button = WebKit::WebMouseEvent::ButtonNone;
webkit_event.modifiers = EventFlagsToWebEventModifiers(event->flags());
webkit_event.timeStampSeconds = event->time_stamp().InSecondsF();
webkit_event.deltaY = ui::GetMouseWheelOffset(event->native_event());
webkit_event.wheelTicksY = webkit_event.deltaY / kPixelsPerTick;
return webkit_event;
}
WebKit::WebMouseWheelEvent MakeWebMouseWheelEventFromAuraEvent(
aura::ScrollEvent* event) {
WebKit::WebMouseWheelEvent webkit_event;
webkit_event.type = WebKit::WebInputEvent::MouseWheel;
webkit_event.button = WebKit::WebMouseEvent::ButtonNone;
webkit_event.modifiers = EventFlagsToWebEventModifiers(event->flags());
webkit_event.timeStampSeconds = event->time_stamp().InSecondsF();
webkit_event.hasPreciseScrollingDeltas = true;
webkit_event.deltaX = event->x_offset();
webkit_event.wheelTicksX = webkit_event.deltaX / kPixelsPerTick;
webkit_event.deltaY = event->y_offset();
webkit_event.wheelTicksY = webkit_event.deltaY / kPixelsPerTick;
return webkit_event;
}
WebKit::WebKeyboardEvent MakeWebKeyboardEventFromAuraEvent(
aura::KeyEvent* event) {
base::NativeEvent native_event = event->native_event();
WebKit::WebKeyboardEvent webkit_event;
XKeyEvent* native_key_event = &native_event->xkey;
webkit_event.timeStampSeconds = event->time_stamp().InSecondsF();
webkit_event.modifiers = XStateToWebEventModifiers(native_key_event->state);
switch (native_event->type) {
case KeyPress:
webkit_event.type = event->is_char() ? WebKit::WebInputEvent::Char :
WebKit::WebInputEvent::RawKeyDown;
break;
case KeyRelease:
webkit_event.type = WebKit::WebInputEvent::KeyUp;
break;
default:
NOTREACHED();
}
if (webkit_event.modifiers & WebKit::WebInputEvent::AltKey)
webkit_event.isSystemKey = true;
webkit_event.windowsKeyCode = XKeyEventToWindowsKeyCode(native_key_event);
webkit_event.nativeKeyCode = native_key_event->keycode;
if (webkit_event.windowsKeyCode == ui::VKEY_RETURN)
webkit_event.unmodifiedText[0] = '\r';
else
webkit_event.unmodifiedText[0] = ui::GetCharacterFromXEvent(native_event);
if (webkit_event.modifiers & WebKit::WebInputEvent::ControlKey) {
webkit_event.text[0] =
GetControlCharacter(
webkit_event.windowsKeyCode,
webkit_event.modifiers & WebKit::WebInputEvent::ShiftKey);
} else {
webkit_event.text[0] = webkit_event.unmodifiedText[0];
}
webkit_event.setKeyIdentifierFromWindowsKeyCode();
// TODO: IsAutoRepeat/IsKeyPad?
return webkit_event;
}
WebKit::WebGestureEvent MakeWebGestureEventFromAuraEvent(
aura::GestureEvent* event) {
WebKit::WebGestureEvent gesture_event;
switch (event->type()) {
case ui::ET_GESTURE_TAP:
gesture_event.type = WebKit::WebInputEvent::GestureTap;
break;
case ui::ET_GESTURE_TAP_DOWN:
gesture_event.type = WebKit::WebInputEvent::GestureTapDown;
break;
case ui::ET_GESTURE_DOUBLE_TAP:
gesture_event.type = WebKit::WebInputEvent::GestureDoubleTap;
break;
case ui::ET_GESTURE_SCROLL_BEGIN:
gesture_event.type = WebKit::WebInputEvent::GestureScrollBegin;
break;
case ui::ET_GESTURE_SCROLL_UPDATE:
gesture_event.type = WebKit::WebInputEvent::GestureScrollUpdate;
break;
case ui::ET_GESTURE_SCROLL_END:
gesture_event.type = WebKit::WebInputEvent::GestureScrollEnd;
break;
default:
NOTREACHED() << "Unknown gesture type: " << event->type();
}
gesture_event.deltaX = event->delta_x();
gesture_event.deltaY = event->delta_y();
return gesture_event;
}
WebKit::WebTouchPoint* UpdateWebTouchEventFromAuraEvent(
aura::TouchEvent* event, WebKit::WebTouchEvent* web_event) {
WebKit::WebTouchPoint* point = NULL;
switch (event->type()) {
case ui::ET_TOUCH_PRESSED:
// Add a new touch point.
if (web_event->touchesLength < WebKit::WebTouchEvent::touchesLengthCap) {
point = &web_event->touches[web_event->touchesLength++];
point->id = event->touch_id();
}
break;
case ui::ET_TOUCH_RELEASED:
case ui::ET_TOUCH_CANCELLED:
case ui::ET_TOUCH_MOVED: {
// The touch point should have been added to the event from an earlier
// _PRESSED event. So find that.
// At the moment, only a maximum of 4 touch-points are allowed. So a
// simple loop should be sufficient.
for (unsigned i = 0; i < web_event->touchesLength; ++i) {
point = web_event->touches + i;
if (point->id == event->touch_id())
break;
point = NULL;
}
break;
}
default:
DLOG(WARNING) << "Unknown touch event " << event->type();
break;
}
if (!point)
return NULL;
point->radiusX = event->radius_x();
point->radiusY = event->radius_y();
point->rotationAngle = event->rotation_angle();
point->force = event->force();
// Update the location and state of the point.
point->state = TouchPointStateFromEvent(event);
if (point->state == WebKit::WebTouchPoint::StateMoved) {
// It is possible for badly written touch drivers to emit Move events even
// when the touch location hasn't changed. In such cases, consume the event
// and pretend nothing happened.
if (point->position.x == event->x() && point->position.y == event->y())
return NULL;
}
point->position.x = event->x();
point->position.y = event->y();
// TODO(sad): Convert to screen coordinates.
point->screenPosition.x = point->position.x;
point->screenPosition.y = point->position.y;
// Mark the rest of the points as stationary.
for (unsigned i = 0; i < web_event->touchesLength; ++i) {
WebKit::WebTouchPoint* iter = web_event->touches + i;
if (iter != point)
iter->state = WebKit::WebTouchPoint::StateStationary;
}
// Update the type of the touch event.
web_event->type = TouchEventTypeFromEvent(event);
web_event->timeStampSeconds = event->time_stamp().InSecondsF();
web_event->modifiers = EventFlagsToWebEventModifiers(event->flags());
return point;
}
} // namespace content
<commit_msg>aura: Send correct screen position for touch-points to webkit.<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.
// Portions based heavily on:
// third_party/WebKit/Source/WebKit/chromium/public/gtk/WebInputEventFactory.cpp
//
/*
* Copyright (C) 2006-2011 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "content/browser/renderer_host/web_input_event_aura.h"
#include <cstdlib>
#include <X11/Xlib.h>
#include "base/event_types.h"
#include "base/logging.h"
#include "ui/aura/event.h"
#include "ui/base/events.h"
#include "ui/base/keycodes/keyboard_codes.h"
#include "ui/base/keycodes/keyboard_code_conversion_x.h"
namespace content {
// chromium WebKit does not provide a WebInputEventFactory for X11, so we have
// to do the work here ourselves.
namespace {
// This matches Firefox behavior.
const int kPixelsPerTick = 53;
int EventFlagsToWebEventModifiers(int flags) {
int modifiers = 0;
if (flags & ui::EF_SHIFT_DOWN)
modifiers |= WebKit::WebInputEvent::ShiftKey;
if (flags & ui::EF_CONTROL_DOWN)
modifiers |= WebKit::WebInputEvent::ControlKey;
if (flags & ui::EF_ALT_DOWN)
modifiers |= WebKit::WebInputEvent::AltKey;
// TODO(beng): MetaKey/META_MASK
if (flags & ui::EF_LEFT_MOUSE_BUTTON)
modifiers |= WebKit::WebInputEvent::LeftButtonDown;
if (flags & ui::EF_MIDDLE_MOUSE_BUTTON)
modifiers |= WebKit::WebInputEvent::MiddleButtonDown;
if (flags & ui::EF_RIGHT_MOUSE_BUTTON)
modifiers |= WebKit::WebInputEvent::RightButtonDown;
if (flags & ui::EF_CAPS_LOCK_DOWN)
modifiers |= WebKit::WebInputEvent::CapsLockOn;
return modifiers;
}
int XStateToWebEventModifiers(unsigned int state) {
int modifiers = 0;
if (state & ShiftMask)
modifiers |= WebKit::WebInputEvent::ShiftKey;
if (state & ControlMask)
modifiers |= WebKit::WebInputEvent::ControlKey;
if (state & Mod1Mask)
modifiers |= WebKit::WebInputEvent::AltKey;
// TODO(beng): MetaKey/META_MASK
if (state & Button1Mask)
modifiers |= WebKit::WebInputEvent::LeftButtonDown;
if (state & Button2Mask)
modifiers |= WebKit::WebInputEvent::MiddleButtonDown;
if (state & Button3Mask)
modifiers |= WebKit::WebInputEvent::RightButtonDown;
if (state & LockMask)
modifiers |= WebKit::WebInputEvent::CapsLockOn;
if (state & Mod2Mask)
modifiers |= WebKit::WebInputEvent::NumLockOn;
return modifiers;
}
int XKeyEventToWindowsKeyCode(XKeyEvent* event) {
return ui::KeyboardCodeFromXKeyEvent((XEvent*)event);
}
// From
// third_party/WebKit/Source/WebKit/chromium/src/gtk/WebInputEventFactory.cpp:
WebKit::WebUChar GetControlCharacter(int windows_key_code, bool shift) {
if (windows_key_code >= ui::VKEY_A &&
windows_key_code <= ui::VKEY_Z) {
// ctrl-A ~ ctrl-Z map to \x01 ~ \x1A
return windows_key_code - ui::VKEY_A + 1;
}
if (shift) {
// following graphics chars require shift key to input.
switch (windows_key_code) {
// ctrl-@ maps to \x00 (Null byte)
case ui::VKEY_2:
return 0;
// ctrl-^ maps to \x1E (Record separator, Information separator two)
case ui::VKEY_6:
return 0x1E;
// ctrl-_ maps to \x1F (Unit separator, Information separator one)
case ui::VKEY_OEM_MINUS:
return 0x1F;
// Returns 0 for all other keys to avoid inputting unexpected chars.
default:
break;
}
} else {
switch (windows_key_code) {
// ctrl-[ maps to \x1B (Escape)
case ui::VKEY_OEM_4:
return 0x1B;
// ctrl-\ maps to \x1C (File separator, Information separator four)
case ui::VKEY_OEM_5:
return 0x1C;
// ctrl-] maps to \x1D (Group separator, Information separator three)
case ui::VKEY_OEM_6:
return 0x1D;
// ctrl-Enter maps to \x0A (Line feed)
case ui::VKEY_RETURN:
return 0x0A;
// Returns 0 for all other keys to avoid inputting unexpected chars.
default:
break;
}
}
return 0;
}
WebKit::WebTouchPoint::State TouchPointStateFromEvent(
const aura::TouchEvent* event) {
switch (event->type()) {
case ui::ET_TOUCH_PRESSED:
return WebKit::WebTouchPoint::StatePressed;
case ui::ET_TOUCH_RELEASED:
return WebKit::WebTouchPoint::StateReleased;
case ui::ET_TOUCH_MOVED:
return WebKit::WebTouchPoint::StateMoved;
case ui::ET_TOUCH_CANCELLED:
return WebKit::WebTouchPoint::StateCancelled;
default:
return WebKit::WebTouchPoint::StateUndefined;
}
}
WebKit::WebInputEvent::Type TouchEventTypeFromEvent(
const aura::TouchEvent* event) {
switch (event->type()) {
case ui::ET_TOUCH_PRESSED:
return WebKit::WebInputEvent::TouchStart;
case ui::ET_TOUCH_RELEASED:
return WebKit::WebInputEvent::TouchEnd;
case ui::ET_TOUCH_MOVED:
return WebKit::WebInputEvent::TouchMove;
case ui::ET_TOUCH_CANCELLED:
return WebKit::WebInputEvent::TouchCancel;
default:
return WebKit::WebInputEvent::Undefined;
}
}
} // namespace
WebKit::WebMouseEvent MakeWebMouseEventFromAuraEvent(aura::MouseEvent* event) {
WebKit::WebMouseEvent webkit_event;
webkit_event.modifiers = EventFlagsToWebEventModifiers(event->flags());
webkit_event.timeStampSeconds = event->time_stamp().InSecondsF();
webkit_event.button = WebKit::WebMouseEvent::ButtonNone;
if (event->flags() & ui::EF_LEFT_MOUSE_BUTTON)
webkit_event.button = WebKit::WebMouseEvent::ButtonLeft;
if (event->flags() & ui::EF_MIDDLE_MOUSE_BUTTON)
webkit_event.button = WebKit::WebMouseEvent::ButtonMiddle;
if (event->flags() & ui::EF_RIGHT_MOUSE_BUTTON)
webkit_event.button = WebKit::WebMouseEvent::ButtonRight;
switch (event->type()) {
case ui::ET_MOUSE_PRESSED:
webkit_event.type = WebKit::WebInputEvent::MouseDown;
webkit_event.clickCount = event->GetClickCount();
break;
case ui::ET_MOUSE_RELEASED:
webkit_event.type = WebKit::WebInputEvent::MouseUp;
break;
case ui::ET_MOUSE_ENTERED:
case ui::ET_MOUSE_EXITED:
case ui::ET_MOUSE_MOVED:
case ui::ET_MOUSE_DRAGGED:
webkit_event.type = WebKit::WebInputEvent::MouseMove;
break;
default:
NOTIMPLEMENTED() << "Received unexpected event: " << event->type();
break;
}
return webkit_event;
}
WebKit::WebMouseWheelEvent MakeWebMouseWheelEventFromAuraEvent(
aura::MouseEvent* event) {
WebKit::WebMouseWheelEvent webkit_event;
webkit_event.type = WebKit::WebInputEvent::MouseWheel;
webkit_event.button = WebKit::WebMouseEvent::ButtonNone;
webkit_event.modifiers = EventFlagsToWebEventModifiers(event->flags());
webkit_event.timeStampSeconds = event->time_stamp().InSecondsF();
webkit_event.deltaY = ui::GetMouseWheelOffset(event->native_event());
webkit_event.wheelTicksY = webkit_event.deltaY / kPixelsPerTick;
return webkit_event;
}
WebKit::WebMouseWheelEvent MakeWebMouseWheelEventFromAuraEvent(
aura::ScrollEvent* event) {
WebKit::WebMouseWheelEvent webkit_event;
webkit_event.type = WebKit::WebInputEvent::MouseWheel;
webkit_event.button = WebKit::WebMouseEvent::ButtonNone;
webkit_event.modifiers = EventFlagsToWebEventModifiers(event->flags());
webkit_event.timeStampSeconds = event->time_stamp().InSecondsF();
webkit_event.hasPreciseScrollingDeltas = true;
webkit_event.deltaX = event->x_offset();
webkit_event.wheelTicksX = webkit_event.deltaX / kPixelsPerTick;
webkit_event.deltaY = event->y_offset();
webkit_event.wheelTicksY = webkit_event.deltaY / kPixelsPerTick;
return webkit_event;
}
WebKit::WebKeyboardEvent MakeWebKeyboardEventFromAuraEvent(
aura::KeyEvent* event) {
base::NativeEvent native_event = event->native_event();
WebKit::WebKeyboardEvent webkit_event;
XKeyEvent* native_key_event = &native_event->xkey;
webkit_event.timeStampSeconds = event->time_stamp().InSecondsF();
webkit_event.modifiers = XStateToWebEventModifiers(native_key_event->state);
switch (native_event->type) {
case KeyPress:
webkit_event.type = event->is_char() ? WebKit::WebInputEvent::Char :
WebKit::WebInputEvent::RawKeyDown;
break;
case KeyRelease:
webkit_event.type = WebKit::WebInputEvent::KeyUp;
break;
default:
NOTREACHED();
}
if (webkit_event.modifiers & WebKit::WebInputEvent::AltKey)
webkit_event.isSystemKey = true;
webkit_event.windowsKeyCode = XKeyEventToWindowsKeyCode(native_key_event);
webkit_event.nativeKeyCode = native_key_event->keycode;
if (webkit_event.windowsKeyCode == ui::VKEY_RETURN)
webkit_event.unmodifiedText[0] = '\r';
else
webkit_event.unmodifiedText[0] = ui::GetCharacterFromXEvent(native_event);
if (webkit_event.modifiers & WebKit::WebInputEvent::ControlKey) {
webkit_event.text[0] =
GetControlCharacter(
webkit_event.windowsKeyCode,
webkit_event.modifiers & WebKit::WebInputEvent::ShiftKey);
} else {
webkit_event.text[0] = webkit_event.unmodifiedText[0];
}
webkit_event.setKeyIdentifierFromWindowsKeyCode();
// TODO: IsAutoRepeat/IsKeyPad?
return webkit_event;
}
WebKit::WebGestureEvent MakeWebGestureEventFromAuraEvent(
aura::GestureEvent* event) {
WebKit::WebGestureEvent gesture_event;
switch (event->type()) {
case ui::ET_GESTURE_TAP:
gesture_event.type = WebKit::WebInputEvent::GestureTap;
break;
case ui::ET_GESTURE_TAP_DOWN:
gesture_event.type = WebKit::WebInputEvent::GestureTapDown;
break;
case ui::ET_GESTURE_DOUBLE_TAP:
gesture_event.type = WebKit::WebInputEvent::GestureDoubleTap;
break;
case ui::ET_GESTURE_SCROLL_BEGIN:
gesture_event.type = WebKit::WebInputEvent::GestureScrollBegin;
break;
case ui::ET_GESTURE_SCROLL_UPDATE:
gesture_event.type = WebKit::WebInputEvent::GestureScrollUpdate;
break;
case ui::ET_GESTURE_SCROLL_END:
gesture_event.type = WebKit::WebInputEvent::GestureScrollEnd;
break;
default:
NOTREACHED() << "Unknown gesture type: " << event->type();
}
gesture_event.deltaX = event->delta_x();
gesture_event.deltaY = event->delta_y();
return gesture_event;
}
WebKit::WebTouchPoint* UpdateWebTouchEventFromAuraEvent(
aura::TouchEvent* event, WebKit::WebTouchEvent* web_event) {
WebKit::WebTouchPoint* point = NULL;
switch (event->type()) {
case ui::ET_TOUCH_PRESSED:
// Add a new touch point.
if (web_event->touchesLength < WebKit::WebTouchEvent::touchesLengthCap) {
point = &web_event->touches[web_event->touchesLength++];
point->id = event->touch_id();
}
break;
case ui::ET_TOUCH_RELEASED:
case ui::ET_TOUCH_CANCELLED:
case ui::ET_TOUCH_MOVED: {
// The touch point should have been added to the event from an earlier
// _PRESSED event. So find that.
// At the moment, only a maximum of 4 touch-points are allowed. So a
// simple loop should be sufficient.
for (unsigned i = 0; i < web_event->touchesLength; ++i) {
point = web_event->touches + i;
if (point->id == event->touch_id())
break;
point = NULL;
}
break;
}
default:
DLOG(WARNING) << "Unknown touch event " << event->type();
break;
}
if (!point)
return NULL;
point->radiusX = event->radius_x();
point->radiusY = event->radius_y();
point->rotationAngle = event->rotation_angle();
point->force = event->force();
// Update the location and state of the point.
point->state = TouchPointStateFromEvent(event);
if (point->state == WebKit::WebTouchPoint::StateMoved) {
// It is possible for badly written touch drivers to emit Move events even
// when the touch location hasn't changed. In such cases, consume the event
// and pretend nothing happened.
if (point->position.x == event->x() && point->position.y == event->y())
return NULL;
}
point->position.x = event->x();
point->position.y = event->y();
const gfx::Point root_point = event->root_location();
point->screenPosition.x = root_point.x();
point->screenPosition.y = root_point.y();
// Mark the rest of the points as stationary.
for (unsigned i = 0; i < web_event->touchesLength; ++i) {
WebKit::WebTouchPoint* iter = web_event->touches + i;
if (iter != point)
iter->state = WebKit::WebTouchPoint::StateStationary;
}
// Update the type of the touch event.
web_event->type = TouchEventTypeFromEvent(event);
web_event->timeStampSeconds = event->time_stamp().InSecondsF();
web_event->modifiers = EventFlagsToWebEventModifiers(event->flags());
return point;
}
} // namespace content
<|endoftext|>
|
<commit_before>/*
DAcase2.c
This program connects to the DAQ data source passed as argument
and populates local "./result.txt" file with the ids of events received
during the run.
The program exits when being asked to shut down (daqDA_checkshutdown)
or End of Run event.
Messages on stdout are exported to DAQ log system.
contact: alice-datesupport@cern.ch
*/
#include "event.h"
#include "monitor.h"
extern "C" {
#include "daqDA.h"
}
#include <stdio.h>
#include <stdlib.h>
#include "AliRawReader.h"
#include "AliRawReaderDate.h"
#include "AliPHOSCalibHistoProducer.h"
/* Main routine
Arguments:
1- monitoring data source
*/
int main(int argc, char **argv) {
int status;
if (argc!=2) {
printf("Wrong number of arguments\n");
return -1;
}
/* open result file */
FILE *fp=NULL;
fp=fopen("./result.txt","a");
if (fp==NULL) {
printf("Failed to open file\n");
return -1;
}
/* define data source : this is argument 1 */
status=monitorSetDataSource( argv[1] );
if (status!=0) {
printf("monitorSetDataSource() failed : %s\n",monitorDecodeError(status));
return -1;
}
/* declare monitoring program */
status=monitorDeclareMp( __FILE__ );
if (status!=0) {
printf("monitorDeclareMp() failed : %s\n",monitorDecodeError(status));
return -1;
}
/* define wait event timeout - 1s max */
monitorSetNowait();
monitorSetNoWaitNetworkTimeout(1000);
/* log start of process */
printf("DA example case2 monitoring program started\n");
/* init some counters */
int nevents_physics=0;
int nevents_total=0;
AliPHOSCalibHistoProducer hp;
hp.SetOldRCUFormat(kTRUE);
hp.SetUpdatingRate(500);
/* main loop (infinite) */
for(;;) {
struct eventHeaderStruct *event;
eventTypeType eventT;
/* check shutdown condition */
if (daqDA_checkShutdown()) {break;}
/* get next event (blocking call until timeout) */
status=monitorGetEventDynamic((void **)&event);
if (status==MON_ERR_EOF) {
printf ("End of File detected\n");
break; /* end of monitoring file has been reached */
}
if (status!=0) {
printf("monitorGetEventDynamic() failed : %s\n",monitorDecodeError(status));
break;
}
/* retry if got no event */
if (event==NULL) {
continue;
}
/* use event - here, just write event id to result file */
eventT=event->eventType;
if (eventT==PHYSICS_EVENT) {
fprintf(fp,"Run #%lu, event size: %lu, BC:%u, Orbit:%u, Period:%u\n",
(unsigned long)event->eventRunNb,
(unsigned long)event->eventSize,
EVENT_ID_GET_BUNCH_CROSSING(event->eventId),
EVENT_ID_GET_ORBIT(event->eventId),
EVENT_ID_GET_PERIOD(event->eventId)
);
AliRawReader *rawReader = new AliRawReaderDate((void*)event);
hp.SetRawReader(rawReader);
hp.Run();
nevents_physics++;
}
nevents_total++;
/* free resources */
free(event);
/* exit when last event received, no need to wait for TERM signal */
if (eventT==END_OF_RUN) {
printf("EOR event detected\n");
break;
}
}
/* write report */
fprintf(fp,"Run #%s, received %d physics events out of %d\n",getenv("DATE_RUN_NUMBER"),nevents_physics,nevents_total);
/* close result file */
fclose(fp);
return status;
}
<commit_msg>Updated version of the DA (Boris)<commit_after>/*
DAcase2.c
This program connects to the DAQ data source passed as argument
and populates local "./result.txt" file with the ids of events received
during the run.
The program exits when being asked to shut down (daqDA_checkshutdown)
or End of Run event.
Messages on stdout are exported to DAQ log system.
contact: alice-datesupport@cern.ch
*/
#include "event.h"
#include "monitor.h"
extern "C" {
#include "daqDA.h"
}
#include <stdio.h>
#include <stdlib.h>
#include "AliRawReader.h"
#include "AliRawReaderDate.h"
#include "AliPHOSCalibHistoProducer.h"
#include "AliPHOSRawDecoder.h"
/* Main routine
Arguments:
1- monitoring data source
*/
int main(int argc, char **argv) {
int status;
if (argc!=2) {
printf("Wrong number of arguments\n");
return -1;
}
/* open result file */
FILE *fp=NULL;
fp=fopen("./result.txt","a");
if (fp==NULL) {
printf("Failed to open file\n");
return -1;
}
/* define data source : this is argument 1 */
status=monitorSetDataSource( argv[1] );
if (status!=0) {
printf("monitorSetDataSource() failed : %s\n",monitorDecodeError(status));
return -1;
}
/* declare monitoring program */
status=monitorDeclareMp( __FILE__ );
if (status!=0) {
printf("monitorDeclareMp() failed : %s\n",monitorDecodeError(status));
return -1;
}
/* define wait event timeout - 1s max */
monitorSetNowait();
monitorSetNoWaitNetworkTimeout(1000);
/* log start of process */
printf("DA example case2 monitoring program started\n");
/* init some counters */
int nevents_physics=0;
int nevents_total=0;
AliRawReader *rawReader = NULL;
AliPHOSCalibHistoProducer hp(200,0.,200.);
hp.SetOldRCUFormat(kTRUE);
hp.SetUpdatingRate(200000);
/* main loop (infinite) */
for(;;) {
struct eventHeaderStruct *event;
eventTypeType eventT;
/* check shutdown condition */
if (daqDA_checkShutdown()) {break;}
/* get next event (blocking call until timeout) */
status=monitorGetEventDynamic((void **)&event);
if (status==MON_ERR_EOF) {
printf ("End of File detected\n");
break; /* end of monitoring file has been reached */
}
if (status!=0) {
printf("monitorGetEventDynamic() failed : %s\n",monitorDecodeError(status));
break;
}
/* retry if got no event */
if (event==NULL) {
continue;
}
/* use event - here, just write event id to result file */
eventT=event->eventType;
if (eventT==PHYSICS_EVENT) {
fprintf(fp,"Run #%lu, event size: %lu, BC:%u, Orbit:%u, Period:%u\n",
(unsigned long)event->eventRunNb,
(unsigned long)event->eventSize,
EVENT_ID_GET_BUNCH_CROSSING(event->eventId),
EVENT_ID_GET_ORBIT(event->eventId),
EVENT_ID_GET_PERIOD(event->eventId)
);
rawReader = new AliRawReaderDate((void*)event);
AliPHOSRawDecoder dc(rawReader);
dc.SubtractPedestals(kTRUE);
hp.SetRawDecoder(&dc);
hp.Run();
nevents_physics++;
}
nevents_total++;
/* free resources */
free(event);
/* exit when last event received, no need to wait for TERM signal */
if (eventT==END_OF_RUN) {
printf("EOR event detected\n");
break;
}
}
/* write report */
fprintf(fp,"Run #%s, received %d physics events out of %d\n",getenv("DATE_RUN_NUMBER"),nevents_physics,nevents_total);
/* close result file */
fclose(fp);
return status;
}
<|endoftext|>
|
<commit_before>// @(#)root/thread:$Id$
// Author: Fons Rademakers 02/07/97
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TPosixThread //
// //
// This class provides an interface to the posix thread routines. //
// //
//////////////////////////////////////////////////////////////////////////
#include "TPosixThread.h"
ClassImp(TPosixThread)
//______________________________________________________________________________
Int_t TPosixThread::Run(TThread *th)
{
// Create a pthread.
int det;
pthread_t id;
pthread_attr_t *attr = new pthread_attr_t;
pthread_attr_init(attr);
// Set detach state
det = (th->fDetached) ? PTHREAD_CREATE_DETACHED : PTHREAD_CREATE_JOINABLE;
pthread_attr_setdetachstate(attr, det);
int ierr = pthread_create(&id, attr, &TThread::Function, th);
if (!ierr) th->fId = (Long_t) id;
pthread_attr_destroy(attr);
delete attr;
return ierr;
}
//______________________________________________________________________________
Int_t TPosixThread::Join(TThread *th, void **ret)
{
// Join suspends the execution of the calling thread until the
// thread identified by th terminates, either by calling pthread_exit
// or by being cancelled.
return pthread_join((pthread_t) th->fId, ret);
}
//______________________________________________________________________________
Int_t TPosixThread::Exit(void *ret)
{
// Terminates the execution of the calling thread.
pthread_exit(ret);
return 0;
}
//______________________________________________________________________________
Int_t TPosixThread::Kill(TThread *th)
{
// Cancellation is the mechanism by which a thread can terminate the
// execution of another thread.
return pthread_cancel((pthread_t) th->fId);
}
//______________________________________________________________________________
Int_t TPosixThread::SetCancelOff()
{
// Turn off the cancellation state of the calling thread.
return pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, 0);
}
//______________________________________________________________________________
Int_t TPosixThread::SetCancelOn()
{
// Turn on the cancellation state of the calling thread.
return pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, 0);
}
//______________________________________________________________________________
Int_t TPosixThread::SetCancelAsynchronous()
{
// Set the cancellation response type of the calling thread to
// asynchronous, i.e. cancel as soon as the cancellation request
// is received.
return pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, 0);
}
//______________________________________________________________________________
Int_t TPosixThread::SetCancelDeferred()
{
// Set the cancellation response type of the calling thread to
// deferred, i.e. cancel only at next cancellation point.
return pthread_setcanceltype (PTHREAD_CANCEL_DEFERRED, 0);
}
//______________________________________________________________________________
Int_t TPosixThread::CancelPoint()
{
// Introduce an explicit cancellation point.
int istate;
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &istate);
pthread_testcancel();
pthread_setcancelstate(istate, 0);
return 0;
}
//______________________________________________________________________________
Int_t TPosixThread::CleanUpPush(void **main, void *free, void *arg)
{
// Add thread cleanup function.
// pthread_cleanup_push(free, arg);
if (!free) Error("CleanUpPush", "cleanup rountine = 0");
new TPosixThreadCleanUp(main, free, arg);
return 0;
}
//______________________________________________________________________________
Int_t TPosixThread::CleanUpPop(void **main,Int_t exe)
{
// Pop thread cleanup function from stack.
// pthread_cleanup_pop(exe); // happy pthread future
if (!main || !*main) return 1;
TPosixThreadCleanUp *l = (TPosixThreadCleanUp*)(*main);
if (!l->fRoutine) Error("CleanUpPop", "cleanup routine = 0");
if (exe && l->fRoutine) ((void (*)(void*))(l->fRoutine))(l->fArgument);
*main = l->fNext; delete l;
return 0;
}
//______________________________________________________________________________
Int_t TPosixThread::CleanUp(void **main)
{
// Default thread cleanup routine.
if (gDebug > 0)
Info("Cleanup", "cleanup 0x%lx", (Long_t)*main);
while (!CleanUpPop(main, 1)) { }
return 0;
}
//______________________________________________________________________________
Long_t TPosixThread::SelfId()
{
// Return the thread identifier for the calling thread.
return (Long_t) pthread_self();
}
// Clean Up section. PTHREAD implementations of cleanup after cancel are
// too different and often too bad. Temporary I invent my own bicycle.
// V.Perev.
//______________________________________________________________________________
TPosixThreadCleanUp::TPosixThreadCleanUp(void **main, void *routine, void *arg)
{
//cleanup function
fNext = (TPosixThreadCleanUp*)*main;
fRoutine = routine; fArgument = arg;
*main = this;
}
<commit_msg>document return codes.<commit_after>// @(#)root/thread:$Id$
// Author: Fons Rademakers 02/07/97
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TPosixThread //
// //
// This class provides an interface to the posix thread routines. //
// //
//////////////////////////////////////////////////////////////////////////
#include "TPosixThread.h"
ClassImp(TPosixThread)
//______________________________________________________________________________
Int_t TPosixThread::Run(TThread *th)
{
// Create a pthread. Returns 0 on success, otherwise an error number will
// be returned.
int det;
pthread_t id;
pthread_attr_t *attr = new pthread_attr_t;
pthread_attr_init(attr);
// Set detach state
det = (th->fDetached) ? PTHREAD_CREATE_DETACHED : PTHREAD_CREATE_JOINABLE;
pthread_attr_setdetachstate(attr, det);
int ierr = pthread_create(&id, attr, &TThread::Function, th);
if (!ierr) th->fId = (Long_t) id;
pthread_attr_destroy(attr);
delete attr;
return ierr;
}
//______________________________________________________________________________
Int_t TPosixThread::Join(TThread *th, void **ret)
{
// Join suspends the execution of the calling thread until the
// thread identified by th terminates, either by calling pthread_exit
// or by being cancelled. Returns 0 on success, otherwise an error number will
// be returned.
return pthread_join((pthread_t) th->fId, ret);
}
//______________________________________________________________________________
Int_t TPosixThread::Exit(void *ret)
{
// Terminates the execution of the calling thread. Return 0.
pthread_exit(ret);
return 0;
}
//______________________________________________________________________________
Int_t TPosixThread::Kill(TThread *th)
{
// Cancellation is the mechanism by which a thread can terminate the
// execution of another thread. Returns 0 on success, otherwise an error
// number will be returned.
return pthread_cancel((pthread_t) th->fId);
}
//______________________________________________________________________________
Int_t TPosixThread::SetCancelOff()
{
// Turn off the cancellation state of the calling thread. Returns 0 on
// success, otherwise an error number will be returned.
return pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, 0);
}
//______________________________________________________________________________
Int_t TPosixThread::SetCancelOn()
{
// Turn on the cancellation state of the calling thread. Returns 0 on
// success, otherwise an error number will be returned.
return pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, 0);
}
//______________________________________________________________________________
Int_t TPosixThread::SetCancelAsynchronous()
{
// Set the cancellation response type of the calling thread to
// asynchronous, i.e. cancel as soon as the cancellation request
// is received.
return pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, 0);
}
//______________________________________________________________________________
Int_t TPosixThread::SetCancelDeferred()
{
// Set the cancellation response type of the calling thread to
// deferred, i.e. cancel only at next cancellation point.
// Returns 0 on success, otherwise an error number will be returned.
return pthread_setcanceltype (PTHREAD_CANCEL_DEFERRED, 0);
}
//______________________________________________________________________________
Int_t TPosixThread::CancelPoint()
{
// Introduce an explicit cancellation point. Returns 0.
int istate;
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &istate);
pthread_testcancel();
pthread_setcancelstate(istate, 0);
return 0;
}
//______________________________________________________________________________
Int_t TPosixThread::CleanUpPush(void **main, void *free, void *arg)
{
// Add thread cleanup function.
// pthread_cleanup_push(free, arg);
if (!free) Error("CleanUpPush", "cleanup rountine = 0");
new TPosixThreadCleanUp(main, free, arg);
return 0;
}
//______________________________________________________________________________
Int_t TPosixThread::CleanUpPop(void **main,Int_t exe)
{
// Pop thread cleanup function from stack.
// pthread_cleanup_pop(exe); // happy pthread future
if (!main || !*main) return 1;
TPosixThreadCleanUp *l = (TPosixThreadCleanUp*)(*main);
if (!l->fRoutine) Error("CleanUpPop", "cleanup routine = 0");
if (exe && l->fRoutine) ((void (*)(void*))(l->fRoutine))(l->fArgument);
*main = l->fNext; delete l;
return 0;
}
//______________________________________________________________________________
Int_t TPosixThread::CleanUp(void **main)
{
// Default thread cleanup routine.
if (gDebug > 0)
Info("Cleanup", "cleanup 0x%lx", (Long_t)*main);
while (!CleanUpPop(main, 1)) { }
return 0;
}
//______________________________________________________________________________
Long_t TPosixThread::SelfId()
{
// Return the thread identifier for the calling thread.
return (Long_t) pthread_self();
}
// Clean Up section. PTHREAD implementations of cleanup after cancel are
// too different and often too bad. Temporary I invent my own bicycle.
// V.Perev.
//______________________________________________________________________________
TPosixThreadCleanUp::TPosixThreadCleanUp(void **main, void *routine, void *arg)
{
//cleanup function
fNext = (TPosixThreadCleanUp*)*main;
fRoutine = routine; fArgument = arg;
*main = this;
}
<|endoftext|>
|
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <sys/mman.h>
#include <limits.h>
#include <unistd.h>
#undef __USE_XOPEN
#include <signal.h>
#include "open/platform_types.h"
#include "port_crash_handler.h"
#include "port_malloc.h"
#include "stack_dump.h"
#include "../linux/include/gdb_crash_handler.h"
#include "signals_internal.h"
#include "port_thread_internal.h"
#define FLAG_CORE ((port_crash_handler_get_flags() & PORT_CRASH_DUMP_PROCESS_CORE) != 0)
#define FLAG_DBG ((port_crash_handler_get_flags() & PORT_CRASH_CALL_DEBUGGER) != 0)
bool is_stack_overflow(port_tls_data_t* tlsdata, void* fault_addr)
{
if (!tlsdata || !fault_addr)
return false;
if (tlsdata->guard_page_addr)
{
return (fault_addr >= tlsdata->guard_page_addr &&
(size_t)fault_addr < (size_t)tlsdata->guard_page_addr
+ tlsdata->guard_page_size);
}
size_t stack_top =
(size_t)tlsdata->stack_addr - tlsdata->stack_size + tlsdata->guard_page_size;
// Determine that fault is beyond stack top
return ((size_t)fault_addr < stack_top &&
(size_t)fault_addr > stack_top - tlsdata->stack_size);
}
static void c_handler(Registers* pregs, size_t signum, void* fault_addr)
{ // this exception handler is executed *after* OS signal handler returned
int result;
port_tls_data_t* tlsdata = get_private_tls_data();
switch ((int)signum)
{
case SIGSEGV:
if (tlsdata->restore_guard_page)
{
// Now it's safe to disable alternative stack
set_alt_stack(tlsdata, FALSE);
result = port_process_signal(PORT_SIGNAL_STACK_OVERFLOW, pregs, fault_addr, FALSE);
}
else
result = port_process_signal(PORT_SIGNAL_GPF, pregs, fault_addr, FALSE);
break;
case SIGFPE:
result = port_process_signal(PORT_SIGNAL_ARITHMETIC, pregs, fault_addr, FALSE);
break;
case SIGTRAP:
// Correct return address
pregs->set_ip((void*)((POINTER_SIZE_INT)pregs->get_ip() - 1));
result = port_process_signal(PORT_SIGNAL_BREAKPOINT, pregs, fault_addr, FALSE);
break;
case SIGINT:
result = port_process_signal(PORT_SIGNAL_CTRL_C, pregs, fault_addr, FALSE);
break;
case SIGQUIT:
result = port_process_signal(PORT_SIGNAL_QUIT, pregs, fault_addr, FALSE);
break;
case SIGABRT:
result = port_process_signal(PORT_SIGNAL_ABORT, NULL, fault_addr, FALSE);
break;
default:
result = port_process_signal(PORT_SIGNAL_UNKNOWN, pregs, fault_addr, TRUE);
}
if (result == 0)
{
// Restore guard page if needed
if (tlsdata->restore_guard_page)
{
port_thread_restore_guard_page();
tlsdata->restore_guard_page = FALSE;
if (port_thread_detach_temporary() == 0)
STD_FREE(tlsdata);
}
return;
}
// We've got a crash
if (signum == SIGSEGV)
{
port_thread_restore_guard_page(); // To catch SO again
tlsdata->restore_guard_page = FALSE;
}
if (result > 0) // invoke debugger
{ // Prepare second catch of signal to attach GDB from signal handler
//assert(tlsdata); // Should be attached - provided by general_signal_handler
tlsdata->debugger = TRUE;
return; // To produce signal again
}
// result < 0 - exit process
if (FLAG_CORE)
{ // Return to the same place to produce the same crash and generate core
signal(signum, SIG_DFL); // setup default handler
return;
}
// No core needed - simply terminate
_exit(-1);
}
static void general_signal_handler(int signum, siginfo_t* info, void* context)
{
Registers regs;
if (!context)
return;
// Convert OS context to Registers
port_thread_context_to_regs(®s, (ucontext_t*)context);
void* fault_addr = info ? info->si_addr : NULL;
// Check if SIGSEGV is produced by port_read/write_memory
port_tls_data_t* tlsdata = get_private_tls_data();
if (tlsdata && tlsdata->violation_flag)
{
tlsdata->violation_flag = 0;
regs.set_ip(tlsdata->restart_address);
return;
}
if (!tlsdata) // Tread is not attached - attach thread temporarily
{
int res;
tlsdata = (port_tls_data_t*)STD_MALLOC(sizeof(port_tls_data_t));
if (tlsdata) // Try to attach the thread
res = port_thread_attach_local(tlsdata, TRUE, TRUE, 0);
if (!tlsdata || res != 0)
{ // Can't process correctly; perform default actions
if (FLAG_DBG)
{
bool result = gdb_crash_handler(®s);
_exit(-1); // Exit process if not sucessful...
}
if (FLAG_CORE &&
signum != SIGABRT) // SIGABRT can't be rethrown
{
signal(signum, SIG_DFL); // setup default handler
return;
}
_exit(-1);
}
// SIGSEGV can represent SO which can't be processed out of signal handler
if (signum == SIGSEGV && // This can occur only when a user set an alternative stack
is_stack_overflow(tlsdata, fault_addr))
{
int result = port_process_signal(PORT_SIGNAL_STACK_OVERFLOW, ®s, fault_addr, FALSE);
if (result == 0)
{
if (port_thread_detach_temporary() == 0)
STD_FREE(tlsdata);
return;
}
if (result > 0)
tlsdata->debugger = TRUE;
else
{
if (FLAG_CORE)
{ // Rethrow crash to generate core
signal(signum, SIG_DFL); // setup default handler
return;
}
_exit(-1);
}
}
}
if (tlsdata->debugger)
{
bool result = gdb_crash_handler(®s);
_exit(-1); // Exit process if not sucessful...
}
if (signum == SIGABRT && // SIGABRT can't be trown again from c_handler
FLAG_DBG)
{ // So attaching GDB right here
bool result = gdb_crash_handler(®s);
_exit(-1); // Exit process if not sucessful...
}
if (signum == SIGSEGV &&
is_stack_overflow(tlsdata, fault_addr))
{
// Second SO while previous SO is not processed yet - is GPF
if (tlsdata->restore_guard_page)
tlsdata->restore_guard_page = FALSE;
else
{ // To process signal on protected stack area
port_thread_clear_guard_page();
// Note: the call above does not disable alternative stack
// It can't be made while we are on alternative stack
// Alt stack will be disabled explicitly in c_handler()
tlsdata->restore_guard_page = TRUE;
}
}
// Prepare registers for transfering control out of signal handler
void* callback = (void*)&c_handler;
port_set_longjump_regs(callback, ®s, 3,
®s, (void*)(size_t)signum, fault_addr);
// Convert prepared Registers back to OS context
port_thread_regs_to_context((ucontext_t*)context, ®s);
// Return from signal handler to go to C handler
}
struct sig_reg
{
int signal;
port_sigtype port_sig;
int flags;
bool set_up;
};
static sig_reg signals_used[] =
{
{ SIGTRAP, PORT_SIGNAL_BREAKPOINT, SA_SIGINFO, false },
{ SIGSEGV, PORT_SIGNAL_GPF, SA_SIGINFO | SA_ONSTACK, false },
{ SIGFPE, PORT_SIGNAL_ARITHMETIC, SA_SIGINFO, false },
{ SIGINT, PORT_SIGNAL_CTRL_C, SA_SIGINFO, false },
{ SIGQUIT, PORT_SIGNAL_QUIT, SA_SIGINFO, false },
{ SIGABRT, PORT_SIGNAL_ABORT, SA_SIGINFO, false }
};
static struct sigaction old_actions[sizeof(signals_used)/sizeof(signals_used[0])];
static void restore_signals()
{
for (size_t i = 0; i < sizeof(signals_used)/sizeof(signals_used[0]); i++)
{
if (!signals_used[i].set_up)
continue;
signals_used[i].set_up = false;
sigaction(signals_used[i].signal, &old_actions[i], NULL);
}
}
int initialize_signals()
{
struct sigaction sa;
for (size_t i = 0; i < sizeof(signals_used)/sizeof(signals_used[0]); i++)
{
if (!sd_is_handler_registered(signals_used[i].port_sig) &&
signals_used[i].signal != SIGSEGV) // Sigsegv is needed for port_memaccess
continue;
sigemptyset(&sa.sa_mask);
sa.sa_flags = signals_used[i].flags;
sa.sa_sigaction = &general_signal_handler;
if (0 != sigaction(signals_used[i].signal, &sa, &old_actions[i]))
{
restore_signals();
return -1;
}
signals_used[i].set_up = true;
}
// Prepare gdb crash handler
if (!init_gdb_crash_handler())
{
restore_signals();
return -1;
}
return 0;
} //initialize_signals
int shutdown_signals()
{
cleanup_gdb_crash_handler();
restore_signals();
return 0;
} //shutdown_signals
void sig_process_crash_flags_change(unsigned added, unsigned removed)
{
// Still empty on Linux
}
<commit_msg>Applied patch for "[#HARMONY-6132] [drlvm][build] SSLSocketImplTest breaks in Fedora since hy.no.sig removal".<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <sys/mman.h>
#include <limits.h>
#include <unistd.h>
#undef __USE_XOPEN
#include <signal.h>
#include "open/platform_types.h"
#include "port_crash_handler.h"
#include "port_malloc.h"
#include "stack_dump.h"
#include "../linux/include/gdb_crash_handler.h"
#include "signals_internal.h"
#include "port_thread_internal.h"
#define FLAG_CORE ((port_crash_handler_get_flags() & PORT_CRASH_DUMP_PROCESS_CORE) != 0)
#define FLAG_DBG ((port_crash_handler_get_flags() & PORT_CRASH_CALL_DEBUGGER) != 0)
bool is_stack_overflow(port_tls_data_t* tlsdata, void* fault_addr)
{
if (!tlsdata || !fault_addr)
return false;
if (tlsdata->guard_page_addr)
{
return (fault_addr >= tlsdata->guard_page_addr &&
(size_t)fault_addr < (size_t)tlsdata->guard_page_addr
+ tlsdata->guard_page_size);
}
size_t stack_top =
(size_t)tlsdata->stack_addr - tlsdata->stack_size + tlsdata->guard_page_size;
// Determine that fault is beyond stack top
return ((size_t)fault_addr < stack_top &&
(size_t)fault_addr > stack_top - tlsdata->stack_size);
}
static void c_handler(Registers* pregs, size_t signum, void* fault_addr)
{ // this exception handler is executed *after* OS signal handler returned
int result;
port_tls_data_t* tlsdata = get_private_tls_data();
switch ((int)signum)
{
case SIGSEGV:
if (tlsdata->restore_guard_page)
{
// Now it's safe to disable alternative stack
set_alt_stack(tlsdata, FALSE);
result = port_process_signal(PORT_SIGNAL_STACK_OVERFLOW, pregs, fault_addr, FALSE);
}
else
result = port_process_signal(PORT_SIGNAL_GPF, pregs, fault_addr, FALSE);
break;
case SIGFPE:
result = port_process_signal(PORT_SIGNAL_ARITHMETIC, pregs, fault_addr, FALSE);
break;
case SIGTRAP:
// Correct return address
pregs->set_ip((void*)((POINTER_SIZE_INT)pregs->get_ip() - 1));
result = port_process_signal(PORT_SIGNAL_BREAKPOINT, pregs, fault_addr, FALSE);
break;
case SIGINT:
result = port_process_signal(PORT_SIGNAL_CTRL_C, pregs, fault_addr, FALSE);
break;
case SIGQUIT:
result = port_process_signal(PORT_SIGNAL_QUIT, pregs, fault_addr, FALSE);
break;
case SIGABRT:
result = port_process_signal(PORT_SIGNAL_ABORT, NULL, fault_addr, FALSE);
break;
default:
result = port_process_signal(PORT_SIGNAL_UNKNOWN, pregs, fault_addr, TRUE);
}
if (result == 0)
{
// Restore guard page if needed
if (tlsdata->restore_guard_page)
{
port_thread_restore_guard_page();
tlsdata->restore_guard_page = FALSE;
if (port_thread_detach_temporary() == 0)
STD_FREE(tlsdata);
}
return;
}
// We've got a crash
if (signum == SIGSEGV)
{
port_thread_restore_guard_page(); // To catch SO again
tlsdata->restore_guard_page = FALSE;
}
if (result > 0) // invoke debugger
{ // Prepare second catch of signal to attach GDB from signal handler
//assert(tlsdata); // Should be attached - provided by general_signal_handler
tlsdata->debugger = TRUE;
return; // To produce signal again
}
// result < 0 - exit process
if (FLAG_CORE)
{ // Return to the same place to produce the same crash and generate core
signal(signum, SIG_DFL); // setup default handler
return;
}
// No core needed - simply terminate
_exit(-1);
}
static void general_signal_handler(int signum, siginfo_t* info, void* context)
{
Registers regs;
if (!context)
return;
// Convert OS context to Registers
port_thread_context_to_regs(®s, (ucontext_t*)context);
void* fault_addr = info ? info->si_addr : NULL;
// Check if SIGSEGV is produced by port_read/write_memory
port_tls_data_t* tlsdata = get_private_tls_data();
if (tlsdata && tlsdata->violation_flag)
{
tlsdata->violation_flag = 0;
regs.set_ip(tlsdata->restart_address);
return;
}
if (!tlsdata) // Tread is not attached - attach thread temporarily
{
int res;
tlsdata = (port_tls_data_t*)STD_MALLOC(sizeof(port_tls_data_t));
if (tlsdata) // Try to attach the thread
res = port_thread_attach_local(tlsdata, TRUE, TRUE, 0);
if (!tlsdata || res != 0)
{ // Can't process correctly; perform default actions
if (FLAG_DBG)
{
bool result = gdb_crash_handler(®s);
_exit(-1); // Exit process if not sucessful...
}
if (FLAG_CORE &&
signum != SIGABRT) // SIGABRT can't be rethrown
{
signal(signum, SIG_DFL); // setup default handler
return;
}
_exit(-1);
}
// SIGSEGV can represent SO which can't be processed out of signal handler
if (signum == SIGSEGV && // This can occur only when a user set an alternative stack
is_stack_overflow(tlsdata, fault_addr))
{
int result = port_process_signal(PORT_SIGNAL_STACK_OVERFLOW, ®s, fault_addr, FALSE);
if (result == 0)
{
if (port_thread_detach_temporary() == 0)
STD_FREE(tlsdata);
return;
}
if (result > 0)
tlsdata->debugger = TRUE;
else
{
if (FLAG_CORE)
{ // Rethrow crash to generate core
signal(signum, SIG_DFL); // setup default handler
return;
}
_exit(-1);
}
}
}
if (tlsdata->debugger)
{
bool result = gdb_crash_handler(®s);
_exit(-1); // Exit process if not sucessful...
}
if (signum == SIGABRT && // SIGABRT can't be trown again from c_handler
FLAG_DBG)
{ // So attaching GDB right here
bool result = gdb_crash_handler(®s);
_exit(-1); // Exit process if not sucessful...
}
if (signum == SIGSEGV &&
is_stack_overflow(tlsdata, fault_addr))
{
// Second SO while previous SO is not processed yet - is GPF
if (tlsdata->restore_guard_page)
tlsdata->restore_guard_page = FALSE;
else
{ // To process signal on protected stack area
port_thread_clear_guard_page();
// Note: the call above does not disable alternative stack
// It can't be made while we are on alternative stack
// Alt stack will be disabled explicitly in c_handler()
tlsdata->restore_guard_page = TRUE;
}
}
// Prepare registers for transfering control out of signal handler
void* callback = (void*)&c_handler;
port_set_longjump_regs(callback, ®s, 3,
®s, (void*)(size_t)signum, fault_addr);
// Convert prepared Registers back to OS context
port_thread_regs_to_context((ucontext_t*)context, ®s);
// Return from signal handler to go to C handler
}
struct sig_reg
{
int signal;
port_sigtype port_sig;
int flags;
bool set_up;
};
static sig_reg signals_used[] =
{
{ SIGTRAP, PORT_SIGNAL_BREAKPOINT, SA_SIGINFO, false },
{ SIGSEGV, PORT_SIGNAL_GPF, SA_SIGINFO | SA_ONSTACK, false },
{ SIGFPE, PORT_SIGNAL_ARITHMETIC, SA_SIGINFO, false },
{ SIGINT, PORT_SIGNAL_CTRL_C, SA_SIGINFO, false },
{ SIGQUIT, PORT_SIGNAL_QUIT, SA_SIGINFO, false },
{ SIGABRT, PORT_SIGNAL_ABORT, SA_SIGINFO, false }
};
static struct sigaction old_actions[sizeof(signals_used)/sizeof(signals_used[0])];
// For signals that must change their default behavior
struct sig_redef
{
int signal;
sighandler_t handler;
bool set_up;
};
static sig_redef signals_other[] =
{
{ SIGPIPE, SIG_IGN, false }
};
static sighandler_t old_handlers[sizeof(signals_other)/sizeof(signals_other[0])];
static void restore_signals()
{
for (size_t i = 0; i < sizeof(signals_used)/sizeof(signals_used[0]); i++)
{
if (!signals_used[i].set_up)
continue;
signals_used[i].set_up = false;
sigaction(signals_used[i].signal, &old_actions[i], NULL);
}
for (size_t j = 0; j < sizeof(signals_other)/sizeof(signals_other[0]); j++)
{
if (!signals_other[j].set_up)
continue;
signals_other[j].set_up = false;
signal(signals_other[j].signal, old_handlers[j]);
}
}
int initialize_signals()
{
struct sigaction sa;
for (size_t i = 0; i < sizeof(signals_used)/sizeof(signals_used[0]); i++)
{
if (!sd_is_handler_registered(signals_used[i].port_sig) &&
signals_used[i].signal != SIGSEGV) // Sigsegv is needed for port_memaccess
continue;
sigemptyset(&sa.sa_mask);
sa.sa_flags = signals_used[i].flags;
sa.sa_sigaction = &general_signal_handler;
if (0 != sigaction(signals_used[i].signal, &sa, &old_actions[i]))
{
restore_signals();
return -1;
}
signals_used[i].set_up = true;
}
for (size_t j = 0; j < sizeof(signals_other)/sizeof(signals_other[0]); j++)
{
old_handlers[j] = signal(signals_other[j].signal, signals_other[j].handler);
if (old_handlers[j] == SIG_ERR)
{
restore_signals();
return -1;
}
signals_other[j].set_up = true;
}
// Prepare gdb crash handler
if (!init_gdb_crash_handler())
{
restore_signals();
return -1;
}
return 0;
} //initialize_signals
int shutdown_signals()
{
cleanup_gdb_crash_handler();
restore_signals();
return 0;
} //shutdown_signals
void sig_process_crash_flags_change(unsigned added, unsigned removed)
{
// Still empty on Linux
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/renderer/pepper/pepper_platform_image_2d_impl.h"
#include "build/build_config.h"
#include "content/common/view_messages.h"
#include "content/renderer/render_thread_impl.h"
#include "ui/surface/transport_dib.h"
namespace content {
PepperPlatformImage2DImpl::PepperPlatformImage2DImpl(int width,
int height,
TransportDIB* dib)
: width_(width),
height_(height),
dib_(dib) {
}
// On Mac, we have to tell the browser to free the transport DIB.
PepperPlatformImage2DImpl::~PepperPlatformImage2DImpl() {
#if defined(OS_MACOSX)
if (dib_.get()) {
RenderThreadImpl::current()->Send(
new ViewHostMsg_FreeTransportDIB(dib_->id()));
}
#endif
}
// static
PepperPlatformImage2DImpl* PepperPlatformImage2DImpl::Create(int width,
int height) {
uint32 buffer_size = width * height * 4;
// Allocate the transport DIB and the PlatformCanvas pointing to it.
#if defined(OS_MACOSX)
// On the Mac, shared memory has to be created in the browser in order to
// work in the sandbox. Do this by sending a message to the browser
// requesting a TransportDIB (see also
// chrome/renderer/webplugin_delegate_proxy.cc, method
// WebPluginDelegateProxy::CreateBitmap() for similar code). The TransportDIB
// is cached in the browser, and is freed (in typical cases) by the
// PepperPlatformImage2DImpl's destructor.
TransportDIB::Handle dib_handle;
IPC::Message* msg = new ViewHostMsg_AllocTransportDIB(buffer_size,
true,
&dib_handle);
if (!RenderThreadImpl::current()->Send(msg))
return NULL;
if (!TransportDIB::is_valid_handle(dib_handle))
return NULL;
TransportDIB* dib = TransportDIB::Map(dib_handle);
#else
static int next_dib_id = 0;
TransportDIB* dib = TransportDIB::Create(buffer_size, next_dib_id++);
if (!dib)
return NULL;
#endif
return new PepperPlatformImage2DImpl(width, height, dib);
}
skia::PlatformCanvas* PepperPlatformImage2DImpl::Map() {
return dib_->GetPlatformCanvas(width_, height_);
}
intptr_t PepperPlatformImage2DImpl::GetSharedMemoryHandle(
uint32* byte_count) const {
*byte_count = dib_->size();
#if defined(OS_WIN)
return reinterpret_cast<intptr_t>(dib_->handle());
#elif defined(OS_MACOSX) || defined(OS_ANDROID)
return static_cast<intptr_t>(dib_->handle().fd);
#elif defined(OS_POSIX)
return static_cast<intptr_t>(dib_->handle());
#endif
}
TransportDIB* PepperPlatformImage2DImpl::GetTransportDIB() const {
return dib_.get();
}
} // namespace content
<commit_msg>PepperPlatformImage2DImpl: don't immediately map shared memory<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/renderer/pepper/pepper_platform_image_2d_impl.h"
#include "build/build_config.h"
#include "content/common/view_messages.h"
#include "content/renderer/render_thread_impl.h"
#include "ui/surface/transport_dib.h"
namespace content {
PepperPlatformImage2DImpl::PepperPlatformImage2DImpl(int width,
int height,
TransportDIB* dib)
: width_(width),
height_(height),
dib_(dib) {
}
// On Mac, we have to tell the browser to free the transport DIB.
PepperPlatformImage2DImpl::~PepperPlatformImage2DImpl() {
#if defined(OS_MACOSX)
if (dib_.get()) {
RenderThreadImpl::current()->Send(
new ViewHostMsg_FreeTransportDIB(dib_->id()));
}
#endif
}
// static
PepperPlatformImage2DImpl* PepperPlatformImage2DImpl::Create(int width,
int height) {
uint32 buffer_size = width * height * 4;
// Allocate the transport DIB and the PlatformCanvas pointing to it.
#if defined(OS_MACOSX)
// On the Mac, shared memory has to be created in the browser in order to
// work in the sandbox. Do this by sending a message to the browser
// requesting a TransportDIB (see also
// chrome/renderer/webplugin_delegate_proxy.cc, method
// WebPluginDelegateProxy::CreateBitmap() for similar code). The TransportDIB
// is cached in the browser, and is freed (in typical cases) by the
// PepperPlatformImage2DImpl's destructor.
TransportDIB::Handle dib_handle;
IPC::Message* msg = new ViewHostMsg_AllocTransportDIB(buffer_size,
true,
&dib_handle);
if (!RenderThreadImpl::current()->Send(msg))
return NULL;
if (!TransportDIB::is_valid_handle(dib_handle))
return NULL;
TransportDIB* dib = TransportDIB::CreateWithHandle(dib_handle);
#else
static int next_dib_id = 0;
TransportDIB* dib = TransportDIB::Create(buffer_size, next_dib_id++);
if (!dib)
return NULL;
#endif
return new PepperPlatformImage2DImpl(width, height, dib);
}
skia::PlatformCanvas* PepperPlatformImage2DImpl::Map() {
return dib_->GetPlatformCanvas(width_, height_);
}
intptr_t PepperPlatformImage2DImpl::GetSharedMemoryHandle(
uint32* byte_count) const {
*byte_count = dib_->size();
#if defined(OS_WIN)
return reinterpret_cast<intptr_t>(dib_->handle());
#elif defined(OS_MACOSX) || defined(OS_ANDROID)
return static_cast<intptr_t>(dib_->handle().fd);
#elif defined(OS_POSIX)
return static_cast<intptr_t>(dib_->handle());
#endif
}
TransportDIB* PepperPlatformImage2DImpl::GetTransportDIB() const {
return dib_.get();
}
} // namespace content
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2012 Stanford University
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string>
#include <ori/oriutil.h>
#include "fuse_cmd.h"
bool OF_HasFuse()
{
return OF_ControlPath() != "";
}
std::string OF_ControlPath()
{
char *cwdbuf = getcwd(NULL, 0);
std::string path = cwdbuf;
free(cwdbuf);
while (path.size() > 0) {
std::string control_path = path + "/" + ORI_CONTROL_FILENAME;
if (Util_FileExists(control_path)) {
return control_path;
}
path = StrUtil_Dirname(path);
}
return "";
}
bool OF_RunCommand(const char *cmd)
{
size_t status;
std::string controlPath = OF_ControlPath();
if (controlPath.size() == 0)
return false;
int fd = open(controlPath.c_str(), O_RDWR | O_TRUNC);
if (fd < 0) {
perror("OF_RunCommand open");
return false;
}
status = write(fd, cmd, strlen(cmd));
if (status < 0) {
perror("Failed to write control node");
return false;
}
fsync(fd);
lseek(fd, 0, SEEK_SET);
// Read output
struct stat sb;
fstat(fd, &sb);
size_t left = sb.st_size;
while (left > 0) {
size_t to_read = left;
if (to_read > 1024)
to_read = 1024;
char buf[1024];
int bytes_read = read(fd, buf, to_read);
if (bytes_read == -1) {
perror("Failed to read control node");
return false;
}
fwrite(buf, bytes_read, 1, stdout);
left -= bytes_read;
}
return true;
}
<commit_msg>Fix error handling in ori CLI FUSE control path.<commit_after>/*
* Copyright (c) 2012 Stanford University
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string>
#include <ori/oriutil.h>
#include "fuse_cmd.h"
bool OF_HasFuse()
{
return OF_ControlPath() != "";
}
std::string OF_ControlPath()
{
char *cwdbuf = getcwd(NULL, 0);
std::string path = cwdbuf;
free(cwdbuf);
while (path.size() > 0) {
std::string control_path = path + "/" + ORI_CONTROL_FILENAME;
if (Util_FileExists(control_path)) {
return control_path;
}
path = StrUtil_Dirname(path);
}
return "";
}
bool OF_RunCommand(const char *cmd)
{
std::string controlPath = OF_ControlPath();
if (controlPath.size() == 0)
return false;
int fd = open(controlPath.c_str(), O_RDWR | O_TRUNC);
if (fd < 0) {
perror("OF_RunCommand open");
return false;
}
int status = write(fd, cmd, strlen(cmd));
if (status < 0) {
perror("Failed to write control node");
return false;
}
fsync(fd);
lseek(fd, 0, SEEK_SET);
// Read output
struct stat sb;
fstat(fd, &sb);
size_t left = sb.st_size;
while (left > 0) {
size_t to_read = left;
if (to_read > 1024)
to_read = 1024;
char buf[1024];
int bytes_read = read(fd, buf, to_read);
if (bytes_read == -1) {
perror("Failed to read control node");
return false;
}
fwrite(buf, bytes_read, 1, stdout);
left -= bytes_read;
}
return true;
}
<|endoftext|>
|
<commit_before><commit_msg>INTEGRATION: CWS dr12 (1.25.12); FILE MERGED 2004/08/27 07:46:05 sab 1.25.12.5: RESYNC: (1.37-1.39); FILE MERGED 2004/07/26 22:44:54 sab 1.25.12.4: RESYNC: (1.30-1.37); FILE MERGED 2004/05/06 11:08:19 dr 1.25.12.3: RESYNC: (1.26-1.30); FILE MERGED 2004/02/25 10:35:23 dr 1.25.12.2: RESYNC: (1.25-1.26); FILE MERGED 2004/02/24 09:58:15 jmarmion 1.25.12.1: #i21255# text formatting for cell notes<commit_after><|endoftext|>
|
<commit_before>//===--- TypeCheckPattern.cpp - Type Checking for Patterns ----------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements semantic analysis for patterns, analysing a
// pattern tree in both bottom-up and top-down ways.
//
//===----------------------------------------------------------------------===//
#include "TypeChecker.h"
#include "swift/AST/Attr.h"
#include "swift/AST/ExprHandle.h"
#include "swift/AST/ASTVisitor.h"
using namespace swift;
namespace {
class ResolvePattern : public ASTVisitor<ResolvePattern,
/*ExprRetTy=*/Pattern*,
/*StmtRetTy=*/void,
/*DeclRetTy=*/void,
/*PatternRetTy=*/Pattern*>
{
public:
ASTContext &C;
ResolvePattern(ASTContext &C) : C(C) {}
// Handle productions that are always leaf patterns or are already resolved.
#define ALWAYS_RESOLVED_PATTERN(Id) \
Pattern *visit##Id##Pattern(Id##Pattern *P) { return P; }
ALWAYS_RESOLVED_PATTERN(Named)
ALWAYS_RESOLVED_PATTERN(Any)
ALWAYS_RESOLVED_PATTERN(Isa)
ALWAYS_RESOLVED_PATTERN(Paren)
ALWAYS_RESOLVED_PATTERN(Tuple)
ALWAYS_RESOLVED_PATTERN(NominalType)
ALWAYS_RESOLVED_PATTERN(Typed)
#undef ALWAYS_RESOLVED_PATTERN
Pattern *visitVarPattern(VarPattern *P) {
Pattern *newSub = visit(P->getSubPattern());
P->setSubPattern(newSub);
return P;
}
Pattern *visitExprPattern(ExprPattern *P) {
if (P->isResolved())
return P;
// Try to convert to a pattern.
Pattern *exprAsPattern = visit(P->getSubExpr());
// If we failed, keep the ExprPattern as is.
if (!exprAsPattern) {
P->setResolved(true);
return P;
}
return exprAsPattern;
}
// Most exprs remain exprs and should be wrapped in ExprPatterns.
Pattern *visitExpr(Expr *E) {
return nullptr;
}
// Unwrap UnresolvedPatternExprs.
Pattern *visitUnresolvedPatternExpr(UnresolvedPatternExpr *E) {
return visit(E->getSubPattern());
}
// Parens and tuples have to become patterns if they contain any patterns. If
// they have only exprs as children, a tuple pattern or expr would be
// equivalent, but it avoids some destructuring if we leave them as leaf
// exprs.
Pattern *visitParenExpr(ParenExpr *E) {
if (Pattern *subPattern = visit(E->getSubExpr()))
return new (C) ParenPattern(E->getLParenLoc(), subPattern,
E->getRParenLoc());
return nullptr;
}
Pattern *visitTupleExpr(TupleExpr *E) {
SmallVector<Pattern*, 4> patterns;
bool hasPattern = false;
for (auto *subExpr : E->getElements()) {
Pattern *pattern = visit(subExpr);
hasPattern |= bool(pattern);
patterns.push_back(pattern);
}
// If there were no subpatterns, leave the entire tuple as a leaf
// expression.
if (!hasPattern)
return nullptr;
// Otherwise, construct a TuplePattern.
// FIXME: Carry over field labels.
SmallVector<TuplePatternElt, 4> patternElts;
for (unsigned i = 0, e = E->getNumElements(); i < e; ++i) {
Pattern *pattern = patterns[i];
if (!pattern)
pattern = new (C) ExprPattern(E->getElement(i),
/*isResolved*/ true,
/*matchFn*/ false);
patternElts.push_back(TuplePatternElt(pattern));
}
return TuplePattern::create(C, E->getLoc(),
patternElts, E->getRParenLoc());
}
// TODO: Call syntax 'T(x...)' forms a pattern if 'T' is a type and '(x...)' is a
// TuplePattern with labeled fields.
/*
Pattern *visitCallExpr(CallExpr *E) {
// The arguments must form a tuple with all named keys.
auto *argTuple = dyn_cast<TupleExpr>(E->getArg());
if (!argTuple)
return nullptr;
if (!argTuple->getElementNames())
return nullptr;
for (unsigned i = 0, e = argTuple->getNumElements(); i < e; ++i)
if (!argTuple->getElementName(i).get())
return nullptr;
...;
}
*/
};
} // end anonymous namespace
/// Perform top-down syntactic disambiguation of a pattern. Where ambiguous
/// expr/pattern productions occur (tuples, function calls, etc.), favor the
/// pattern interpretation if it forms a valid pattern; otherwise, leave it as
/// an expression.
Pattern *TypeChecker::resolvePattern(Pattern *P) {
return ResolvePattern(Context).visit(P);
}
/// Perform bottom-up type-checking on a pattern. If this returns
/// false, the type of the pattern will have been set. If allowUnknownTypes is
/// true, then this accepts "any" and "named" patterns, setting their type to
/// UnresolvedType.
bool TypeChecker::typeCheckPattern(Pattern *P, DeclContext *dc,
bool isFirstPass,
bool allowUnknownTypes) {
switch (P->getKind()) {
// Type-check paren patterns by checking the sub-pattern and
// propagating that type out.
case PatternKind::Paren: {
Pattern *SP = cast<ParenPattern>(P)->getSubPattern();
if (typeCheckPattern(SP, dc, isFirstPass, allowUnknownTypes)) {
P->setType(ErrorType::get(Context));
return true;
}
P->setType(SP->getType());
return false;
}
// If we see an explicit type annotation, coerce the sub-pattern to
// that type.
case PatternKind::Typed: {
bool hadError = false;
TypedPattern *TP = cast<TypedPattern>(P);
if (validateType(TP->getTypeLoc())) {
TP->setType(ErrorType::get(Context));
hadError = true;
} else {
TP->setType(TP->getTypeLoc().getType());
}
hadError |= coerceToType(TP->getSubPattern(), dc, P->getType());
return hadError;
}
// A wildcard or name pattern cannot appear by itself in a context
// which requires an explicit type.
case PatternKind::Any:
case PatternKind::Named:
// If we're type checking this pattern in a context that can provide type
// information, then the lack of type information is not an error. Just set
// our type to UnresolvedType.
if (allowUnknownTypes) {
P->setType(Context.TheUnstructuredUnresolvedType);
return false;
}
diagnose(P->getLoc(), diag::cannot_infer_type_for_pattern);
P->setType(ErrorType::get(Context));
return true;
// A tuple pattern propagates its tuple-ness out.
case PatternKind::Tuple: {
bool hadError = false;
SmallVector<TupleTypeElt, 8> typeElts;
for (TuplePatternElt &elt : cast<TuplePattern>(P)->getFields()) {
Type type;
ExprHandle *init = elt.getInit();
Pattern *pattern = elt.getPattern();
if (typeCheckPattern(pattern, dc, isFirstPass, allowUnknownTypes)) {
hadError = true;
} else {
type = pattern->getType();
}
if (init && !isFirstPass && !init->alreadyChecked()) {
Expr *e = init->getExpr();
typeCheckExpression(e, dc, type);
init->setExpr(e, true);
}
typeElts.push_back(TupleTypeElt(type, pattern->getBoundName(), init,
elt.getVarargBaseType()));
}
if (hadError) {
P->setType(ErrorType::get(Context));
return true;
}
P->setType(TupleType::get(typeElts, Context));
return false;
}
#define PATTERN(Id, Parent)
#define REFUTABLE_PATTERN(Id, Parent) case PatternKind::Id:
#include "swift/AST/PatternNodes.def"
llvm_unreachable("not implemented");
}
llvm_unreachable("bad pattern kind!");
}
/// Perform top-down type coercion on the given pattern.
bool TypeChecker::coerceToType(Pattern *P, DeclContext *dc, Type type) {
switch (P->getKind()) {
// For parens and vars, just set the type annotation and propagate inwards.
case PatternKind::Paren:
P->setType(type);
return coerceToType(cast<ParenPattern>(P)->getSubPattern(), dc, type);
case PatternKind::Var:
P->setType(type);
return coerceToType(cast<VarPattern>(P)->getSubPattern(), dc, type);
// If we see an explicit type annotation, coerce the sub-pattern to
// that type.
case PatternKind::Typed: {
TypedPattern *TP = cast<TypedPattern>(P);
bool hadError = false;
if (validateType(TP->getTypeLoc())) {
TP->overwriteType(ErrorType::get(Context));
hadError = true;
} else {
TP->setType(TP->getTypeLoc().getType());
if (!type->isEqual(TP->getType()) && !type->is<ErrorType>()) {
// Complain if the types don't match exactly.
// TODO: allow implicit conversions?
diagnose(P->getLoc(), diag::pattern_type_mismatch_context, type);
hadError = true;
}
}
hadError |= coerceToType(TP->getSubPattern(), dc, TP->getType());
return hadError;
}
// For wildcard and name patterns, just set the type.
case PatternKind::Named: {
NamedPattern *NP = cast<NamedPattern>(P);
NP->getDecl()->overwriteType(type);
P->setType(type);
return false;
}
case PatternKind::Any:
P->setType(type);
return false;
// We can match a tuple pattern with a tuple type.
// TODO: permit implicit conversions?
case PatternKind::Tuple: {
TuplePattern *TP = cast<TuplePattern>(P);
bool hadError = false;
if (type->is<ErrorType>())
hadError = true;
// The context type must be a tuple.
TupleType *tupleTy = type->getAs<TupleType>();
if (!tupleTy && !hadError) {
diagnose(TP->getLParenLoc(), diag::tuple_pattern_in_non_tuple_context,
type);
hadError = true;
}
// The number of elements must match exactly.
// TODO: incomplete tuple patterns, with some syntax.
if (!hadError && tupleTy->getFields().size() != TP->getNumFields()) {
diagnose(TP->getLParenLoc(), diag::tuple_pattern_length_mismatch, type);
hadError = true;
}
// Coerce each tuple element to the respective type.
// TODO: detect and diagnose shuffling
// TODO: permit shuffling
P->setType(type);
for (unsigned i = 0, e = TP->getNumFields(); i != e; ++i) {
TuplePatternElt &elt = TP->getFields()[i];
Pattern *pattern = elt.getPattern();
Type CoercionType;
if (hadError)
CoercionType = ErrorType::get(Context);
else
CoercionType = tupleTy->getFields()[i].getType();
hadError |= coerceToType(pattern, dc, CoercionType);
// Type-check the initialization expression.
if (ExprHandle *initHandle = elt.getInit()) {
Expr *init = initHandle->getExpr();
if (initHandle->alreadyChecked()) {
// Nothing to do
} else if (typeCheckExpression(init, dc, CoercionType)) {
initHandle->setExpr(nullptr, true);
} else {
initHandle->setExpr(init, true);
}
}
}
return hadError;
}
// Coerce expressions to the type.
// TODO: Look up a match operator to resolve the type of the expression.
case PatternKind::Expr: {
ExprPattern *EP = dyn_cast<ExprPattern>(P);
Expr *subExpr = EP->getSubExpr();
if (typeCheckExpression(subExpr, dc, type))
return true;
EP->setSubExpr(subExpr);
EP->setType(type);
return false;
}
// Coerce an 'is' pattern by determining the cast kind.
case PatternKind::Isa: {
// TODO: Resolve the cast kind.
P->setType(type);
return false;
}
case PatternKind::NominalType:
// TODO: Check the type against the coerced type, then coerce the
// subpatterns to the field types.
llvm_unreachable("not implemented");
}
llvm_unreachable("bad pattern kind!");
}
<commit_msg>Fix warning about bool-to-pointer conversion.<commit_after>//===--- TypeCheckPattern.cpp - Type Checking for Patterns ----------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements semantic analysis for patterns, analysing a
// pattern tree in both bottom-up and top-down ways.
//
//===----------------------------------------------------------------------===//
#include "TypeChecker.h"
#include "swift/AST/Attr.h"
#include "swift/AST/ExprHandle.h"
#include "swift/AST/ASTVisitor.h"
using namespace swift;
namespace {
class ResolvePattern : public ASTVisitor<ResolvePattern,
/*ExprRetTy=*/Pattern*,
/*StmtRetTy=*/void,
/*DeclRetTy=*/void,
/*PatternRetTy=*/Pattern*>
{
public:
ASTContext &C;
ResolvePattern(ASTContext &C) : C(C) {}
// Handle productions that are always leaf patterns or are already resolved.
#define ALWAYS_RESOLVED_PATTERN(Id) \
Pattern *visit##Id##Pattern(Id##Pattern *P) { return P; }
ALWAYS_RESOLVED_PATTERN(Named)
ALWAYS_RESOLVED_PATTERN(Any)
ALWAYS_RESOLVED_PATTERN(Isa)
ALWAYS_RESOLVED_PATTERN(Paren)
ALWAYS_RESOLVED_PATTERN(Tuple)
ALWAYS_RESOLVED_PATTERN(NominalType)
ALWAYS_RESOLVED_PATTERN(Typed)
#undef ALWAYS_RESOLVED_PATTERN
Pattern *visitVarPattern(VarPattern *P) {
Pattern *newSub = visit(P->getSubPattern());
P->setSubPattern(newSub);
return P;
}
Pattern *visitExprPattern(ExprPattern *P) {
if (P->isResolved())
return P;
// Try to convert to a pattern.
Pattern *exprAsPattern = visit(P->getSubExpr());
// If we failed, keep the ExprPattern as is.
if (!exprAsPattern) {
P->setResolved(true);
return P;
}
return exprAsPattern;
}
// Most exprs remain exprs and should be wrapped in ExprPatterns.
Pattern *visitExpr(Expr *E) {
return nullptr;
}
// Unwrap UnresolvedPatternExprs.
Pattern *visitUnresolvedPatternExpr(UnresolvedPatternExpr *E) {
return visit(E->getSubPattern());
}
// Parens and tuples have to become patterns if they contain any patterns. If
// they have only exprs as children, a tuple pattern or expr would be
// equivalent, but it avoids some destructuring if we leave them as leaf
// exprs.
Pattern *visitParenExpr(ParenExpr *E) {
if (Pattern *subPattern = visit(E->getSubExpr()))
return new (C) ParenPattern(E->getLParenLoc(), subPattern,
E->getRParenLoc());
return nullptr;
}
Pattern *visitTupleExpr(TupleExpr *E) {
SmallVector<Pattern*, 4> patterns;
bool hasPattern = false;
for (auto *subExpr : E->getElements()) {
Pattern *pattern = visit(subExpr);
hasPattern |= bool(pattern);
patterns.push_back(pattern);
}
// If there were no subpatterns, leave the entire tuple as a leaf
// expression.
if (!hasPattern)
return nullptr;
// Otherwise, construct a TuplePattern.
// FIXME: Carry over field labels.
SmallVector<TuplePatternElt, 4> patternElts;
for (unsigned i = 0, e = E->getNumElements(); i < e; ++i) {
Pattern *pattern = patterns[i];
if (!pattern)
pattern = new (C) ExprPattern(E->getElement(i),
/*isResolved*/ true,
/*matchFn*/ nullptr);
patternElts.push_back(TuplePatternElt(pattern));
}
return TuplePattern::create(C, E->getLoc(),
patternElts, E->getRParenLoc());
}
// TODO: Call syntax 'T(x...)' forms a pattern if 'T' is a type and '(x...)' is a
// TuplePattern with labeled fields.
/*
Pattern *visitCallExpr(CallExpr *E) {
// The arguments must form a tuple with all named keys.
auto *argTuple = dyn_cast<TupleExpr>(E->getArg());
if (!argTuple)
return nullptr;
if (!argTuple->getElementNames())
return nullptr;
for (unsigned i = 0, e = argTuple->getNumElements(); i < e; ++i)
if (!argTuple->getElementName(i).get())
return nullptr;
...;
}
*/
};
} // end anonymous namespace
/// Perform top-down syntactic disambiguation of a pattern. Where ambiguous
/// expr/pattern productions occur (tuples, function calls, etc.), favor the
/// pattern interpretation if it forms a valid pattern; otherwise, leave it as
/// an expression.
Pattern *TypeChecker::resolvePattern(Pattern *P) {
return ResolvePattern(Context).visit(P);
}
/// Perform bottom-up type-checking on a pattern. If this returns
/// false, the type of the pattern will have been set. If allowUnknownTypes is
/// true, then this accepts "any" and "named" patterns, setting their type to
/// UnresolvedType.
bool TypeChecker::typeCheckPattern(Pattern *P, DeclContext *dc,
bool isFirstPass,
bool allowUnknownTypes) {
switch (P->getKind()) {
// Type-check paren patterns by checking the sub-pattern and
// propagating that type out.
case PatternKind::Paren: {
Pattern *SP = cast<ParenPattern>(P)->getSubPattern();
if (typeCheckPattern(SP, dc, isFirstPass, allowUnknownTypes)) {
P->setType(ErrorType::get(Context));
return true;
}
P->setType(SP->getType());
return false;
}
// If we see an explicit type annotation, coerce the sub-pattern to
// that type.
case PatternKind::Typed: {
bool hadError = false;
TypedPattern *TP = cast<TypedPattern>(P);
if (validateType(TP->getTypeLoc())) {
TP->setType(ErrorType::get(Context));
hadError = true;
} else {
TP->setType(TP->getTypeLoc().getType());
}
hadError |= coerceToType(TP->getSubPattern(), dc, P->getType());
return hadError;
}
// A wildcard or name pattern cannot appear by itself in a context
// which requires an explicit type.
case PatternKind::Any:
case PatternKind::Named:
// If we're type checking this pattern in a context that can provide type
// information, then the lack of type information is not an error. Just set
// our type to UnresolvedType.
if (allowUnknownTypes) {
P->setType(Context.TheUnstructuredUnresolvedType);
return false;
}
diagnose(P->getLoc(), diag::cannot_infer_type_for_pattern);
P->setType(ErrorType::get(Context));
return true;
// A tuple pattern propagates its tuple-ness out.
case PatternKind::Tuple: {
bool hadError = false;
SmallVector<TupleTypeElt, 8> typeElts;
for (TuplePatternElt &elt : cast<TuplePattern>(P)->getFields()) {
Type type;
ExprHandle *init = elt.getInit();
Pattern *pattern = elt.getPattern();
if (typeCheckPattern(pattern, dc, isFirstPass, allowUnknownTypes)) {
hadError = true;
} else {
type = pattern->getType();
}
if (init && !isFirstPass && !init->alreadyChecked()) {
Expr *e = init->getExpr();
typeCheckExpression(e, dc, type);
init->setExpr(e, true);
}
typeElts.push_back(TupleTypeElt(type, pattern->getBoundName(), init,
elt.getVarargBaseType()));
}
if (hadError) {
P->setType(ErrorType::get(Context));
return true;
}
P->setType(TupleType::get(typeElts, Context));
return false;
}
#define PATTERN(Id, Parent)
#define REFUTABLE_PATTERN(Id, Parent) case PatternKind::Id:
#include "swift/AST/PatternNodes.def"
llvm_unreachable("not implemented");
}
llvm_unreachable("bad pattern kind!");
}
/// Perform top-down type coercion on the given pattern.
bool TypeChecker::coerceToType(Pattern *P, DeclContext *dc, Type type) {
switch (P->getKind()) {
// For parens and vars, just set the type annotation and propagate inwards.
case PatternKind::Paren:
P->setType(type);
return coerceToType(cast<ParenPattern>(P)->getSubPattern(), dc, type);
case PatternKind::Var:
P->setType(type);
return coerceToType(cast<VarPattern>(P)->getSubPattern(), dc, type);
// If we see an explicit type annotation, coerce the sub-pattern to
// that type.
case PatternKind::Typed: {
TypedPattern *TP = cast<TypedPattern>(P);
bool hadError = false;
if (validateType(TP->getTypeLoc())) {
TP->overwriteType(ErrorType::get(Context));
hadError = true;
} else {
TP->setType(TP->getTypeLoc().getType());
if (!type->isEqual(TP->getType()) && !type->is<ErrorType>()) {
// Complain if the types don't match exactly.
// TODO: allow implicit conversions?
diagnose(P->getLoc(), diag::pattern_type_mismatch_context, type);
hadError = true;
}
}
hadError |= coerceToType(TP->getSubPattern(), dc, TP->getType());
return hadError;
}
// For wildcard and name patterns, just set the type.
case PatternKind::Named: {
NamedPattern *NP = cast<NamedPattern>(P);
NP->getDecl()->overwriteType(type);
P->setType(type);
return false;
}
case PatternKind::Any:
P->setType(type);
return false;
// We can match a tuple pattern with a tuple type.
// TODO: permit implicit conversions?
case PatternKind::Tuple: {
TuplePattern *TP = cast<TuplePattern>(P);
bool hadError = false;
if (type->is<ErrorType>())
hadError = true;
// The context type must be a tuple.
TupleType *tupleTy = type->getAs<TupleType>();
if (!tupleTy && !hadError) {
diagnose(TP->getLParenLoc(), diag::tuple_pattern_in_non_tuple_context,
type);
hadError = true;
}
// The number of elements must match exactly.
// TODO: incomplete tuple patterns, with some syntax.
if (!hadError && tupleTy->getFields().size() != TP->getNumFields()) {
diagnose(TP->getLParenLoc(), diag::tuple_pattern_length_mismatch, type);
hadError = true;
}
// Coerce each tuple element to the respective type.
// TODO: detect and diagnose shuffling
// TODO: permit shuffling
P->setType(type);
for (unsigned i = 0, e = TP->getNumFields(); i != e; ++i) {
TuplePatternElt &elt = TP->getFields()[i];
Pattern *pattern = elt.getPattern();
Type CoercionType;
if (hadError)
CoercionType = ErrorType::get(Context);
else
CoercionType = tupleTy->getFields()[i].getType();
hadError |= coerceToType(pattern, dc, CoercionType);
// Type-check the initialization expression.
if (ExprHandle *initHandle = elt.getInit()) {
Expr *init = initHandle->getExpr();
if (initHandle->alreadyChecked()) {
// Nothing to do
} else if (typeCheckExpression(init, dc, CoercionType)) {
initHandle->setExpr(nullptr, true);
} else {
initHandle->setExpr(init, true);
}
}
}
return hadError;
}
// Coerce expressions to the type.
// TODO: Look up a match operator to resolve the type of the expression.
case PatternKind::Expr: {
ExprPattern *EP = dyn_cast<ExprPattern>(P);
Expr *subExpr = EP->getSubExpr();
if (typeCheckExpression(subExpr, dc, type))
return true;
EP->setSubExpr(subExpr);
EP->setType(type);
return false;
}
// Coerce an 'is' pattern by determining the cast kind.
case PatternKind::Isa: {
// TODO: Resolve the cast kind.
P->setType(type);
return false;
}
case PatternKind::NominalType:
// TODO: Check the type against the coerced type, then coerce the
// subpatterns to the field types.
llvm_unreachable("not implemented");
}
llvm_unreachable("bad pattern kind!");
}
<|endoftext|>
|
<commit_before>//===-- ConstantRange.cpp - ConstantRange implementation ------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Represent a range of possible values that may occur when the program is run
// for an integral value. This keeps track of a lower and upper bound for the
// constant, which MAY wrap around the end of the numeric range. To do this, it
// keeps track of a [lower, upper) bound, which specifies an interval just like
// STL iterators. When used with boolean values, the following are important
// ranges (other integral ranges use min/max values for special range values):
//
// [F, F) = {} = Empty set
// [T, F) = {T}
// [F, T) = {F}
// [T, T) = {F, T} = Full set
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/ConstantRange.h"
#include "llvm/Support/Streams.h"
#include <ostream>
using namespace llvm;
/// Initialize a full (the default) or empty set for the specified type.
///
ConstantRange::ConstantRange(uint32_t BitWidth, bool Full) :
Lower(BitWidth, 0), Upper(BitWidth, 0) {
if (Full)
Lower = Upper = APInt::getMaxValue(BitWidth);
else
Lower = Upper = APInt::getMinValue(BitWidth);
}
/// Initialize a range to hold the single specified value.
///
ConstantRange::ConstantRange(const APInt & V) : Lower(V), Upper(V + 1) { }
ConstantRange::ConstantRange(const APInt &L, const APInt &U) :
Lower(L), Upper(U) {
assert(L.getBitWidth() == U.getBitWidth() &&
"ConstantRange with unequal bit widths");
uint32_t BitWidth = L.getBitWidth();
assert((L != U || (L == APInt::getMaxValue(BitWidth) ||
L == APInt::getMinValue(BitWidth))) &&
"Lower == Upper, but they aren't min or max value!");
}
/// isFullSet - Return true if this set contains all of the elements possible
/// for this data-type
bool ConstantRange::isFullSet() const {
return Lower == Upper && Lower == APInt::getMaxValue(getBitWidth());
}
/// isEmptySet - Return true if this set contains no members.
///
bool ConstantRange::isEmptySet() const {
return Lower == Upper && Lower == APInt::getMinValue(getBitWidth());
}
/// isWrappedSet - Return true if this set wraps around the top of the range,
/// for example: [100, 8)
///
bool ConstantRange::isWrappedSet() const {
return Lower.ugt(Upper);
}
/// getSetSize - Return the number of elements in this set.
///
APInt ConstantRange::getSetSize() const {
if (isEmptySet())
return APInt(getBitWidth(), 0);
if (getBitWidth() == 1) {
if (Lower != Upper) // One of T or F in the set...
return APInt(2, 1);
return APInt(2, 2); // Must be full set...
}
// Simply subtract the bounds...
return Upper - Lower;
}
/// contains - Return true if the specified value is in the set.
///
bool ConstantRange::contains(const APInt &V) const {
if (Lower == Upper)
return isFullSet();
if (!isWrappedSet())
return Lower.ule(V) && V.ult(Upper);
else
return Lower.ule(V) || V.ult(Upper);
}
/// subtract - Subtract the specified constant from the endpoints of this
/// constant range.
ConstantRange ConstantRange::subtract(const APInt &Val) const {
assert(Val.getBitWidth() == getBitWidth() && "Wrong bit width");
// If the set is empty or full, don't modify the endpoints.
if (Lower == Upper)
return *this;
return ConstantRange(Lower - Val, Upper - Val);
}
// intersect1Wrapped - This helper function is used to intersect two ranges when
// it is known that LHS is wrapped and RHS isn't.
//
ConstantRange
ConstantRange::intersect1Wrapped(const ConstantRange &LHS,
const ConstantRange &RHS) {
assert(LHS.isWrappedSet() && !RHS.isWrappedSet());
// Check to see if we overlap on the Left side of RHS...
//
if (RHS.Lower.ult(LHS.Upper)) {
// We do overlap on the left side of RHS, see if we overlap on the right of
// RHS...
if (RHS.Upper.ugt(LHS.Lower)) {
// Ok, the result overlaps on both the left and right sides. See if the
// resultant interval will be smaller if we wrap or not...
//
if (LHS.getSetSize().ult(RHS.getSetSize()))
return LHS;
else
return RHS;
} else {
// No overlap on the right, just on the left.
return ConstantRange(RHS.Lower, LHS.Upper);
}
} else {
// We don't overlap on the left side of RHS, see if we overlap on the right
// of RHS...
if (RHS.Upper.ugt(LHS.Lower)) {
// Simple overlap...
return ConstantRange(LHS.Lower, RHS.Upper);
} else {
// No overlap...
return ConstantRange(LHS.getBitWidth(), false);
}
}
}
/// intersectWith - Return the range that results from the intersection of this
/// range with another range.
///
ConstantRange ConstantRange::intersectWith(const ConstantRange &CR) const {
assert(getBitWidth() == CR.getBitWidth() &&
"ConstantRange types don't agree!");
// Handle common special cases
if (isEmptySet() || CR.isFullSet())
return *this;
if (isFullSet() || CR.isEmptySet())
return CR;
if (!isWrappedSet()) {
if (!CR.isWrappedSet()) {
using namespace APIntOps;
APInt L = umax(Lower, CR.Lower);
APInt U = umin(Upper, CR.Upper);
if (L.ult(U)) // If range isn't empty...
return ConstantRange(L, U);
else
return ConstantRange(getBitWidth(), false);// Otherwise, empty set
} else
return intersect1Wrapped(CR, *this);
} else { // We know "this" is wrapped...
if (!CR.isWrappedSet())
return intersect1Wrapped(*this, CR);
else {
// Both ranges are wrapped...
using namespace APIntOps;
APInt L = umax(Lower, CR.Lower);
APInt U = umin(Upper, CR.Upper);
return ConstantRange(L, U);
}
}
return *this;
}
/// unionWith - Return the range that results from the union of this range with
/// another range. The resultant range is guaranteed to include the elements of
/// both sets, but may contain more. For example, [3, 9) union [12,15) is [3,
/// 15), which includes 9, 10, and 11, which were not included in either set
/// before.
///
ConstantRange ConstantRange::unionWith(const ConstantRange &CR) const {
assert(getBitWidth() == CR.getBitWidth() &&
"ConstantRange types don't agree!");
assert(0 && "Range union not implemented yet!");
return *this;
}
/// zeroExtend - Return a new range in the specified integer type, which must
/// be strictly larger than the current type. The returned range will
/// correspond to the possible range of values as if the source range had been
/// zero extended.
ConstantRange ConstantRange::zeroExtend(uint32_t DstTySize) const {
unsigned SrcTySize = getBitWidth();
assert(SrcTySize < DstTySize && "Not a value extension");
if (isFullSet())
// Change a source full set into [0, 1 << 8*numbytes)
return ConstantRange(APInt(DstTySize,0), APInt(DstTySize,1).shl(SrcTySize));
APInt L = Lower; L.zext(DstTySize);
APInt U = Upper; U.zext(DstTySize);
return ConstantRange(L, U);
}
/// truncate - Return a new range in the specified integer type, which must be
/// strictly smaller than the current type. The returned range will
/// correspond to the possible range of values as if the source range had been
/// truncated to the specified type.
ConstantRange ConstantRange::truncate(uint32_t DstTySize) const {
unsigned SrcTySize = getBitWidth();
assert(SrcTySize > DstTySize && "Not a value truncation");
APInt Size = APInt::getMaxValue(DstTySize).zext(SrcTySize);
if (isFullSet() || getSetSize().ugt(Size))
return ConstantRange(DstTySize);
APInt L = Lower; L.trunc(DstTySize);
APInt U = Upper; U.trunc(DstTySize);
return ConstantRange(L, U);
}
/// print - Print out the bounds to a stream...
///
void ConstantRange::print(std::ostream &OS) const {
OS << "[" << Lower.toStringSigned(10) << ","
<< Upper.toStringSigned(10) << " )";
}
/// dump - Allow printing from a debugger easily...
///
void ConstantRange::dump() const {
print(cerr);
}
<commit_msg>Implement unionWith.<commit_after>//===-- ConstantRange.cpp - ConstantRange implementation ------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Represent a range of possible values that may occur when the program is run
// for an integral value. This keeps track of a lower and upper bound for the
// constant, which MAY wrap around the end of the numeric range. To do this, it
// keeps track of a [lower, upper) bound, which specifies an interval just like
// STL iterators. When used with boolean values, the following are important
// ranges (other integral ranges use min/max values for special range values):
//
// [F, F) = {} = Empty set
// [T, F) = {T}
// [F, T) = {F}
// [T, T) = {F, T} = Full set
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/ConstantRange.h"
#include "llvm/Support/Streams.h"
#include <ostream>
using namespace llvm;
/// Initialize a full (the default) or empty set for the specified type.
///
ConstantRange::ConstantRange(uint32_t BitWidth, bool Full) :
Lower(BitWidth, 0), Upper(BitWidth, 0) {
if (Full)
Lower = Upper = APInt::getMaxValue(BitWidth);
else
Lower = Upper = APInt::getMinValue(BitWidth);
}
/// Initialize a range to hold the single specified value.
///
ConstantRange::ConstantRange(const APInt & V) : Lower(V), Upper(V + 1) { }
ConstantRange::ConstantRange(const APInt &L, const APInt &U) :
Lower(L), Upper(U) {
assert(L.getBitWidth() == U.getBitWidth() &&
"ConstantRange with unequal bit widths");
uint32_t BitWidth = L.getBitWidth();
assert((L != U || (L == APInt::getMaxValue(BitWidth) ||
L == APInt::getMinValue(BitWidth))) &&
"Lower == Upper, but they aren't min or max value!");
}
/// isFullSet - Return true if this set contains all of the elements possible
/// for this data-type
bool ConstantRange::isFullSet() const {
return Lower == Upper && Lower == APInt::getMaxValue(getBitWidth());
}
/// isEmptySet - Return true if this set contains no members.
///
bool ConstantRange::isEmptySet() const {
return Lower == Upper && Lower == APInt::getMinValue(getBitWidth());
}
/// isWrappedSet - Return true if this set wraps around the top of the range,
/// for example: [100, 8)
///
bool ConstantRange::isWrappedSet() const {
return Lower.ugt(Upper);
}
/// getSetSize - Return the number of elements in this set.
///
APInt ConstantRange::getSetSize() const {
if (isEmptySet())
return APInt(getBitWidth(), 0);
if (getBitWidth() == 1) {
if (Lower != Upper) // One of T or F in the set...
return APInt(2, 1);
return APInt(2, 2); // Must be full set...
}
// Simply subtract the bounds...
return Upper - Lower;
}
/// contains - Return true if the specified value is in the set.
///
bool ConstantRange::contains(const APInt &V) const {
if (Lower == Upper)
return isFullSet();
if (!isWrappedSet())
return Lower.ule(V) && V.ult(Upper);
else
return Lower.ule(V) || V.ult(Upper);
}
/// subtract - Subtract the specified constant from the endpoints of this
/// constant range.
ConstantRange ConstantRange::subtract(const APInt &Val) const {
assert(Val.getBitWidth() == getBitWidth() && "Wrong bit width");
// If the set is empty or full, don't modify the endpoints.
if (Lower == Upper)
return *this;
return ConstantRange(Lower - Val, Upper - Val);
}
// intersect1Wrapped - This helper function is used to intersect two ranges when
// it is known that LHS is wrapped and RHS isn't.
//
ConstantRange
ConstantRange::intersect1Wrapped(const ConstantRange &LHS,
const ConstantRange &RHS) {
assert(LHS.isWrappedSet() && !RHS.isWrappedSet());
// Check to see if we overlap on the Left side of RHS...
//
if (RHS.Lower.ult(LHS.Upper)) {
// We do overlap on the left side of RHS, see if we overlap on the right of
// RHS...
if (RHS.Upper.ugt(LHS.Lower)) {
// Ok, the result overlaps on both the left and right sides. See if the
// resultant interval will be smaller if we wrap or not...
//
if (LHS.getSetSize().ult(RHS.getSetSize()))
return LHS;
else
return RHS;
} else {
// No overlap on the right, just on the left.
return ConstantRange(RHS.Lower, LHS.Upper);
}
} else {
// We don't overlap on the left side of RHS, see if we overlap on the right
// of RHS...
if (RHS.Upper.ugt(LHS.Lower)) {
// Simple overlap...
return ConstantRange(LHS.Lower, RHS.Upper);
} else {
// No overlap...
return ConstantRange(LHS.getBitWidth(), false);
}
}
}
/// intersectWith - Return the range that results from the intersection of this
/// range with another range.
///
ConstantRange ConstantRange::intersectWith(const ConstantRange &CR) const {
assert(getBitWidth() == CR.getBitWidth() &&
"ConstantRange types don't agree!");
// Handle common special cases
if (isEmptySet() || CR.isFullSet())
return *this;
if (isFullSet() || CR.isEmptySet())
return CR;
if (!isWrappedSet()) {
if (!CR.isWrappedSet()) {
using namespace APIntOps;
APInt L = umax(Lower, CR.Lower);
APInt U = umin(Upper, CR.Upper);
if (L.ult(U)) // If range isn't empty...
return ConstantRange(L, U);
else
return ConstantRange(getBitWidth(), false);// Otherwise, empty set
} else
return intersect1Wrapped(CR, *this);
} else { // We know "this" is wrapped...
if (!CR.isWrappedSet())
return intersect1Wrapped(*this, CR);
else {
// Both ranges are wrapped...
using namespace APIntOps;
APInt L = umax(Lower, CR.Lower);
APInt U = umin(Upper, CR.Upper);
return ConstantRange(L, U);
}
}
return *this;
}
/// unionWith - Return the range that results from the union of this range with
/// another range. The resultant range is guaranteed to include the elements of
/// both sets, but may contain more. For example, [3, 9) union [12,15) is [3,
/// 15), which includes 9, 10, and 11, which were not included in either set
/// before.
///
ConstantRange ConstantRange::unionWith(const ConstantRange &CR) const {
assert(getBitWidth() == CR.getBitWidth() &&
"ConstantRange types don't agree!");
if ( isFullSet() || CR.isEmptySet()) return *this;
if (CR.isFullSet() || isEmptySet()) return CR;
APInt L = Lower, U = Upper;
if (!contains(CR.Lower))
L = APIntOps::umin(L, CR.Lower);
if (!contains(CR.Upper - 1))
U = APIntOps::umax(U, CR.Upper);
return ConstantRange(L, U);
}
/// zeroExtend - Return a new range in the specified integer type, which must
/// be strictly larger than the current type. The returned range will
/// correspond to the possible range of values as if the source range had been
/// zero extended.
ConstantRange ConstantRange::zeroExtend(uint32_t DstTySize) const {
unsigned SrcTySize = getBitWidth();
assert(SrcTySize < DstTySize && "Not a value extension");
if (isFullSet())
// Change a source full set into [0, 1 << 8*numbytes)
return ConstantRange(APInt(DstTySize,0), APInt(DstTySize,1).shl(SrcTySize));
APInt L = Lower; L.zext(DstTySize);
APInt U = Upper; U.zext(DstTySize);
return ConstantRange(L, U);
}
/// truncate - Return a new range in the specified integer type, which must be
/// strictly smaller than the current type. The returned range will
/// correspond to the possible range of values as if the source range had been
/// truncated to the specified type.
ConstantRange ConstantRange::truncate(uint32_t DstTySize) const {
unsigned SrcTySize = getBitWidth();
assert(SrcTySize > DstTySize && "Not a value truncation");
APInt Size = APInt::getMaxValue(DstTySize).zext(SrcTySize);
if (isFullSet() || getSetSize().ugt(Size))
return ConstantRange(DstTySize);
APInt L = Lower; L.trunc(DstTySize);
APInt U = Upper; U.trunc(DstTySize);
return ConstantRange(L, U);
}
/// print - Print out the bounds to a stream...
///
void ConstantRange::print(std::ostream &OS) const {
OS << "[" << Lower.toStringSigned(10) << ","
<< Upper.toStringSigned(10) << " )";
}
/// dump - Allow printing from a debugger easily...
///
void ConstantRange::dump() const {
print(cerr);
}
<|endoftext|>
|
<commit_before>//g++ *.cpp -lpthread -lwiringPi -std=c++11
//LATER MET GUI MAKEFILE <sudo make>
#include "Sensor.h"
#include "I22cCom.h"
#include "Log.h"
#include "Camera.h"
#include "Light.h"
#include "MotionSensor.h"
#include "PressureSensor.h"
#define I2CLOC "/dev/i2c-1"// <-- this is the real I2C device you need with the scale model
///#define I2CLOC "/dev/simudrv"
#define LOG "Slaaplog.txt"
#include <vector>
#include <iostream>
#include <wiringPi.h> //compile with -lwiringPi
using namespace std;
vector<Sensor*> motionSensors; //Vector of the sensors
vector<Light*> lights; //Vector of the lights
vector<int> active;
PressureSensor& pressureSensor;
Camera* cam; //Pointer to the camera
Log* log;
int pressureValue;
bool sleep = false;
bool day = true;
bool anomaly = false;
int temperature = 20;
int sumActive(int active[]) {
int sum=0;
for(int i=0;i<sizeof(active[])/sizeof(active[0]);i++)
sum+=active[i];
return sum;
}
void checkAnomaly();
void updateSensors();
void checkCam();
void sendAlert();
void init();
int main() {
init();
while(1) {
/*
for(int i=0;i<sensors.capacity();i++) // For every sensor
if(sensors[i]->Check()) { // Call their check function
active[i]=1; // And if the check is positive (returns true).
//TODO ENABLE LIGHTS
} else active[i]=0;
if(sumActive(active)==0) {
sendAlert();
}
for(i=0;i<lights.capacity();i++) // For every light
lights[i]->Check(); // Check if timer expired yet
*/
updateSensors();
checkAnomaly();
checkCam();
}
}
/*Init for the main*/
void init() {
wiringPiSetupGpio();
I2CCom i2c(I2CLOC); //the i2c to communicate with sensors
Light x(22);
MotionSensor s1(0x05,i2c);
PressureSensor s2(0x06, i2c);
Log l1(LOG);
Camera c1();
cam = &c1
log = &l1;
pressureSensor = &s2;
motionSensors.push_back(&s1);
lights.push_back(&x);
active.resize(motionSensors.size);
}
/*Updates sensors*/
void updateSensors() {
//update van elke sensor de value en de active
bool alert = true;
for(int i = 0; i<motionSensors.size();i++) {
if(motionSensors[i]->check()) {
active[i]=1;
alert = false;
} else {
active[i]=0;
}
}
if(alert && sleep = false) {
sendAlert();
}
}
/*Send Alarm*/
void sendAlert(){
cout<<"Alert"<<endl;
}
/*Sets the camera*/
void checkCam(){
if(day) {
cam.setCamera(true);
} else if(anomaly) {
cam.setCamera(true);
} else {
cam.setCamera(false);
}
}
void checkAnomaly(){
if(pressureValue > 20 && pressureValue < 150) {
anomaly = true;
}
if(pressureValue > 150 && pressureValue < 200) { // Changing positions while asleep
//Do nothing, maybe verify if person really is sleeping
}
if(pressureValue > 200) {
sleep = true;
}
}
<commit_msg>bug fix<commit_after>//g++ *.cpp -lpthread -lwiringPi -std=c++11
//LATER MET GUI MAKEFILE <sudo make>
#include "Sensor.h"
#include "I22cCom.h"
#include "Log.h"
#include "Camera.h"
#include "Light.h"
#include "MotionSensor.h"
#include "PressureSensor.h"
#define I2CLOC "/dev/i2c-1"// <-- this is the real I2C device you need with the scale model
///#define I2CLOC "/dev/simudrv"
#define LOG "Slaaplog.txt"
#include <vector>
#include <iostream>
#include <wiringPi.h> //compile with -lwiringPi
using namespace std;
vector<Sensor*> motionSensors; //Vector of the sensors
vector<Light*> lights; //Vector of the lights
vector<int> active;
PressureSensor& pressureSensor;
Camera* cam; //Pointer to the camera
Log* log;
int pressureValue;
bool sleep = false;
bool day = true;
bool anomaly = false;
int temperature = 20;
int sumActive(int active[]) {
int sum=0;
for(int i=0;i<sizeof(active[])/sizeof(active[0]);i++)
sum+=active[i];
return sum;
}
void checkAnomaly();
void updateSensors();
void checkCam();
void sendAlert();
void init();
int main() {
init();
while(1) {
/*
for(int i=0;i<sensors.capacity();i++) // For every sensor
if(sensors[i]->Check()) { // Call their check function
active[i]=1; // And if the check is positive (returns true).
//TODO ENABLE LIGHTS
} else active[i]=0;
if(sumActive(active)==0) {
sendAlert();
}
for(i=0;i<lights.capacity();i++) // For every light
lights[i]->Check(); // Check if timer expired yet
*/
updateSensors();
checkAnomaly();
checkCam();
}
}
/*Init for the main*/
void init() {
wiringPiSetupGpio();
I2CCom i2c(I2CLOC); //the i2c to communicate with sensors
Light x(22);
MotionSensor s1(0x05,i2c);
PressureSensor s2(0x06, i2c);
Log l1(LOG);
Camera c1();
cam = &c1
log = &l1;
pressureSensor = &s2;
motionSensors.push_back(&s1);
lights.push_back(&x);
active.resize(motionSensors.size);
}
/*Updates sensors*/
void updateSensors() {
//update van elke sensor de value en de active
bool alert = true;
for(int i = 0; i<motionSensors.size();i++) {
if(motionSensors[i]->check()) {
active[i]=1;
alert = false;
} else {
active[i]=0;
}
}
if(alert && sleep = false) {
sendAlert();
}
}
/*Send Alarm*/
void sendAlert(){
cout<<"Alert"<<endl;
}
/*Sets the camera*/
void checkCam(){
if(day) {
cam->setCamera(true);
} else if(anomaly) {
cam->setCamera(true);
} else {
cam->setCamera(false);
}
}
void checkAnomaly(){
if(pressureValue > 20 && pressureValue < 150) {
anomaly = true;
}
if(pressureValue > 150 && pressureValue < 200) { // Changing positions while asleep
//Do nothing, maybe verify if person really is sleeping
}
if(pressureValue > 200) {
sleep = true;
}
}
<|endoftext|>
|
<commit_before>//===-- X86JITInfo.cpp - Implement the JIT interfaces for the X86 target --===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the JIT interfaces for the X86 target.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "jit"
#include <cstdlib>
#include "X86JITInfo.h"
#include "X86Relocations.h"
#include "llvm/CodeGen/MachineCodeEmitter.h"
#include "llvm/Config/alloca.h"
using namespace llvm;
void X86JITInfo::replaceMachineCodeForFunction(void *Old, void *New) {
unsigned char *OldByte = (unsigned char *)Old;
*OldByte++ = 0xE9; // Emit JMP opcode.
unsigned *OldWord = (unsigned *)OldByte;
unsigned NewAddr = (intptr_t)New;
unsigned OldAddr = (intptr_t)OldWord;
*OldWord = NewAddr - OldAddr - 4; // Emit PC-relative addr of New code.
}
/// JITCompilerFunction - This contains the address of the JIT function used to
/// compile a function lazily.
static TargetJITInfo::JITCompilerFn JITCompilerFunction;
// Provide a wrapper for X86CompilationCallback2 that saves non-traditional
// callee saved registers, for the fastcc calling convention.
extern "C" {
#if defined(__i386__) || defined(i386) || defined(_M_IX86)
#ifndef _MSC_VER
void X86CompilationCallback(void);
asm(
".text\n"
".align 8\n"
".globl X86CompilationCallback\n"
"X86CompilationCallback:\n"
"pushl %ebp\n"
"movl %esp, %ebp\n" // Standard prologue
"pushl %eax\n"
"pushl %edx\n" // save EAX/EDX
"call X86CompilationCallback2\n"
"popl %edx\n"
"popl %eax\n"
"popl %ebp\n"
"ret\n");
#else
extern "C" void *_AddressOfReturnAddress(void);
#pragma intrinsic(_AddressOfReturnAddress)
void X86CompilationCallback2(void);
_declspec(naked) void X86CompilationCallback(void) {
__asm {
push eax
push edx
call X86CompilationCallback2
pop edx
pop eax
ret
}
}
#endif
#else
// Not an i386 host
void X86CompilationCallback() {
assert(0 && "This is not a X86, you can't execute this!");
abort();
}
#endif
}
/// X86CompilationCallback - This is the target-specific function invoked by the
/// function stub when we did not know the real target of a call. This function
/// must locate the start of the stub or call site and pass it into the JIT
/// compiler function.
extern "C" void X86CompilationCallback2() {
#ifdef _MSC_VER
assert(sizeof(size_t) == 4); // FIXME: handle Win64
unsigned *RetAddrLoc = (unsigned *)_AddressOfReturnAddress();
RetAddrLoc += 3; // skip over ret addr, edx, eax
unsigned RetAddr = *RetAddrLoc;
#else
unsigned *StackPtr = (unsigned*)__builtin_frame_address(1);
unsigned RetAddr = (unsigned)(intptr_t)__builtin_return_address(1);
unsigned *RetAddrLoc = &StackPtr[1];
// NOTE: __builtin_frame_address doesn't work if frame pointer elimination has
// been performed. Having a variable sized alloca disables frame pointer
// elimination currently, even if it's dead. This is a gross hack.
alloca(10+(RetAddr >> 31));
#endif
assert(*RetAddrLoc == RetAddr &&
"Could not find return address on the stack!");
// It's a stub if there is an interrupt marker after the call.
bool isStub = ((unsigned char*)(intptr_t)RetAddr)[0] == 0xCD;
// The call instruction should have pushed the return value onto the stack...
RetAddr -= 4; // Backtrack to the reference itself...
#if 0
DEBUG(std::cerr << "In callback! Addr=" << (void*)RetAddr
<< " ESP=" << (void*)StackPtr
<< ": Resolving call to function: "
<< TheVM->getFunctionReferencedName((void*)RetAddr) << "\n");
#endif
// Sanity check to make sure this really is a call instruction.
assert(((unsigned char*)(intptr_t)RetAddr)[-1] == 0xE8 &&"Not a call instr!");
unsigned NewVal = (intptr_t)JITCompilerFunction((void*)(intptr_t)RetAddr);
// Rewrite the call target... so that we don't end up here every time we
// execute the call.
*(unsigned*)(intptr_t)RetAddr = NewVal-RetAddr-4;
if (isStub) {
// If this is a stub, rewrite the call into an unconditional branch
// instruction so that two return addresses are not pushed onto the stack
// when the requested function finally gets called. This also makes the
// 0xCD byte (interrupt) dead, so the marker doesn't effect anything.
((unsigned char*)(intptr_t)RetAddr)[-1] = 0xE9;
}
// Change the return address to reexecute the call instruction...
*RetAddrLoc -= 5;
}
TargetJITInfo::LazyResolverFn
X86JITInfo::getLazyResolverFunction(JITCompilerFn F) {
JITCompilerFunction = F;
return X86CompilationCallback;
}
void *X86JITInfo::emitFunctionStub(void *Fn, MachineCodeEmitter &MCE) {
if (Fn != X86CompilationCallback) {
MCE.startFunctionStub(5);
MCE.emitByte(0xE9);
MCE.emitWord((intptr_t)Fn-MCE.getCurrentPCValue()-4);
return MCE.finishFunctionStub(0);
}
MCE.startFunctionStub(6);
MCE.emitByte(0xE8); // Call with 32 bit pc-rel destination...
MCE.emitWord((intptr_t)Fn-MCE.getCurrentPCValue()-4);
MCE.emitByte(0xCD); // Interrupt - Just a marker identifying the stub!
return MCE.finishFunctionStub(0);
}
/// relocate - Before the JIT can run a block of code that has been emitted,
/// it must rewrite the code to contain the actual addresses of any
/// referenced global symbols.
void X86JITInfo::relocate(void *Function, MachineRelocation *MR,
unsigned NumRelocs) {
for (unsigned i = 0; i != NumRelocs; ++i, ++MR) {
void *RelocPos = (char*)Function + MR->getMachineCodeOffset();
intptr_t ResultPtr = (intptr_t)MR->getResultPointer();
switch ((X86::RelocationType)MR->getRelocationType()) {
case X86::reloc_pcrel_word:
// PC relative relocation, add the relocated value to the value already in
// memory, after we adjust it for where the PC is.
ResultPtr = ResultPtr-(intptr_t)RelocPos-4;
*((intptr_t*)RelocPos) += ResultPtr;
break;
case X86::reloc_absolute_word:
// Absolute relocation, just add the relocated value to the value already
// in memory.
*((intptr_t*)RelocPos) += ResultPtr;
break;
}
}
}
<commit_msg>Since everyone else has "fixed" this file, might as well join in the fun. * Change assert() to std::cerr printout, as it will not appear in opt builds * Add comments to clarify what #ifdef/#else/#endif match what condition(s)<commit_after>//===-- X86JITInfo.cpp - Implement the JIT interfaces for the X86 target --===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the JIT interfaces for the X86 target.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "jit"
#include <cstdlib>
#include "X86JITInfo.h"
#include "X86Relocations.h"
#include "llvm/CodeGen/MachineCodeEmitter.h"
#include "llvm/Config/alloca.h"
using namespace llvm;
void X86JITInfo::replaceMachineCodeForFunction(void *Old, void *New) {
unsigned char *OldByte = (unsigned char *)Old;
*OldByte++ = 0xE9; // Emit JMP opcode.
unsigned *OldWord = (unsigned *)OldByte;
unsigned NewAddr = (intptr_t)New;
unsigned OldAddr = (intptr_t)OldWord;
*OldWord = NewAddr - OldAddr - 4; // Emit PC-relative addr of New code.
}
/// JITCompilerFunction - This contains the address of the JIT function used to
/// compile a function lazily.
static TargetJITInfo::JITCompilerFn JITCompilerFunction;
// Provide a wrapper for X86CompilationCallback2 that saves non-traditional
// callee saved registers, for the fastcc calling convention.
extern "C" {
#if defined(__i386__) || defined(i386) || defined(_M_IX86)
#ifndef _MSC_VER
void X86CompilationCallback(void);
asm(
".text\n"
".align 8\n"
".globl X86CompilationCallback\n"
"X86CompilationCallback:\n"
"pushl %ebp\n"
"movl %esp, %ebp\n" // Standard prologue
"pushl %eax\n"
"pushl %edx\n" // save EAX/EDX
"call X86CompilationCallback2\n"
"popl %edx\n"
"popl %eax\n"
"popl %ebp\n"
"ret\n");
#else
extern "C" void *_AddressOfReturnAddress(void);
#pragma intrinsic(_AddressOfReturnAddress)
void X86CompilationCallback2(void);
_declspec(naked) void X86CompilationCallback(void) {
__asm {
push eax
push edx
call X86CompilationCallback2
pop edx
pop eax
ret
}
}
#endif // _MSC_VER
#else // Not an i386 host
void X86CompilationCallback() {
std::cerr << "Cannot call X86CompilationCallback() on a non-x86 arch!\n";
abort();
}
#endif
}
/// X86CompilationCallback - This is the target-specific function invoked by the
/// function stub when we did not know the real target of a call. This function
/// must locate the start of the stub or call site and pass it into the JIT
/// compiler function.
extern "C" void X86CompilationCallback2() {
#ifdef _MSC_VER
assert(sizeof(size_t) == 4); // FIXME: handle Win64
unsigned *RetAddrLoc = (unsigned *)_AddressOfReturnAddress();
RetAddrLoc += 3; // skip over ret addr, edx, eax
unsigned RetAddr = *RetAddrLoc;
#else
unsigned *StackPtr = (unsigned*)__builtin_frame_address(1);
unsigned RetAddr = (unsigned)(intptr_t)__builtin_return_address(1);
unsigned *RetAddrLoc = &StackPtr[1];
// NOTE: __builtin_frame_address doesn't work if frame pointer elimination has
// been performed. Having a variable sized alloca disables frame pointer
// elimination currently, even if it's dead. This is a gross hack.
alloca(10+(RetAddr >> 31));
#endif
assert(*RetAddrLoc == RetAddr &&
"Could not find return address on the stack!");
// It's a stub if there is an interrupt marker after the call.
bool isStub = ((unsigned char*)(intptr_t)RetAddr)[0] == 0xCD;
// The call instruction should have pushed the return value onto the stack...
RetAddr -= 4; // Backtrack to the reference itself...
#if 0
DEBUG(std::cerr << "In callback! Addr=" << (void*)RetAddr
<< " ESP=" << (void*)StackPtr
<< ": Resolving call to function: "
<< TheVM->getFunctionReferencedName((void*)RetAddr) << "\n");
#endif
// Sanity check to make sure this really is a call instruction.
assert(((unsigned char*)(intptr_t)RetAddr)[-1] == 0xE8 &&"Not a call instr!");
unsigned NewVal = (intptr_t)JITCompilerFunction((void*)(intptr_t)RetAddr);
// Rewrite the call target... so that we don't end up here every time we
// execute the call.
*(unsigned*)(intptr_t)RetAddr = NewVal-RetAddr-4;
if (isStub) {
// If this is a stub, rewrite the call into an unconditional branch
// instruction so that two return addresses are not pushed onto the stack
// when the requested function finally gets called. This also makes the
// 0xCD byte (interrupt) dead, so the marker doesn't effect anything.
((unsigned char*)(intptr_t)RetAddr)[-1] = 0xE9;
}
// Change the return address to reexecute the call instruction...
*RetAddrLoc -= 5;
}
TargetJITInfo::LazyResolverFn
X86JITInfo::getLazyResolverFunction(JITCompilerFn F) {
JITCompilerFunction = F;
return X86CompilationCallback;
}
void *X86JITInfo::emitFunctionStub(void *Fn, MachineCodeEmitter &MCE) {
if (Fn != X86CompilationCallback) {
MCE.startFunctionStub(5);
MCE.emitByte(0xE9);
MCE.emitWord((intptr_t)Fn-MCE.getCurrentPCValue()-4);
return MCE.finishFunctionStub(0);
}
MCE.startFunctionStub(6);
MCE.emitByte(0xE8); // Call with 32 bit pc-rel destination...
MCE.emitWord((intptr_t)Fn-MCE.getCurrentPCValue()-4);
MCE.emitByte(0xCD); // Interrupt - Just a marker identifying the stub!
return MCE.finishFunctionStub(0);
}
/// relocate - Before the JIT can run a block of code that has been emitted,
/// it must rewrite the code to contain the actual addresses of any
/// referenced global symbols.
void X86JITInfo::relocate(void *Function, MachineRelocation *MR,
unsigned NumRelocs) {
for (unsigned i = 0; i != NumRelocs; ++i, ++MR) {
void *RelocPos = (char*)Function + MR->getMachineCodeOffset();
intptr_t ResultPtr = (intptr_t)MR->getResultPointer();
switch ((X86::RelocationType)MR->getRelocationType()) {
case X86::reloc_pcrel_word:
// PC relative relocation, add the relocated value to the value already in
// memory, after we adjust it for where the PC is.
ResultPtr = ResultPtr-(intptr_t)RelocPos-4;
*((intptr_t*)RelocPos) += ResultPtr;
break;
case X86::reloc_absolute_word:
// Absolute relocation, just add the relocated value to the value already
// in memory.
*((intptr_t*)RelocPos) += ResultPtr;
break;
}
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: salvd.cxx,v $
*
* $Revision: 1.22 $
*
* last change: $Author: kz $ $Date: 2008-03-05 17:01:28 $
*
* 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
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_vcl.hxx"
#include "salvd.h"
#include "salinst.h"
#include "salgdi.h"
#include "saldata.hxx"
#include "vcl/sysdata.hxx"
// -----------------------------------------------------------------------
SalVirtualDevice* AquaSalInstance::CreateVirtualDevice( SalGraphics* pGraphics,
long nDX, long nDY, USHORT nBitCount, const SystemGraphicsData *pData )
{
return new AquaSalVirtualDevice( static_cast< AquaSalGraphics* >( pGraphics ), nDX, nDY, nBitCount, pData );
}
// -----------------------------------------------------------------------
void AquaSalInstance::DestroyVirtualDevice( SalVirtualDevice* pDevice )
{
delete pDevice;
}
// =======================================================================
AquaSalVirtualDevice::AquaSalVirtualDevice( AquaSalGraphics* pGraphic, long nDX, long nDY, USHORT nBitCount, const SystemGraphicsData *pData )
: mbGraphicsUsed( false ),
mxContext( 0 )
{
if( pGraphic && pData && pData->rCGContext)
{
// Create virtual device based on existing SystemGraphicsData
// We ignore nDx and nDY, as the desired size comes from the SystemGraphicsData
mxContext = pData->rCGContext;
mbForeignContext = true; // the mxContext is from pData
mpGraphics = pGraphic;
mpGraphics->SetVirDevGraphics( mxContext, true );
}
else
{
// create empty new virtual device
mbForeignContext = false; // the mxContext is created within VCL
mpGraphics = new AquaSalGraphics(); // never fails
if( nDX && nDY )
SetSize( nDX, nDY );
// NOTE: if SetSize does not succeed, we just ignore the nDX and nDY
}
}
// -----------------------------------------------------------------------
AquaSalVirtualDevice::~AquaSalVirtualDevice()
{
if( mpGraphics )
{
mpGraphics->SetVirDevGraphics( 0, true );
delete mpGraphics;
mpGraphics = 0;
}
Destroy();
}
// -----------------------------------------------------------------------
void AquaSalVirtualDevice::Destroy()
{
if( mbForeignContext ) {
// Do not delete mxContext that we have received from outside VCL
return;
}
if( mxContext )
{
if( mpGraphics )
mpGraphics->SetVirDevGraphics( 0, true );
void* pBuffer = CGBitmapContextGetData(mxContext);
CFRelease( mxContext );
mxContext = 0;
if( pBuffer )
free( pBuffer );
}
}
// -----------------------------------------------------------------------
SalGraphics* AquaSalVirtualDevice::GetGraphics()
{
if( mbGraphicsUsed || !mpGraphics )
return 0;
mbGraphicsUsed = true;
return mpGraphics;
}
// -----------------------------------------------------------------------
void AquaSalVirtualDevice::ReleaseGraphics( SalGraphics *pGraphics )
{
mbGraphicsUsed = false;
}
// -----------------------------------------------------------------------
BOOL AquaSalVirtualDevice::SetSize( long nDX, long nDY )
{
if( mbForeignContext )
{
// Do not delete/resize mxContext that we have received from outside VCL
return true;
}
if( mxContext &&
( nDX == static_cast<long> (CGBitmapContextGetWidth( mxContext ) ) ) &&
( nDY == static_cast<long> (CGBitmapContextGetHeight( mxContext ) ) ) )
{
// Yay, we do not have to do anything :)
return true;
}
Destroy();
void* pData = malloc( nDX * 4 * nDY );
if (pData)
{
mxContext = CGBitmapContextCreate( pData, nDX, nDY, 8, nDX * 4, GetSalData()->mxRGBSpace, kCGImageAlphaNoneSkipFirst );
if( mxContext )
{
if( mpGraphics )
mpGraphics->SetVirDevGraphics( mxContext, true );
}
else
{
free (pData);
DBG_ERROR( "vcl::AquaSalVirtualDevice::SetSize(), could not create Bitmap Context" );
}
}
else
{
DBG_ERROR( "vcl::AquaSalVirtualDevice::SetSize(), could not allocate bitmap data" );
}
return mxContext != 0;
}
// -----------------------------------------------------------------------
void AquaSalVirtualDevice::GetSize( long& rWidth, long& rHeight )
{
if( mxContext )
{
rWidth = CGBitmapContextGetWidth( mxContext );
rHeight = CGBitmapContextGetHeight( mxContext );
}
else
{
rWidth = 0;
rHeight = 0;
}
}
<commit_msg>INTEGRATION: CWS changefileheader (1.22.22); FILE MERGED 2008/03/28 15:44:06 rt 1.22.22.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: salvd.cxx,v $
* $Revision: 1.23 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org 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 version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_vcl.hxx"
#include "salvd.h"
#include "salinst.h"
#include "salgdi.h"
#include "saldata.hxx"
#include "vcl/sysdata.hxx"
// -----------------------------------------------------------------------
SalVirtualDevice* AquaSalInstance::CreateVirtualDevice( SalGraphics* pGraphics,
long nDX, long nDY, USHORT nBitCount, const SystemGraphicsData *pData )
{
return new AquaSalVirtualDevice( static_cast< AquaSalGraphics* >( pGraphics ), nDX, nDY, nBitCount, pData );
}
// -----------------------------------------------------------------------
void AquaSalInstance::DestroyVirtualDevice( SalVirtualDevice* pDevice )
{
delete pDevice;
}
// =======================================================================
AquaSalVirtualDevice::AquaSalVirtualDevice( AquaSalGraphics* pGraphic, long nDX, long nDY, USHORT nBitCount, const SystemGraphicsData *pData )
: mbGraphicsUsed( false ),
mxContext( 0 )
{
if( pGraphic && pData && pData->rCGContext)
{
// Create virtual device based on existing SystemGraphicsData
// We ignore nDx and nDY, as the desired size comes from the SystemGraphicsData
mxContext = pData->rCGContext;
mbForeignContext = true; // the mxContext is from pData
mpGraphics = pGraphic;
mpGraphics->SetVirDevGraphics( mxContext, true );
}
else
{
// create empty new virtual device
mbForeignContext = false; // the mxContext is created within VCL
mpGraphics = new AquaSalGraphics(); // never fails
if( nDX && nDY )
SetSize( nDX, nDY );
// NOTE: if SetSize does not succeed, we just ignore the nDX and nDY
}
}
// -----------------------------------------------------------------------
AquaSalVirtualDevice::~AquaSalVirtualDevice()
{
if( mpGraphics )
{
mpGraphics->SetVirDevGraphics( 0, true );
delete mpGraphics;
mpGraphics = 0;
}
Destroy();
}
// -----------------------------------------------------------------------
void AquaSalVirtualDevice::Destroy()
{
if( mbForeignContext ) {
// Do not delete mxContext that we have received from outside VCL
return;
}
if( mxContext )
{
if( mpGraphics )
mpGraphics->SetVirDevGraphics( 0, true );
void* pBuffer = CGBitmapContextGetData(mxContext);
CFRelease( mxContext );
mxContext = 0;
if( pBuffer )
free( pBuffer );
}
}
// -----------------------------------------------------------------------
SalGraphics* AquaSalVirtualDevice::GetGraphics()
{
if( mbGraphicsUsed || !mpGraphics )
return 0;
mbGraphicsUsed = true;
return mpGraphics;
}
// -----------------------------------------------------------------------
void AquaSalVirtualDevice::ReleaseGraphics( SalGraphics *pGraphics )
{
mbGraphicsUsed = false;
}
// -----------------------------------------------------------------------
BOOL AquaSalVirtualDevice::SetSize( long nDX, long nDY )
{
if( mbForeignContext )
{
// Do not delete/resize mxContext that we have received from outside VCL
return true;
}
if( mxContext &&
( nDX == static_cast<long> (CGBitmapContextGetWidth( mxContext ) ) ) &&
( nDY == static_cast<long> (CGBitmapContextGetHeight( mxContext ) ) ) )
{
// Yay, we do not have to do anything :)
return true;
}
Destroy();
void* pData = malloc( nDX * 4 * nDY );
if (pData)
{
mxContext = CGBitmapContextCreate( pData, nDX, nDY, 8, nDX * 4, GetSalData()->mxRGBSpace, kCGImageAlphaNoneSkipFirst );
if( mxContext )
{
if( mpGraphics )
mpGraphics->SetVirDevGraphics( mxContext, true );
}
else
{
free (pData);
DBG_ERROR( "vcl::AquaSalVirtualDevice::SetSize(), could not create Bitmap Context" );
}
}
else
{
DBG_ERROR( "vcl::AquaSalVirtualDevice::SetSize(), could not allocate bitmap data" );
}
return mxContext != 0;
}
// -----------------------------------------------------------------------
void AquaSalVirtualDevice::GetSize( long& rWidth, long& rHeight )
{
if( mxContext )
{
rWidth = CGBitmapContextGetWidth( mxContext );
rHeight = CGBitmapContextGetHeight( mxContext );
}
else
{
rWidth = 0;
rHeight = 0;
}
}
<|endoftext|>
|
<commit_before><commit_msg>protect against past-the-end access of empty string<commit_after><|endoftext|>
|
<commit_before>#ifndef TAKEWHILE__H__
#define TAKEWHILE__H__
#include "iterbase.hpp"
#include <utility>
#include <iterator>
#include <initializer_list>
namespace iter {
//Forward declarations of TakeWhile and takewhile
template <typename FilterFunc, typename Container>
class TakeWhile;
template <typename FilterFunc, typename Container>
TakeWhile<FilterFunc, Container> takewhile(FilterFunc, Container&&);
template <typename FilterFunc, typename T>
TakeWhile<FilterFunc, std::initializer_list<T>> takewhile(
FilterFunc, std::initializer_list<T>);
template <typename FilterFunc, typename Container>
class TakeWhile {
private:
Container container;
FilterFunc filter_func;
friend TakeWhile takewhile<FilterFunc, Container>(
FilterFunc, Container&&);
template <typename FF, typename T>
friend TakeWhile<FF, std::initializer_list<T>> takewhile(
FF, std::initializer_list<T>);
// Value constructor for use only in the takewhile function
TakeWhile(FilterFunc filter_func, Container container)
: container(std::forward<Container>(container)),
filter_func(filter_func)
{ }
TakeWhile () = delete;
TakeWhile& operator=(const TakeWhile&) = delete;
public:
TakeWhile(const TakeWhile&) = default;
class Iterator {
private:
using iter_type = iterator_type<Container>;
iterator_type<Container> sub_iter;
const iterator_type<Container> sub_end;
FilterFunc filter_func;
// check if the current value is true under the predicate
// if it is not, set the sub_iter to the end using
// placement new to avoid the requirement of the iterator
// having an operator=
void check_current() {
if (!this->filter_func(*this->sub_iter)) {
this->sub_iter.~iter_type();
new(&this->sub_iter) iterator_type<Container>(
this->sub_end);
}
}
public:
Iterator (iterator_type<Container> iter,
iterator_type<Container> end,
FilterFunc filter_func)
: sub_iter{iter},
sub_end{end},
filter_func(filter_func)
{
if (this->sub_iter != this->sub_end) {
// only do the check if not already at the end
this->check_current();
}
}
iterator_deref<Container> operator*() const {
return *this->sub_iter;
}
Iterator& operator++() {
++this->sub_iter;
this->check_current();
return *this;
}
bool operator!=(const Iterator& other) const {
return this->sub_iter != other.sub_iter;
}
};
Iterator begin() {
return {std::begin(this->container),
std::end(this->container),
this->filter_func};
}
Iterator end() {
return {std::end(this->container),
std::end(this->container),
this->filter_func};
}
};
// Helper function to instantiate a TakeWhile
template <typename FilterFunc, typename Container>
TakeWhile<FilterFunc, Container> takewhile(
FilterFunc filter_func, Container&& container) {
return {filter_func, std::forward<Container>(container)};
}
template <typename FilterFunc, typename T>
TakeWhile<FilterFunc, std::initializer_list<T>> takewhile(
FilterFunc filter_func, std::initializer_list<T> il)
{
return {filter_func, std::move(il)};
}
}
#endif //ifndef TAKEWHILE__H__
<commit_msg>takewhile iter inherits from std iterator<commit_after>#ifndef ITER_TAKEWHILE_H_
#define ITER_TAKEWHILE_H_
#include "iterbase.hpp"
#include <utility>
#include <iterator>
#include <initializer_list>
namespace iter {
//Forward declarations of TakeWhile and takewhile
template <typename FilterFunc, typename Container>
class TakeWhile;
template <typename FilterFunc, typename Container>
TakeWhile<FilterFunc, Container> takewhile(FilterFunc, Container&&);
template <typename FilterFunc, typename T>
TakeWhile<FilterFunc, std::initializer_list<T>> takewhile(
FilterFunc, std::initializer_list<T>);
template <typename FilterFunc, typename Container>
class TakeWhile {
private:
Container container;
FilterFunc filter_func;
friend TakeWhile takewhile<FilterFunc, Container>(
FilterFunc, Container&&);
template <typename FF, typename T>
friend TakeWhile<FF, std::initializer_list<T>> takewhile(
FF, std::initializer_list<T>);
// Value constructor for use only in the takewhile function
TakeWhile(FilterFunc filter_func, Container container)
: container(std::forward<Container>(container)),
filter_func(filter_func)
{ }
public:
class Iterator
: public std::iterator<std::input_iterator_tag,
iterator_traits_deref<Container>>
{
private:
using iter_type = iterator_type<Container>;
iterator_type<Container> sub_iter;
const iterator_type<Container> sub_end;
FilterFunc filter_func;
// check if the current value is true under the predicate
// if it is not, set the sub_iter to the end using
// placement new to avoid the requirement of the iterator
// having an operator=
void check_current() {
if (!this->filter_func(*this->sub_iter)) {
this->sub_iter.~iter_type();
new(&this->sub_iter) iterator_type<Container>(
this->sub_end);
}
}
public:
Iterator (iterator_type<Container> iter,
iterator_type<Container> end,
FilterFunc filter_func)
: sub_iter{iter},
sub_end{end},
filter_func(filter_func)
{
if (this->sub_iter != this->sub_end) {
// only do the check if not already at the end
this->check_current();
}
}
iterator_deref<Container> operator*() const {
return *this->sub_iter;
}
Iterator& operator++() {
++this->sub_iter;
this->check_current();
return *this;
}
bool operator!=(const Iterator& other) const {
return this->sub_iter != other.sub_iter;
}
};
Iterator begin() {
return {std::begin(this->container),
std::end(this->container),
this->filter_func};
}
Iterator end() {
return {std::end(this->container),
std::end(this->container),
this->filter_func};
}
};
// Helper function to instantiate a TakeWhile
template <typename FilterFunc, typename Container>
TakeWhile<FilterFunc, Container> takewhile(
FilterFunc filter_func, Container&& container) {
return {filter_func, std::forward<Container>(container)};
}
template <typename FilterFunc, typename T>
TakeWhile<FilterFunc, std::initializer_list<T>> takewhile(
FilterFunc filter_func, std::initializer_list<T> il)
{
return {filter_func, std::move(il)};
}
}
#endif
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <cstdio>
#include <map>
#include "testing/gtest/include/gtest/gtest.h"
#include "webrtc/system_wrappers/interface/clock.h"
#include "webrtc/typedefs.h"
#include "webrtc/video_engine/new_include/video_engine.h"
#include "webrtc/video_engine/test/common/direct_transport.h"
#include "webrtc/video_engine/test/common/flags.h"
#include "webrtc/video_engine/test/common/generate_ssrcs.h"
#include "webrtc/video_engine/test/common/run_tests.h"
#include "webrtc/video_engine/test/common/video_capturer.h"
#include "webrtc/video_engine/test/common/video_renderer.h"
namespace webrtc {
class LoopbackTest : public ::testing::Test {
protected:
std::map<uint32_t, bool> reserved_ssrcs;
};
TEST_F(LoopbackTest, Test) {
test::VideoRenderer* local_preview = test::VideoRenderer::Create(
"Local Preview", test::flags::Width(), test::flags::Height());
test::VideoRenderer* loopback_video = test::VideoRenderer::Create(
"Loopback Video", test::flags::Width(), test::flags::Height());
newapi::VideoEngine* video_engine =
newapi::VideoEngine::Create(webrtc::newapi::VideoEngineConfig());
test::DirectTransport transport(NULL);
newapi::VideoCall* call = video_engine->CreateCall(&transport);
// Loopback, call sends to itself.
transport.SetReceiver(call->Receiver());
newapi::VideoSendStream::Config send_config = call->GetDefaultSendConfig();
test::GenerateRandomSsrcs(&send_config, &reserved_ssrcs);
send_config.local_renderer = local_preview;
// TODO(pbos): static_cast shouldn't be required after mflodman refactors the
// VideoCodec struct.
send_config.codec.width = static_cast<uint16_t>(test::flags::Width());
send_config.codec.height = static_cast<uint16_t>(test::flags::Height());
send_config.codec.minBitrate =
static_cast<unsigned int>(test::flags::MinBitrate());
send_config.codec.startBitrate =
static_cast<unsigned int>(test::flags::StartBitrate());
send_config.codec.maxBitrate =
static_cast<unsigned int>(test::flags::MaxBitrate());
newapi::VideoSendStream* send_stream = call->CreateSendStream(send_config);
Clock* test_clock = Clock::GetRealTimeClock();
test::VideoCapturer* camera =
test::VideoCapturer::Create(send_stream->Input(),
test::flags::Width(),
test::flags::Height(),
test::flags::Fps(),
test_clock);
newapi::VideoReceiveStream::Config receive_config =
call->GetDefaultReceiveConfig();
receive_config.rtp.ssrc = send_config.rtp.ssrcs[0];
receive_config.renderer = loopback_video;
newapi::VideoReceiveStream* receive_stream =
call->CreateReceiveStream(receive_config);
receive_stream->StartReceive();
send_stream->StartSend();
camera->Start();
// TODO(pbos): Run this time limited (optionally), so it can run automated.
puts(">> Press ENTER to continue...");
while (getchar() != '\n' && !feof(stdin));
receive_stream->StopReceive();
send_stream->StopSend();
// Stop sending
delete camera;
call->DestroyReceiveStream(receive_stream);
call->DestroySendStream(send_stream);
delete call;
delete video_engine;
delete loopback_video;
delete local_preview;
}
} // webrtc
int main(int argc, char* argv[]) {
::testing::InitGoogleTest(&argc, argv);
webrtc::test::flags::Init(&argc, &argv);
return webrtc::test::RunAllTests();
}
<commit_msg>Use scoped_ptr<> for loopback.cc<commit_after>/*
* Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <cstdio>
#include <map>
#include "testing/gtest/include/gtest/gtest.h"
#include "webrtc/system_wrappers/interface/clock.h"
#include "webrtc/system_wrappers/interface/scoped_ptr.h"
#include "webrtc/typedefs.h"
#include "webrtc/video_engine/new_include/video_engine.h"
#include "webrtc/video_engine/test/common/direct_transport.h"
#include "webrtc/video_engine/test/common/flags.h"
#include "webrtc/video_engine/test/common/generate_ssrcs.h"
#include "webrtc/video_engine/test/common/run_tests.h"
#include "webrtc/video_engine/test/common/video_capturer.h"
#include "webrtc/video_engine/test/common/video_renderer.h"
namespace webrtc {
class LoopbackTest : public ::testing::Test {
protected:
std::map<uint32_t, bool> reserved_ssrcs;
};
TEST_F(LoopbackTest, Test) {
scoped_ptr<test::VideoRenderer> local_preview(test::VideoRenderer::Create(
"Local Preview", test::flags::Width(), test::flags::Height()));
scoped_ptr<test::VideoRenderer> loopback_video(test::VideoRenderer::Create(
"Loopback Video", test::flags::Width(), test::flags::Height()));
scoped_ptr<newapi::VideoEngine> video_engine(
newapi::VideoEngine::Create(webrtc::newapi::VideoEngineConfig()));
test::DirectTransport transport(NULL);
scoped_ptr<newapi::VideoCall> call(video_engine->CreateCall(&transport));
// Loopback, call sends to itself.
transport.SetReceiver(call->Receiver());
newapi::VideoSendStream::Config send_config = call->GetDefaultSendConfig();
test::GenerateRandomSsrcs(&send_config, &reserved_ssrcs);
send_config.local_renderer = local_preview.get();
// TODO(pbos): static_cast shouldn't be required after mflodman refactors the
// VideoCodec struct.
send_config.codec.width = static_cast<uint16_t>(test::flags::Width());
send_config.codec.height = static_cast<uint16_t>(test::flags::Height());
send_config.codec.minBitrate =
static_cast<unsigned int>(test::flags::MinBitrate());
send_config.codec.startBitrate =
static_cast<unsigned int>(test::flags::StartBitrate());
send_config.codec.maxBitrate =
static_cast<unsigned int>(test::flags::MaxBitrate());
newapi::VideoSendStream* send_stream = call->CreateSendStream(send_config);
Clock* test_clock = Clock::GetRealTimeClock();
scoped_ptr<test::VideoCapturer> camera(
test::VideoCapturer::Create(send_stream->Input(),
test::flags::Width(),
test::flags::Height(),
test::flags::Fps(),
test_clock));
newapi::VideoReceiveStream::Config receive_config =
call->GetDefaultReceiveConfig();
receive_config.rtp.ssrc = send_config.rtp.ssrcs[0];
receive_config.renderer = loopback_video.get();
newapi::VideoReceiveStream* receive_stream =
call->CreateReceiveStream(receive_config);
receive_stream->StartReceive();
send_stream->StartSend();
camera->Start();
// TODO(pbos): Run this time limited (optionally), so it can run automated.
puts(">> Press ENTER to continue...");
while (getchar() != '\n' && !feof(stdin))
;
camera->Stop();
send_stream->StopSend();
receive_stream->StopReceive();
call->DestroyReceiveStream(receive_stream);
call->DestroySendStream(send_stream);
}
} // webrtc
int main(int argc, char* argv[]) {
::testing::InitGoogleTest(&argc, argv);
webrtc::test::flags::Init(&argc, &argv);
return webrtc::test::RunAllTests();
}
<|endoftext|>
|
<commit_before>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#include "paddle/pybind/protobuf.h"
#include <deque>
#include "paddle/framework/attribute.h"
namespace paddle {
namespace pybind {
using namespace paddle::framework; // NOLINT
template <typename T>
inline std::vector<T> RepeatedToVector(
const google::protobuf::RepeatedField<T> &repeated_field) {
std::vector<T> ret;
ret.reserve(repeated_field.size());
std::copy(
repeated_field.begin(), repeated_field.end(), std::back_inserter(ret));
return ret;
}
template <typename T, typename RepeatedField>
inline void VectorToRepeated(const std::vector<T> &vec,
RepeatedField *repeated_field) {
repeated_field->Reserve(vec.size());
for (auto &elem : vec) {
*repeated_field->Add() = elem;
}
}
class ProgramDescBind;
class OpDescBind;
class BlockDescBind;
class VarDescBind;
class VarDescBind {
public:
explicit VarDescBind(const std::string &name) { desc_.set_name(name); }
VarDesc *Proto() { return &desc_; }
void SetShape(const std::vector<int64_t> &dims) {
VectorToRepeated(dims, desc_.mutable_lod_tensor()->mutable_dims());
}
void SetDataType(int type_id) {
desc_.mutable_lod_tensor()->set_data_type(static_cast<DataType>(type_id));
}
std::vector<int64_t> Shape() {
return RepeatedToVector(desc_.lod_tensor().dims());
}
private:
VarDesc desc_;
};
class OpDescBind {
public:
OpDesc *Proto() {
Sync();
return &op_desc_;
}
std::string Type() const { return op_desc_.type(); }
void SetType(const std::string &type) { op_desc_.set_type(type); }
const std::vector<std::string> &Input(const std::string &name) const {
auto it = inputs_.find(name);
PADDLE_ENFORCE(
it != inputs_.end(), "Input %s cannot be found in Op %s", name, Type());
return it->second;
}
std::vector<std::string> InputNames() const {
std::vector<std::string> retv;
retv.reserve(this->inputs_.size());
for (auto &ipt : this->inputs_) {
retv.push_back(ipt.first);
}
return retv;
}
void SetInput(const std::string ¶m_name,
const std::vector<std::string> &args) {
need_update_ = true;
inputs_[param_name] = args;
}
const std::vector<std::string> &Output(const std::string &name) const {
auto it = outputs_.find(name);
PADDLE_ENFORCE(it != outputs_.end(),
"Output %s cannot be found in Op %s",
name,
Type());
return it->second;
}
std::vector<std::string> OutputNames() const {
std::vector<std::string> retv;
retv.reserve(this->outputs_.size());
for (auto &ipt : this->outputs_) {
retv.push_back(ipt.first);
}
return retv;
}
void SetOutput(const std::string ¶m_name,
const std::vector<std::string> &args) {
need_update_ = true;
this->outputs_[param_name] = args;
}
std::string DebugString() { return this->Proto()->DebugString(); }
struct SetAttrDescVisitor : public boost::static_visitor<void> {
explicit SetAttrDescVisitor(OpDesc::Attr *attr) : attr_(attr) {}
OpDesc::Attr *attr_;
void operator()(int v) { attr_->set_i(v); }
void operator()(float v) { attr_->set_f(v); }
void operator()(const std::string &v) { attr_->set_s(v); }
};
void Sync() {
if (need_update_) {
this->op_desc_.mutable_inputs()->Clear();
for (auto &ipt : inputs_) {
auto *input = op_desc_.add_inputs();
input->set_parameter(ipt.first);
VectorToRepeated(ipt.second, input->mutable_arguments());
}
this->op_desc_.mutable_outputs()->Clear();
for (auto &opt : outputs_) {
auto *output = op_desc_.add_outputs();
output->set_parameter(opt.first);
VectorToRepeated(opt.second, output->mutable_arguments());
}
this->op_desc_.mutable_attrs()->Clear();
for (auto &attr : attrs_) {
auto *attr_desc = op_desc_.add_attrs();
attr_desc->set_name(attr.first);
attr_desc->set_type(static_cast<AttrType>(attr.second.which() - 1));
}
need_update_ = false;
}
}
private:
OpDesc op_desc_;
std::unordered_map<std::string, std::vector<std::string>> inputs_;
std::unordered_map<std::string, std::vector<std::string>> outputs_;
std::unordered_map<std::string, Attribute> attrs_;
bool need_update_{false};
};
class BlockDescBind {
public:
BlockDescBind(ProgramDescBind *prog, BlockDesc *desc)
: prog_(prog), desc_(desc), need_update_(false) {}
BlockDescBind(const BlockDescBind &o) = delete;
BlockDescBind &operator=(const BlockDescBind &o) = delete;
int32_t id() const { return desc_->idx(); }
int32_t Parent() const { return desc_->parent_idx(); }
VarDescBind *NewVar(py::bytes name_bytes) {
std::string name = name_bytes;
need_update_ = true;
auto it = vars_.find(name);
PADDLE_ENFORCE(it == vars_.end(), "Duplicated variable %s", name);
auto var = new VarDescBind(name);
vars_[name].reset(var);
return var;
}
BlockDescBind *ParentBlock() const;
OpDescBind *AppendOp() {
need_update_ = true;
ops_.emplace_back(new OpDescBind());
return ops_.back().get();
}
void Sync() {
if (need_update_) {
auto &op_field = *this->desc_->mutable_ops();
op_field.Clear();
op_field.Reserve(static_cast<int>(ops_.size()));
for (auto &op_desc : ops_) {
op_field.AddAllocated(op_desc->Proto());
}
need_update_ = false;
}
}
private:
ProgramDescBind *prog_; // not_own
BlockDesc *desc_; // not_own
bool need_update_;
std::deque<std::unique_ptr<OpDescBind>> ops_;
std::unordered_map<std::string, std::unique_ptr<VarDescBind>> vars_;
};
using ProgDescMap =
std::unordered_map<ProgramDesc *, std::unique_ptr<ProgramDescBind>>;
static ProgDescMap *g_bind_map = nullptr;
class ProgramDescBind {
public:
static ProgramDescBind &Instance(ProgramDesc *prog) {
if (g_bind_map == nullptr) {
g_bind_map = new ProgDescMap();
}
auto &map = *g_bind_map;
auto &ptr = map[prog];
if (ptr == nullptr) {
ptr.reset(new ProgramDescBind(prog));
}
return *ptr;
}
ProgramDescBind(const ProgramDescBind &o) = delete;
ProgramDescBind &operator=(const ProgramDescBind &o) = delete;
BlockDescBind *AppendBlock(const BlockDescBind &parent) {
auto *b = prog_->add_blocks();
b->set_parent_idx(parent.id());
b->set_idx(prog_->blocks_size() - 1);
blocks_.emplace_back(new BlockDescBind(this, b));
return blocks_.back().get();
}
BlockDescBind *Block(size_t idx) { return blocks_[idx].get(); }
std::string DebugString() { return Proto()->DebugString(); }
size_t Size() const { return blocks_.size(); }
ProgramDesc *Proto() {
for (auto &block : blocks_) {
block->Sync();
}
return prog_;
}
private:
explicit ProgramDescBind(ProgramDesc *prog) : prog_(prog) {
for (auto &block : *prog->mutable_blocks()) {
blocks_.emplace_back(new BlockDescBind(this, &block));
}
}
// Not owned
ProgramDesc *prog_;
std::vector<std::unique_ptr<BlockDescBind>> blocks_;
};
BlockDescBind *BlockDescBind::ParentBlock() const {
if (this->desc_->parent_idx() == -1) {
return nullptr;
}
return prog_->Block(static_cast<size_t>(this->desc_->parent_idx()));
}
void BindProgramDesc(py::module &m) {
py::class_<ProgramDescBind>(m, "ProgramDesc", "")
.def_static("instance",
[]() -> ProgramDescBind * {
return &ProgramDescBind::Instance(&GetProgramDesc());
},
py::return_value_policy::reference)
.def_static("__create_program_desc__",
[]() -> ProgramDescBind * {
// Only used for unit-test
auto *prog_desc = new ProgramDesc;
auto *block = prog_desc->mutable_blocks()->Add();
block->set_idx(0);
block->set_parent_idx(-1);
return &ProgramDescBind::Instance(prog_desc);
},
py::return_value_policy::reference)
.def("append_block",
&ProgramDescBind::AppendBlock,
py::return_value_policy::reference)
.def("block", &ProgramDescBind::Block, py::return_value_policy::reference)
.def("__str__", &ProgramDescBind::DebugString)
.def("num_blocks", &ProgramDescBind::Size);
}
void BindBlockDesc(py::module &m) {
py::class_<BlockDescBind>(m, "BlockDesc", "")
.def_property_readonly("id", &BlockDescBind::id)
.def_property_readonly("parent", &BlockDescBind::Parent)
.def("append_op",
&BlockDescBind::AppendOp,
py::return_value_policy::reference)
.def("new_var",
&BlockDescBind::NewVar,
py::return_value_policy::reference);
}
void BindVarDsec(py::module &m) {
py::class_<VarDescBind>(m, "VarDesc", "")
.def("set_shape", &VarDescBind::SetShape)
.def("set_data_type", &VarDescBind::SetDataType)
.def("shape", &VarDescBind::Shape);
}
void BindOpDesc(py::module &m) {
py::class_<OpDescBind>(m, "OpDesc", "")
.def("type", &OpDescBind::Type)
.def("set_type", &OpDescBind::SetType)
.def("input", &OpDescBind::Input)
.def("input_names", &OpDescBind::InputNames)
.def("set_input", &OpDescBind::SetInput)
.def("output", &OpDescBind::Output)
.def("output_names", &OpDescBind::OutputNames)
.def("set_output", &OpDescBind::SetOutput)
.def("__str__", &OpDescBind::DebugString)
.def("__repr__", &OpDescBind::DebugString);
}
} // namespace pybind
} // namespace paddle
<commit_msg>Refine Visitor<commit_after>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#include "paddle/pybind/protobuf.h"
#include <deque>
#include "paddle/framework/attribute.h"
namespace paddle {
namespace pybind {
using namespace paddle::framework; // NOLINT
template <typename T>
inline std::vector<T> RepeatedToVector(
const google::protobuf::RepeatedField<T> &repeated_field) {
std::vector<T> ret;
ret.reserve(repeated_field.size());
std::copy(
repeated_field.begin(), repeated_field.end(), std::back_inserter(ret));
return ret;
}
template <typename T, typename RepeatedField>
inline void VectorToRepeated(const std::vector<T> &vec,
RepeatedField *repeated_field) {
repeated_field->Reserve(vec.size());
for (auto &elem : vec) {
*repeated_field->Add() = elem;
}
}
class ProgramDescBind;
class OpDescBind;
class BlockDescBind;
class VarDescBind;
class VarDescBind {
public:
explicit VarDescBind(const std::string &name) { desc_.set_name(name); }
VarDesc *Proto() { return &desc_; }
void SetShape(const std::vector<int64_t> &dims) {
VectorToRepeated(dims, desc_.mutable_lod_tensor()->mutable_dims());
}
void SetDataType(int type_id) {
desc_.mutable_lod_tensor()->set_data_type(static_cast<DataType>(type_id));
}
std::vector<int64_t> Shape() {
return RepeatedToVector(desc_.lod_tensor().dims());
}
private:
VarDesc desc_;
};
class OpDescBind {
public:
OpDesc *Proto() {
Sync();
return &op_desc_;
}
std::string Type() const { return op_desc_.type(); }
void SetType(const std::string &type) { op_desc_.set_type(type); }
const std::vector<std::string> &Input(const std::string &name) const {
auto it = inputs_.find(name);
PADDLE_ENFORCE(
it != inputs_.end(), "Input %s cannot be found in Op %s", name, Type());
return it->second;
}
std::vector<std::string> InputNames() const {
std::vector<std::string> retv;
retv.reserve(this->inputs_.size());
for (auto &ipt : this->inputs_) {
retv.push_back(ipt.first);
}
return retv;
}
void SetInput(const std::string ¶m_name,
const std::vector<std::string> &args) {
need_update_ = true;
inputs_[param_name] = args;
}
const std::vector<std::string> &Output(const std::string &name) const {
auto it = outputs_.find(name);
PADDLE_ENFORCE(it != outputs_.end(),
"Output %s cannot be found in Op %s",
name,
Type());
return it->second;
}
std::vector<std::string> OutputNames() const {
std::vector<std::string> retv;
retv.reserve(this->outputs_.size());
for (auto &ipt : this->outputs_) {
retv.push_back(ipt.first);
}
return retv;
}
void SetOutput(const std::string ¶m_name,
const std::vector<std::string> &args) {
need_update_ = true;
this->outputs_[param_name] = args;
}
std::string DebugString() { return this->Proto()->DebugString(); }
struct SetAttrDescVisitor : public boost::static_visitor<void> {
explicit SetAttrDescVisitor(OpDesc::Attr *attr) : attr_(attr) {}
mutable OpDesc::Attr *attr_;
void operator()(int v) const { attr_->set_i(v); }
void operator()(float v) const { attr_->set_f(v); }
void operator()(const std::string &v) const { attr_->set_s(v); }
void operator()(bool b) const { attr_->set_b(b); }
void operator()(const std::vector<int> &v) const {
VectorToRepeated(v, attr_->mutable_ints());
}
void operator()(const std::vector<float> &v) const {
VectorToRepeated(v, attr_->mutable_floats());
}
void operator()(const std::vector<std::string> &v) const {
VectorToRepeated(v, attr_->mutable_strings());
}
void operator()(const std::vector<bool> &v) const {
VectorToRepeated(v, attr_->mutable_bools());
}
};
void Sync() {
if (need_update_) {
this->op_desc_.mutable_inputs()->Clear();
for (auto &ipt : inputs_) {
auto *input = op_desc_.add_inputs();
input->set_parameter(ipt.first);
VectorToRepeated(ipt.second, input->mutable_arguments());
}
this->op_desc_.mutable_outputs()->Clear();
for (auto &opt : outputs_) {
auto *output = op_desc_.add_outputs();
output->set_parameter(opt.first);
VectorToRepeated(opt.second, output->mutable_arguments());
}
this->op_desc_.mutable_attrs()->Clear();
for (auto &attr : attrs_) {
auto *attr_desc = op_desc_.add_attrs();
attr_desc->set_name(attr.first);
attr_desc->set_type(static_cast<AttrType>(attr.second.which() - 1));
}
need_update_ = false;
}
}
private:
OpDesc op_desc_;
std::unordered_map<std::string, std::vector<std::string>> inputs_;
std::unordered_map<std::string, std::vector<std::string>> outputs_;
std::unordered_map<std::string, Attribute> attrs_;
bool need_update_{false};
};
class BlockDescBind {
public:
BlockDescBind(ProgramDescBind *prog, BlockDesc *desc)
: prog_(prog), desc_(desc), need_update_(false) {}
BlockDescBind(const BlockDescBind &o) = delete;
BlockDescBind &operator=(const BlockDescBind &o) = delete;
int32_t id() const { return desc_->idx(); }
int32_t Parent() const { return desc_->parent_idx(); }
VarDescBind *NewVar(py::bytes name_bytes) {
std::string name = name_bytes;
need_update_ = true;
auto it = vars_.find(name);
PADDLE_ENFORCE(it == vars_.end(), "Duplicated variable %s", name);
auto var = new VarDescBind(name);
vars_[name].reset(var);
return var;
}
BlockDescBind *ParentBlock() const;
OpDescBind *AppendOp() {
need_update_ = true;
ops_.emplace_back(new OpDescBind());
return ops_.back().get();
}
void Sync() {
if (need_update_) {
auto &op_field = *this->desc_->mutable_ops();
op_field.Clear();
op_field.Reserve(static_cast<int>(ops_.size()));
for (auto &op_desc : ops_) {
op_field.AddAllocated(op_desc->Proto());
}
need_update_ = false;
}
}
private:
ProgramDescBind *prog_; // not_own
BlockDesc *desc_; // not_own
bool need_update_;
std::deque<std::unique_ptr<OpDescBind>> ops_;
std::unordered_map<std::string, std::unique_ptr<VarDescBind>> vars_;
};
using ProgDescMap =
std::unordered_map<ProgramDesc *, std::unique_ptr<ProgramDescBind>>;
static ProgDescMap *g_bind_map = nullptr;
class ProgramDescBind {
public:
static ProgramDescBind &Instance(ProgramDesc *prog) {
if (g_bind_map == nullptr) {
g_bind_map = new ProgDescMap();
}
auto &map = *g_bind_map;
auto &ptr = map[prog];
if (ptr == nullptr) {
ptr.reset(new ProgramDescBind(prog));
}
return *ptr;
}
ProgramDescBind(const ProgramDescBind &o) = delete;
ProgramDescBind &operator=(const ProgramDescBind &o) = delete;
BlockDescBind *AppendBlock(const BlockDescBind &parent) {
auto *b = prog_->add_blocks();
b->set_parent_idx(parent.id());
b->set_idx(prog_->blocks_size() - 1);
blocks_.emplace_back(new BlockDescBind(this, b));
return blocks_.back().get();
}
BlockDescBind *Block(size_t idx) { return blocks_[idx].get(); }
std::string DebugString() { return Proto()->DebugString(); }
size_t Size() const { return blocks_.size(); }
ProgramDesc *Proto() {
for (auto &block : blocks_) {
block->Sync();
}
return prog_;
}
private:
explicit ProgramDescBind(ProgramDesc *prog) : prog_(prog) {
for (auto &block : *prog->mutable_blocks()) {
blocks_.emplace_back(new BlockDescBind(this, &block));
}
}
// Not owned
ProgramDesc *prog_;
std::vector<std::unique_ptr<BlockDescBind>> blocks_;
};
BlockDescBind *BlockDescBind::ParentBlock() const {
if (this->desc_->parent_idx() == -1) {
return nullptr;
}
return prog_->Block(static_cast<size_t>(this->desc_->parent_idx()));
}
void BindProgramDesc(py::module &m) {
py::class_<ProgramDescBind>(m, "ProgramDesc", "")
.def_static("instance",
[]() -> ProgramDescBind * {
return &ProgramDescBind::Instance(&GetProgramDesc());
},
py::return_value_policy::reference)
.def_static("__create_program_desc__",
[]() -> ProgramDescBind * {
// Only used for unit-test
auto *prog_desc = new ProgramDesc;
auto *block = prog_desc->mutable_blocks()->Add();
block->set_idx(0);
block->set_parent_idx(-1);
return &ProgramDescBind::Instance(prog_desc);
},
py::return_value_policy::reference)
.def("append_block",
&ProgramDescBind::AppendBlock,
py::return_value_policy::reference)
.def("block", &ProgramDescBind::Block, py::return_value_policy::reference)
.def("__str__", &ProgramDescBind::DebugString)
.def("num_blocks", &ProgramDescBind::Size);
}
void BindBlockDesc(py::module &m) {
py::class_<BlockDescBind>(m, "BlockDesc", "")
.def_property_readonly("id", &BlockDescBind::id)
.def_property_readonly("parent", &BlockDescBind::Parent)
.def("append_op",
&BlockDescBind::AppendOp,
py::return_value_policy::reference)
.def("new_var",
&BlockDescBind::NewVar,
py::return_value_policy::reference);
}
void BindVarDsec(py::module &m) {
py::class_<VarDescBind>(m, "VarDesc", "")
.def("set_shape", &VarDescBind::SetShape)
.def("set_data_type", &VarDescBind::SetDataType)
.def("shape", &VarDescBind::Shape);
}
void BindOpDesc(py::module &m) {
py::class_<OpDescBind>(m, "OpDesc", "")
.def("type", &OpDescBind::Type)
.def("set_type", &OpDescBind::SetType)
.def("input", &OpDescBind::Input)
.def("input_names", &OpDescBind::InputNames)
.def("set_input", &OpDescBind::SetInput)
.def("output", &OpDescBind::Output)
.def("output_names", &OpDescBind::OutputNames)
.def("set_output", &OpDescBind::SetOutput)
.def("__str__", &OpDescBind::DebugString)
.def("__repr__", &OpDescBind::DebugString);
}
} // namespace pybind
} // namespace paddle
<|endoftext|>
|
<commit_before>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2008, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "ros/transport/transport_tcp.h"
#include "ros/poll_set.h"
#include "ros/header.h"
#include "ros/file_log.h"
#include <ros/assert.h>
#include <sstream>
#include <boost/bind.hpp>
#include <sys/socket.h>
#include <netinet/tcp.h>
#include <sys/poll.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <fcntl.h>
#include <errno.h>
namespace ros
{
TransportTCP::TransportTCP(PollSet* poll_set, int flags)
: sock_(-1)
, closed_(false)
, expecting_read_(false)
, expecting_write_(false)
, is_server_(false)
, server_port_(-1)
, poll_set_(poll_set)
, flags_(flags)
{
}
TransportTCP::~TransportTCP()
{
ROS_ASSERT_MSG(sock_ == -1, "TransportTCP socket [%d] was never closed", sock_);
}
bool TransportTCP::setSocket(int sock)
{
sock_ = sock;
return initializeSocket();
}
bool TransportTCP::initializeSocket()
{
ROS_ASSERT(sock_ != -1);
if (!(flags_ & SYNCHRONOUS))
{
// make the socket non-blocking
if(fcntl(sock_, F_SETFL, O_NONBLOCK) == -1)
{
ROS_ERROR("fcntl (non-blocking) to socket [%d] failed with error [%s]", sock_, strerror(errno));
close();
return false;
}
}
if (is_server_)
{
cached_remote_host_ = "TCPServer Socket";
}
else
{
std::stringstream ss;
ss << getClientURI() << " on socket " << sock_;
cached_remote_host_ = ss.str();
}
#ifdef ROSCPP_USE_TCP_NODELAY
setNoDelay(true);
#endif
ROS_ASSERT(poll_set_ || (flags_ & SYNCHRONOUS));
if (poll_set_)
{
poll_set_->addSocket(sock_, boost::bind(&TransportTCP::socketUpdate, this, _1), shared_from_this());
}
if (!(flags_ & SYNCHRONOUS))
{
enableRead();
}
return true;
}
void TransportTCP::parseHeader(const Header& header)
{
std::string nodelay;
if (header.getValue("tcp_nodelay", nodelay) && nodelay == "1")
{
ROS_INFO("Setting nodelay on socket");
setNoDelay(true);
}
}
void TransportTCP::setNoDelay(bool nodelay)
{
int flag = nodelay ? 1 : 0;
int result = setsockopt(sock_, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int));
if (result < 0)
{
ROS_ERROR("setsockopt failed to set TCP_NODELAY on socket [%d] [%s]", sock_, cached_remote_host_.c_str());
}
}
bool TransportTCP::connect(const std::string& host, int port)
{
sock_ = socket(AF_INET, SOCK_STREAM, 0);
if (sock_ == -1)
{
ROS_ERROR("socket() failed with error [%s]", strerror(errno));
return false;
}
sockaddr_in sin;
sin.sin_family = AF_INET;
if (inet_addr(host.c_str()) == INADDR_NONE)
{
struct addrinfo* addr;
if (getaddrinfo(host.c_str(), NULL, NULL, &addr) != 0)
{
close();
ROS_ERROR("couldn't resolve publisher host [%s]", host.c_str());
return false;
}
bool found = false;
struct addrinfo* it = addr;
for (; it; it = it->ai_next)
{
if (it->ai_family == AF_INET)
{
memcpy(&sin, it->ai_addr, it->ai_addrlen);
sin.sin_family = it->ai_family;
sin.sin_port = htons(port);
found = true;
break;
}
}
freeaddrinfo(addr);
if (!found)
{
ROS_ERROR("Couldn't find an AF_INET address for [%s]\n", host.c_str());
return false;
}
ROSCPP_LOG_DEBUG("Resolved publisher host [%s] to [%s]", host.c_str(), inet_ntoa(sin.sin_addr));
}
else
{
sin.sin_addr.s_addr = inet_addr(host.c_str()); // already an IP addr
}
sin.sin_port = htons(port);
if (::connect(sock_, (sockaddr *)&sin, sizeof(sin)))
{
ROSCPP_LOG_DEBUG("Connect to tcpros publisher [%s:%d] failed with error [%s]", host.c_str(), port, strerror(errno));
close();
return false;
}
if (!initializeSocket())
{
return false;
}
ROSCPP_LOG_DEBUG("Connect succeeded to [%s:%d] on socket [%d]", host.c_str(), port, sock_);
return true;
}
bool TransportTCP::listen(int port, int backlog, const AcceptCallback& accept_cb)
{
is_server_ = true;
accept_cb_ = accept_cb;
sock_ = socket(AF_INET, SOCK_STREAM, 0);
if (sock_ <= 0)
{
ROS_ERROR("socket() failed with error [%s]", strerror(errno));
return false;
}
server_address_.sin_family = AF_INET;
server_address_.sin_port = htons(port);
server_address_.sin_addr.s_addr = INADDR_ANY;
if (bind(sock_, (sockaddr *)&server_address_, sizeof(server_address_)) < 0)
{
ROS_ERROR("bind() failed with error [%s]", strerror(errno));
return false;
}
::listen(sock_, backlog);
socklen_t len = sizeof(server_address_);
getsockname(sock_, (sockaddr *)&server_address_, &len);
server_port_ = ntohs(server_address_.sin_port);
if (!initializeSocket())
{
return false;
}
return true;
}
void TransportTCP::close()
{
Callback disconnect_cb;
if (!closed_)
{
{
boost::recursive_mutex::scoped_lock lock(close_mutex_);
if (!closed_)
{
closed_ = true;
ROSCPP_LOG_DEBUG("TCP socket [%d] closed", sock_);
ROS_ASSERT(sock_ != -1);
if (poll_set_)
{
poll_set_->delSocket(sock_);
}
::shutdown(sock_, SHUT_RDWR);
if (::close(sock_) < 0)
{
ROS_ERROR("Error closing socket [%d]: [%s]", sock_, strerror(errno));
}
closed_ = true;
sock_ = -1;
disconnect_cb = disconnect_cb_;
disconnect_cb_ = Callback();
read_cb_ = Callback();
write_cb_ = Callback();
accept_cb_ = AcceptCallback();
}
}
}
if (disconnect_cb)
{
disconnect_cb(shared_from_this());
}
}
int32_t TransportTCP::read(uint8_t* buffer, uint32_t size)
{
{
boost::recursive_mutex::scoped_lock lock(close_mutex_);
if (closed_)
{
ROSCPP_LOG_DEBUG("Tried to read on a closed socket [%d]", sock_);
return -1;
}
}
ROS_ASSERT((int32_t)size > 0);
int num_bytes = ::recv(sock_, buffer, size, 0);
if (num_bytes < 0)
{
if (errno != EAGAIN)
{
ROSCPP_LOG_DEBUG("recv() failed with error [%s]", strerror(errno));
}
else
{
num_bytes = 0;
}
}
else if (num_bytes == 0)
{
ROSCPP_LOG_DEBUG("Socket [%d] received 0/%d bytes, closing", sock_, size);
close();
return -1;
}
return num_bytes;
}
int32_t TransportTCP::write(uint8_t* buffer, uint32_t size)
{
{
boost::recursive_mutex::scoped_lock lock(close_mutex_);
if (closed_)
{
ROSCPP_LOG_DEBUG("Tried to write on a closed socket [%d]", sock_);
return -1;
}
}
ROS_ASSERT((int32_t)size > 0);
int num_bytes = ::send(sock_, buffer, size, 0);
if (num_bytes < 0)
{
if(errno != EAGAIN)
{
ROSCPP_LOG_DEBUG("send() failed with error [%s]", strerror(errno));
close();
}
else
{
num_bytes = 0;
}
}
return num_bytes;
}
void TransportTCP::enableRead()
{
ROS_ASSERT(!(flags_ & SYNCHRONOUS));
{
boost::recursive_mutex::scoped_lock lock(close_mutex_);
if (closed_)
{
return;
}
}
if (!expecting_read_)
{
poll_set_->addEvents(sock_, POLLIN);
expecting_read_ = true;
}
}
void TransportTCP::enableWrite()
{
ROS_ASSERT(!(flags_ & SYNCHRONOUS));
{
boost::recursive_mutex::scoped_lock lock(close_mutex_);
if (closed_)
{
return;
}
}
if (!expecting_write_)
{
poll_set_->addEvents(sock_, POLLOUT);
expecting_write_ = true;
}
}
void TransportTCP::disableWrite()
{
ROS_ASSERT(!(flags_ & SYNCHRONOUS));
{
boost::recursive_mutex::scoped_lock lock(close_mutex_);
if (closed_)
{
return;
}
}
if (expecting_write_)
{
poll_set_->delEvents(sock_, POLLOUT);
expecting_write_ = false;
}
}
TransportTCPPtr TransportTCP::accept()
{
ROS_ASSERT(is_server_);
sockaddr client_address;
socklen_t len = sizeof(client_address);
int new_sock = ::accept(sock_, (sockaddr *)&client_address, &len);
if (new_sock >= 0)
{
ROSCPP_LOG_DEBUG("Accepted connection on socket [%d]", new_sock);
TransportTCPPtr transport(new TransportTCP(poll_set_, flags_));
if (!transport->setSocket(new_sock))
{
ROS_ERROR("Failed to set socket on transport for socket %d", new_sock);
}
return transport;
}
else
{
ROS_ERROR("accept() on socket [%d] failed with error [%s]", sock_, strerror(errno));
}
return TransportTCPPtr();
}
void TransportTCP::socketUpdate(int events)
{
boost::recursive_mutex::scoped_lock lock(close_mutex_);
if (closed_)
{
return;
}
if((events & POLLERR) ||
(events & POLLHUP) ||
(events & POLLNVAL))
{
ROSCPP_LOG_DEBUG("Socket %d closed with (ERR|HUP|NVAL) events %d", sock_, events);
close();
}
else
{
if ((events & POLLIN) && expecting_read_)
{
if (is_server_)
{
// Should not block here, because poll() said that it's ready
// for reading
TransportTCPPtr transport = accept();
if (transport)
{
ROS_ASSERT(accept_cb_);
accept_cb_(transport);
}
}
else
{
if (read_cb_)
{
read_cb_(shared_from_this());
}
}
}
if ((events & POLLOUT) && expecting_write_)
{
if (write_cb_)
{
write_cb_(shared_from_this());
}
}
}
}
std::string TransportTCP::getTransportInfo()
{
return "TCPROS connection to [" + cached_remote_host_ + "]";
}
std::string TransportTCP::getClientURI()
{
ROS_ASSERT(!is_server_);
sockaddr_in addr;
socklen_t len = sizeof(addr);
getpeername(sock_, (sockaddr *)&addr, &len);
int port = ntohs(addr.sin_port);
std::string ip = inet_ntoa(addr.sin_addr);
std::stringstream uri;
uri << ip << ":" << port;
return uri.str();
}
} // namespace ros
<commit_msg>Turn an old debug INFO into a debug<commit_after>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2008, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "ros/transport/transport_tcp.h"
#include "ros/poll_set.h"
#include "ros/header.h"
#include "ros/file_log.h"
#include <ros/assert.h>
#include <sstream>
#include <boost/bind.hpp>
#include <sys/socket.h>
#include <netinet/tcp.h>
#include <sys/poll.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <fcntl.h>
#include <errno.h>
namespace ros
{
TransportTCP::TransportTCP(PollSet* poll_set, int flags)
: sock_(-1)
, closed_(false)
, expecting_read_(false)
, expecting_write_(false)
, is_server_(false)
, server_port_(-1)
, poll_set_(poll_set)
, flags_(flags)
{
}
TransportTCP::~TransportTCP()
{
ROS_ASSERT_MSG(sock_ == -1, "TransportTCP socket [%d] was never closed", sock_);
}
bool TransportTCP::setSocket(int sock)
{
sock_ = sock;
return initializeSocket();
}
bool TransportTCP::initializeSocket()
{
ROS_ASSERT(sock_ != -1);
if (!(flags_ & SYNCHRONOUS))
{
// make the socket non-blocking
if(fcntl(sock_, F_SETFL, O_NONBLOCK) == -1)
{
ROS_ERROR("fcntl (non-blocking) to socket [%d] failed with error [%s]", sock_, strerror(errno));
close();
return false;
}
}
if (is_server_)
{
cached_remote_host_ = "TCPServer Socket";
}
else
{
std::stringstream ss;
ss << getClientURI() << " on socket " << sock_;
cached_remote_host_ = ss.str();
}
#ifdef ROSCPP_USE_TCP_NODELAY
setNoDelay(true);
#endif
ROS_ASSERT(poll_set_ || (flags_ & SYNCHRONOUS));
if (poll_set_)
{
poll_set_->addSocket(sock_, boost::bind(&TransportTCP::socketUpdate, this, _1), shared_from_this());
}
if (!(flags_ & SYNCHRONOUS))
{
enableRead();
}
return true;
}
void TransportTCP::parseHeader(const Header& header)
{
std::string nodelay;
if (header.getValue("tcp_nodelay", nodelay) && nodelay == "1")
{
ROSCPP_LOG_DEBUG("Setting nodelay on socket [%d]", sock_);
setNoDelay(true);
}
}
void TransportTCP::setNoDelay(bool nodelay)
{
int flag = nodelay ? 1 : 0;
int result = setsockopt(sock_, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int));
if (result < 0)
{
ROS_ERROR("setsockopt failed to set TCP_NODELAY on socket [%d] [%s]", sock_, cached_remote_host_.c_str());
}
}
bool TransportTCP::connect(const std::string& host, int port)
{
sock_ = socket(AF_INET, SOCK_STREAM, 0);
if (sock_ == -1)
{
ROS_ERROR("socket() failed with error [%s]", strerror(errno));
return false;
}
sockaddr_in sin;
sin.sin_family = AF_INET;
if (inet_addr(host.c_str()) == INADDR_NONE)
{
struct addrinfo* addr;
if (getaddrinfo(host.c_str(), NULL, NULL, &addr) != 0)
{
close();
ROS_ERROR("couldn't resolve publisher host [%s]", host.c_str());
return false;
}
bool found = false;
struct addrinfo* it = addr;
for (; it; it = it->ai_next)
{
if (it->ai_family == AF_INET)
{
memcpy(&sin, it->ai_addr, it->ai_addrlen);
sin.sin_family = it->ai_family;
sin.sin_port = htons(port);
found = true;
break;
}
}
freeaddrinfo(addr);
if (!found)
{
ROS_ERROR("Couldn't find an AF_INET address for [%s]\n", host.c_str());
return false;
}
ROSCPP_LOG_DEBUG("Resolved publisher host [%s] to [%s]", host.c_str(), inet_ntoa(sin.sin_addr));
}
else
{
sin.sin_addr.s_addr = inet_addr(host.c_str()); // already an IP addr
}
sin.sin_port = htons(port);
if (::connect(sock_, (sockaddr *)&sin, sizeof(sin)))
{
ROSCPP_LOG_DEBUG("Connect to tcpros publisher [%s:%d] failed with error [%s]", host.c_str(), port, strerror(errno));
close();
return false;
}
if (!initializeSocket())
{
return false;
}
ROSCPP_LOG_DEBUG("Connect succeeded to [%s:%d] on socket [%d]", host.c_str(), port, sock_);
return true;
}
bool TransportTCP::listen(int port, int backlog, const AcceptCallback& accept_cb)
{
is_server_ = true;
accept_cb_ = accept_cb;
sock_ = socket(AF_INET, SOCK_STREAM, 0);
if (sock_ <= 0)
{
ROS_ERROR("socket() failed with error [%s]", strerror(errno));
return false;
}
server_address_.sin_family = AF_INET;
server_address_.sin_port = htons(port);
server_address_.sin_addr.s_addr = INADDR_ANY;
if (bind(sock_, (sockaddr *)&server_address_, sizeof(server_address_)) < 0)
{
ROS_ERROR("bind() failed with error [%s]", strerror(errno));
return false;
}
::listen(sock_, backlog);
socklen_t len = sizeof(server_address_);
getsockname(sock_, (sockaddr *)&server_address_, &len);
server_port_ = ntohs(server_address_.sin_port);
if (!initializeSocket())
{
return false;
}
return true;
}
void TransportTCP::close()
{
Callback disconnect_cb;
if (!closed_)
{
{
boost::recursive_mutex::scoped_lock lock(close_mutex_);
if (!closed_)
{
closed_ = true;
ROSCPP_LOG_DEBUG("TCP socket [%d] closed", sock_);
ROS_ASSERT(sock_ != -1);
if (poll_set_)
{
poll_set_->delSocket(sock_);
}
::shutdown(sock_, SHUT_RDWR);
if (::close(sock_) < 0)
{
ROS_ERROR("Error closing socket [%d]: [%s]", sock_, strerror(errno));
}
closed_ = true;
sock_ = -1;
disconnect_cb = disconnect_cb_;
disconnect_cb_ = Callback();
read_cb_ = Callback();
write_cb_ = Callback();
accept_cb_ = AcceptCallback();
}
}
}
if (disconnect_cb)
{
disconnect_cb(shared_from_this());
}
}
int32_t TransportTCP::read(uint8_t* buffer, uint32_t size)
{
{
boost::recursive_mutex::scoped_lock lock(close_mutex_);
if (closed_)
{
ROSCPP_LOG_DEBUG("Tried to read on a closed socket [%d]", sock_);
return -1;
}
}
ROS_ASSERT((int32_t)size > 0);
int num_bytes = ::recv(sock_, buffer, size, 0);
if (num_bytes < 0)
{
if (errno != EAGAIN)
{
ROSCPP_LOG_DEBUG("recv() failed with error [%s]", strerror(errno));
}
else
{
num_bytes = 0;
}
}
else if (num_bytes == 0)
{
ROSCPP_LOG_DEBUG("Socket [%d] received 0/%d bytes, closing", sock_, size);
close();
return -1;
}
return num_bytes;
}
int32_t TransportTCP::write(uint8_t* buffer, uint32_t size)
{
{
boost::recursive_mutex::scoped_lock lock(close_mutex_);
if (closed_)
{
ROSCPP_LOG_DEBUG("Tried to write on a closed socket [%d]", sock_);
return -1;
}
}
ROS_ASSERT((int32_t)size > 0);
int num_bytes = ::send(sock_, buffer, size, 0);
if (num_bytes < 0)
{
if(errno != EAGAIN)
{
ROSCPP_LOG_DEBUG("send() failed with error [%s]", strerror(errno));
close();
}
else
{
num_bytes = 0;
}
}
return num_bytes;
}
void TransportTCP::enableRead()
{
ROS_ASSERT(!(flags_ & SYNCHRONOUS));
{
boost::recursive_mutex::scoped_lock lock(close_mutex_);
if (closed_)
{
return;
}
}
if (!expecting_read_)
{
poll_set_->addEvents(sock_, POLLIN);
expecting_read_ = true;
}
}
void TransportTCP::enableWrite()
{
ROS_ASSERT(!(flags_ & SYNCHRONOUS));
{
boost::recursive_mutex::scoped_lock lock(close_mutex_);
if (closed_)
{
return;
}
}
if (!expecting_write_)
{
poll_set_->addEvents(sock_, POLLOUT);
expecting_write_ = true;
}
}
void TransportTCP::disableWrite()
{
ROS_ASSERT(!(flags_ & SYNCHRONOUS));
{
boost::recursive_mutex::scoped_lock lock(close_mutex_);
if (closed_)
{
return;
}
}
if (expecting_write_)
{
poll_set_->delEvents(sock_, POLLOUT);
expecting_write_ = false;
}
}
TransportTCPPtr TransportTCP::accept()
{
ROS_ASSERT(is_server_);
sockaddr client_address;
socklen_t len = sizeof(client_address);
int new_sock = ::accept(sock_, (sockaddr *)&client_address, &len);
if (new_sock >= 0)
{
ROSCPP_LOG_DEBUG("Accepted connection on socket [%d]", new_sock);
TransportTCPPtr transport(new TransportTCP(poll_set_, flags_));
if (!transport->setSocket(new_sock))
{
ROS_ERROR("Failed to set socket on transport for socket %d", new_sock);
}
return transport;
}
else
{
ROS_ERROR("accept() on socket [%d] failed with error [%s]", sock_, strerror(errno));
}
return TransportTCPPtr();
}
void TransportTCP::socketUpdate(int events)
{
boost::recursive_mutex::scoped_lock lock(close_mutex_);
if (closed_)
{
return;
}
if((events & POLLERR) ||
(events & POLLHUP) ||
(events & POLLNVAL))
{
ROSCPP_LOG_DEBUG("Socket %d closed with (ERR|HUP|NVAL) events %d", sock_, events);
close();
}
else
{
if ((events & POLLIN) && expecting_read_)
{
if (is_server_)
{
// Should not block here, because poll() said that it's ready
// for reading
TransportTCPPtr transport = accept();
if (transport)
{
ROS_ASSERT(accept_cb_);
accept_cb_(transport);
}
}
else
{
if (read_cb_)
{
read_cb_(shared_from_this());
}
}
}
if ((events & POLLOUT) && expecting_write_)
{
if (write_cb_)
{
write_cb_(shared_from_this());
}
}
}
}
std::string TransportTCP::getTransportInfo()
{
return "TCPROS connection to [" + cached_remote_host_ + "]";
}
std::string TransportTCP::getClientURI()
{
ROS_ASSERT(!is_server_);
sockaddr_in addr;
socklen_t len = sizeof(addr);
getpeername(sock_, (sockaddr *)&addr, &len);
int port = ntohs(addr.sin_port);
std::string ip = inet_ntoa(addr.sin_addr);
std::stringstream uri;
uri << ip << ":" << port;
return uri.str();
}
} // namespace ros
<|endoftext|>
|
<commit_before>#ifndef __GLOBALS_HPP_INCLUDED
#define __GLOBALS_HPP_INCLUDED
#include "any_value.hpp"
// GCC (at least g++ 4.7.2) and Visual Studio 2015 do support
// setting default values of a struct using C++11 syntax.
// Clang 3.7.0 and Visual Studio 2013 do not support
// setting default values of a struct using C++11 syntax.
// Visual Studio 2013 fails to compile, whereas Clang-compiled
// executable with code with setting default values of a struct
// causes Segmentation fault upon execution of the program.
// Compilers that don't support setting default values of a struct
// are handled by setting the default values in a macro.
// http://stackoverflow.com/questions/16782103/initializing-default-values-in-a-struct/16783513#16783513
#ifdef __clang__
#elif defined(__GNUC__)
#define __STRUCT_DEFAULT_VALUES_ARE_ACCEPTED
#elif defined(_WIN32)
#if (_MSC_VER >= 1900)
#define __STRUCT_DEFAULT_VALUES_ARE_ACCEPTED
#endif
#endif
// Include GLEW
#ifndef __GL_GLEW_H_INCLUDED
#define __GL_GLEW_H_INCLUDED
#include <GL/glew.h> // GLfloat, GLuint etc.
#endif
// Include GLFW
#ifndef __GLFW3_H_INCLUDED
#define __GLFW3_H_INCLUDED
#include <glfw3.h>
#endif
// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp> // glm
#endif
// Include standard headers
#include <cmath> // NAN, std::isnan, std::pow
#include <stdint.h> // uint32_t etc.
#include <string> // std::string
#include <vector> // std::vector
#ifndef WINDOW_WIDTH
#define WINDOW_WIDTH (1600.0f)
#endif
#ifndef WINDOW_HEIGHT
#define WINDOW_HEIGHT (900.0f)
#endif
#ifndef ASPECT_RATIO
#define ASPECT_RATIO (WINDOW_WIDTH / WINDOW_HEIGHT)
#endif
#ifndef PI
#define PI 3.14159265359f
#endif
#ifndef EARTH_RADIUS
#define EARTH_RADIUS 6371000.0f
#endif
#ifndef TEXT_SIZE
#define TEXT_SIZE 40
#endif
#ifndef FONT_SIZE
#define FONT_SIZE 16
#endif
#ifndef MAX_FPS
#define MAX_FPS 60
#endif
extern glm::mat4 ProjectionMatrix;
extern glm::mat4 ViewMatrix;
extern glm::vec3 position;
extern GLfloat gravity;
extern bool is_flight_mode_in_use;
extern bool in_help_mode;
extern GLfloat fallSpeed;
extern double horizontalAngle;
extern double verticalAngle;
extern GLfloat initialFoV;
extern double earth_radius;
extern bool hasMouseEverMoved;
extern bool is_invert_mouse_in_use;
extern bool is_key_I_released;
extern bool is_key_F_released;
extern bool is_key_F1_released;
extern bool is_world_loaded; // no more than one world object can be loaded. TODO: check that no more than one world is loaded!
extern bool is_world_spherical;
extern GLfloat speed;
extern GLfloat turbo_factor;
extern GLfloat twin_turbo_factor;
extern GLfloat mouseSpeed;
extern glm::vec3 camera_position;
namespace model
{
class World;
class Scene;
class Shader;
class Graph;
class Material;
class VectorFont;
class Species;
class Glyph;
class Text3D;
}
typedef struct ShaderStruct
{
ShaderStruct()
: parent_pointer(nullptr)
{
// constructor.
}
model::Scene* parent_pointer; // pointer to the scene (draw list).
std::string vertex_shader; // filename of vertex shader.
std::string fragment_shader; // filename of fragment shader.
} ShaderStruct;
typedef struct MaterialStruct
{
MaterialStruct()
: parent_pointer(nullptr)
{
// constructor.
}
model::Shader* parent_pointer; // pointer to the shader.
std::string texture_file_format; // type of the texture file. supported file formats so far: `"bmp"`/`"BMP"`, `"dds"`/`"DDS"`.
std::string texture_filename; // filename of the model file.
std::string image_path;
} MaterialStruct;
typedef struct NodeStruct
{
NodeStruct()
: parent_pointer(nullptr)
{
// constructor.
}
GLuint nodeID;
model::Graph* parent_pointer;
glm::vec3 coordinate_vector;
std::vector<uint32_t> neighbor_nodeIDs;
} NodeStruct;
typedef struct ObjectStruct
{
ObjectStruct()
: species_parent_pointer(nullptr), glyph_parent_pointer(nullptr), text3D_parent_pointer(nullptr), original_scale_vector(glm::vec3(1.0f, 1.0f, 1.0f)), rotate_angle(NAN), is_character(false)
{
// constructor.
}
model::Species* species_parent_pointer; // pointer to the parent `Species`.
model::Glyph* glyph_parent_pointer; // pointer to the parent `Glyph`.
model::Text3D* text3D_parent_pointer; // pointer to the parent `Text3D`.
glm::vec3 original_scale_vector; // original scale vector.
GLfloat rotate_angle; // rotate angle.
bool is_character; // The parent of a character object is a Glyph. The parent of a regular object is a Species.
glm::vec3 coordinate_vector; // coordinate vector.
glm::vec3 rotate_vector; // rotate vector.
glm::vec3 translate_vector; // translate vector.
} ObjectStruct;
typedef struct SpeciesStruct
{
SpeciesStruct()
: parent_pointer(nullptr), is_world(false), world_radius(NAN), triangulation_type("bilinear_interpolation")
{
// constructor.
}
// used for all files (for all species).
model::Material* parent_pointer; // pointer to the material object.
bool is_world; // worlds currently do not rotate nor translate.
double world_radius; // radius of sea level in meters. used only for worlds.
std::string model_file_format; // type of the model file. supported file formats so far: `"bmp"`/`"BMP"`, `"obj"`/`"OBJ"`.
// TODO: add support for `"SRTM"`.
std::string model_filename; // filename of the model file.
// for `"bmp"` model files.
std::string color_channel; // color channel to use for altitude data.
glm::vec3 light_position; // light position.
std::string coordinate_system; // used only for worlds (`is_world` == `true`). valid values: `"cartesian"`.
// TODO: add support for `"spherical"`. `"spherical"` is used eg. in SRTM heightmaps.
std::string triangulation_type;
} SpeciesStruct;
#define DEFAULT_VERTEX_SCALING_FACTOR (0.001f)
typedef struct VectorFontStruct
{
VectorFontStruct()
: parent_pointer(nullptr), vertex_scaling_factor(DEFAULT_VERTEX_SCALING_FACTOR)
{
// constructor.
}
// used for all files (for all font).
model::Material* parent_pointer; // pointer to the material object.
GLfloat vertex_scaling_factor;
std::string font_file_format; // type of the font file. supported file formats so far: `"svg"`/`"SVG"`.
std::string font_filename; // filename of the font file.
} VectorFontStruct;
typedef struct Text3DStruct
{
Text3DStruct()
: parent_pointer(nullptr), original_scale_vector(glm::vec3(1.0f, 1.0f, 1.0f)), rotate_angle(NAN)
{
// constructor.
}
model::VectorFont* parent_pointer; // pointer to the parent `VectorFont`.
std::string text_string;
glm::vec3 original_scale_vector; // original scale vector.
GLfloat rotate_angle; // rotate angle.
glm::vec3 coordinate_vector; // coordinate vector.
glm::vec3 rotate_vector; // rotate vector.
glm::vec3 translate_vector; // translate vector.
} Text3DStruct;
typedef struct GlyphStruct
{
GlyphStruct()
: parent_pointer(nullptr)
{
// constructor.
}
// used for all files (for all glyph).
std::vector<std::vector<glm::vec2>>* glyph_vertex_data;
std::string* glyph_name_pointer; // we need only a pointer, because glyphs are always created by the `VectorFont` constructor.
std::string* unicode_string_pointer; // we need only a pointer, because glyphs are always created by the `VectorFont` constructor.
model::VectorFont* parent_pointer; // pointer to the font object.
glm::vec3 light_position; // light position.
} GlyphStruct;
typedef struct
{
GLuint screen_width;
GLuint screen_height;
GLuint x;
GLuint y;
GLuint text_size;
GLuint font_size;
const char* text;
const char* char_font_texture_file_format;
const char* horizontal_alignment;
const char* vertical_alignment;
} PrintingStruct;
typedef struct
{
double rho;
double theta;
double phi;
} SphericalCoordinatesStruct;
typedef struct SphericalWorldStruct
{
SphericalWorldStruct()
:SRTM_latitude_step_in_degrees(1.0f/1200.0f), SRTM_longitude_step_in_degrees(1.0f/1200.0f)
{
// constructor.
}
double southern_latitude;
double northern_latitude;
double western_longitude;
double eastern_longitude;
double SRTM_latitude_step_in_degrees;
double SRTM_longitude_step_in_degrees;
} SphericalWorldStruct;
typedef struct TriangulateQuadsStruct
{
TriangulateQuadsStruct()
: should_ylikuutio_use_real_texture_coordinates(true)
{
// constructor.
}
GLuint* input_vertex_pointer;
uint32_t image_width;
uint32_t image_height;
std::string triangulation_type;
bool should_ylikuutio_use_real_texture_coordinates;
double sphere_radius;
SphericalWorldStruct spherical_world_struct;
} TriangulateQuadsStruct;
typedef struct
{
uint32_t* input_vertex_pointer;
uint32_t image_width;
uint32_t image_height;
bool should_ylikuutio_use_real_texture_coordinates;
} BilinearInterpolationStruct;
typedef struct
{
uint32_t image_width;
uint32_t image_height;
double sphere_radius;
bool is_bilinear_interpolation_in_use;
SphericalWorldStruct spherical_world_struct;
} TransformationStruct;
namespace callback_system
{
class CallbackEngine;
class CallbackParameter;
}
typedef datatypes::AnyValue* (*InputParametersToAnyValueCallback)(callback_system::CallbackEngine*, std::vector<callback_system::CallbackParameter*>);
extern SphericalCoordinatesStruct spherical_position;
#endif
<commit_msg>Modified `typedef struct Text3DStruct`.<commit_after>#ifndef __GLOBALS_HPP_INCLUDED
#define __GLOBALS_HPP_INCLUDED
#include "any_value.hpp"
// GCC (at least g++ 4.7.2) and Visual Studio 2015 do support
// setting default values of a struct using C++11 syntax.
// Clang 3.7.0 and Visual Studio 2013 do not support
// setting default values of a struct using C++11 syntax.
// Visual Studio 2013 fails to compile, whereas Clang-compiled
// executable with code with setting default values of a struct
// causes Segmentation fault upon execution of the program.
// Compilers that don't support setting default values of a struct
// are handled by setting the default values in a macro.
// http://stackoverflow.com/questions/16782103/initializing-default-values-in-a-struct/16783513#16783513
#ifdef __clang__
#elif defined(__GNUC__)
#define __STRUCT_DEFAULT_VALUES_ARE_ACCEPTED
#elif defined(_WIN32)
#if (_MSC_VER >= 1900)
#define __STRUCT_DEFAULT_VALUES_ARE_ACCEPTED
#endif
#endif
// Include GLEW
#ifndef __GL_GLEW_H_INCLUDED
#define __GL_GLEW_H_INCLUDED
#include <GL/glew.h> // GLfloat, GLuint etc.
#endif
// Include GLFW
#ifndef __GLFW3_H_INCLUDED
#define __GLFW3_H_INCLUDED
#include <glfw3.h>
#endif
// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp> // glm
#endif
// Include standard headers
#include <cmath> // NAN, std::isnan, std::pow
#include <stdint.h> // uint32_t etc.
#include <string> // std::string
#include <vector> // std::vector
#ifndef WINDOW_WIDTH
#define WINDOW_WIDTH (1600.0f)
#endif
#ifndef WINDOW_HEIGHT
#define WINDOW_HEIGHT (900.0f)
#endif
#ifndef ASPECT_RATIO
#define ASPECT_RATIO (WINDOW_WIDTH / WINDOW_HEIGHT)
#endif
#ifndef PI
#define PI 3.14159265359f
#endif
#ifndef EARTH_RADIUS
#define EARTH_RADIUS 6371000.0f
#endif
#ifndef TEXT_SIZE
#define TEXT_SIZE 40
#endif
#ifndef FONT_SIZE
#define FONT_SIZE 16
#endif
#ifndef MAX_FPS
#define MAX_FPS 60
#endif
extern glm::mat4 ProjectionMatrix;
extern glm::mat4 ViewMatrix;
extern glm::vec3 position;
extern GLfloat gravity;
extern bool is_flight_mode_in_use;
extern bool in_help_mode;
extern GLfloat fallSpeed;
extern double horizontalAngle;
extern double verticalAngle;
extern GLfloat initialFoV;
extern double earth_radius;
extern bool hasMouseEverMoved;
extern bool is_invert_mouse_in_use;
extern bool is_key_I_released;
extern bool is_key_F_released;
extern bool is_key_F1_released;
extern bool is_world_loaded; // no more than one world object can be loaded. TODO: check that no more than one world is loaded!
extern bool is_world_spherical;
extern GLfloat speed;
extern GLfloat turbo_factor;
extern GLfloat twin_turbo_factor;
extern GLfloat mouseSpeed;
extern glm::vec3 camera_position;
namespace model
{
class World;
class Scene;
class Shader;
class Graph;
class Material;
class VectorFont;
class Species;
class Glyph;
class Text3D;
}
typedef struct ShaderStruct
{
ShaderStruct()
: parent_pointer(nullptr)
{
// constructor.
}
model::Scene* parent_pointer; // pointer to the scene (draw list).
std::string vertex_shader; // filename of vertex shader.
std::string fragment_shader; // filename of fragment shader.
} ShaderStruct;
typedef struct MaterialStruct
{
MaterialStruct()
: parent_pointer(nullptr)
{
// constructor.
}
model::Shader* parent_pointer; // pointer to the shader.
std::string texture_file_format; // type of the texture file. supported file formats so far: `"bmp"`/`"BMP"`, `"dds"`/`"DDS"`.
std::string texture_filename; // filename of the model file.
std::string image_path;
} MaterialStruct;
typedef struct NodeStruct
{
NodeStruct()
: parent_pointer(nullptr)
{
// constructor.
}
GLuint nodeID;
model::Graph* parent_pointer;
glm::vec3 coordinate_vector;
std::vector<uint32_t> neighbor_nodeIDs;
} NodeStruct;
typedef struct ObjectStruct
{
ObjectStruct()
: species_parent_pointer(nullptr), glyph_parent_pointer(nullptr), text3D_parent_pointer(nullptr), original_scale_vector(glm::vec3(1.0f, 1.0f, 1.0f)), rotate_angle(NAN), is_character(false)
{
// constructor.
}
model::Species* species_parent_pointer; // pointer to the parent `Species`.
model::Glyph* glyph_parent_pointer; // pointer to the parent `Glyph`.
model::Text3D* text3D_parent_pointer; // pointer to the parent `Text3D`.
glm::vec3 original_scale_vector; // original scale vector.
GLfloat rotate_angle; // rotate angle.
bool is_character; // The parent of a character object is a Glyph. The parent of a regular object is a Species.
glm::vec3 coordinate_vector; // coordinate vector.
glm::vec3 rotate_vector; // rotate vector.
glm::vec3 translate_vector; // translate vector.
} ObjectStruct;
typedef struct SpeciesStruct
{
SpeciesStruct()
: parent_pointer(nullptr), is_world(false), world_radius(NAN), triangulation_type("bilinear_interpolation")
{
// constructor.
}
// used for all files (for all species).
model::Material* parent_pointer; // pointer to the material object.
bool is_world; // worlds currently do not rotate nor translate.
double world_radius; // radius of sea level in meters. used only for worlds.
std::string model_file_format; // type of the model file. supported file formats so far: `"bmp"`/`"BMP"`, `"obj"`/`"OBJ"`.
// TODO: add support for `"SRTM"`.
std::string model_filename; // filename of the model file.
// for `"bmp"` model files.
std::string color_channel; // color channel to use for altitude data.
glm::vec3 light_position; // light position.
std::string coordinate_system; // used only for worlds (`is_world` == `true`). valid values: `"cartesian"`.
// TODO: add support for `"spherical"`. `"spherical"` is used eg. in SRTM heightmaps.
std::string triangulation_type;
} SpeciesStruct;
#define DEFAULT_VERTEX_SCALING_FACTOR (0.001f)
typedef struct VectorFontStruct
{
VectorFontStruct()
: parent_pointer(nullptr), vertex_scaling_factor(DEFAULT_VERTEX_SCALING_FACTOR)
{
// constructor.
}
// used for all files (for all font).
model::Material* parent_pointer; // pointer to the material object.
GLfloat vertex_scaling_factor;
std::string font_file_format; // type of the font file. supported file formats so far: `"svg"`/`"SVG"`.
std::string font_filename; // filename of the font file.
} VectorFontStruct;
typedef struct Text3DStruct
{
Text3DStruct()
: parent_pointer(nullptr), original_scale_vector(glm::vec3(1.0f, 1.0f, 1.0f)), rotate_angle(NAN)
{
// constructor.
}
model::VectorFont* parent_pointer; // pointer to the parent `VectorFont`.
std::string text_string;
const char* text_string_char;
glm::vec3 original_scale_vector; // original scale vector.
GLfloat rotate_angle; // rotate angle.
glm::vec3 coordinate_vector; // coordinate vector.
glm::vec3 rotate_vector; // rotate vector.
glm::vec3 translate_vector; // translate vector.
} Text3DStruct;
typedef struct GlyphStruct
{
GlyphStruct()
: parent_pointer(nullptr)
{
// constructor.
}
// used for all files (for all glyph).
std::vector<std::vector<glm::vec2>>* glyph_vertex_data;
std::string* glyph_name_pointer; // we need only a pointer, because glyphs are always created by the `VectorFont` constructor.
std::string* unicode_string_pointer; // we need only a pointer, because glyphs are always created by the `VectorFont` constructor.
model::VectorFont* parent_pointer; // pointer to the font object.
glm::vec3 light_position; // light position.
} GlyphStruct;
typedef struct
{
GLuint screen_width;
GLuint screen_height;
GLuint x;
GLuint y;
GLuint text_size;
GLuint font_size;
const char* text;
const char* char_font_texture_file_format;
const char* horizontal_alignment;
const char* vertical_alignment;
} PrintingStruct;
typedef struct
{
double rho;
double theta;
double phi;
} SphericalCoordinatesStruct;
typedef struct SphericalWorldStruct
{
SphericalWorldStruct()
:SRTM_latitude_step_in_degrees(1.0f/1200.0f), SRTM_longitude_step_in_degrees(1.0f/1200.0f)
{
// constructor.
}
double southern_latitude;
double northern_latitude;
double western_longitude;
double eastern_longitude;
double SRTM_latitude_step_in_degrees;
double SRTM_longitude_step_in_degrees;
} SphericalWorldStruct;
typedef struct TriangulateQuadsStruct
{
TriangulateQuadsStruct()
: should_ylikuutio_use_real_texture_coordinates(true)
{
// constructor.
}
GLuint* input_vertex_pointer;
uint32_t image_width;
uint32_t image_height;
std::string triangulation_type;
bool should_ylikuutio_use_real_texture_coordinates;
double sphere_radius;
SphericalWorldStruct spherical_world_struct;
} TriangulateQuadsStruct;
typedef struct
{
uint32_t* input_vertex_pointer;
uint32_t image_width;
uint32_t image_height;
bool should_ylikuutio_use_real_texture_coordinates;
} BilinearInterpolationStruct;
typedef struct
{
uint32_t image_width;
uint32_t image_height;
double sphere_radius;
bool is_bilinear_interpolation_in_use;
SphericalWorldStruct spherical_world_struct;
} TransformationStruct;
namespace callback_system
{
class CallbackEngine;
class CallbackParameter;
}
typedef datatypes::AnyValue* (*InputParametersToAnyValueCallback)(callback_system::CallbackEngine*, std::vector<callback_system::CallbackParameter*>);
extern SphericalCoordinatesStruct spherical_position;
#endif
<|endoftext|>
|
<commit_before>#include "ws2812b.h"
#include "string.h"
int WS2812B_init(WS2812B *self, int pin, Colour *pixels, int flags, unsigned int columns, unsigned int rows)
{
if (digitalPinToPort(pin) == NOT_A_PIN) return 1;
self->port = portOutputRegister(digitalPinToPort(pin));
self->bit = digitalPinToBitMask(pin);
self->pin = pin;
self->count = columns*rows;
self->pixels = pixels;
self->flags = flags;
self->columns = columns;
self->rows = rows;
return 0;
}
void WS2812B_sync(WS2812B *self)
{
// https://cdn-shop.adafruit.com/datasheets/WS2812B.pdf
volatile uint16_t count = self->count*3;
uint8_t *ptr = (uint8_t*)self->pixels; // Next byte ptr (initialized to first here)
uint8_t byte = *ptr++; // Current byte
uint8_t hi = *self->port | self->bit; // Cached high state
uint8_t lo = *self->port & ~self->bit; // Cached low state
volatile uint8_t next = lo;
volatile uint8_t bit = 8;
if (!count) return;
cli(); // Disable interrupts
// @TODO: Go through instruction set to see if we can relax the timing.
// Note that the C code on the side is pseudo-pseudocode.
// Some of the C code on the side would get optimsed, while some of it
// can't be optimsed as effectively, which would significantly skew
// the signal timing a WS281X chip expects. The timing here is on a very
// tight schedule anyway, so we need to be careful.
//
//
// See footnotes for extended descriptions.
asm volatile (
"__colour_bit: \n\t" // __colour_bit:
"st %a[port], %[hi] \n\t" // *port = hi;
"sbrc %[byte], 7 \n\t\t" // if (byte & 0x80)
"mov %[next], %[hi] \n\t" // next = hi;
"dec %[bit] \n\t" // --bit;
"st %a[port], %[next] \n\t" // *port = next;
"mov %[next], %[lo] \n\t" // next = lo;
"breq __colour_byte \n\t" // if (bit == 0) goto __colour_byte; // See [0]
"lsl %[byte] \n\t" // byte = (byte << 1);
"nop; nop; nop \n\t" // sleep_cycles(3);
"st %a[port], %[lo] \n\t" // *port = lo;
"nop; nop; nop \n\t" // sleep_cycles(3);
"rjmp __colour_bit \n" // goto __colour_bit;
//
"__colour_byte: \n\t" // __colour_byte:
"ldi %[bit], 8 \n\t" // bit = 8;
"ld %[byte], %a[ptr]+ \n\t" // byte = *ptr++;
"st %a[port], %[lo] \n\t" // *port = lo;
"nop \n\t" // sleep_cycles(1);
"sbiw %[count], 1 \n\t" // --count;
"brne __colour_bit \n" // if (bit != 0) goto __colour_bit; // See [1]
// The benefit of extended ASM is that we can define registers and
// operands elegantly:
: [port] "+e" (self->port),
[count] "+w" (count),
[bit] "+r" (bit),
[byte] "+r" (byte),
[next] "+r" (next)
: [ptr] "e" (ptr),
[hi] "r" (hi),
[lo] "r" (lo)
);
// Enable interrupts
sei();
// Wait for *at least* 50µs; this causes the chip to latch the voltage onto
// the individual LEDs contained within the RGB component.
_delay_us(51);
/**
* # 1. `breq __colour_byte`
* What this effectively does is test whether the Z flag in SREG register is
* set to `1`, and if so, jumps to the defined symbol (`__colour_byte`).
*
* The Z flag (Zero flag) gets set when the previous arithmetic expression
* evaluated to `0`. In our case, the last arithmetic expression was the
* subtraction `dec %[bit]` (`--bit`).
*
* # 2. `brne __colour_bit`
* This is similar to `breq`, but tests whether the Z flag in SREG is *not*
* `1` before jumping. The flag gets cleared after the prevous arithmetic
* expression evaluates to anything but `0`.
*
* ---
* PS: "expression" is used as a synonym for "instruction"
*
* More detailed documentation can be found [here][doclink].
*
* [doclink]: http://www.atmel.com/webdoc/avrassembler/avrassembler.wb_instruction_list.html
*/
}
int WS2812B_init_palette(WS2812B *self, ColourPalette* palette, unsigned int size)
{
self->palette_size = size;
self->palette_used = 0;
self->palette = palette;
return 0;
}
int WS2812B_add_colour(WS2812B *self, char id, Colour c)
{
if (self->palette_used >= self->palette_size) return 1;
self->palette[self->palette_used++] = {id, c};
return 0;
}
int WS2812B_set_pixel(WS2812B *self, unsigned int x, unsigned int y, Colour c)
{
return _WS2812B_spf(self, x, y, _WS2812B_cc(c, self->flags & WS2812B_SCHEMES));
}
int WS2812B_set_pixel_at_offset(WS2812B *self, uint16_t offset, Colour c)
{
if (offset >= self->count) return 1;
self->pixels[offset] = _WS2812B_cc(c, self->flags & WS2812B_SCHEMES);
return 0;
}
int WS2812B_set_all(WS2812B *self, Colour c)
{
Colour _c = _WS2812B_cc(c, self->flags & WS2812B_SCHEMES);
uint16_t count = self->count;
while (count) self->pixels[--count] = _c;
return 0;
}
Colour WS2812B_get_pixel(WS2812B *self, unsigned int x, unsigned int y)
{
uint16_t offset = 0;
if (x >= self->columns || y >= self->rows) return {0,0,0};
if (self->flags & WS2812B_ZIGZAG_ODD && y % 2 != 0)
x = self->columns - x - 1;
if (self->flags & WS2812B_ZIGZAG_EVEN && y % 2 == 0)
x = self->columns - x - 1;
if(_WS2812B_addr(x, y, self->columns, &offset)) return {0,0,0};
return self->pixels[offset];
}
int WS2812B_set_row(WS2812B *self, unsigned int row, Colour c)
{
if (row >= self->rows) return 1;
Colour _c = _WS2812B_cc(c, self->flags & WS2812B_SCHEMES);
for (unsigned int i = 0; i < self->columns; i++)
_WS2812B_spf(self, i, row, _c);
return 0;
}
int WS2812B_set_column(WS2812B *self, unsigned int col, Colour c)
{
if (col >= self->columns) return 1;
Colour _c = _WS2812B_cc(c, self->flags & WS2812B_SCHEMES);
for (unsigned int i = 0; i < self->rows; i++)
_WS2812B_spf(self, col, i, _c);
return 0;
}
int WS2812B_render(WS2812B *self, const char *ascii_art)
{
size_t count = MIN(strlen(ascii_art), self->count);
for (size_t i = 0; i < count; ++i) {
unsigned int x, y;
x = _WS2812B_x(i, self->columns);
y = _WS2812B_y(i, self->columns);
WS2812B_set_pixel(self, x, y, _WS2812B_lupc(self, ascii_art[i]));
}
return self->count - strlen(ascii_art);
}
/* Helper functions */
int _WS2812B_addr(unsigned int x, unsigned int y, unsigned int c, unsigned int *addr)
{
if (x >= c) return 1;
*addr = c * y + x;
return 0;
}
int _WS2812B_spf(WS2812B *self, unsigned int x, unsigned int y, Colour c)
{
uint16_t offset = 0;
if (x >= self->columns || y >= self->rows) return 1;
if (self->flags & WS2812B_ZIGZAG_ODD && y % 2 != 0)
x = self->columns - x - 1;
if (self->flags & WS2812B_ZIGZAG_EVEN && y % 2 == 0)
x = self->columns - x - 1;
if(_WS2812B_addr(x, y, self->columns, &offset)) return 1;
self->pixels[offset] = c;
return 0;
}
unsigned int _WS2812B_x(unsigned int addr, unsigned int c) {
return addr % c;
}
unsigned int _WS2812B_y(unsigned int addr, unsigned int c) {
return addr / c;
}
Colour _WS2812B_lupc(WS2812B *self, char id)
{
for (size_t i = 0; i < self->palette_used; ++i) {
ColourPalette p = self->palette[i];
if (p.id == id) return p.col;
}
return {0,0,0};
}
Colour _WS2812B_cc(Colour c, int order)
{
switch (order) {
case WS2812B_RBG: return {c.red, c.blue, c.green};
case WS2812B_GRB: return {c.green, c.red, c.blue};
case WS2812B_GBR: return {c.green, c.blue, c.red};
case WS2812B_BRG: return {c.blue, c.red, c.green};
case WS2812B_BGR: return {c.blue, c.green, c.red};
default /* RGB */: return c;
}
}
<commit_msg>Add support for redefining colours<commit_after>#include "ws2812b.h"
#include "string.h"
int WS2812B_init(WS2812B *self, int pin, Colour *pixels, int flags, unsigned int columns, unsigned int rows)
{
if (digitalPinToPort(pin) == NOT_A_PIN) return 1;
self->port = portOutputRegister(digitalPinToPort(pin));
self->bit = digitalPinToBitMask(pin);
self->pin = pin;
self->count = columns*rows;
self->pixels = pixels;
self->flags = flags;
self->columns = columns;
self->rows = rows;
return 0;
}
void WS2812B_sync(WS2812B *self)
{
// https://cdn-shop.adafruit.com/datasheets/WS2812B.pdf
volatile uint16_t count = self->count*3;
uint8_t *ptr = (uint8_t*)self->pixels; // Next byte ptr (initialized to first here)
uint8_t byte = *ptr++; // Current byte
uint8_t hi = *self->port | self->bit; // Cached high state
uint8_t lo = *self->port & ~self->bit; // Cached low state
volatile uint8_t next = lo;
volatile uint8_t bit = 8;
if (!count) return;
cli(); // Disable interrupts
// @TODO: Go through instruction set to see if we can relax the timing.
// Note that the C code on the side is pseudo-pseudocode.
// Some of the C code on the side would get optimsed, while some of it
// can't be optimsed as effectively, which would significantly skew
// the signal timing a WS281X chip expects. The timing here is on a very
// tight schedule anyway, so we need to be careful.
//
//
// See footnotes for extended descriptions.
asm volatile (
"__colour_bit: \n\t" // __colour_bit:
"st %a[port], %[hi] \n\t" // *port = hi;
"sbrc %[byte], 7 \n\t\t" // if (byte & 0x80)
"mov %[next], %[hi] \n\t" // next = hi;
"dec %[bit] \n\t" // --bit;
"st %a[port], %[next] \n\t" // *port = next;
"mov %[next], %[lo] \n\t" // next = lo;
"breq __colour_byte \n\t" // if (bit == 0) goto __colour_byte; // See [0]
"lsl %[byte] \n\t" // byte = (byte << 1);
"nop; nop; nop \n\t" // sleep_cycles(3);
"st %a[port], %[lo] \n\t" // *port = lo;
"nop; nop; nop \n\t" // sleep_cycles(3);
"rjmp __colour_bit \n" // goto __colour_bit;
//
"__colour_byte: \n\t" // __colour_byte:
"ldi %[bit], 8 \n\t" // bit = 8;
"ld %[byte], %a[ptr]+ \n\t" // byte = *ptr++;
"st %a[port], %[lo] \n\t" // *port = lo;
"nop \n\t" // sleep_cycles(1);
"sbiw %[count], 1 \n\t" // --count;
"brne __colour_bit \n" // if (bit != 0) goto __colour_bit; // See [1]
// The benefit of extended ASM is that we can define registers and
// operands elegantly:
: [port] "+e" (self->port),
[count] "+w" (count),
[bit] "+r" (bit),
[byte] "+r" (byte),
[next] "+r" (next)
: [ptr] "e" (ptr),
[hi] "r" (hi),
[lo] "r" (lo)
);
// Enable interrupts
sei();
// Wait for *at least* 50µs; this causes the chip to latch the voltage onto
// the individual LEDs contained within the RGB component.
_delay_us(51);
/**
* # 1. `breq __colour_byte`
* What this effectively does is test whether the Z flag in SREG register is
* set to `1`, and if so, jumps to the defined symbol (`__colour_byte`).
*
* The Z flag (Zero flag) gets set when the previous arithmetic expression
* evaluated to `0`. In our case, the last arithmetic expression was the
* subtraction `dec %[bit]` (`--bit`).
*
* # 2. `brne __colour_bit`
* This is similar to `breq`, but tests whether the Z flag in SREG is *not*
* `1` before jumping. The flag gets cleared after the prevous arithmetic
* expression evaluates to anything but `0`.
*
* ---
* PS: "expression" is used as a synonym for "instruction"
*
* More detailed documentation can be found [here][doclink].
*
* [doclink]: http://www.atmel.com/webdoc/avrassembler/avrassembler.wb_instruction_list.html
*/
}
int WS2812B_init_palette(WS2812B *self, ColourPalette* palette, unsigned int size)
{
self->palette_size = size;
self->palette_used = 0;
self->palette = palette;
return 0;
}
int WS2812B_add_colour(WS2812B *self, char id, Colour c)
{
if (self->palette_used >= self->palette_size) return 1;
for (size_t i = 0; i < self->palette_used; ++i) {
if (self->palette[i].id == id) {
self->palette[i].c = c;
return 0;
}
}
self->palette[self->palette_used++] = {id, c};
return 0;
}
int WS2812B_set_pixel(WS2812B *self, unsigned int x, unsigned int y, Colour c)
{
return _WS2812B_spf(self, x, y, _WS2812B_cc(c, self->flags & WS2812B_SCHEMES));
}
int WS2812B_set_pixel_at_offset(WS2812B *self, uint16_t offset, Colour c)
{
if (offset >= self->count) return 1;
self->pixels[offset] = _WS2812B_cc(c, self->flags & WS2812B_SCHEMES);
return 0;
}
int WS2812B_set_all(WS2812B *self, Colour c)
{
Colour _c = _WS2812B_cc(c, self->flags & WS2812B_SCHEMES);
uint16_t count = self->count;
while (count) self->pixels[--count] = _c;
return 0;
}
Colour WS2812B_get_pixel(WS2812B *self, unsigned int x, unsigned int y)
{
uint16_t offset = 0;
if (x >= self->columns || y >= self->rows) return {0,0,0};
if (self->flags & WS2812B_ZIGZAG_ODD && y % 2 != 0)
x = self->columns - x - 1;
if (self->flags & WS2812B_ZIGZAG_EVEN && y % 2 == 0)
x = self->columns - x - 1;
if(_WS2812B_addr(x, y, self->columns, &offset)) return {0,0,0};
return self->pixels[offset];
}
int WS2812B_set_row(WS2812B *self, unsigned int row, Colour c)
{
if (row >= self->rows) return 1;
Colour _c = _WS2812B_cc(c, self->flags & WS2812B_SCHEMES);
for (unsigned int i = 0; i < self->columns; i++)
_WS2812B_spf(self, i, row, _c);
return 0;
}
int WS2812B_set_column(WS2812B *self, unsigned int col, Colour c)
{
if (col >= self->columns) return 1;
Colour _c = _WS2812B_cc(c, self->flags & WS2812B_SCHEMES);
for (unsigned int i = 0; i < self->rows; i++)
_WS2812B_spf(self, col, i, _c);
return 0;
}
int WS2812B_render(WS2812B *self, const char *ascii_art)
{
size_t count = MIN(strlen(ascii_art), self->count);
for (size_t i = 0; i < count; ++i) {
unsigned int x, y;
x = _WS2812B_x(i, self->columns);
y = _WS2812B_y(i, self->columns);
WS2812B_set_pixel(self, x, y, _WS2812B_lupc(self, ascii_art[i]));
}
return self->count - strlen(ascii_art);
}
/* Helper functions */
int _WS2812B_addr(unsigned int x, unsigned int y, unsigned int c, unsigned int *addr)
{
if (x >= c) return 1;
*addr = c * y + x;
return 0;
}
int _WS2812B_spf(WS2812B *self, unsigned int x, unsigned int y, Colour c)
{
uint16_t offset = 0;
if (x >= self->columns || y >= self->rows) return 1;
if (self->flags & WS2812B_ZIGZAG_ODD && y % 2 != 0)
x = self->columns - x - 1;
if (self->flags & WS2812B_ZIGZAG_EVEN && y % 2 == 0)
x = self->columns - x - 1;
if(_WS2812B_addr(x, y, self->columns, &offset)) return 1;
self->pixels[offset] = c;
return 0;
}
unsigned int _WS2812B_x(unsigned int addr, unsigned int c) {
return addr % c;
}
unsigned int _WS2812B_y(unsigned int addr, unsigned int c) {
return addr / c;
}
Colour _WS2812B_lupc(WS2812B *self, char id)
{
for (size_t i = 0; i < self->palette_used; ++i) {
ColourPalette p = self->palette[i];
if (p.id == id) return p.col;
}
return {0,0,0};
}
Colour _WS2812B_cc(Colour c, int order)
{
switch (order) {
case WS2812B_RBG: return {c.red, c.blue, c.green};
case WS2812B_GRB: return {c.green, c.red, c.blue};
case WS2812B_GBR: return {c.green, c.blue, c.red};
case WS2812B_BRG: return {c.blue, c.red, c.green};
case WS2812B_BGR: return {c.blue, c.green, c.red};
default /* RGB */: return c;
}
}
<|endoftext|>
|
<commit_before>/*
* File: PPAxisAncestor.cpp
* Copyright (C) 2004 The Institute for System Programming of the Russian Academy of Sciences (ISP RAS)
*/
#include "common/sedna.h"
#include "tr/executor/xqops/PPAxisAncestor.h"
#include "tr/crmutils/node_utils.h"
#include "tr/executor/base/PPUtils.h"
#include "tr/executor/base/dm_accessors.h"
void PPAxisAncestor::init_function()
{
switch (nt_type)
{
case node_test_processing_instruction : next_fun = &PPAxisAncestor::next_processing_instruction; break;
case node_test_comment : next_fun = &PPAxisAncestor::next_comment; break;
case node_test_text : next_fun = &PPAxisAncestor::next_text; break;
case node_test_node : next_fun = &PPAxisAncestor::next_node; break;
case node_test_string : next_fun = &PPAxisAncestor::next_string; break;
case node_test_qname : next_fun = &PPAxisAncestor::next_qname; break;
case node_test_wildcard_star : next_fun = &PPAxisAncestor::next_wildcard_star; break;
case node_test_wildcard_ncname_star : next_fun = &PPAxisAncestor::next_wildcard_ncname_star; break;
case node_test_wildcard_star_ncname : next_fun = &PPAxisAncestor::next_wildcard_star_ncname; break;
case node_test_function_call : next_fun = &PPAxisAncestor::next_function_call; break;
case node_test_var_name : next_fun = &PPAxisAncestor::next_var_name; break;
default : throw USER_EXCEPTION2(SE1003, "Unexpected node test");
}
}
PPAxisAncestor::PPAxisAncestor(dynamic_context *_cxt_,
PPOpIn _child_,
NodeTestType _nt_type_,
NodeTestData _nt_data_):PPIterator(_cxt_),
child(_child_),
nt_type(_nt_type_),
nt_data(_nt_data_)
{
self=false;
init_function();
}
PPAxisAncestor::PPAxisAncestor(dynamic_context *_cxt_,
PPOpIn _child_,
NodeTestType _nt_type_,
NodeTestData _nt_data_,bool _self_) : PPIterator(_cxt_),
child(_child_),
nt_type(_nt_type_),
nt_data(_nt_data_),
self(_self_)
{
init_function();
}
PPAxisAncestor::~PPAxisAncestor()
{
delete child.op;
child.op = NULL;
}
void PPAxisAncestor::open ()
{
child.op->open();
cur = XNULL;
}
void PPAxisAncestor::reopen()
{
child.op->reopen();
cur = XNULL;
}
void PPAxisAncestor::close ()
{
child.op->close();
}
PPIterator* PPAxisAncestor::copy(dynamic_context *_cxt_)
{
PPAxisAncestor *res = self ? se_new PPAxisAncestor(_cxt_, child, nt_type, nt_data, true) :
se_new PPAxisAncestor(_cxt_, child, nt_type, nt_data);
res->child.op = child.op->copy(_cxt_);
res->set_xquery_line(__xquery_line);
return res;
}
bool PPAxisAncestor::result(PPIterator* cur, dynamic_context *cxt, void*& r)
{
return true;
}
PPAxisAncestorOrSelf::PPAxisAncestorOrSelf(dynamic_context *_cxt_,
PPOpIn _child_,
NodeTestType _nt_type_,
NodeTestData _nt_data_):PPAxisAncestor(_cxt_, _child_, _nt_type_, _nt_data_,true)
{
}
void PPAxisAncestor::next_processing_instruction(tuple &t)
{
while (true)
{
child.op->next(t);
if (t.is_eos()) {RESTORE_CURRENT_PP; return;}
if (!(child.get(t).is_node())) throw XQUERY_EXCEPTION(XPTY0020);
}
}
void PPAxisAncestor::next_comment(tuple &t)
{
while (true)
{
child.op->next(t);
if (t.is_eos()) {RESTORE_CURRENT_PP; return;}
if (!(child.get(t).is_node())) throw XQUERY_EXCEPTION(XPTY0020);
}
}
void PPAxisAncestor::next_text(tuple &t)
{
while (true)
{
child.op->next(t);
if (t.is_eos()) {RESTORE_CURRENT_PP; return;}
if (!(child.get(t).is_node())) throw XQUERY_EXCEPTION(XPTY0020);
}
}
void PPAxisAncestor::next_node(tuple &t)
{
while (cur == XNULL)
{
child.op->next(t);
if (t.is_eos()) {RESTORE_CURRENT_PP; return;}
if (!(child.get(t).is_node())) throw XQUERY_EXCEPTION(XPTY0020);
cur = child.get(t).get_node();
if (!self) cur = get_parent_node(cur);
if (cur!=XNULL)
{
CHECKP(cur);
if (GETSCHEMENODEX(cur)->type==virtual_root)
cur=XNULL;
}
}
t.copy(tuple_cell::node(cur));
cur = get_parent_node(cur);
}
void PPAxisAncestor::next_string(tuple &t)
{
throw USER_EXCEPTION2(SE1002, "PPAxisAncestor::next_string");
}
void PPAxisAncestor::next_qname(tuple &t)
{
while (cur == XNULL)
{
child.op->next(t);
if (t.is_eos()) {RESTORE_CURRENT_PP; return;}
if (!(child.get(t).is_node())) throw XQUERY_EXCEPTION(XPTY0020);
cur = child.get(t).get_node();
if (!self) cur = get_parent_node(cur);
while (cur!=XNULL)
{
CHECKP(cur);
if (comp_qname_type(GETSCHEMENODEX(cur),
nt_data.uri,
nt_data.ncname_local,
element))
break;
cur = get_parent_node(cur);
}
}
t.copy(tuple_cell::node(cur));
cur = get_parent_node(cur);
while (cur!=XNULL)
{
CHECKP(cur);
if (comp_qname_type(GETSCHEMENODEX(cur),
nt_data.uri,
nt_data.ncname_local,
element))
{RESTORE_CURRENT_PP; return;}
cur = get_parent_node(cur);
}
}
void PPAxisAncestor::next_wildcard_star(tuple &t)
{
while (cur == NULL)
{
child.op->next(t);
if (t.is_eos()) {RESTORE_CURRENT_PP; return;}
if (!(child.get(t).is_node())) throw XQUERY_EXCEPTION(XPTY0020);
cur = child.get(t).get_node();
if (!self) cur = get_parent_node(cur);
while (cur!=XNULL)
{
CHECKP(cur);
if (comp_type(GETSCHEMENODEX(cur),
NULL,
NULL,
element))
break;
cur = get_parent_node(cur);
}
}
t.copy(tuple_cell::node(cur));
cur = get_parent_node(cur);
while (cur!=XNULL)
{
CHECKP(cur);
if ( comp_type(GETSCHEMENODEX(cur),
NULL,
NULL,
element))
{RESTORE_CURRENT_PP; return;}
cur = get_parent_node(cur);
}
}
void PPAxisAncestor::next_wildcard_ncname_star(tuple &t)
{
while (cur == NULL)
{
child.op->next(t);
if (t.is_eos()) {RESTORE_CURRENT_PP; return;}
if (!(child.get(t).is_node())) throw XQUERY_EXCEPTION(XPTY0020);
cur = child.get(t).get_node();
if (!self) cur = get_parent_node(cur);
while (cur!=XNULL)
{
CHECKP(cur);
if (comp_type(GETSCHEMENODEX(cur),
nt_data.uri,
NULL,
element))
break;
cur = get_parent_node(cur);
}
}
t.copy(tuple_cell::node(cur));
cur = get_parent_node(cur);
while (cur!=XNULL)
{
CHECKP(cur);
if (comp_type(GETSCHEMENODEX(cur),
nt_data.uri,
NULL,
element))
{RESTORE_CURRENT_PP; return;}
cur = get_parent_node(cur);
}
}
void PPAxisAncestor::next_wildcard_star_ncname(tuple &t)
{
while (cur == NULL)
{
child.op->next(t);
if (t.is_eos()) {RESTORE_CURRENT_PP; return;}
if (!(child.get(t).is_node())) throw XQUERY_EXCEPTION(XPTY0020);
cur = child.get(t).get_node();
if (!self) cur = get_parent_node(cur);
while (cur!=XNULL)
{
CHECKP(cur);
if (comp_local_type(GETSCHEMENODEX(cur),
NULL,
nt_data.ncname_local,
element))
break;
cur = get_parent_node(cur);
}
}
t.copy(tuple_cell::node(cur));
cur = get_parent_node(cur);
while (true)
{
CHECKP(cur);
if (comp_local_type(GETSCHEMENODEX(cur),
NULL,
nt_data.ncname_local,
element))
{RESTORE_CURRENT_PP; return;}
cur = get_parent_node(cur);
}
}
void PPAxisAncestor::next_function_call(tuple &t)
{
throw USER_EXCEPTION2(SE1002, "PPAxisAncestor::next_function_call");
}
void PPAxisAncestor::next_var_name(tuple &t)
{
throw USER_EXCEPTION2(SE1002, "PPAxisAncestor::next_var_name");
}
<commit_msg>ancestor or self fix<commit_after>/*
* File: PPAxisAncestor.cpp
* Copyright (C) 2004 The Institute for System Programming of the Russian Academy of Sciences (ISP RAS)
*/
#include "common/sedna.h"
#include "tr/executor/xqops/PPAxisAncestor.h"
#include "tr/crmutils/node_utils.h"
#include "tr/executor/base/PPUtils.h"
#include "tr/executor/base/dm_accessors.h"
void PPAxisAncestor::init_function()
{
switch (nt_type)
{
case node_test_processing_instruction : next_fun = &PPAxisAncestor::next_processing_instruction; break;
case node_test_comment : next_fun = &PPAxisAncestor::next_comment; break;
case node_test_text : next_fun = &PPAxisAncestor::next_text; break;
case node_test_node : next_fun = &PPAxisAncestor::next_node; break;
case node_test_string : next_fun = &PPAxisAncestor::next_string; break;
case node_test_qname : next_fun = &PPAxisAncestor::next_qname; break;
case node_test_wildcard_star : next_fun = &PPAxisAncestor::next_wildcard_star; break;
case node_test_wildcard_ncname_star : next_fun = &PPAxisAncestor::next_wildcard_ncname_star; break;
case node_test_wildcard_star_ncname : next_fun = &PPAxisAncestor::next_wildcard_star_ncname; break;
case node_test_function_call : next_fun = &PPAxisAncestor::next_function_call; break;
case node_test_var_name : next_fun = &PPAxisAncestor::next_var_name; break;
default : throw USER_EXCEPTION2(SE1003, "Unexpected node test");
}
}
PPAxisAncestor::PPAxisAncestor(dynamic_context *_cxt_,
PPOpIn _child_,
NodeTestType _nt_type_,
NodeTestData _nt_data_):PPIterator(_cxt_),
child(_child_),
nt_type(_nt_type_),
nt_data(_nt_data_)
{
self=false;
init_function();
}
PPAxisAncestor::PPAxisAncestor(dynamic_context *_cxt_,
PPOpIn _child_,
NodeTestType _nt_type_,
NodeTestData _nt_data_,bool _self_) : PPIterator(_cxt_),
child(_child_),
nt_type(_nt_type_),
nt_data(_nt_data_),
self(_self_)
{
init_function();
}
PPAxisAncestor::~PPAxisAncestor()
{
delete child.op;
child.op = NULL;
}
void PPAxisAncestor::open ()
{
child.op->open();
cur = XNULL;
}
void PPAxisAncestor::reopen()
{
child.op->reopen();
cur = XNULL;
}
void PPAxisAncestor::close ()
{
child.op->close();
}
PPIterator* PPAxisAncestor::copy(dynamic_context *_cxt_)
{
PPAxisAncestor *res = self ? se_new PPAxisAncestor(_cxt_, child, nt_type, nt_data, true) :
se_new PPAxisAncestor(_cxt_, child, nt_type, nt_data);
res->child.op = child.op->copy(_cxt_);
res->set_xquery_line(__xquery_line);
return res;
}
bool PPAxisAncestor::result(PPIterator* cur, dynamic_context *cxt, void*& r)
{
return true;
}
PPAxisAncestorOrSelf::PPAxisAncestorOrSelf(dynamic_context *_cxt_,
PPOpIn _child_,
NodeTestType _nt_type_,
NodeTestData _nt_data_):PPAxisAncestor(_cxt_, _child_, _nt_type_, _nt_data_,true)
{
}
void PPAxisAncestor::next_processing_instruction(tuple &t)
{
while (true)
{
child.op->next(t);
if (t.is_eos()) {RESTORE_CURRENT_PP; return;}
if (!(child.get(t).is_node())) throw XQUERY_EXCEPTION(XPTY0020);
}
}
void PPAxisAncestor::next_comment(tuple &t)
{
while (true)
{
child.op->next(t);
if (t.is_eos()) {RESTORE_CURRENT_PP; return;}
if (!(child.get(t).is_node())) throw XQUERY_EXCEPTION(XPTY0020);
}
}
void PPAxisAncestor::next_text(tuple &t)
{
while (true)
{
child.op->next(t);
if (t.is_eos()) {RESTORE_CURRENT_PP; return;}
if (!(child.get(t).is_node())) throw XQUERY_EXCEPTION(XPTY0020);
}
}
void PPAxisAncestor::next_node(tuple &t)
{
while (cur == XNULL)
{
child.op->next(t);
if (t.is_eos()) {RESTORE_CURRENT_PP; return;}
if (!(child.get(t).is_node())) throw XQUERY_EXCEPTION(XPTY0020);
cur = child.get(t).get_node();
if (!self) cur = get_parent_node(cur);
if (cur!=XNULL)
{
CHECKP(cur);
if (GETSCHEMENODEX(cur)->type==virtual_root)
cur=XNULL;
}
}
t.copy(tuple_cell::node(cur));
cur = get_parent_node(cur);
if (GETSCHEMENODEX(cur)->type==virtual_root)
cur=XNULL;
}
void PPAxisAncestor::next_string(tuple &t)
{
throw USER_EXCEPTION2(SE1002, "PPAxisAncestor::next_string");
}
void PPAxisAncestor::next_qname(tuple &t)
{
while (cur == XNULL)
{
child.op->next(t);
if (t.is_eos()) {RESTORE_CURRENT_PP; return;}
if (!(child.get(t).is_node())) throw XQUERY_EXCEPTION(XPTY0020);
cur = child.get(t).get_node();
if (!self) cur = get_parent_node(cur);
while (cur!=XNULL)
{
CHECKP(cur);
if (comp_qname_type(GETSCHEMENODEX(cur),
nt_data.uri,
nt_data.ncname_local,
element))
break;
cur = get_parent_node(cur);
}
}
t.copy(tuple_cell::node(cur));
cur = get_parent_node(cur);
while (cur!=XNULL)
{
CHECKP(cur);
if (comp_qname_type(GETSCHEMENODEX(cur),
nt_data.uri,
nt_data.ncname_local,
element))
{RESTORE_CURRENT_PP; return;}
cur = get_parent_node(cur);
}
}
void PPAxisAncestor::next_wildcard_star(tuple &t)
{
while (cur == NULL)
{
child.op->next(t);
if (t.is_eos()) {RESTORE_CURRENT_PP; return;}
if (!(child.get(t).is_node())) throw XQUERY_EXCEPTION(XPTY0020);
cur = child.get(t).get_node();
if (!self) cur = get_parent_node(cur);
while (cur!=XNULL)
{
CHECKP(cur);
if (comp_type(GETSCHEMENODEX(cur),
NULL,
NULL,
element))
break;
cur = get_parent_node(cur);
}
}
t.copy(tuple_cell::node(cur));
cur = get_parent_node(cur);
while (cur!=XNULL)
{
CHECKP(cur);
if ( comp_type(GETSCHEMENODEX(cur),
NULL,
NULL,
element))
{RESTORE_CURRENT_PP; return;}
cur = get_parent_node(cur);
}
}
void PPAxisAncestor::next_wildcard_ncname_star(tuple &t)
{
while (cur == NULL)
{
child.op->next(t);
if (t.is_eos()) {RESTORE_CURRENT_PP; return;}
if (!(child.get(t).is_node())) throw XQUERY_EXCEPTION(XPTY0020);
cur = child.get(t).get_node();
if (!self) cur = get_parent_node(cur);
while (cur!=XNULL)
{
CHECKP(cur);
if (comp_type(GETSCHEMENODEX(cur),
nt_data.uri,
NULL,
element))
break;
cur = get_parent_node(cur);
}
}
t.copy(tuple_cell::node(cur));
cur = get_parent_node(cur);
while (cur!=XNULL)
{
CHECKP(cur);
if (comp_type(GETSCHEMENODEX(cur),
nt_data.uri,
NULL,
element))
{RESTORE_CURRENT_PP; return;}
cur = get_parent_node(cur);
}
}
void PPAxisAncestor::next_wildcard_star_ncname(tuple &t)
{
while (cur == NULL)
{
child.op->next(t);
if (t.is_eos()) {RESTORE_CURRENT_PP; return;}
if (!(child.get(t).is_node())) throw XQUERY_EXCEPTION(XPTY0020);
cur = child.get(t).get_node();
if (!self) cur = get_parent_node(cur);
while (cur!=XNULL)
{
CHECKP(cur);
if (comp_local_type(GETSCHEMENODEX(cur),
NULL,
nt_data.ncname_local,
element))
break;
cur = get_parent_node(cur);
}
}
t.copy(tuple_cell::node(cur));
cur = get_parent_node(cur);
while (true)
{
CHECKP(cur);
if (comp_local_type(GETSCHEMENODEX(cur),
NULL,
nt_data.ncname_local,
element))
{RESTORE_CURRENT_PP; return;}
cur = get_parent_node(cur);
}
}
void PPAxisAncestor::next_function_call(tuple &t)
{
throw USER_EXCEPTION2(SE1002, "PPAxisAncestor::next_function_call");
}
void PPAxisAncestor::next_var_name(tuple &t)
{
throw USER_EXCEPTION2(SE1002, "PPAxisAncestor::next_var_name");
}
<|endoftext|>
|
<commit_before>#include <znc/main.h>
#include <znc/User.h>
#include <znc/IRCNetwork.h>
#include <znc/Modules.h>
#include <znc/Nick.h>
#include <znc/Chan.h>
#include <znc/IRCSock.h>
#include <znc/version.h>
#include <limits>
#include "twitchtmi.h"
#include "jload.h"
#if (VERSION_MAJOR < 1) || (VERSION_MAJOR == 1 && VERSION_MINOR < 7)
#error This module needs at least ZNC 1.7.0 or later.
#endif
TwitchTMI::~TwitchTMI()
{
}
bool TwitchTMI::OnLoad(const CString& sArgsi, CString& sMessage)
{
OnBoot();
if(GetNetwork())
{
for(CChan *ch: GetNetwork()->GetChans())
{
ch->SetTopic(CString());
CString chname = ch->GetName().substr(1);
CThreadPool::Get().addJob(new TwitchTMIJob(this, chname));
}
}
if(GetArgs().Token(0) != "FrankerZ")
lastFrankerZ = std::numeric_limits<decltype(lastFrankerZ)>::max();
PutIRC("CAP REQ :twitch.tv/membership");
PutIRC("CAP REQ :twitch.tv/commands");
PutIRC("CAP REQ :twitch.tv/tags");
return true;
}
bool TwitchTMI::OnBoot()
{
initCurl();
timer = new TwitchTMIUpdateTimer(this);
AddTimer(timer);
return true;
}
void TwitchTMI::OnIRCConnected()
{
PutIRC("CAP REQ :twitch.tv/membership");
PutIRC("CAP REQ :twitch.tv/commands");
PutIRC("CAP REQ :twitch.tv/tags");
}
CModule::EModRet TwitchTMI::OnUserRaw(CString &sLine)
{
if(sLine.Left(5).Equals("WHO #"))
return CModule::HALT;
if(sLine.Left(5).Equals("AWAY "))
return CModule::HALT;
if(sLine.Left(12).Equals("TWITCHCLIENT"))
return CModule::HALT;
if(sLine.Left(9).Equals("JTVCLIENT"))
return CModule::HALT;
return CModule::CONTINUE;
}
CModule::EModRet TwitchTMI::OnRawMessage(CMessage &msg)
{
if(msg.GetCommand().Equals("HOSTTARGET"))
{
return CModule::HALT;
}
else if(msg.GetCommand().Equals("CLEARCHAT"))
{
msg.SetCommand("NOTICE");
if(msg.GetParam(1) != "")
{
msg.SetParam(1, msg.GetParam(1) + " was timed out.");
}
else
{
msg.SetParam(1, "Chat was cleared by a moderator.");
}
}
else if(msg.GetCommand().Equals("USERSTATE"))
{
return CModule::HALT;
}
else if(msg.GetCommand().Equals("ROOMSTATE"))
{
return CModule::HALT;
}
else if(msg.GetCommand().Equals("RECONNECT"))
{
return CModule::HALT;
}
else if(msg.GetCommand().Equals("GLOBALUSERSTATE"))
{
return CModule::HALT;
}
else if(msg.GetCommand().Equals("WHISPER"))
{
msg.SetCommand("PRIVMSG");
}
else if(msg.GetCommand().Equals("USERNOTICE"))
{
//TODO: Translate Tags to useful message
msg.SetCommand("PRIVMSG");
msg.SetParam(1, "<<<RESUB>>> " + msg.GetParam(1));
}
CString realNick = msg.GetTag("display-name").Trim_n();
if(realNick != "")
msg.GetNick().SetNick(realNick);
return CModule::CONTINUE;
}
CModule::EModRet TwitchTMI::OnUserJoin(CString& sChannel, CString& sKey)
{
CString chname = sChannel.substr(1);
CThreadPool::Get().addJob(new TwitchTMIJob(this, chname));
return CModule::CONTINUE;
}
CModule::EModRet TwitchTMI::OnPrivMessage(CTextMessage &Message)
{
if(Message.GetNick().GetNick().Equals("jtv"))
return CModule::HALT;
return CModule::CONTINUE;
}
void TwitchTMI::PutUserChanMessage(CChan *chan, const CString &from, const CString &msg)
{
std::stringstream ss;
ss << ":" << from << " PRIVMSG " << chan->GetName() << " :";
CString s = ss.str();
PutUser(s + msg);
if(!chan->AutoClearChanBuffer() || !GetNetwork()->IsUserOnline() || chan->IsDetached())
chan->AddBuffer(s + "{text}", msg);
}
CModule::EModRet TwitchTMI::OnChanMessage(CTextMessage &Message)
{
if(Message.GetNick().GetNick().Equals("jtv"))
return CModule::HALT;
if(Message.GetText() == "FrankerZ" && std::time(nullptr) - lastFrankerZ > 10)
{
std::stringstream ss;
CString mynick = GetNetwork()->GetIRCNick().GetNickMask();
CChan *chan = Message.GetChan();
ss << "PRIVMSG " << chan->GetName() << " :FrankerZ";
PutIRC(ss.str());
CThreadPool::Get().addJob(new GenericJob([]() {}, [this, chan, mynick]()
{
PutUserChanMessage(chan, mynick, "FrankerZ");
}));
lastFrankerZ = std::time(nullptr);
}
return CModule::CONTINUE;
}
bool TwitchTMI::OnServerCapAvailable(const CString &sCap)
{
if(sCap == "twitch.tv/membership")
return true;
else if(sCap == "twitch.tv/tags")
return true;
else if(sCap == "twitch.tv/commands")
return true;
return false;
}
CModule::EModRet TwitchTMI::OnUserTextMessage(CTextMessage &msg)
{
if(msg.GetTarget().Left(1).Equals("#"))
return CModule::CONTINUE;
msg.SetText(msg.GetText().insert(0, " ").insert(0, msg.GetTarget()).insert(0, "/w "));
msg.SetTarget("#jtv");
return CModule::CONTINUE;
}
TwitchTMIUpdateTimer::TwitchTMIUpdateTimer(TwitchTMI *tmod)
:CTimer(tmod, 30, 0, "TwitchTMIUpdateTimer", "Downloads Twitch information")
,mod(tmod)
{
}
void TwitchTMIUpdateTimer::RunJob()
{
if(!mod->GetNetwork())
return;
for(CChan *chan: mod->GetNetwork()->GetChans())
{
CString chname = chan->GetName().substr(1);
CThreadPool::Get().addJob(new TwitchTMIJob(mod, chname));
}
}
void TwitchTMIJob::runThread()
{
std::stringstream ss, ss2;
ss << "https://api.twitch.tv/kraken/channels/" << channel;
ss2 << "https://api.twitch.tv/kraken/streams/" << channel;
CString url = ss.str();
CString url2 = ss2.str();
Json::Value root = getJsonFromUrl(url.c_str(), "Accept: application/vnd.twitchtv.v3+json");
Json::Value root2 = getJsonFromUrl(url2.c_str(), "Accept: application/vnd.twitchtv.v3+json");
if(!root.isNull())
{
Json::Value &titleVal = root["status"];
title = CString();
if(!titleVal.isString())
titleVal = root["title"];
if(titleVal.isString())
{
title = titleVal.asString();
title.Trim();
}
}
live = false;
if(!root2.isNull())
{
Json::Value &streamVal = root2["stream"];
if(!streamVal.isNull())
live = true;
}
}
void TwitchTMIJob::runMain()
{
if(title.empty())
return;
CChan *chan = mod->GetNetwork()->FindChan(CString("#") + channel);
if(!chan)
return;
if(chan->GetTopic() != title)
{
chan->SetTopic(title);
chan->SetTopicOwner("jtv");
chan->SetTopicDate((unsigned long)time(nullptr));
std::stringstream ss;
ss << ":jtv TOPIC #" << channel << " :" << title;
mod->PutUser(ss.str());
}
auto it = mod->liveChannels.find(channel);
if(it != mod->liveChannels.end())
{
if(!live)
{
mod->liveChannels.erase(it);
mod->PutUserChanMessage(chan, "jtv", ">>> Channel just went offline! <<<");
}
}
else
{
if(live)
{
mod->liveChannels.insert(channel);
mod->PutUserChanMessage(chan, "jtv", ">>> Channel just went live! <<<");
}
}
}
template<> void TModInfo<TwitchTMI>(CModInfo &info)
{
info.SetWikiPage("Twitch");
info.SetHasArgs(true);
}
NETWORKMODULEDEFS(TwitchTMI, "Twitch IRC helper module")
<commit_msg>Update to v5 API<commit_after>#include <znc/main.h>
#include <znc/User.h>
#include <znc/IRCNetwork.h>
#include <znc/Modules.h>
#include <znc/Nick.h>
#include <znc/Chan.h>
#include <znc/IRCSock.h>
#include <znc/version.h>
#include <limits>
#include "twitchtmi.h"
#include "jload.h"
#if (VERSION_MAJOR < 1) || (VERSION_MAJOR == 1 && VERSION_MINOR < 7)
#error This module needs at least ZNC 1.7.0 or later.
#endif
TwitchTMI::~TwitchTMI()
{
}
bool TwitchTMI::OnLoad(const CString& sArgsi, CString& sMessage)
{
OnBoot();
if(GetNetwork())
{
for(CChan *ch: GetNetwork()->GetChans())
{
ch->SetTopic(CString());
CString chname = ch->GetName().substr(1);
CThreadPool::Get().addJob(new TwitchTMIJob(this, chname));
}
}
if(GetArgs().Token(0) != "FrankerZ")
lastFrankerZ = std::numeric_limits<decltype(lastFrankerZ)>::max();
PutIRC("CAP REQ :twitch.tv/membership");
PutIRC("CAP REQ :twitch.tv/commands");
PutIRC("CAP REQ :twitch.tv/tags");
return true;
}
bool TwitchTMI::OnBoot()
{
initCurl();
timer = new TwitchTMIUpdateTimer(this);
AddTimer(timer);
return true;
}
void TwitchTMI::OnIRCConnected()
{
PutIRC("CAP REQ :twitch.tv/membership");
PutIRC("CAP REQ :twitch.tv/commands");
PutIRC("CAP REQ :twitch.tv/tags");
}
CModule::EModRet TwitchTMI::OnUserRaw(CString &sLine)
{
if(sLine.Left(5).Equals("WHO #"))
return CModule::HALT;
if(sLine.Left(5).Equals("AWAY "))
return CModule::HALT;
if(sLine.Left(12).Equals("TWITCHCLIENT"))
return CModule::HALT;
if(sLine.Left(9).Equals("JTVCLIENT"))
return CModule::HALT;
return CModule::CONTINUE;
}
CModule::EModRet TwitchTMI::OnRawMessage(CMessage &msg)
{
if(msg.GetCommand().Equals("HOSTTARGET"))
{
return CModule::HALT;
}
else if(msg.GetCommand().Equals("CLEARCHAT"))
{
msg.SetCommand("NOTICE");
if(msg.GetParam(1) != "")
{
msg.SetParam(1, msg.GetParam(1) + " was timed out.");
}
else
{
msg.SetParam(1, "Chat was cleared by a moderator.");
}
}
else if(msg.GetCommand().Equals("USERSTATE"))
{
return CModule::HALT;
}
else if(msg.GetCommand().Equals("ROOMSTATE"))
{
return CModule::HALT;
}
else if(msg.GetCommand().Equals("RECONNECT"))
{
return CModule::HALT;
}
else if(msg.GetCommand().Equals("GLOBALUSERSTATE"))
{
return CModule::HALT;
}
else if(msg.GetCommand().Equals("WHISPER"))
{
msg.SetCommand("PRIVMSG");
}
else if(msg.GetCommand().Equals("USERNOTICE"))
{
//TODO: Translate Tags to useful message
msg.SetCommand("PRIVMSG");
msg.SetParam(1, "<<<RESUB>>> " + msg.GetParam(1));
}
CString realNick = msg.GetTag("display-name").Trim_n();
if(realNick != "")
msg.GetNick().SetNick(realNick);
return CModule::CONTINUE;
}
CModule::EModRet TwitchTMI::OnUserJoin(CString& sChannel, CString& sKey)
{
CString chname = sChannel.substr(1);
CThreadPool::Get().addJob(new TwitchTMIJob(this, chname));
return CModule::CONTINUE;
}
CModule::EModRet TwitchTMI::OnPrivMessage(CTextMessage &Message)
{
if(Message.GetNick().GetNick().Equals("jtv"))
return CModule::HALT;
return CModule::CONTINUE;
}
void TwitchTMI::PutUserChanMessage(CChan *chan, const CString &from, const CString &msg)
{
std::stringstream ss;
ss << ":" << from << " PRIVMSG " << chan->GetName() << " :";
CString s = ss.str();
PutUser(s + msg);
if(!chan->AutoClearChanBuffer() || !GetNetwork()->IsUserOnline() || chan->IsDetached())
chan->AddBuffer(s + "{text}", msg);
}
CModule::EModRet TwitchTMI::OnChanMessage(CTextMessage &Message)
{
if(Message.GetNick().GetNick().Equals("jtv"))
return CModule::HALT;
if(Message.GetText() == "FrankerZ" && std::time(nullptr) - lastFrankerZ > 10)
{
std::stringstream ss;
CString mynick = GetNetwork()->GetIRCNick().GetNickMask();
CChan *chan = Message.GetChan();
ss << "PRIVMSG " << chan->GetName() << " :FrankerZ";
PutIRC(ss.str());
CThreadPool::Get().addJob(new GenericJob([]() {}, [this, chan, mynick]()
{
PutUserChanMessage(chan, mynick, "FrankerZ");
}));
lastFrankerZ = std::time(nullptr);
}
return CModule::CONTINUE;
}
bool TwitchTMI::OnServerCapAvailable(const CString &sCap)
{
if(sCap == "twitch.tv/membership")
return true;
else if(sCap == "twitch.tv/tags")
return true;
else if(sCap == "twitch.tv/commands")
return true;
return false;
}
CModule::EModRet TwitchTMI::OnUserTextMessage(CTextMessage &msg)
{
if(msg.GetTarget().Left(1).Equals("#"))
return CModule::CONTINUE;
msg.SetText(msg.GetText().insert(0, " ").insert(0, msg.GetTarget()).insert(0, "/w "));
msg.SetTarget("#jtv");
return CModule::CONTINUE;
}
TwitchTMIUpdateTimer::TwitchTMIUpdateTimer(TwitchTMI *tmod)
:CTimer(tmod, 30, 0, "TwitchTMIUpdateTimer", "Downloads Twitch information")
,mod(tmod)
{
}
void TwitchTMIUpdateTimer::RunJob()
{
if(!mod->GetNetwork())
return;
for(CChan *chan: mod->GetNetwork()->GetChans())
{
CString chname = chan->GetName().substr(1);
CThreadPool::Get().addJob(new TwitchTMIJob(mod, chname));
}
}
void TwitchTMIJob::runThread()
{
std::stringstream ss, ss2;
ss << "https://api.twitch.tv/kraken/channels/" << channel;
ss2 << "https://api.twitch.tv/kraken/streams/" << channel;
CString url = ss.str();
CString url2 = ss2.str();
Json::Value root = getJsonFromUrl(url.c_str(), "Accept: application/vnd.twitchtv.v5+json");
Json::Value root2 = getJsonFromUrl(url2.c_str(), "Accept: application/vnd.twitchtv.v5+json");
if(!root.isNull())
{
Json::Value &titleVal = root["status"];
title = CString();
if(!titleVal.isString())
titleVal = root["title"];
if(titleVal.isString())
{
title = titleVal.asString();
title.Trim();
}
}
live = false;
if(!root2.isNull())
{
Json::Value &streamVal = root2["stream"];
if(!streamVal.isNull())
live = true;
}
}
void TwitchTMIJob::runMain()
{
if(title.empty())
return;
CChan *chan = mod->GetNetwork()->FindChan(CString("#") + channel);
if(!chan)
return;
if(chan->GetTopic() != title)
{
chan->SetTopic(title);
chan->SetTopicOwner("jtv");
chan->SetTopicDate((unsigned long)time(nullptr));
std::stringstream ss;
ss << ":jtv TOPIC #" << channel << " :" << title;
mod->PutUser(ss.str());
}
auto it = mod->liveChannels.find(channel);
if(it != mod->liveChannels.end())
{
if(!live)
{
mod->liveChannels.erase(it);
mod->PutUserChanMessage(chan, "jtv", ">>> Channel just went offline! <<<");
}
}
else
{
if(live)
{
mod->liveChannels.insert(channel);
mod->PutUserChanMessage(chan, "jtv", ">>> Channel just went live! <<<");
}
}
}
template<> void TModInfo<TwitchTMI>(CModInfo &info)
{
info.SetWikiPage("Twitch");
info.SetHasArgs(true);
}
NETWORKMODULEDEFS(TwitchTMI, "Twitch IRC helper module")
<|endoftext|>
|
<commit_before>// Copyright 2017-2020 The Verible Authors.
//
// 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.
// verilog_format is a command-line utility to format verilog source code
// for a given file.
//
// Example usage:
// verilog_format original-file > new-file
//
// Exit code:
// 0: stdout output can be used to replace original file
// nonzero: stdout output (if any) should be discarded
#include <fstream>
#include <iostream>
#include <memory>
#include <sstream> // IWYU pragma: keep // for ostringstream
#include <string> // for string, allocator, etc
#include <vector>
#include "absl/flags/flag.h"
#include "absl/status/status.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_join.h"
#include "absl/strings/str_split.h"
#include "absl/strings/string_view.h"
#include "common/util/file_util.h"
#include "common/util/init_command_line.h"
#include "common/util/interval_set.h"
#include "common/util/logging.h" // for operator<<, LOG, LogMessage, etc
#include "verilog/formatting/format_style.h"
#include "verilog/formatting/formatter.h"
using absl::StatusCode;
using verilog::formatter::ExecutionControl;
using verilog::formatter::FormatStyle;
using verilog::formatter::FormatVerilog;
// Pseudo-singleton, so that repeated flag occurrences accumulate values.
// --flag x --flag y yields [x, y]
struct LineRanges {
// need to copy string, cannot just use string_view
typedef std::vector<std::string> storage_type;
static storage_type values;
};
LineRanges::storage_type LineRanges::values; // global initializer
bool AbslParseFlag(absl::string_view flag_arg, LineRanges* /* unused */,
std::string* error) {
auto& values = LineRanges::values;
// Pre-split strings, so that "--flag v1,v2" and "--flag v1 --flag v2" are
// equivalent.
const std::vector<absl::string_view> tokens = absl::StrSplit(flag_arg, ',');
values.reserve(values.size() + tokens.size());
for (const auto& token : tokens) {
// need to copy string, cannot just use string_view
values.push_back(std::string(token.begin(), token.end()));
}
// Range validation done later.
return true;
}
std::string AbslUnparseFlag(LineRanges /* unused */) {
const auto& values = LineRanges::values;
return absl::StrJoin(values.begin(), values.end(), ",",
absl::StreamFormatter());
}
// TODO(fangism): Provide -i alias, as it is canonical to many formatters
ABSL_FLAG(bool, inplace, false,
"If true, overwrite the input file on successful conditions.");
ABSL_FLAG(std::string, stdin_name, "<stdin>",
"When using '-' to read from stdin, this gives an alternate name for "
"diagnostic purposes. Otherwise this is ignored.");
ABSL_FLAG(LineRanges, lines, {},
"Specific lines to format, 1-based, comma-separated, inclusive N-M "
"ranges, N is short for N-N. By default, left unspecified, "
"all lines are enabled for formatting. (repeatable, cumulative)");
ABSL_FLAG(int, show_largest_token_partitions, 0,
"If > 0, print token partitioning and then "
"exit without formatting output.");
ABSL_FLAG(bool, show_token_partition_tree, false,
"If true, print diagnostics after token partitioning and then "
"exit without formatting output.");
ABSL_FLAG(bool, show_inter_token_info, false,
"If true, along with show_token_partition_tree, include inter-token "
"information such as spacing and break penalties.");
ABSL_FLAG(bool, show_equally_optimal_wrappings, false,
"If true, print when multiple optimal solutions are found (stderr), "
"but continue to operate normally.");
ABSL_FLAG(int, max_search_states, 100000,
"Limits the number of search states explored during "
"line wrap optimization.");
// These flags exist in the short term to disable formatting of some regions.
ABSL_FLAG(bool, format_module_port_declarations, false,
"If true, format module declarations' list of port declarations, "
"else leave them unformatted.");
int main(int argc, char** argv) {
const auto usage = absl::StrCat("usage: ", argv[0],
" [options] <file>\n"
"To pipe from stdin, use '-' as <file>.");
const auto file_args = verible::InitCommandLine(usage, &argc, &argv);
// Currently accepts only one file positional argument.
// TODO(fangism): Support multiple file names.
QCHECK_GT(file_args.size(), 1)
<< "Missing required positional argument (filename).";
const absl::string_view filename = file_args[1];
const bool inplace = FLAGS_inplace.Get();
const bool is_stdin = filename == "-";
const auto& stdin_name = FLAGS_stdin_name.Get();
if (inplace && is_stdin) {
std::cerr << "--inplace is incompatible with stdin. Ignoring --inplace "
"and writing to stdout."
<< std::endl;
}
absl::string_view diagnostic_filename = filename;
if (is_stdin) {
diagnostic_filename = stdin_name;
}
// Parse LineRanges into a line set, to validate the --lines flag(s)
verilog::formatter::LineNumberSet lines_to_format;
if (!verible::ParseInclusiveRanges(
&lines_to_format, LineRanges::values.begin(),
LineRanges::values.end(), &std::cerr, '-')) {
std::cerr << "Error parsing --lines." << std::endl;
std::cerr << "Got: --lines=" << AbslUnparseFlag(LineRanges()) << std::endl;
return 1;
}
// Read contents into memory first.
std::string content;
if (!verible::file::GetContents(filename, &content)) return 1;
// TODO(fangism): When requesting --inplace, verify that file
// is write-able, and fail-early if it is not.
// TODO(fangism): support style configuration from flags.
FormatStyle format_style;
// Handle special debugging modes.
ExecutionControl formatter_control;
{
// execution control flags
formatter_control.stream = &std::cout; // for diagnostics only
formatter_control.show_largest_token_partitions =
FLAGS_show_largest_token_partitions.Get();
formatter_control.show_token_partition_tree =
FLAGS_show_token_partition_tree.Get();
formatter_control.show_inter_token_info = FLAGS_show_inter_token_info.Get();
formatter_control.show_equally_optimal_wrappings =
FLAGS_show_equally_optimal_wrappings.Get();
formatter_control.max_search_states = FLAGS_max_search_states.Get();
// formatting style flags
format_style.format_module_port_declarations =
FLAGS_format_module_port_declarations.Get();
}
std::ostringstream stream;
const auto format_status =
FormatVerilog(content, diagnostic_filename, format_style, stream,
lines_to_format, formatter_control);
const std::string& formatted_output(stream.str());
if (!format_status.ok()) {
if (!inplace) {
// Fall back to printing original content regardless of error condition.
std::cout << content;
}
// Print the error message last so it shows up in user's console.
std::cerr << format_status.message();
switch (format_status.code()) {
case StatusCode::kCancelled:
case StatusCode::kInvalidArgument:
break;
case StatusCode::kDataLoss:
std::cerr << "Problematic formatter output is:\n"
<< formatted_output << "<<EOF>>" << std::endl;
break;
default:
std::cerr << "[other error status]" << std::endl;
break;
}
return 1;
}
// Safe to write out result, having passed above verification.
int exit_code = 0;
std::ostream* output_stream = &std::cout;
std::ofstream inplace_file;
if (inplace && !is_stdin) {
inplace_file.open(std::string(filename));
if (inplace_file.good()) {
output_stream = &inplace_file;
} else {
std::cerr << "Error writing to file: " << filename << std::endl;
std::cerr << "Printing to stdout instead." << std::endl;
exit_code = 1;
}
}
*output_stream << formatted_output;
return exit_code;
}
<commit_msg>Add missing newline in diagnostic.<commit_after>// Copyright 2017-2020 The Verible Authors.
//
// 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.
// verilog_format is a command-line utility to format verilog source code
// for a given file.
//
// Example usage:
// verilog_format original-file > new-file
//
// Exit code:
// 0: stdout output can be used to replace original file
// nonzero: stdout output (if any) should be discarded
#include <fstream>
#include <iostream>
#include <memory>
#include <sstream> // IWYU pragma: keep // for ostringstream
#include <string> // for string, allocator, etc
#include <vector>
#include "absl/flags/flag.h"
#include "absl/status/status.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_join.h"
#include "absl/strings/str_split.h"
#include "absl/strings/string_view.h"
#include "common/util/file_util.h"
#include "common/util/init_command_line.h"
#include "common/util/interval_set.h"
#include "common/util/logging.h" // for operator<<, LOG, LogMessage, etc
#include "verilog/formatting/format_style.h"
#include "verilog/formatting/formatter.h"
using absl::StatusCode;
using verilog::formatter::ExecutionControl;
using verilog::formatter::FormatStyle;
using verilog::formatter::FormatVerilog;
// Pseudo-singleton, so that repeated flag occurrences accumulate values.
// --flag x --flag y yields [x, y]
struct LineRanges {
// need to copy string, cannot just use string_view
typedef std::vector<std::string> storage_type;
static storage_type values;
};
LineRanges::storage_type LineRanges::values; // global initializer
bool AbslParseFlag(absl::string_view flag_arg, LineRanges* /* unused */,
std::string* error) {
auto& values = LineRanges::values;
// Pre-split strings, so that "--flag v1,v2" and "--flag v1 --flag v2" are
// equivalent.
const std::vector<absl::string_view> tokens = absl::StrSplit(flag_arg, ',');
values.reserve(values.size() + tokens.size());
for (const auto& token : tokens) {
// need to copy string, cannot just use string_view
values.push_back(std::string(token.begin(), token.end()));
}
// Range validation done later.
return true;
}
std::string AbslUnparseFlag(LineRanges /* unused */) {
const auto& values = LineRanges::values;
return absl::StrJoin(values.begin(), values.end(), ",",
absl::StreamFormatter());
}
// TODO(fangism): Provide -i alias, as it is canonical to many formatters
ABSL_FLAG(bool, inplace, false,
"If true, overwrite the input file on successful conditions.");
ABSL_FLAG(std::string, stdin_name, "<stdin>",
"When using '-' to read from stdin, this gives an alternate name for "
"diagnostic purposes. Otherwise this is ignored.");
ABSL_FLAG(LineRanges, lines, {},
"Specific lines to format, 1-based, comma-separated, inclusive N-M "
"ranges, N is short for N-N. By default, left unspecified, "
"all lines are enabled for formatting. (repeatable, cumulative)");
ABSL_FLAG(int, show_largest_token_partitions, 0,
"If > 0, print token partitioning and then "
"exit without formatting output.");
ABSL_FLAG(bool, show_token_partition_tree, false,
"If true, print diagnostics after token partitioning and then "
"exit without formatting output.");
ABSL_FLAG(bool, show_inter_token_info, false,
"If true, along with show_token_partition_tree, include inter-token "
"information such as spacing and break penalties.");
ABSL_FLAG(bool, show_equally_optimal_wrappings, false,
"If true, print when multiple optimal solutions are found (stderr), "
"but continue to operate normally.");
ABSL_FLAG(int, max_search_states, 100000,
"Limits the number of search states explored during "
"line wrap optimization.");
// These flags exist in the short term to disable formatting of some regions.
ABSL_FLAG(bool, format_module_port_declarations, false,
"If true, format module declarations' list of port declarations, "
"else leave them unformatted.");
int main(int argc, char** argv) {
const auto usage = absl::StrCat("usage: ", argv[0],
" [options] <file>\n"
"To pipe from stdin, use '-' as <file>.");
const auto file_args = verible::InitCommandLine(usage, &argc, &argv);
// Currently accepts only one file positional argument.
// TODO(fangism): Support multiple file names.
QCHECK_GT(file_args.size(), 1)
<< "Missing required positional argument (filename).";
const absl::string_view filename = file_args[1];
const bool inplace = FLAGS_inplace.Get();
const bool is_stdin = filename == "-";
const auto& stdin_name = FLAGS_stdin_name.Get();
if (inplace && is_stdin) {
std::cerr << "--inplace is incompatible with stdin. Ignoring --inplace "
"and writing to stdout."
<< std::endl;
}
absl::string_view diagnostic_filename = filename;
if (is_stdin) {
diagnostic_filename = stdin_name;
}
// Parse LineRanges into a line set, to validate the --lines flag(s)
verilog::formatter::LineNumberSet lines_to_format;
if (!verible::ParseInclusiveRanges(
&lines_to_format, LineRanges::values.begin(),
LineRanges::values.end(), &std::cerr, '-')) {
std::cerr << "Error parsing --lines." << std::endl;
std::cerr << "Got: --lines=" << AbslUnparseFlag(LineRanges()) << std::endl;
return 1;
}
// Read contents into memory first.
std::string content;
if (!verible::file::GetContents(filename, &content)) return 1;
// TODO(fangism): When requesting --inplace, verify that file
// is write-able, and fail-early if it is not.
// TODO(fangism): support style configuration from flags.
FormatStyle format_style;
// Handle special debugging modes.
ExecutionControl formatter_control;
{
// execution control flags
formatter_control.stream = &std::cout; // for diagnostics only
formatter_control.show_largest_token_partitions =
FLAGS_show_largest_token_partitions.Get();
formatter_control.show_token_partition_tree =
FLAGS_show_token_partition_tree.Get();
formatter_control.show_inter_token_info = FLAGS_show_inter_token_info.Get();
formatter_control.show_equally_optimal_wrappings =
FLAGS_show_equally_optimal_wrappings.Get();
formatter_control.max_search_states = FLAGS_max_search_states.Get();
// formatting style flags
format_style.format_module_port_declarations =
FLAGS_format_module_port_declarations.Get();
}
std::ostringstream stream;
const auto format_status =
FormatVerilog(content, diagnostic_filename, format_style, stream,
lines_to_format, formatter_control);
const std::string& formatted_output(stream.str());
if (!format_status.ok()) {
if (!inplace) {
// Fall back to printing original content regardless of error condition.
std::cout << content;
}
// Print the error message last so it shows up in user's console.
std::cerr << format_status.message() << std::endl;
switch (format_status.code()) {
case StatusCode::kCancelled:
case StatusCode::kInvalidArgument:
break;
case StatusCode::kDataLoss:
std::cerr << "Problematic formatter output is:\n"
<< formatted_output << "<<EOF>>" << std::endl;
break;
default:
std::cerr << "[other error status]" << std::endl;
break;
}
return 1;
}
// Safe to write out result, having passed above verification.
int exit_code = 0;
std::ostream* output_stream = &std::cout;
std::ofstream inplace_file;
if (inplace && !is_stdin) {
inplace_file.open(std::string(filename));
if (inplace_file.good()) {
output_stream = &inplace_file;
} else {
std::cerr << "Error writing to file: " << filename << std::endl;
std::cerr << "Printing to stdout instead." << std::endl;
exit_code = 1;
}
}
*output_stream << formatted_output;
return exit_code;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/video_engine/vie_base_impl.h"
#include <sstream>
#include <string>
#include "webrtc/engine_configurations.h"
#include "webrtc/modules/rtp_rtcp/interface/rtp_rtcp.h"
#include "webrtc/modules/video_coding/main/interface/video_coding.h"
#include "webrtc/modules/video_processing/main/interface/video_processing.h"
#include "webrtc/modules/video_render/include/video_render.h"
#include "webrtc/system_wrappers/interface/critical_section_wrapper.h"
#include "webrtc/system_wrappers/interface/trace.h"
#include "webrtc/video_engine/include/vie_errors.h"
#include "webrtc/video_engine/vie_channel.h"
#include "webrtc/video_engine/vie_channel_manager.h"
#include "webrtc/video_engine/vie_defines.h"
#include "webrtc/video_engine/vie_encoder.h"
#include "webrtc/video_engine/vie_impl.h"
#include "webrtc/video_engine/vie_input_manager.h"
#include "webrtc/video_engine/vie_shared_data.h"
namespace webrtc {
ViEBase* ViEBase::GetInterface(VideoEngine* video_engine) {
if (!video_engine) {
return NULL;
}
VideoEngineImpl* vie_impl = static_cast<VideoEngineImpl*>(video_engine);
ViEBaseImpl* vie_base_impl = vie_impl;
(*vie_base_impl)++; // Increase ref count.
return vie_base_impl;
}
int ViEBaseImpl::Release() {
WEBRTC_TRACE(kTraceApiCall, kTraceVideo, shared_data_.instance_id(),
"ViEBase::Release()");
(*this)--; // Decrease ref count.
int32_t ref_count = GetCount();
if (ref_count < 0) {
WEBRTC_TRACE(kTraceWarning, kTraceVideo, shared_data_.instance_id(),
"ViEBase release too many times");
shared_data_.SetLastError(kViEAPIDoesNotExist);
return -1;
}
WEBRTC_TRACE(kTraceInfo, kTraceVideo, shared_data_.instance_id(),
"ViEBase reference count: %d", ref_count);
return ref_count;
}
ViEBaseImpl::ViEBaseImpl(const Config& config)
: shared_data_(config) {
WEBRTC_TRACE(kTraceMemory, kTraceVideo, shared_data_.instance_id(),
"ViEBaseImpl::ViEBaseImpl() Ctor");
}
ViEBaseImpl::~ViEBaseImpl() {
WEBRTC_TRACE(kTraceMemory, kTraceVideo, shared_data_.instance_id(),
"ViEBaseImpl::ViEBaseImpl() Dtor");
}
int ViEBaseImpl::Init() {
WEBRTC_TRACE(kTraceApiCall, kTraceVideo, shared_data_.instance_id(),
"Init");
return 0;
}
int ViEBaseImpl::SetVoiceEngine(VoiceEngine* voice_engine) {
WEBRTC_TRACE(kTraceApiCall, kTraceVideo, ViEId(shared_data_.instance_id()),
"%s", __FUNCTION__);
if (shared_data_.channel_manager()->SetVoiceEngine(voice_engine) != 0) {
shared_data_.SetLastError(kViEBaseVoEFailure);
return -1;
}
return 0;
}
int ViEBaseImpl::CreateChannel(int& video_channel) { // NOLINT
WEBRTC_TRACE(kTraceApiCall, kTraceVideo, ViEId(shared_data_.instance_id()),
"%s", __FUNCTION__);
if (shared_data_.channel_manager()->CreateChannel(&video_channel) == -1) {
WEBRTC_TRACE(kTraceError, kTraceVideo, ViEId(shared_data_.instance_id()),
"%s: Could not create channel", __FUNCTION__);
video_channel = -1;
shared_data_.SetLastError(kViEBaseChannelCreationFailed);
return -1;
}
WEBRTC_TRACE(kTraceInfo, kTraceVideo, ViEId(shared_data_.instance_id()),
"%s: channel created: %d", __FUNCTION__, video_channel);
return 0;
}
int ViEBaseImpl::CreateChannel(int& video_channel, // NOLINT
int original_channel) {
return CreateChannel(video_channel, original_channel, true);
}
int ViEBaseImpl::CreateReceiveChannel(int& video_channel, // NOLINT
int original_channel) {
return CreateChannel(video_channel, original_channel, false);
}
int ViEBaseImpl::DeleteChannel(const int video_channel) {
WEBRTC_TRACE(kTraceApiCall, kTraceVideo, ViEId(shared_data_.instance_id()),
"%s(%d)", __FUNCTION__, video_channel);
{
ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));
ViEChannel* vie_channel = cs.Channel(video_channel);
if (!vie_channel) {
WEBRTC_TRACE(kTraceError, kTraceVideo,
ViEId(shared_data_.instance_id()),
"%s: channel %d doesn't exist", __FUNCTION__, video_channel);
shared_data_.SetLastError(kViEBaseInvalidChannelId);
return -1;
}
// Deregister the ViEEncoder if no other channel is using it.
ViEEncoder* vie_encoder = cs.Encoder(video_channel);
if (cs.ChannelUsingViEEncoder(video_channel) == false) {
ViEInputManagerScoped is(*(shared_data_.input_manager()));
ViEFrameProviderBase* provider = is.FrameProvider(vie_encoder);
if (provider) {
provider->DeregisterFrameCallback(vie_encoder);
}
}
}
if (shared_data_.channel_manager()->DeleteChannel(video_channel) == -1) {
WEBRTC_TRACE(kTraceError, kTraceVideo, ViEId(shared_data_.instance_id()),
"%s: Could not delete channel %d", __FUNCTION__,
video_channel);
shared_data_.SetLastError(kViEBaseUnknownError);
return -1;
}
WEBRTC_TRACE(kTraceInfo, kTraceVideo, ViEId(shared_data_.instance_id()),
"%s: channel deleted: %d", __FUNCTION__, video_channel);
return 0;
}
int ViEBaseImpl::ConnectAudioChannel(const int video_channel,
const int audio_channel) {
WEBRTC_TRACE(kTraceApiCall, kTraceVideo, ViEId(shared_data_.instance_id()),
"%s(%d)", __FUNCTION__, video_channel);
ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));
if (!cs.Channel(video_channel)) {
WEBRTC_TRACE(kTraceError, kTraceVideo, ViEId(shared_data_.instance_id()),
"%s: channel %d doesn't exist", __FUNCTION__, video_channel);
shared_data_.SetLastError(kViEBaseInvalidChannelId);
return -1;
}
if (shared_data_.channel_manager()->ConnectVoiceChannel(video_channel,
audio_channel) != 0) {
shared_data_.SetLastError(kViEBaseVoEFailure);
return -1;
}
return 0;
}
int ViEBaseImpl::DisconnectAudioChannel(const int video_channel) {
WEBRTC_TRACE(kTraceApiCall, kTraceVideo, ViEId(shared_data_.instance_id()),
"%s(%d)", __FUNCTION__, video_channel);
ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));
if (!cs.Channel(video_channel)) {
WEBRTC_TRACE(kTraceError, kTraceVideo, ViEId(shared_data_.instance_id()),
"%s: channel %d doesn't exist", __FUNCTION__, video_channel);
shared_data_.SetLastError(kViEBaseInvalidChannelId);
return -1;
}
if (shared_data_.channel_manager()->DisconnectVoiceChannel(
video_channel) != 0) {
shared_data_.SetLastError(kViEBaseVoEFailure);
return -1;
}
return 0;
}
int ViEBaseImpl::StartSend(const int video_channel) {
WEBRTC_TRACE(kTraceApiCall, kTraceVideo,
ViEId(shared_data_.instance_id(), video_channel),
"%s(channel: %d)", __FUNCTION__, video_channel);
ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));
ViEChannel* vie_channel = cs.Channel(video_channel);
if (!vie_channel) {
WEBRTC_TRACE(kTraceError, kTraceVideo,
ViEId(shared_data_.instance_id(), video_channel),
"%s: Channel %d does not exist", __FUNCTION__, video_channel);
shared_data_.SetLastError(kViEBaseInvalidChannelId);
return -1;
}
ViEEncoder* vie_encoder = cs.Encoder(video_channel);
assert(vie_encoder != NULL);
if (vie_encoder->Owner() != video_channel) {
WEBRTC_TRACE(kTraceError, kTraceVideo,
ViEId(shared_data_.instance_id(), video_channel),
"Can't start ssend on a receive only channel.");
shared_data_.SetLastError(kViEBaseReceiveOnlyChannel);
return -1;
}
// Pause and trigger a key frame.
vie_encoder->Pause();
int32_t error = vie_channel->StartSend();
if (error != 0) {
vie_encoder->Restart();
WEBRTC_TRACE(kTraceError, kTraceVideo,
ViEId(shared_data_.instance_id(), video_channel),
"%s: Could not start sending on channel %d", __FUNCTION__,
video_channel);
if (error == kViEBaseAlreadySending) {
shared_data_.SetLastError(kViEBaseAlreadySending);
}
shared_data_.SetLastError(kViEBaseUnknownError);
return -1;
}
vie_encoder->SendKeyFrame();
vie_encoder->Restart();
return 0;
}
int ViEBaseImpl::StopSend(const int video_channel) {
WEBRTC_TRACE(kTraceApiCall, kTraceVideo,
ViEId(shared_data_.instance_id(), video_channel),
"%s(channel: %d)", __FUNCTION__, video_channel);
ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));
ViEChannel* vie_channel = cs.Channel(video_channel);
if (!vie_channel) {
WEBRTC_TRACE(kTraceError, kTraceVideo,
ViEId(shared_data_.instance_id(), video_channel),
"%s: Channel %d does not exist", __FUNCTION__, video_channel);
shared_data_.SetLastError(kViEBaseInvalidChannelId);
return -1;
}
int32_t error = vie_channel->StopSend();
if (error != 0) {
WEBRTC_TRACE(kTraceError, kTraceVideo,
ViEId(shared_data_.instance_id(), video_channel),
"%s: Could not stop sending on channel %d", __FUNCTION__,
video_channel);
if (error == kViEBaseNotSending) {
shared_data_.SetLastError(kViEBaseNotSending);
} else {
shared_data_.SetLastError(kViEBaseUnknownError);
}
return -1;
}
return 0;
}
int ViEBaseImpl::StartReceive(const int video_channel) {
WEBRTC_TRACE(kTraceApiCall, kTraceVideo,
ViEId(shared_data_.instance_id(), video_channel),
"%s(channel: %d)", __FUNCTION__, video_channel);
ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));
ViEChannel* vie_channel = cs.Channel(video_channel);
if (!vie_channel) {
WEBRTC_TRACE(kTraceError, kTraceVideo,
ViEId(shared_data_.instance_id(), video_channel),
"%s: Channel %d does not exist", __FUNCTION__, video_channel);
shared_data_.SetLastError(kViEBaseInvalidChannelId);
return -1;
}
if (vie_channel->StartReceive() != 0) {
shared_data_.SetLastError(kViEBaseUnknownError);
return -1;
}
return 0;
}
int ViEBaseImpl::StopReceive(const int video_channel) {
WEBRTC_TRACE(kTraceApiCall, kTraceVideo,
ViEId(shared_data_.instance_id(), video_channel),
"%s(channel: %d)", __FUNCTION__, video_channel);
ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));
ViEChannel* vie_channel = cs.Channel(video_channel);
if (!vie_channel) {
WEBRTC_TRACE(kTraceError, kTraceVideo,
ViEId(shared_data_.instance_id(), video_channel),
"%s: Channel %d does not exist", __FUNCTION__, video_channel);
shared_data_.SetLastError(kViEBaseInvalidChannelId);
return -1;
}
if (vie_channel->StopReceive() != 0) {
shared_data_.SetLastError(kViEBaseUnknownError);
return -1;
}
return 0;
}
int ViEBaseImpl::GetVersion(char version[1024]) {
WEBRTC_TRACE(kTraceApiCall, kTraceVideo, ViEId(shared_data_.instance_id()),
"GetVersion(version=?)");
assert(kViEVersionMaxMessageSize == 1024);
if (!version) {
shared_data_.SetLastError(kViEBaseInvalidArgument);
return -1;
}
// Add WebRTC Version.
std::stringstream version_stream;
version_stream << "VideoEngine 3.32.0" << std::endl;
// Add build info.
version_stream << "Build: svn:" << WEBRTC_SVNREVISION << " " << BUILDINFO
<< std::endl;
#ifdef WEBRTC_EXTERNAL_TRANSPORT
version_stream << "External transport build" << std::endl;
#endif
int version_length = version_stream.tellp();
assert(version_length < 1024);
memcpy(version, version_stream.str().c_str(), version_length);
version[version_length] = '\0';
WEBRTC_TRACE(kTraceStateInfo, kTraceVideo,
ViEId(shared_data_.instance_id()), "GetVersion() => %s",
version);
return 0;
}
int ViEBaseImpl::LastError() {
return shared_data_.LastErrorInternal();
}
int ViEBaseImpl::CreateChannel(int& video_channel, // NOLINT
int original_channel, bool sender) {
ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));
if (!cs.Channel(original_channel)) {
WEBRTC_TRACE(kTraceError, kTraceVideo, ViEId(shared_data_.instance_id()),
"%s - original_channel does not exist.", __FUNCTION__,
shared_data_.instance_id());
shared_data_.SetLastError(kViEBaseInvalidChannelId);
return -1;
}
if (shared_data_.channel_manager()->CreateChannel(&video_channel,
original_channel,
sender) == -1) {
WEBRTC_TRACE(kTraceError, kTraceVideo, ViEId(shared_data_.instance_id()),
"%s: Could not create channel", __FUNCTION__);
video_channel = -1;
shared_data_.SetLastError(kViEBaseChannelCreationFailed);
return -1;
}
WEBRTC_TRACE(kTraceInfo, kTraceVideo, ViEId(shared_data_.instance_id()),
"%s: channel created: %d", __FUNCTION__, video_channel);
return 0;
}
} // namespace webrtc
<commit_msg>Updated WebRTC version to 3.33<commit_after>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/video_engine/vie_base_impl.h"
#include <sstream>
#include <string>
#include "webrtc/engine_configurations.h"
#include "webrtc/modules/rtp_rtcp/interface/rtp_rtcp.h"
#include "webrtc/modules/video_coding/main/interface/video_coding.h"
#include "webrtc/modules/video_processing/main/interface/video_processing.h"
#include "webrtc/modules/video_render/include/video_render.h"
#include "webrtc/system_wrappers/interface/critical_section_wrapper.h"
#include "webrtc/system_wrappers/interface/trace.h"
#include "webrtc/video_engine/include/vie_errors.h"
#include "webrtc/video_engine/vie_channel.h"
#include "webrtc/video_engine/vie_channel_manager.h"
#include "webrtc/video_engine/vie_defines.h"
#include "webrtc/video_engine/vie_encoder.h"
#include "webrtc/video_engine/vie_impl.h"
#include "webrtc/video_engine/vie_input_manager.h"
#include "webrtc/video_engine/vie_shared_data.h"
namespace webrtc {
ViEBase* ViEBase::GetInterface(VideoEngine* video_engine) {
if (!video_engine) {
return NULL;
}
VideoEngineImpl* vie_impl = static_cast<VideoEngineImpl*>(video_engine);
ViEBaseImpl* vie_base_impl = vie_impl;
(*vie_base_impl)++; // Increase ref count.
return vie_base_impl;
}
int ViEBaseImpl::Release() {
WEBRTC_TRACE(kTraceApiCall, kTraceVideo, shared_data_.instance_id(),
"ViEBase::Release()");
(*this)--; // Decrease ref count.
int32_t ref_count = GetCount();
if (ref_count < 0) {
WEBRTC_TRACE(kTraceWarning, kTraceVideo, shared_data_.instance_id(),
"ViEBase release too many times");
shared_data_.SetLastError(kViEAPIDoesNotExist);
return -1;
}
WEBRTC_TRACE(kTraceInfo, kTraceVideo, shared_data_.instance_id(),
"ViEBase reference count: %d", ref_count);
return ref_count;
}
ViEBaseImpl::ViEBaseImpl(const Config& config)
: shared_data_(config) {
WEBRTC_TRACE(kTraceMemory, kTraceVideo, shared_data_.instance_id(),
"ViEBaseImpl::ViEBaseImpl() Ctor");
}
ViEBaseImpl::~ViEBaseImpl() {
WEBRTC_TRACE(kTraceMemory, kTraceVideo, shared_data_.instance_id(),
"ViEBaseImpl::ViEBaseImpl() Dtor");
}
int ViEBaseImpl::Init() {
WEBRTC_TRACE(kTraceApiCall, kTraceVideo, shared_data_.instance_id(),
"Init");
return 0;
}
int ViEBaseImpl::SetVoiceEngine(VoiceEngine* voice_engine) {
WEBRTC_TRACE(kTraceApiCall, kTraceVideo, ViEId(shared_data_.instance_id()),
"%s", __FUNCTION__);
if (shared_data_.channel_manager()->SetVoiceEngine(voice_engine) != 0) {
shared_data_.SetLastError(kViEBaseVoEFailure);
return -1;
}
return 0;
}
int ViEBaseImpl::CreateChannel(int& video_channel) { // NOLINT
WEBRTC_TRACE(kTraceApiCall, kTraceVideo, ViEId(shared_data_.instance_id()),
"%s", __FUNCTION__);
if (shared_data_.channel_manager()->CreateChannel(&video_channel) == -1) {
WEBRTC_TRACE(kTraceError, kTraceVideo, ViEId(shared_data_.instance_id()),
"%s: Could not create channel", __FUNCTION__);
video_channel = -1;
shared_data_.SetLastError(kViEBaseChannelCreationFailed);
return -1;
}
WEBRTC_TRACE(kTraceInfo, kTraceVideo, ViEId(shared_data_.instance_id()),
"%s: channel created: %d", __FUNCTION__, video_channel);
return 0;
}
int ViEBaseImpl::CreateChannel(int& video_channel, // NOLINT
int original_channel) {
return CreateChannel(video_channel, original_channel, true);
}
int ViEBaseImpl::CreateReceiveChannel(int& video_channel, // NOLINT
int original_channel) {
return CreateChannel(video_channel, original_channel, false);
}
int ViEBaseImpl::DeleteChannel(const int video_channel) {
WEBRTC_TRACE(kTraceApiCall, kTraceVideo, ViEId(shared_data_.instance_id()),
"%s(%d)", __FUNCTION__, video_channel);
{
ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));
ViEChannel* vie_channel = cs.Channel(video_channel);
if (!vie_channel) {
WEBRTC_TRACE(kTraceError, kTraceVideo,
ViEId(shared_data_.instance_id()),
"%s: channel %d doesn't exist", __FUNCTION__, video_channel);
shared_data_.SetLastError(kViEBaseInvalidChannelId);
return -1;
}
// Deregister the ViEEncoder if no other channel is using it.
ViEEncoder* vie_encoder = cs.Encoder(video_channel);
if (cs.ChannelUsingViEEncoder(video_channel) == false) {
ViEInputManagerScoped is(*(shared_data_.input_manager()));
ViEFrameProviderBase* provider = is.FrameProvider(vie_encoder);
if (provider) {
provider->DeregisterFrameCallback(vie_encoder);
}
}
}
if (shared_data_.channel_manager()->DeleteChannel(video_channel) == -1) {
WEBRTC_TRACE(kTraceError, kTraceVideo, ViEId(shared_data_.instance_id()),
"%s: Could not delete channel %d", __FUNCTION__,
video_channel);
shared_data_.SetLastError(kViEBaseUnknownError);
return -1;
}
WEBRTC_TRACE(kTraceInfo, kTraceVideo, ViEId(shared_data_.instance_id()),
"%s: channel deleted: %d", __FUNCTION__, video_channel);
return 0;
}
int ViEBaseImpl::ConnectAudioChannel(const int video_channel,
const int audio_channel) {
WEBRTC_TRACE(kTraceApiCall, kTraceVideo, ViEId(shared_data_.instance_id()),
"%s(%d)", __FUNCTION__, video_channel);
ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));
if (!cs.Channel(video_channel)) {
WEBRTC_TRACE(kTraceError, kTraceVideo, ViEId(shared_data_.instance_id()),
"%s: channel %d doesn't exist", __FUNCTION__, video_channel);
shared_data_.SetLastError(kViEBaseInvalidChannelId);
return -1;
}
if (shared_data_.channel_manager()->ConnectVoiceChannel(video_channel,
audio_channel) != 0) {
shared_data_.SetLastError(kViEBaseVoEFailure);
return -1;
}
return 0;
}
int ViEBaseImpl::DisconnectAudioChannel(const int video_channel) {
WEBRTC_TRACE(kTraceApiCall, kTraceVideo, ViEId(shared_data_.instance_id()),
"%s(%d)", __FUNCTION__, video_channel);
ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));
if (!cs.Channel(video_channel)) {
WEBRTC_TRACE(kTraceError, kTraceVideo, ViEId(shared_data_.instance_id()),
"%s: channel %d doesn't exist", __FUNCTION__, video_channel);
shared_data_.SetLastError(kViEBaseInvalidChannelId);
return -1;
}
if (shared_data_.channel_manager()->DisconnectVoiceChannel(
video_channel) != 0) {
shared_data_.SetLastError(kViEBaseVoEFailure);
return -1;
}
return 0;
}
int ViEBaseImpl::StartSend(const int video_channel) {
WEBRTC_TRACE(kTraceApiCall, kTraceVideo,
ViEId(shared_data_.instance_id(), video_channel),
"%s(channel: %d)", __FUNCTION__, video_channel);
ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));
ViEChannel* vie_channel = cs.Channel(video_channel);
if (!vie_channel) {
WEBRTC_TRACE(kTraceError, kTraceVideo,
ViEId(shared_data_.instance_id(), video_channel),
"%s: Channel %d does not exist", __FUNCTION__, video_channel);
shared_data_.SetLastError(kViEBaseInvalidChannelId);
return -1;
}
ViEEncoder* vie_encoder = cs.Encoder(video_channel);
assert(vie_encoder != NULL);
if (vie_encoder->Owner() != video_channel) {
WEBRTC_TRACE(kTraceError, kTraceVideo,
ViEId(shared_data_.instance_id(), video_channel),
"Can't start ssend on a receive only channel.");
shared_data_.SetLastError(kViEBaseReceiveOnlyChannel);
return -1;
}
// Pause and trigger a key frame.
vie_encoder->Pause();
int32_t error = vie_channel->StartSend();
if (error != 0) {
vie_encoder->Restart();
WEBRTC_TRACE(kTraceError, kTraceVideo,
ViEId(shared_data_.instance_id(), video_channel),
"%s: Could not start sending on channel %d", __FUNCTION__,
video_channel);
if (error == kViEBaseAlreadySending) {
shared_data_.SetLastError(kViEBaseAlreadySending);
}
shared_data_.SetLastError(kViEBaseUnknownError);
return -1;
}
vie_encoder->SendKeyFrame();
vie_encoder->Restart();
return 0;
}
int ViEBaseImpl::StopSend(const int video_channel) {
WEBRTC_TRACE(kTraceApiCall, kTraceVideo,
ViEId(shared_data_.instance_id(), video_channel),
"%s(channel: %d)", __FUNCTION__, video_channel);
ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));
ViEChannel* vie_channel = cs.Channel(video_channel);
if (!vie_channel) {
WEBRTC_TRACE(kTraceError, kTraceVideo,
ViEId(shared_data_.instance_id(), video_channel),
"%s: Channel %d does not exist", __FUNCTION__, video_channel);
shared_data_.SetLastError(kViEBaseInvalidChannelId);
return -1;
}
int32_t error = vie_channel->StopSend();
if (error != 0) {
WEBRTC_TRACE(kTraceError, kTraceVideo,
ViEId(shared_data_.instance_id(), video_channel),
"%s: Could not stop sending on channel %d", __FUNCTION__,
video_channel);
if (error == kViEBaseNotSending) {
shared_data_.SetLastError(kViEBaseNotSending);
} else {
shared_data_.SetLastError(kViEBaseUnknownError);
}
return -1;
}
return 0;
}
int ViEBaseImpl::StartReceive(const int video_channel) {
WEBRTC_TRACE(kTraceApiCall, kTraceVideo,
ViEId(shared_data_.instance_id(), video_channel),
"%s(channel: %d)", __FUNCTION__, video_channel);
ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));
ViEChannel* vie_channel = cs.Channel(video_channel);
if (!vie_channel) {
WEBRTC_TRACE(kTraceError, kTraceVideo,
ViEId(shared_data_.instance_id(), video_channel),
"%s: Channel %d does not exist", __FUNCTION__, video_channel);
shared_data_.SetLastError(kViEBaseInvalidChannelId);
return -1;
}
if (vie_channel->StartReceive() != 0) {
shared_data_.SetLastError(kViEBaseUnknownError);
return -1;
}
return 0;
}
int ViEBaseImpl::StopReceive(const int video_channel) {
WEBRTC_TRACE(kTraceApiCall, kTraceVideo,
ViEId(shared_data_.instance_id(), video_channel),
"%s(channel: %d)", __FUNCTION__, video_channel);
ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));
ViEChannel* vie_channel = cs.Channel(video_channel);
if (!vie_channel) {
WEBRTC_TRACE(kTraceError, kTraceVideo,
ViEId(shared_data_.instance_id(), video_channel),
"%s: Channel %d does not exist", __FUNCTION__, video_channel);
shared_data_.SetLastError(kViEBaseInvalidChannelId);
return -1;
}
if (vie_channel->StopReceive() != 0) {
shared_data_.SetLastError(kViEBaseUnknownError);
return -1;
}
return 0;
}
int ViEBaseImpl::GetVersion(char version[1024]) {
WEBRTC_TRACE(kTraceApiCall, kTraceVideo, ViEId(shared_data_.instance_id()),
"GetVersion(version=?)");
assert(kViEVersionMaxMessageSize == 1024);
if (!version) {
shared_data_.SetLastError(kViEBaseInvalidArgument);
return -1;
}
// Add WebRTC Version.
std::stringstream version_stream;
version_stream << "VideoEngine 3.33.0" << std::endl;
// Add build info.
version_stream << "Build: svn:" << WEBRTC_SVNREVISION << " " << BUILDINFO
<< std::endl;
#ifdef WEBRTC_EXTERNAL_TRANSPORT
version_stream << "External transport build" << std::endl;
#endif
int version_length = version_stream.tellp();
assert(version_length < 1024);
memcpy(version, version_stream.str().c_str(), version_length);
version[version_length] = '\0';
WEBRTC_TRACE(kTraceStateInfo, kTraceVideo,
ViEId(shared_data_.instance_id()), "GetVersion() => %s",
version);
return 0;
}
int ViEBaseImpl::LastError() {
return shared_data_.LastErrorInternal();
}
int ViEBaseImpl::CreateChannel(int& video_channel, // NOLINT
int original_channel, bool sender) {
ViEChannelManagerScoped cs(*(shared_data_.channel_manager()));
if (!cs.Channel(original_channel)) {
WEBRTC_TRACE(kTraceError, kTraceVideo, ViEId(shared_data_.instance_id()),
"%s - original_channel does not exist.", __FUNCTION__,
shared_data_.instance_id());
shared_data_.SetLastError(kViEBaseInvalidChannelId);
return -1;
}
if (shared_data_.channel_manager()->CreateChannel(&video_channel,
original_channel,
sender) == -1) {
WEBRTC_TRACE(kTraceError, kTraceVideo, ViEId(shared_data_.instance_id()),
"%s: Could not create channel", __FUNCTION__);
video_channel = -1;
shared_data_.SetLastError(kViEBaseChannelCreationFailed);
return -1;
}
WEBRTC_TRACE(kTraceInfo, kTraceVideo, ViEId(shared_data_.instance_id()),
"%s: channel created: %d", __FUNCTION__, video_channel);
return 0;
}
} // namespace webrtc
<|endoftext|>
|
<commit_before>#ifndef CAT2MAP_HPP
#define CAT2MAP_HPP
#include <fstream>
#include <iostream>
#include <exception>
#include <vector>
#include <cmath>
#include <cassert>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include <boost/log/trivial.hpp>
#include <boost/tokenizer.hpp>
#include <healpix_map.h>
#include <pointing.h>
#include <healpix_map_fitsio.h>
#include <datatypes.h>
class Cat2Map
{
public:
typedef boost::property_tree::ptree propertyTreeType;
typedef Healpix_Map<double> mapType;
static const constexpr double deg2rad = M_PI/double(180);
static const constexpr double rotPhi = double(0);
Cat2Map(std::string const& iniFileName)
{
BOOST_LOG_TRIVIAL(info) << std::string("Reading the ini file ") + std::string(iniFileName);
boost::property_tree::ini_parser::read_ini(iniFileName,mPropTree);
// set the output maps
BOOST_LOG_TRIVIAL(info) << "Resulution of the output map is "<<mPropTree.get<std::string>("output.n_side");
int nSide = mPropTree.get<int>("output.n_side");
mMapN.SetNside(nSide,RING);
mMapE1.SetNside(nSide,RING);
mMapE2.SetNside(nSide,RING);
mMapN.fill(double(0));
mMapE1.fill(double(0));
mMapE1.fill(double(0));
// read the mask
read_Healpix_map_from_fits(mPropTree.get<std::string>("input.mask_file_name"),mMask);
try
{
std::string testMapFileName = mPropTree.get<std::string>("test.map_file_name");
BOOST_LOG_TRIVIAL(info) << "Test map file specified as "<< testMapFileName;
read_Healpix_map_from_fits(testMapFileName,mTestE1,int(2),int(2));
read_Healpix_map_from_fits(testMapFileName,mTestE2,int(3),int(2));
mDoTest = true;
}
catch(std::exception)
{
BOOST_LOG_TRIVIAL(info) << "No test map file specified.";
mDoTest = false;
}
mMisMatchCountE1 = size_t(0);
mMisMatchCountE2 = size_t(0);
}
void accumulate()
{
// open file for reading
std::ifstream inputCatFile;
inputCatFile.open( mPropTree.get<std::string>("input.catlogue_file_name").c_str(),std::ios::in );
if(inputCatFile.is_open())
{
BOOST_LOG_TRIVIAL(info) << "Accumulating objects";
BOOST_LOG_TRIVIAL(info) << "Number of rows to be skipped = " << mPropTree.get<std::string>("input.skip_rows");
BOOST_LOG_TRIVIAL(info) << "Delimiter for separation is "<< mPropTree.get<std::string>("input.delimiter");
size_t col_ra = mPropTree.get<size_t>("input.col_ra");
size_t col_dec = mPropTree.get<size_t>("input.col_dec");
size_t col_z = mPropTree.get<size_t>("input.col_z");
size_t col_ellip_1 = mPropTree.get<size_t>("input.col_ellip_1");
size_t col_ellip_2 = mPropTree.get<size_t>("input.col_ellip_2");
BOOST_LOG_TRIVIAL(info) << "Column of ra values = "<< col_ra;
BOOST_LOG_TRIVIAL(info) << "Column of dec values = "<< col_dec;
BOOST_LOG_TRIVIAL(info) << "Column of z values = "<< col_z;
BOOST_LOG_TRIVIAL(info) << "Column of ellip_1 values = "<< col_ellip_1;
BOOST_LOG_TRIVIAL(info) << "Column of ellip_2 values = "<< col_ellip_2;
size_t line_id = 0;
while(!inputCatFile.eof())
{
std::string line;
std::getline(inputCatFile,line);
++line_id;
if(line_id > mPropTree.get<size_t>("input.skip_rows"))
{
typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
boost::char_separator<char> sep(mPropTree.get<std::string>("input.delimiter").c_str());
tokenizer tokens(line, sep);
std::vector<double> ents;
for(tokenizer::iterator tokIter = tokens.begin(); tokIter !=tokens.end(); ++tokIter)
{
ents.push_back(boost::lexical_cast<double>(*tokIter));
}
if(ents.size()>0)
{
assert(col_ra<ents.size());
assert(col_dec<ents.size());
assert(col_ellip_1<ents.size());
assert(col_ellip_2<ents.size());
double ra = ents[col_ra];
double dec = ents[col_dec];
double e1 = ents[col_ellip_1];
double e2 = ents[col_ellip_2];
double theta = -deg2rad*dec + M_PI*double(0.5);
double phi = deg2rad*(ra - rotPhi);
auto pix = mMapE1.ang2pix(pointing(theta,phi));
// check if the pixel falls in the masked region
if(mMask[pix]>0)
{
if(mDoTest)
{
// if testing accumulate the miss-match
// between pixel values
if(std::abs( (e1 - mTestE1[pix])/e1 ) >= 1e-5)
{
mMisMatchCountE1 += size_t(1);
}
if(std::abs( (e2 - mTestE2[pix])/e2 ) > 1e-5)
{
mMisMatchCountE2 += size_t(1);
}
}
// do accumulation
mMapN[pix] += double(1);
mMapE1[pix] += e1;
mMapE2[pix] += e2;
}
}
}
else
{
BOOST_LOG_TRIVIAL(info) << "Skipping line " << line_id;
}
}
// make it the average
for(auto pix = 0; pix<mMapN.Npix(); ++pix)
{
if(mMapN[pix]>0) // TODO how many gals we need to make an estimate
{
mMapE1[pix] /= mMapN[pix];
mMapE2[pix] /= mMapN[pix];
}
else
{
// make the new mask
mMask[pix] = 0;
}
}
// if testing print the mismatch stats
if(mDoTest)
{
size_t nPix = (size_t) mTestE1.Npix();
double fracMissMatchE1 = (double)mMisMatchCountE1 / (double)nPix;
double fracMissMatchE2 = (double)mMisMatchCountE2 / (double)nPix;
BOOST_LOG_TRIVIAL(warning) << "Pixel value miss-match for e1 = "<<fracMissMatchE1;
BOOST_LOG_TRIVIAL(warning) << "Pixel value miss-match for e2 = "<<fracMissMatchE2;
}
}
else
{
std::string msg = std::string("Input catalogue file ")
+ std::string(mPropTree.get<std::string>("input.catlogue_file_name"))
+ std::string(" failed to open.");
BOOST_LOG_TRIVIAL(error) << msg;
throw std::runtime_error(msg);
}
}
void writeMaps()
{
BOOST_LOG_TRIVIAL(info) << "Output data map file name : "
<< mPropTree.get<std::string>("output.data_map_file_name");
write_Healpix_map_to_fits(std::string("!")+mPropTree.get<std::string>("output.data_map_file_name"),
mMapN,mMapE1,mMapE2,planckType<double>());
BOOST_LOG_TRIVIAL(info) << "Output augmented mask file name : "
<< mPropTree.get<std::string>("output.augmented_mask_file_name");
write_Healpix_map_to_fits(std::string("!")+mPropTree.get<std::string>("output.augmented_mask_file_name"),
mMask,planckType<double>());
}
private:
propertyTreeType mPropTree;
mapType mMapN;
mapType mMapE1;
mapType mMapE2;
mapType mMask;
mapType mTestE1;
mapType mTestE2;
bool mDoTest;
size_t mMisMatchCountE1;
size_t mMisMatchCountE2;
};
#endif //CAT2MAP_HPP
<commit_msg>sky fraction now an output<commit_after>#ifndef CAT2MAP_HPP
#define CAT2MAP_HPP
#include <fstream>
#include <iostream>
#include <exception>
#include <vector>
#include <cmath>
#include <cassert>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include <boost/log/trivial.hpp>
#include <boost/tokenizer.hpp>
#include <healpix_map.h>
#include <pointing.h>
#include <healpix_map_fitsio.h>
#include <datatypes.h>
class Cat2Map
{
public:
typedef boost::property_tree::ptree propertyTreeType;
typedef Healpix_Map<double> mapType;
static const constexpr double deg2rad = M_PI/double(180);
static const constexpr double rotPhi = double(0);
Cat2Map(std::string const& iniFileName)
{
BOOST_LOG_TRIVIAL(info) << std::string("Reading the ini file ") + std::string(iniFileName);
boost::property_tree::ini_parser::read_ini(iniFileName,mPropTree);
// set the output maps
BOOST_LOG_TRIVIAL(info) << "Resulution of the output map is "<<mPropTree.get<std::string>("output.n_side");
int nSide = mPropTree.get<int>("output.n_side");
mMapN.SetNside(nSide,RING);
mMapE1.SetNside(nSide,RING);
mMapE2.SetNside(nSide,RING);
mMapN.fill(double(0));
mMapE1.fill(double(0));
mMapE1.fill(double(0));
// read the mask
read_Healpix_map_from_fits(mPropTree.get<std::string>("input.mask_file_name"),mMask);
try
{
std::string testMapFileName = mPropTree.get<std::string>("test.map_file_name");
BOOST_LOG_TRIVIAL(info) << "Test map file specified as "<< testMapFileName;
read_Healpix_map_from_fits(testMapFileName,mTestE1,int(2),int(2));
read_Healpix_map_from_fits(testMapFileName,mTestE2,int(3),int(2));
mDoTest = true;
}
catch(std::exception)
{
BOOST_LOG_TRIVIAL(info) << "No test map file specified.";
mDoTest = false;
}
mMisMatchCountE1 = size_t(0);
mMisMatchCountE2 = size_t(0);
mNumObsPix = size_t(0);
}
void accumulate()
{
// open file for reading
std::ifstream inputCatFile;
inputCatFile.open( mPropTree.get<std::string>("input.catlogue_file_name").c_str(),std::ios::in );
if(inputCatFile.is_open())
{
BOOST_LOG_TRIVIAL(info) << "Accumulating objects";
BOOST_LOG_TRIVIAL(info) << "Number of rows to be skipped = " << mPropTree.get<std::string>("input.skip_rows");
BOOST_LOG_TRIVIAL(info) << "Delimiter for separation is "<< mPropTree.get<std::string>("input.delimiter");
size_t col_ra = mPropTree.get<size_t>("input.col_ra");
size_t col_dec = mPropTree.get<size_t>("input.col_dec");
size_t col_z = mPropTree.get<size_t>("input.col_z");
size_t col_ellip_1 = mPropTree.get<size_t>("input.col_ellip_1");
size_t col_ellip_2 = mPropTree.get<size_t>("input.col_ellip_2");
BOOST_LOG_TRIVIAL(info) << "Column of ra values = "<< col_ra;
BOOST_LOG_TRIVIAL(info) << "Column of dec values = "<< col_dec;
BOOST_LOG_TRIVIAL(info) << "Column of z values = "<< col_z;
BOOST_LOG_TRIVIAL(info) << "Column of ellip_1 values = "<< col_ellip_1;
BOOST_LOG_TRIVIAL(info) << "Column of ellip_2 values = "<< col_ellip_2;
size_t line_id = 0;
while(!inputCatFile.eof())
{
std::string line;
std::getline(inputCatFile,line);
++line_id;
if(line_id > mPropTree.get<size_t>("input.skip_rows"))
{
typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
boost::char_separator<char> sep(mPropTree.get<std::string>("input.delimiter").c_str());
tokenizer tokens(line, sep);
std::vector<double> ents;
for(tokenizer::iterator tokIter = tokens.begin(); tokIter !=tokens.end(); ++tokIter)
{
ents.push_back(boost::lexical_cast<double>(*tokIter));
}
if(ents.size()>0)
{
assert(col_ra<ents.size());
assert(col_dec<ents.size());
assert(col_ellip_1<ents.size());
assert(col_ellip_2<ents.size());
double ra = ents[col_ra];
double dec = ents[col_dec];
double e1 = ents[col_ellip_1];
double e2 = ents[col_ellip_2];
double theta = -deg2rad*dec + M_PI*double(0.5);
double phi = deg2rad*(ra - rotPhi);
auto pix = mMapE1.ang2pix(pointing(theta,phi));
// check if the pixel falls in the masked region
if(mMask[pix]>0)
{
if(mDoTest)
{
// if testing accumulate the miss-match
// between pixel values
if(std::abs( (e1 - mTestE1[pix])/e1 ) >= 1e-5)
{
mMisMatchCountE1 += size_t(1);
}
if(std::abs( (e2 - mTestE2[pix])/e2 ) > 1e-5)
{
mMisMatchCountE2 += size_t(1);
}
}
// do accumulation
mMapN[pix] += double(1);
mMapE1[pix] += e1;
mMapE2[pix] += e2;
mNumObsPix += size_t(1);
}
}
}
else
{
BOOST_LOG_TRIVIAL(info) << "Skipping line " << line_id;
}
}
// make it the average
for(auto pix = 0; pix<mMapN.Npix(); ++pix)
{
if(mMapN[pix]>0) // TODO how many gals we need to make an estimate
{
mMapE1[pix] /= mMapN[pix];
mMapE2[pix] /= mMapN[pix];
}
else
{
// make the new mask
mMask[pix] = 0;
}
}
// output the sky fraction of the augmented mask
size_t nPix = (size_t) mTestE1.Npix();
double fKsy = (double)mNumObsPix / (double)nPix;
BOOST_LOG_TRIVIAL(info) << "Sky fraction " << fKsy;
// if testing print the mismatch stats
if(mDoTest)
{
double fracMissMatchE1 = (double)mMisMatchCountE1 / (double)mNumObsPix;
double fracMissMatchE2 = (double)mMisMatchCountE2 / (double)mNumObsPix;
BOOST_LOG_TRIVIAL(warning) << "Pixel value miss-match for e1 = "<<fracMissMatchE1;
BOOST_LOG_TRIVIAL(warning) << "Pixel value miss-match for e2 = "<<fracMissMatchE2;
}
}
else
{
std::string msg = std::string("Input catalogue file ")
+ std::string(mPropTree.get<std::string>("input.catlogue_file_name"))
+ std::string(" failed to open.");
BOOST_LOG_TRIVIAL(error) << msg;
throw std::runtime_error(msg);
}
}
void writeMaps()
{
BOOST_LOG_TRIVIAL(info) << "Output data map file name : "
<< mPropTree.get<std::string>("output.data_map_file_name");
write_Healpix_map_to_fits(std::string("!")+mPropTree.get<std::string>("output.data_map_file_name"),
mMapN,mMapE1,mMapE2,planckType<double>());
BOOST_LOG_TRIVIAL(info) << "Output augmented mask file name : "
<< mPropTree.get<std::string>("output.augmented_mask_file_name");
write_Healpix_map_to_fits(std::string("!")+mPropTree.get<std::string>("output.augmented_mask_file_name"),
mMask,planckType<double>());
}
private:
propertyTreeType mPropTree;
mapType mMapN;
mapType mMapE1;
mapType mMapE2;
mapType mMask;
mapType mTestE1;
mapType mTestE2;
bool mDoTest;
size_t mMisMatchCountE1;
size_t mMisMatchCountE2;
size_t mNumObsPix;
};
#endif //CAT2MAP_HPP
<|endoftext|>
|
<commit_before>/***************************************************************************
* Copyright (C) 2006 by Ingo Kloecker <kloecker@kde.org> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Library General Public License as *
* published by the Free Software Foundation; either version 2 of the *
* License, or (at your option) any later version. *
* *
* This program 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 General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
***************************************************************************/
#include <QDebug>
#include "akonadi.h"
#include "akonadiconnection.h"
#include "storagebackend.h"
#include "storage/datastore.h"
#include "storage/entity.h"
#include "create.h"
#include "response.h"
using namespace Akonadi;
Create::Create(): Handler()
{
}
Create::~Create()
{
}
bool Create::handleLine(const QByteArray& line )
{
// parse out the reference name and mailbox name
const int startOfCommand = line.indexOf( ' ' ) + 1;
const int startOfMailbox = line.indexOf( ' ', startOfCommand ) + 1;
QByteArray mailbox = stripQuotes( line.right( line.size() - startOfMailbox ) );
// strip off a trailing '/'
if ( !mailbox.isEmpty() && mailbox[0] == '/' )
mailbox = mailbox.right( mailbox.size() - 1 );
// Responses:
// OK - create completed
// NO - create failure: can't create mailbox with that name
// BAD - command unknown or arguments invalid
Response response;
response.setTag( tag() );
if ( mailbox.isEmpty() || mailbox.contains( "//" ) ) {
response.setError();
response.setString( "Invalid argument" );
emit responseAvailable( response );
}
else {
DataStore *db = connection()->storageBackend();
const int startOfLocation = mailbox.indexOf( '/' ) + 1;
const QByteArray resourceName = mailbox.left( startOfLocation - 1 );
const QByteArray locationName = mailbox.right( startOfLocation );
qDebug() << "Create: " << locationName
<< " in resource: " << resourceName;
Resource resource = db->getResourceByName( resourceName );
// first check whether location already exists
if ( db->getLocationByName( resource, locationName ).isValid() ) {
response.setFailure();
response.setString( "A folder with that name does already exist");
emit responseAvailable( response );
}
// we have to create all superior hierarchical folders, so look for the
// starting point
QList<QByteArray> foldersToCreate;
foldersToCreate.append( locationName );
for ( int endOfSupFolder = locationName.lastIndexOf( '/', locationName.size() - 1 );
endOfSupFolder > 0;
endOfSupFolder = locationName.lastIndexOf( '/', endOfSupFolder - 2 ) ) {
// check whether the superior hierarchical folder exists
qDebug() << "Does " << locationName.left( endOfSupFolder )
<< " exist in " << resourceName;
if ( !db->getLocationByName( resource, locationName.left( endOfSupFolder ) ).isValid() ) {
// the superior folder does not exist, so it has to be created
foldersToCreate.prepend( locationName.left( endOfSupFolder ) );
}
else {
// the superior folder exists, so we can stop here
break;
}
}
// now we try to create all necessary folders
// first check whether the existing superior folder can contain subfolders
const int endOfSupFolder = foldersToCreate[0].lastIndexOf( '/' );
if ( endOfSupFolder > 0 ) {
bool canContainSubfolders = false;
const QList<MimeType> mimeTypes = db->getMimeTypesForLocation( db->getLocationByName( resource, locationName.left( endOfSupFolder ) ).getId() );
foreach ( MimeType m, mimeTypes ) {
if ( m.getMimeType().toLower() == "directory/inode" ) {
canContainSubfolders = true;
break;
}
}
if ( !canContainSubfolders ) {
response.setFailure();
response.setString( "Superior folder cannot contain subfolders" );
emit responseAvailable( response );
deleteLater();
return true;
}
}
// everything looks good, now we create the folders
foreach ( QByteArray folderName, foldersToCreate ) {
int locationId = 0;
db->appendLocation( folderName, resource, &locationId );
//db->appendMimeTypeForLocation( locationId, MimeType( "directory/inode" ) );
}
}
response.setSuccess();
response.setString( "Completed" );
emit responseAvailable( response );
deleteLater();
return true;
}
<commit_msg>It's right( len ), not right( start ). So I simply use mid( start ) instead.<commit_after>/***************************************************************************
* Copyright (C) 2006 by Ingo Kloecker <kloecker@kde.org> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Library General Public License as *
* published by the Free Software Foundation; either version 2 of the *
* License, or (at your option) any later version. *
* *
* This program 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 General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
***************************************************************************/
#include <QDebug>
#include "akonadi.h"
#include "akonadiconnection.h"
#include "storagebackend.h"
#include "storage/datastore.h"
#include "storage/entity.h"
#include "create.h"
#include "response.h"
using namespace Akonadi;
Create::Create(): Handler()
{
}
Create::~Create()
{
}
bool Create::handleLine(const QByteArray& line )
{
// parse out the reference name and mailbox name
const int startOfCommand = line.indexOf( ' ' ) + 1;
const int startOfMailbox = line.indexOf( ' ', startOfCommand ) + 1;
QByteArray mailbox = stripQuotes( line.right( line.size() - startOfMailbox ) );
// strip off a trailing '/'
if ( !mailbox.isEmpty() && mailbox[0] == '/' )
mailbox = mailbox.right( mailbox.size() - 1 );
// Responses:
// OK - create completed
// NO - create failure: can't create mailbox with that name
// BAD - command unknown or arguments invalid
Response response;
response.setTag( tag() );
if ( mailbox.isEmpty() || mailbox.contains( "//" ) ) {
response.setError();
response.setString( "Invalid argument" );
emit responseAvailable( response );
}
else {
DataStore *db = connection()->storageBackend();
const int startOfLocation = mailbox.indexOf( '/' ) + 1;
const QByteArray resourceName = mailbox.left( startOfLocation - 1 );
const QByteArray locationName = mailbox.mid( startOfLocation );
qDebug() << "Create: " << locationName
<< " in resource: " << resourceName;
Resource resource = db->getResourceByName( resourceName );
// first check whether location already exists
if ( db->getLocationByName( resource, locationName ).isValid() ) {
response.setFailure();
response.setString( "A folder with that name does already exist");
emit responseAvailable( response );
}
// we have to create all superior hierarchical folders, so look for the
// starting point
QList<QByteArray> foldersToCreate;
foldersToCreate.append( locationName );
for ( int endOfSupFolder = locationName.lastIndexOf( '/', locationName.size() - 1 );
endOfSupFolder > 0;
endOfSupFolder = locationName.lastIndexOf( '/', endOfSupFolder - 2 ) ) {
// check whether the superior hierarchical folder exists
qDebug() << "Does " << locationName.left( endOfSupFolder )
<< " exist in " << resourceName << "?";
if ( !db->getLocationByName( resource, locationName.left( endOfSupFolder ) ).isValid() ) {
// the superior folder does not exist, so it has to be created
qDebug() << "No, it has to be created";
foldersToCreate.prepend( locationName.left( endOfSupFolder ) );
}
else {
// the superior folder exists, so we can stop here
qDebug() << "Yes, it exists";
break;
}
}
// now we try to create all necessary folders
// first check whether the existing superior folder can contain subfolders
const int endOfSupFolder = foldersToCreate[0].lastIndexOf( '/' );
if ( endOfSupFolder > 0 ) {
bool canContainSubfolders = false;
const QList<MimeType> mimeTypes = db->getMimeTypesForLocation( db->getLocationByName( resource, locationName.left( endOfSupFolder ) ).getId() );
foreach ( MimeType m, mimeTypes ) {
if ( m.getMimeType().toLower() == "directory/inode" ) {
canContainSubfolders = true;
break;
}
}
if ( !canContainSubfolders ) {
response.setFailure();
response.setString( "Superior folder cannot contain subfolders" );
emit responseAvailable( response );
deleteLater();
return true;
}
}
// everything looks good, now we create the folders
foreach ( QByteArray folderName, foldersToCreate ) {
int locationId = 0;
db->appendLocation( folderName, resource, &locationId );
//db->appendMimeTypeForLocation( locationId, MimeType( "directory/inode" ) );
}
}
response.setSuccess();
response.setString( "Completed" );
emit responseAvailable( response );
deleteLater();
return true;
}
<|endoftext|>
|
<commit_before>/*
* ReaderWriterMutex.hpp
*
* Copyright (C) 2019 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant to the terms of a commercial license agreement
* with RStudio, then this program is licensed to you under the following terms:
*
* 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.
*
*/
#ifndef SHARED_CORE_READER_WRITER_MUTEX_HPP
#define SHARED_CORE_READER_WRITER_MUTEX_HPP
#include "PImpl.hpp"
#include <boost/thread/exceptions.hpp>
namespace rstudio {
namespace core {
namespace thread {
/**
* @brief Reentrant reader-writer mutex implementation. This implementation is write-preferring.
*/
class ReaderWriterMutex
{
public:
/**
* @brief Constructor.
*/
ReaderWriterMutex();
/**
* @brief Move constructor.
*
* @param in_other The mutex to move to this mutex.
*/
ReaderWriterMutex(ReaderWriterMutex&& in_other) noexcept;
/**
* @brief Deleted copy constructor to prevent copy.
*/
ReaderWriterMutex(const ReaderWriterMutex&) = delete;
/**
* @brief Deleted assignment operator to prevent copy.
*/
ReaderWriterMutex& operator=(const ReaderWriterMutex&) = delete;
/**
* @brief Locks the mutex for read.
*
* Note: unlockRead() must be called once for each time lockRead() was called.
*/
void lockRead();
/**
* @brief Locks the mutex for write.
*
* Note: unlockWrite() must be called once for each time lockWrite() was called.
*/
void lockWrite();
/**
* @brief Unlocks the mutex after a read operation.
*
* Note: unlockRead() must be called once for each time lockRead() was called.
*/
void unlockRead();
/**
* @brief Unlocks the mutex after a write operation.
*
* Note: unlockWrite() must be called once for each time lockWrite() was called.
*/
void unlockWrite();
private:
PRIVATE_IMPL(m_impl);
};
/**
* @brief RAII class which allows you to lock a ReaderWriterMutex for read.
*/
class ReaderLock
{
public:
/**
* @brief Constructor. Locks the specified mutex for read.
*
* @param in_mutex The mutex to lock for read.
*/
explicit ReaderLock(ReaderWriterMutex& in_mutex);
/**
* @brief Destructor.
*/
~ReaderLock();
private:
// The mutex this lock manages.
ReaderWriterMutex& m_mutex;
};
/**
* @brief RAII class which allows you to lock a ReaderWriterMutex for write.
*/
class WriterLock
{
public:
/**
* @brief Constructor. Locks the specified mutex for write.
*
* @param in_mutex The mutex to lock for write.
*/
explicit WriterLock(ReaderWriterMutex& in_mutex);
/**
* @brief Destructor.
*/
~WriterLock();
private:
// The mutex this lock manages.
ReaderWriterMutex& m_mutex;
};
} // namespace thread
} // namespace core
} // namespace rstudio
#define READ_LOCK_BEGIN(mutex) \
try \
{ \
rstudio::core::thread::ReaderLock lock(mutex); \
#define WRITE_LOCK_BEGIN(mutex) \
try \
{ \
rstudio::core::thread::WriterLock lock(mutex); \
#define RW_LOCK_END(tryLog) \
} \
catch (const boost::thread_resource_error& e) \
{ \
if (tryLog) \
log::logErrorMessage("Failed to acquire lock: thread resource error", \
ERROR_LOCATION); \
} \
catch (const std::exception& e) \
{ \
if (tryLog) \
log::logErrorMessage(std::string("Unexpected exception: ") + e.what(), \
ERROR_LOCATION); \
} \
catch (...) \
{ \
if (tryLog) \
log::logErrorMessage("Unknown exception while trying to acquire lock."); \
} \
#endif //SHARED_CORE_READER_WRITER_MUTEX_HPP
<commit_msg>fix a whitespacing issue<commit_after>/*
* ReaderWriterMutex.hpp
*
* Copyright (C) 2019 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant to the terms of a commercial license agreement
* with RStudio, then this program is licensed to you under the following terms:
*
* 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.
*
*/
#ifndef SHARED_CORE_READER_WRITER_MUTEX_HPP
#define SHARED_CORE_READER_WRITER_MUTEX_HPP
#include "PImpl.hpp"
#include <boost/thread/exceptions.hpp>
namespace rstudio {
namespace core {
namespace thread {
/**
* @brief Reentrant reader-writer mutex implementation. This implementation is write-preferring.
*/
class ReaderWriterMutex
{
public:
/**
* @brief Constructor.
*/
ReaderWriterMutex();
/**
* @brief Move constructor.
*
* @param in_other The mutex to move to this mutex.
*/
ReaderWriterMutex(ReaderWriterMutex&& in_other) noexcept;
/**
* @brief Deleted copy constructor to prevent copy.
*/
ReaderWriterMutex(const ReaderWriterMutex&) = delete;
/**
* @brief Deleted assignment operator to prevent copy.
*/
ReaderWriterMutex& operator=(const ReaderWriterMutex&) = delete;
/**
* @brief Locks the mutex for read.
*
* Note: unlockRead() must be called once for each time lockRead() was called.
*/
void lockRead();
/**
* @brief Locks the mutex for write.
*
* Note: unlockWrite() must be called once for each time lockWrite() was called.
*/
void lockWrite();
/**
* @brief Unlocks the mutex after a read operation.
*
* Note: unlockRead() must be called once for each time lockRead() was called.
*/
void unlockRead();
/**
* @brief Unlocks the mutex after a write operation.
*
* Note: unlockWrite() must be called once for each time lockWrite() was called.
*/
void unlockWrite();
private:
PRIVATE_IMPL(m_impl);
};
/**
* @brief RAII class which allows you to lock a ReaderWriterMutex for read.
*/
class ReaderLock
{
public:
/**
* @brief Constructor. Locks the specified mutex for read.
*
* @param in_mutex The mutex to lock for read.
*/
explicit ReaderLock(ReaderWriterMutex& in_mutex);
/**
* @brief Destructor.
*/
~ReaderLock();
private:
// The mutex this lock manages.
ReaderWriterMutex& m_mutex;
};
/**
* @brief RAII class which allows you to lock a ReaderWriterMutex for write.
*/
class WriterLock
{
public:
/**
* @brief Constructor. Locks the specified mutex for write.
*
* @param in_mutex The mutex to lock for write.
*/
explicit WriterLock(ReaderWriterMutex& in_mutex);
/**
* @brief Destructor.
*/
~WriterLock();
private:
// The mutex this lock manages.
ReaderWriterMutex& m_mutex;
};
} // namespace thread
} // namespace core
} // namespace rstudio
#define READ_LOCK_BEGIN(mutex) \
try \
{ \
rstudio::core::thread::ReaderLock lock(mutex); \
#define WRITE_LOCK_BEGIN(mutex) \
try \
{ \
rstudio::core::thread::WriterLock lock(mutex); \
#define RW_LOCK_END(tryLog) \
} \
catch (const boost::thread_resource_error& e) \
{ \
if (tryLog) \
log::logErrorMessage("Failed to acquire lock: thread resource error", \
ERROR_LOCATION); \
} \
catch (const std::exception& e) \
{ \
if (tryLog) \
log::logErrorMessage(std::string("Unexpected exception: ") + e.what(), \
ERROR_LOCATION); \
} \
catch (...) \
{ \
if (tryLog) \
log::logErrorMessage("Unknown exception while trying to acquire lock."); \
} \
#endif //SHARED_CORE_READER_WRITER_MUTEX_HPP
<|endoftext|>
|
<commit_before>//===----------------------------------------------------------------------===//
//
// Peloton
//
// operator_to_plan_transformer.cpp
//
// Identification: src/optimizer/operator_to_plan_transformer.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "optimizer/plan_generator.h"
#include "optimizer/operator_expression.h"
#include "planner/aggregate_plan.h"
#include "planner/delete_plan.h"
#include "planner/hash_join_plan.h"
#include "planner/hash_plan.h"
#include "planner/index_scan_plan.h"
#include "planner/insert_plan.h"
#include "planner/limit_plan.h"
#include "planner/nested_loop_join_plan.h"
#include "planner/order_by_plan.h"
#include "planner/projection_plan.h"
#include "planner/seq_scan_plan.h"
#include "planner/update_plan.h"
#include "settings/settings_manager.h"
#include "storage/data_table.h"
using std::vector;
using std::make_pair;
using std::string;
using std::to_string;
using std::unique_ptr;
using std::shared_ptr;
using std::move;
using std::make_tuple;
using std::make_pair;
using std::pair;
namespace peloton {
namespace optimizer {
PlanGenerator::PlanGenerator() {}
unique_ptr<planner::AbstractPlan> PlanGenerator::ConvertOpExpression(
shared_ptr<OperatorExpression> op, shared_ptr<PropertySet> required_props,
vector<expression::AbstractExpression *> required_cols,
vector<expression::AbstractExpression *> output_cols,
vector<unique_ptr<planner::AbstractPlan>> &children_plans,
vector<ExprMap> children_expr_map) {
required_props_ = required_props;
required_cols_ = required_cols;
output_cols_ = output_cols;
children_plans_ = move(children_plans);
children_expr_map_ = move(children_expr_map);
op->Op().Accept(this);
BuildProjectionPlan();
return move(output_plan_);
}
void PlanGenerator::Visit(const DummyScan *) {
// DummyScan is used in case of SELECT without FROM so that enforcer
// can enforce a PhysicalProjection on top of DummyScan to generate correct
// result. But here, no need to translate DummyScan to any physical plan.
output_plan_ = nullptr;
}
void PlanGenerator::Visit(const PhysicalSeqScan *op) {
vector<oid_t> column_ids = GenerateColumnsForScan();
auto predicate = GeneratePredicateForScan(
expression::ExpressionUtil::JoinAnnotatedExprs(op->predicates),
op->table_alias, op->table_);
output_plan_.reset(new planner::SeqScanPlan(op->table_, predicate.release(), column_ids));
}
void PlanGenerator::Visit(const PhysicalIndexScan *op) {
vector<oid_t> column_ids = GenerateColumnsForScan();
auto predicate = GeneratePredicateForScan(
expression::ExpressionUtil::JoinAnnotatedExprs(op->predicates),
op->table_alias, op->table_);
// TODO build index scan plan
}
void PlanGenerator::Visit(const QueryDerivedScan *) {}
void PlanGenerator::Visit(const PhysicalProject *) {}
void PlanGenerator::Visit(const PhysicalLimit *) {}
void PlanGenerator::Visit(const PhysicalOrderBy *) {
vector<oid_t> column_ids;
PL_ASSERT(children_expr_map_.size() == 1);
auto &child_cols_map = children_expr_map_[0];
for (size_t i = 0; i < required_cols_.size(); ++i) {
column_ids.push_back(child_cols_map[required_cols_[i]]);
}
auto sort_prop = required_props_->GetPropertyOfType(PropertyType::SORT)
->As<PropertySort>();
auto sort_columns_size = sort_prop->GetSortColumnSize();
vector<oid_t> sort_col_ids;
vector<bool> sort_flags;
for (size_t i = 0; i < sort_columns_size; ++i) {
sort_col_ids.push_back(child_cols_map[sort_prop->GetSortColumn(i)]);
// planner use desc flag
sort_flags.push_back(!sort_prop->GetSortAscending(i));
}
output_plan_.reset(
new planner::OrderByPlan(sort_col_ids, sort_flags, column_ids));
}
void PlanGenerator::Visit(const PhysicalHashGroupBy *) {}
void PlanGenerator::Visit(const PhysicalSortGroupBy *) {}
void PlanGenerator::Visit(const PhysicalAggregate *) {}
void PlanGenerator::Visit(const PhysicalDistinct *) {}
void PlanGenerator::Visit(const PhysicalFilter *) {}
void PlanGenerator::Visit(const PhysicalInnerNLJoin *) {}
void PlanGenerator::Visit(const PhysicalLeftNLJoin *) {}
void PlanGenerator::Visit(const PhysicalRightNLJoin *) {}
void PlanGenerator::Visit(const PhysicalOuterNLJoin *) {}
void PlanGenerator::Visit(const PhysicalInnerHashJoin *) {}
void PlanGenerator::Visit(const PhysicalLeftHashJoin *) {}
void PlanGenerator::Visit(const PhysicalRightHashJoin *) {}
void PlanGenerator::Visit(const PhysicalOuterHashJoin *) {}
void PlanGenerator::Visit(const PhysicalInsert *) {}
void PlanGenerator::Visit(const PhysicalInsertSelect *) {}
void PlanGenerator::Visit(const PhysicalDelete *) {}
void PlanGenerator::Visit(const PhysicalUpdate *) {}
ExprMap PlanGenerator::GenerateTableExprMap(const std::string &alias,
const storage::DataTable *table) {
ExprMap expr_map;
auto db_id = table->GetDatabaseOid();
oid_t table_id = table->GetOid();
auto cols = table->GetSchema()->GetColumns();
size_t num_col = cols.size();
for (oid_t col_id = 0; col_id < num_col; ++col_id) {
// Only bound_obj_id is needed for expr_map
// TODO potential memory leak here?
expression::TupleValueExpression *col_expr =
new expression::TupleValueExpression(cols[col_id].column_name.c_str(),
alias.c_str());
col_expr->SetValueType(table->GetSchema()->GetColumn(col_id).GetType());
col_expr->SetBoundOid(db_id, table_id, col_id);
expr_map[col_expr] = col_id;
}
return expr_map;
}
// Generate columns for scan plan
vector<oid_t> PlanGenerator::GenerateColumnsForScan() {
vector<oid_t> column_ids;
for (oid_t idx = 0; idx < output_cols_.size(); ++idx) {
auto &output_expr = output_cols_[idx];
PL_ASSERT(output_expr->GetExpressionType() == ExpressionType::VALUE_TUPLE);
auto output_tvexpr =
reinterpret_cast<expression::TupleValueExpression *>(output_expr);
// Set column offset
PL_ASSERT(output_tvexpr->GetIsBound() == true);
auto col_id = std::get<2>(output_tvexpr->GetBoundOid());
column_ids.push_back(col_id);
}
return column_ids;
}
std::unique_ptr<expression::AbstractExpression>
PlanGenerator::GeneratePredicateForScan(
const std::shared_ptr<expression::AbstractExpression> predicate_expr,
const std::string &alias, const storage::DataTable *table) {
if (predicate_expr == nullptr) {
return nullptr;
}
ExprMap table_expr_map = GenerateTableExprMap(alias, table);
unique_ptr<expression::AbstractExpression> predicate =
std::unique_ptr<expression::AbstractExpression>(predicate_expr->Copy());
expression::ExpressionUtil::EvaluateExpression({table_expr_map},
predicate.get());
return predicate;
}
void PlanGenerator::BuildProjectionPlan() {
bool no_projection = false;
if (output_cols_.size() == required_cols_.size()) {
no_projection = true;
size_t cols_size = output_cols_.size();
for (size_t idx = 0; idx < cols_size; ++idx) {
if (output_cols_[idx] != required_cols_[idx]) {
no_projection = false;
break;
}
}
}
if (no_projection) {
return;
}
// TODO Construct projection plan
// TODO(boweic): For now, we only produce tv exprs and aggregate expr as
// output column, but we should handle arbitary expressions in the future
// ExprMap output_cols_map;
// for (auto &col : output_cols_) {
// PL_ASSERT(col->GetExpressionType() == ExpressionType::VALUE_TUPLE ||
// col->GetExpressionType() == ExpressionType::AggregateType);
//
// }
}
} // namespace optimizer
} // namespace peloton
<commit_msg>Finish build index scan plan in plan generator<commit_after>//===----------------------------------------------------------------------===//
//
// Peloton
//
// operator_to_plan_transformer.cpp
//
// Identification: src/optimizer/operator_to_plan_transformer.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "optimizer/plan_generator.h"
#include "optimizer/operator_expression.h"
#include "planner/aggregate_plan.h"
#include "planner/delete_plan.h"
#include "planner/hash_join_plan.h"
#include "planner/hash_plan.h"
#include "planner/index_scan_plan.h"
#include "planner/insert_plan.h"
#include "planner/limit_plan.h"
#include "planner/nested_loop_join_plan.h"
#include "planner/order_by_plan.h"
#include "planner/projection_plan.h"
#include "planner/seq_scan_plan.h"
#include "planner/update_plan.h"
#include "settings/settings_manager.h"
#include "storage/data_table.h"
using std::vector;
using std::make_pair;
using std::string;
using std::to_string;
using std::unique_ptr;
using std::shared_ptr;
using std::move;
using std::make_tuple;
using std::make_pair;
using std::pair;
namespace peloton {
namespace optimizer {
PlanGenerator::PlanGenerator() {}
unique_ptr<planner::AbstractPlan> PlanGenerator::ConvertOpExpression(
shared_ptr<OperatorExpression> op, shared_ptr<PropertySet> required_props,
vector<expression::AbstractExpression *> required_cols,
vector<expression::AbstractExpression *> output_cols,
vector<unique_ptr<planner::AbstractPlan>> &children_plans,
vector<ExprMap> children_expr_map) {
required_props_ = required_props;
required_cols_ = required_cols;
output_cols_ = output_cols;
children_plans_ = move(children_plans);
children_expr_map_ = move(children_expr_map);
op->Op().Accept(this);
BuildProjectionPlan();
return move(output_plan_);
}
void PlanGenerator::Visit(const DummyScan *) {
// DummyScan is used in case of SELECT without FROM so that enforcer
// can enforce a PhysicalProjection on top of DummyScan to generate correct
// result. But here, no need to translate DummyScan to any physical plan.
output_plan_ = nullptr;
}
void PlanGenerator::Visit(const PhysicalSeqScan *op) {
vector<oid_t> column_ids = GenerateColumnsForScan();
auto predicate = GeneratePredicateForScan(
expression::ExpressionUtil::JoinAnnotatedExprs(op->predicates),
op->table_alias, op->table_);
output_plan_.reset(new planner::SeqScanPlan(op->table_, predicate.release(), column_ids));
}
void PlanGenerator::Visit(const PhysicalIndexScan *op) {
vector<oid_t> column_ids = GenerateColumnsForScan();
auto predicate = GeneratePredicateForScan(
expression::ExpressionUtil::JoinAnnotatedExprs(op->predicates),
op->table_alias, op->table_);
auto index = op->table_->GetIndex(op->index_id);
vector<expression::AbstractExpression *> runtime_keys;
// Create index scan desc
planner::IndexScanPlan::IndexScanDesc index_scan_desc(
index, op->key_column_id_list, op->expr_type_list, op->value_list, runtime_keys);
output_plan_.reset(new planner::IndexScanPlan(
op->table_, predicate.release(), column_ids, index_scan_desc, false));
}
void PlanGenerator::Visit(const QueryDerivedScan *) {}
void PlanGenerator::Visit(const PhysicalProject *) {}
void PlanGenerator::Visit(const PhysicalLimit *) {}
void PlanGenerator::Visit(const PhysicalOrderBy *) {
vector<oid_t> column_ids;
PL_ASSERT(children_expr_map_.size() == 1);
auto &child_cols_map = children_expr_map_[0];
for (size_t i = 0; i < required_cols_.size(); ++i) {
column_ids.push_back(child_cols_map[required_cols_[i]]);
}
auto sort_prop = required_props_->GetPropertyOfType(PropertyType::SORT)
->As<PropertySort>();
auto sort_columns_size = sort_prop->GetSortColumnSize();
vector<oid_t> sort_col_ids;
vector<bool> sort_flags;
for (size_t i = 0; i < sort_columns_size; ++i) {
sort_col_ids.push_back(child_cols_map[sort_prop->GetSortColumn(i)]);
// planner use desc flag
sort_flags.push_back(!sort_prop->GetSortAscending(i));
}
output_plan_.reset(
new planner::OrderByPlan(sort_col_ids, sort_flags, column_ids));
}
void PlanGenerator::Visit(const PhysicalHashGroupBy *) {}
void PlanGenerator::Visit(const PhysicalSortGroupBy *) {}
void PlanGenerator::Visit(const PhysicalAggregate *) {}
void PlanGenerator::Visit(const PhysicalDistinct *) {}
void PlanGenerator::Visit(const PhysicalFilter *) {}
void PlanGenerator::Visit(const PhysicalInnerNLJoin *) {}
void PlanGenerator::Visit(const PhysicalLeftNLJoin *) {}
void PlanGenerator::Visit(const PhysicalRightNLJoin *) {}
void PlanGenerator::Visit(const PhysicalOuterNLJoin *) {}
void PlanGenerator::Visit(const PhysicalInnerHashJoin *) {}
void PlanGenerator::Visit(const PhysicalLeftHashJoin *) {}
void PlanGenerator::Visit(const PhysicalRightHashJoin *) {}
void PlanGenerator::Visit(const PhysicalOuterHashJoin *) {}
void PlanGenerator::Visit(const PhysicalInsert *) {}
void PlanGenerator::Visit(const PhysicalInsertSelect *) {}
void PlanGenerator::Visit(const PhysicalDelete *) {}
void PlanGenerator::Visit(const PhysicalUpdate *) {}
ExprMap PlanGenerator::GenerateTableExprMap(const std::string &alias,
const storage::DataTable *table) {
ExprMap expr_map;
auto db_id = table->GetDatabaseOid();
oid_t table_id = table->GetOid();
auto cols = table->GetSchema()->GetColumns();
size_t num_col = cols.size();
for (oid_t col_id = 0; col_id < num_col; ++col_id) {
// Only bound_obj_id is needed for expr_map
// TODO potential memory leak here?
expression::TupleValueExpression *col_expr =
new expression::TupleValueExpression(cols[col_id].column_name.c_str(),
alias.c_str());
col_expr->SetValueType(table->GetSchema()->GetColumn(col_id).GetType());
col_expr->SetBoundOid(db_id, table_id, col_id);
expr_map[col_expr] = col_id;
}
return expr_map;
}
// Generate columns for scan plan
vector<oid_t> PlanGenerator::GenerateColumnsForScan() {
vector<oid_t> column_ids;
for (oid_t idx = 0; idx < output_cols_.size(); ++idx) {
auto &output_expr = output_cols_[idx];
PL_ASSERT(output_expr->GetExpressionType() == ExpressionType::VALUE_TUPLE);
auto output_tvexpr =
reinterpret_cast<expression::TupleValueExpression *>(output_expr);
// Set column offset
PL_ASSERT(output_tvexpr->GetIsBound() == true);
auto col_id = std::get<2>(output_tvexpr->GetBoundOid());
column_ids.push_back(col_id);
}
return column_ids;
}
std::unique_ptr<expression::AbstractExpression>
PlanGenerator::GeneratePredicateForScan(
const std::shared_ptr<expression::AbstractExpression> predicate_expr,
const std::string &alias, const storage::DataTable *table) {
if (predicate_expr == nullptr) {
return nullptr;
}
ExprMap table_expr_map = GenerateTableExprMap(alias, table);
unique_ptr<expression::AbstractExpression> predicate =
std::unique_ptr<expression::AbstractExpression>(predicate_expr->Copy());
expression::ExpressionUtil::EvaluateExpression({table_expr_map},
predicate.get());
return predicate;
}
void PlanGenerator::BuildProjectionPlan() {
bool no_projection = false;
if (output_cols_.size() == required_cols_.size()) {
no_projection = true;
size_t cols_size = output_cols_.size();
for (size_t idx = 0; idx < cols_size; ++idx) {
if (output_cols_[idx] != required_cols_[idx]) {
no_projection = false;
break;
}
}
}
if (no_projection) {
return;
}
// TODO Construct projection plan
// TODO(boweic): For now, we only produce tv exprs and aggregate expr as
// output column, but we should handle arbitary expressions in the future
// ExprMap output_cols_map;
// for (auto &col : output_cols_) {
// PL_ASSERT(col->GetExpressionType() == ExpressionType::VALUE_TUPLE ||
// col->GetExpressionType() == ExpressionType::AggregateType);
//
// }
}
} // namespace optimizer
} // namespace peloton
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2014 odan
* License: MIT License
*/
#include "LCG.hpp"
namespace PokeRNG {
template<typename UIntType, UIntType mul, UIntType add, UIntType mask>
LCG<UIntType, mul, add, mask>::LCG() :
div(calc_inverse_tmp<UIntType, mul, mask>::value), sub(~(div * add) + 1ULL) { }
template<typename UIntType, UIntType mul, UIntType add, UIntType mask>
UIntType LCG<UIntType, mul, add, mask>::next(UIntType s) const {
return ((s * mul) + add);
}
template<typename UIntType, UIntType mul, UIntType add, UIntType mask>
UIntType LCG<UIntType, mul, add, mask>::prev(UIntType s) const {
return ((s * div) + sub);
}
template<typename UIntType, UIntType mul, UIntType add, UIntType mask>
UIntType LCG<UIntType, mul, add, mask>::skip_lcg(UIntType s, UIntType n, UIntType a, UIntType b) const {
while(n) {
if(n & 1) s = ((s * a) + b);
b = (a * b + b);
a = (a * a);
n >>= 1;
}
return s;
}
template<typename UIntType, UIntType mul, UIntType add, UIntType mask>
UIntType LCG<UIntType, mul, add, mask>::next_n(UIntType s, UIntType n) const {
return skip_lcg(s, n, mul, add);
}
template<typename UIntType, UIntType mul, UIntType add, UIntType mask>
UIntType LCG<UIntType, mul, add, mask>::prev_n(UIntType s, UIntType n) const {
return skip_lcg(s, n, div, sub);
}
/*
* 参考
* http://plusletool.hatenablog.jp/entry/2014/11/05/230000
*/
template<typename UIntType, UIntType mul, UIntType add, UIntType mask>
UIntType LCG<UIntType, mul, add, mask>::index(UIntType s) const {
u64 a = mul;
u64 b = add;
u64 n = 0;
u64 x = 1;
while(x) {
if(s & x) {
n |= x;
s -= b;
b *= a;
}
b *= a + 1;
a *= a;
x <<= 1;
}
return n;
}
template class LCG<u64, 0x5D588B656C078965, 0x269EC3, 0xFFFFFFFFFFFFFFFF>;
template class LCG<u32, 0x41C64E6D, 0x6073, 0xFFFFFFFF>;
template class LCG<u64, 0x5D583D6D6C078979, 0x26A693, 0xFFFFFFFFFFFFFFFF>;
} // end PokeRNG
<commit_msg>LCGのindexの計算時に使用する型を変更<commit_after>/*
* Copyright (c) 2014 odan
* License: MIT License
*/
#include "LCG.hpp"
namespace PokeRNG {
template<typename UIntType, UIntType mul, UIntType add, UIntType mask>
LCG<UIntType, mul, add, mask>::LCG() :
div(calc_inverse_tmp<UIntType, mul, mask>::value), sub(~(div * add) + 1ULL) { }
template<typename UIntType, UIntType mul, UIntType add, UIntType mask>
UIntType LCG<UIntType, mul, add, mask>::next(UIntType s) const {
return ((s * mul) + add);
}
template<typename UIntType, UIntType mul, UIntType add, UIntType mask>
UIntType LCG<UIntType, mul, add, mask>::prev(UIntType s) const {
return ((s * div) + sub);
}
template<typename UIntType, UIntType mul, UIntType add, UIntType mask>
UIntType LCG<UIntType, mul, add, mask>::skip_lcg(UIntType s, UIntType n, UIntType a, UIntType b) const {
while(n) {
if(n & 1) s = ((s * a) + b);
b = (a * b + b);
a = (a * a);
n >>= 1;
}
return s;
}
template<typename UIntType, UIntType mul, UIntType add, UIntType mask>
UIntType LCG<UIntType, mul, add, mask>::next_n(UIntType s, UIntType n) const {
return skip_lcg(s, n, mul, add);
}
template<typename UIntType, UIntType mul, UIntType add, UIntType mask>
UIntType LCG<UIntType, mul, add, mask>::prev_n(UIntType s, UIntType n) const {
return skip_lcg(s, n, div, sub);
}
/*
* 参考
* http://plusletool.hatenablog.jp/entry/2014/11/05/230000
*/
template<typename UIntType, UIntType mul, UIntType add, UIntType mask>
UIntType LCG<UIntType, mul, add, mask>::index(UIntType s) const {
UIntType a = mul;
UIntType b = add;
UIntType n = 0;
UIntType x = 1;
while(x) {
if(s & x) {
n |= x;
s -= b;
b *= a;
}
b *= a + 1;
a *= a;
x <<= 1;
}
return n;
}
template class LCG<u64, 0x5D588B656C078965, 0x269EC3, 0xFFFFFFFFFFFFFFFF>;
template class LCG<u32, 0x41C64E6D, 0x6073, 0xFFFFFFFF>;
template class LCG<u64, 0x5D583D6D6C078979, 0x26A693, 0xFFFFFFFFFFFFFFFF>;
} // end PokeRNG
<|endoftext|>
|
<commit_before>/**
* @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may find a copy of the License in the LICENCE file.
*
* 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.
*
* @file JPetManager.cpp
*/
#include "./JPetManager.h"
#include <cassert>
#include <ctime>
#include <string>
#include "../JPetLoggerInclude.h"
#include "../JPetScopeReader/JPetScopeReader.h"
#include "../JPetCommonTools/JPetCommonTools.h"
#include "../JPetCmdParser/JPetCmdParser.h"
#include <TDSet.h>
#include <TThread.h>
JPetManager& JPetManager::getManager()
{
static JPetManager instance;
return instance;
}
void JPetManager::run()
{
INFO( "======== Starting processing all tasks: " + JPetCommonTools::getTimeString() + " ========\n" );
std::vector<JPetTaskExecutor*> executors;
std::vector<TThread*> threads;
auto i = 0;
for (auto opt : fOptions) {
JPetTaskExecutor* executor = new JPetTaskExecutor(fTaskGeneratorChain, i, opt);
executors.push_back(executor);
auto thr = executor->run();
if (thr) {
threads.push_back(thr);
} else {
ERROR("thread pointer is null");
}
i++;
}
for (auto thread : threads) {
thread->Join();
}
for (auto executor : executors) {
delete executor;
}
INFO( "======== Finished processing all tasks: " + JPetCommonTools::getTimeString() + " ========\n" );
}
void JPetManager::parseCmdLine(int argc, char** argv)
{
JPetCmdParser parser;
fOptions = parser.parseAndGenerateOptions(argc, (const char**)argv);
}
JPetManager::~JPetManager()
{
/**/
}
void JPetManager::registerTask(const TaskGenerator& taskGen)
{
assert(fTaskGeneratorChain);
fTaskGeneratorChain->push_back(taskGen);
}
<commit_msg>In JPetManager destructor add cleaning of param caches.<commit_after>/**
* @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may find a copy of the License in the LICENCE file.
*
* 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.
*
* @file JPetManager.cpp
*/
#include "./JPetManager.h"
#include <cassert>
#include <ctime>
#include <string>
#include "../JPetLoggerInclude.h"
#include "../JPetScopeReader/JPetScopeReader.h"
#include "../JPetCommonTools/JPetCommonTools.h"
#include "../JPetCmdParser/JPetCmdParser.h"
#include <TDSet.h>
#include <TThread.h>
JPetManager& JPetManager::getManager()
{
static JPetManager instance;
return instance;
}
void JPetManager::run()
{
INFO( "======== Starting processing all tasks: " + JPetCommonTools::getTimeString() + " ========\n" );
std::vector<JPetTaskExecutor*> executors;
std::vector<TThread*> threads;
auto i = 0;
for (auto opt : fOptions) {
JPetTaskExecutor* executor = new JPetTaskExecutor(fTaskGeneratorChain, i, opt);
executors.push_back(executor);
auto thr = executor->run();
if (thr) {
threads.push_back(thr);
} else {
ERROR("thread pointer is null");
}
i++;
}
for (auto thread : threads) {
thread->Join();
}
for (auto& executor : executors) {
if (executor) {
delete executor;
executor = 0;
}
}
INFO( "======== Finished processing all tasks: " + JPetCommonTools::getTimeString() + " ========\n" );
}
void JPetManager::parseCmdLine(int argc, char** argv)
{
JPetCmdParser parser;
fOptions = parser.parseAndGenerateOptions(argc, (const char**)argv);
}
JPetManager::~JPetManager()
{
/// delete shared caches for paramBanks
/// @todo I think that should be changed
JPetDBParamGetter::clearParamCache();
JPetScopeParamGetter::clearParamCache();
}
void JPetManager::registerTask(const TaskGenerator& taskGen)
{
assert(fTaskGeneratorChain);
fTaskGeneratorChain->push_back(taskGen);
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: window3.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: hr $ $Date: 2007-06-27 20:36:17 $
*
* 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
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_vcl.hxx"
#define _SV_WINDOW_CXX
#ifndef _SV_SVSYS_HXX
#include <svsys.h>
#endif
#ifndef _SV_WINDOW_H
#include <window.h>
#endif
#ifndef _SV_WINDOW_HXX
#include <vcl/window.hxx>
#endif
#ifndef _SV_WAITOBJ_HXX
#include <vcl/waitobj.hxx>
#endif
#ifndef _SV_SALGDI_HXX
#include <vcl/salgdi.hxx>
#endif
#ifndef _SV_NATIVEWIDGETS_HXX
#include <vcl/salnativewidgets.hxx>
#endif
#ifndef _SV_SALCTRLHANDLE_HXX
#include <vcl/salctrlhandle.hxx>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
using namespace rtl;
// -----------------------------------------------------------------------
// These functions are mainly passthrough functions that allow access to
// the SalFrame behind a Window object for native widget rendering purposes.
// -----------------------------------------------------------------------
void Window::ImplInitSalControlHandle()
{
// create SalControlHandle on demand
// not needed for ordinary windows
// TODO: move creation to SalGraphics
//if( !ImplGetWinData()->mpSalControlHandle )
// ImplGetWinData()->mpSalControlHandle = new SalControlHandle;
}
// -----------------------------------------------------------------------
BOOL Window::IsNativeControlSupported( ControlType nType, ControlPart nPart )
{
if( !IsNativeWidgetEnabled() )
return FALSE;
if ( !mpGraphics )
if ( !ImplGetGraphics() )
return FALSE;
return( mpGraphics->IsNativeControlSupported(nType, nPart) );
}
// -----------------------------------------------------------------------
BOOL Window::HitTestNativeControl( ControlType nType,
ControlPart nPart,
const Region& rControlRegion,
const Point& aPos,
BOOL& rIsInside )
{
if( !IsNativeWidgetEnabled() )
return FALSE;
if ( !mpGraphics )
if ( !ImplGetGraphics() )
return FALSE;
ImplInitSalControlHandle();
Point aWinOffs;
aWinOffs = OutputToScreenPixel( aWinOffs );
Region screenRegion( rControlRegion );
screenRegion.Move( aWinOffs.X(), aWinOffs.Y());
return( mpGraphics->HitTestNativeControl(nType, nPart, screenRegion, OutputToScreenPixel( aPos ), *ImplGetWinData()->mpSalControlHandle, rIsInside, this ) );
}
// -----------------------------------------------------------------------
void Window::ImplMoveControlValue( ControlType nType, const ImplControlValue& aValue, const Point& rDelta ) const
{
if( aValue.getOptionalVal() )
{
switch( nType )
{
case CTRL_SCROLLBAR:
{
ScrollbarValue* pScVal = reinterpret_cast<ScrollbarValue*>(aValue.getOptionalVal());
pScVal->maThumbRect.Move( rDelta.X(), rDelta.Y() );
pScVal->maButton1Rect.Move( rDelta.X(), rDelta.Y() );
pScVal->maButton2Rect.Move( rDelta.X(), rDelta.Y() );
}
break;
case CTRL_SPINBOX:
case CTRL_SPINBUTTONS:
{
SpinbuttonValue* pSpVal = reinterpret_cast<SpinbuttonValue*>(aValue.getOptionalVal());
pSpVal->maUpperRect.Move( rDelta.X(), rDelta.Y() );
pSpVal->maLowerRect.Move( rDelta.X(), rDelta.Y() );
}
break;
case CTRL_TOOLBAR:
{
ToolbarValue* pTVal = reinterpret_cast<ToolbarValue*>(aValue.getOptionalVal());
pTVal->maGripRect.Move( rDelta.X(), rDelta.Y() );
}
break;
}
}
}
BOOL Window::DrawNativeControl( ControlType nType,
ControlPart nPart,
const Region& rControlRegion,
ControlState nState,
const ImplControlValue& aValue,
OUString aCaption )
{
if( !IsNativeWidgetEnabled() )
return FALSE;
/*
if( !IsInPaint() && IsPaintTransparent() )
{
// only required if called directly (ie, we're not in Paint() ):
// force redraw (Paint()) for transparent controls
// to trigger a repaint of the background
Region aClipRgn( GetClipRegion() );
if( !rControlRegion.IsEmpty() )
aClipRgn.Intersect( rControlRegion );
Invalidate( aClipRgn, INVALIDATE_UPDATE );
return TRUE;
}
*/
ImplInitSalControlHandle();
// make sure the current clip region is initialized correctly
if ( !mpGraphics )
if ( !ImplGetGraphics() )
return FALSE;
if ( mbInitClipRegion )
ImplInitClipRegion();
if ( mbOutputClipped )
return TRUE;
if ( mbInitLineColor )
ImplInitLineColor();
if ( mbInitFillColor )
ImplInitFillColor();
// Convert the coordinates from relative to Window-absolute, so we draw
// in the correct place in platform code
Point aWinOffs;
aWinOffs = OutputToScreenPixel( aWinOffs );
Region screenRegion( rControlRegion );
screenRegion.Move( aWinOffs.X(), aWinOffs.Y());
// do so for ImplControlValue members, also
ImplMoveControlValue( nType, aValue, aWinOffs );
Region aTestRegion( GetActiveClipRegion() );
aTestRegion.Intersect( rControlRegion );
if( aTestRegion == rControlRegion )
nState |= CTRL_CACHING_ALLOWED; // control is not clipped, caching allowed
BOOL bRet = mpGraphics->DrawNativeControl(nType, nPart, screenRegion, nState, aValue, *ImplGetWinData()->mpSalControlHandle, aCaption, this );
// transform back ImplControlValue members
ImplMoveControlValue( nType, aValue, Point()-aWinOffs );
return bRet;
}
// -----------------------------------------------------------------------
BOOL Window::DrawNativeControlText(ControlType nType,
ControlPart nPart,
const Region& rControlRegion,
ControlState nState,
const ImplControlValue& aValue,
OUString aCaption )
{
if( !IsNativeWidgetEnabled() )
return FALSE;
ImplInitSalControlHandle();
// make sure the current clip region is initialized correctly
if ( !mpGraphics )
if ( !ImplGetGraphics() )
return false;
if ( mbInitClipRegion )
ImplInitClipRegion();
if ( mbOutputClipped )
return true;
if ( mbInitLineColor )
ImplInitLineColor();
if ( mbInitFillColor )
ImplInitFillColor();
// Convert the coordinates from relative to Window-absolute, so we draw
// in the correct place in platform code
Point aWinOffs;
aWinOffs = OutputToScreenPixel( aWinOffs );
Region screenRegion( rControlRegion );
screenRegion.Move( aWinOffs.X(), aWinOffs.Y());
ImplMoveControlValue( nType, aValue, aWinOffs );
BOOL bRet = mpGraphics->DrawNativeControlText(nType, nPart, screenRegion, nState, aValue, *ImplGetWinData()->mpSalControlHandle, aCaption, this );
// transform back ImplControlValue members
ImplMoveControlValue( nType, aValue, Point()-aWinOffs );
return bRet;
}
// -----------------------------------------------------------------------
BOOL Window::GetNativeControlRegion( ControlType nType,
ControlPart nPart,
const Region& rControlRegion,
ControlState nState,
const ImplControlValue& aValue,
OUString aCaption,
Region &rNativeBoundingRegion,
Region &rNativeContentRegion )
{
if( !IsNativeWidgetEnabled() )
return FALSE;
if ( !mpGraphics )
if ( !ImplGetGraphics() )
return FALSE;
ImplInitSalControlHandle();
// Convert the coordinates from relative to Window-absolute, so we draw
// in the correct place in platform code
Point aWinOffs;
aWinOffs = OutputToScreenPixel( aWinOffs );
Region screenRegion( rControlRegion );
screenRegion.Move( aWinOffs.X(), aWinOffs.Y());
ImplMoveControlValue( nType, aValue, aWinOffs );
BOOL bRet = mpGraphics->GetNativeControlRegion(nType, nPart, screenRegion, nState, aValue,
*ImplGetWinData()->mpSalControlHandle, aCaption, rNativeBoundingRegion,
rNativeContentRegion, this );
if( bRet )
{
// transform back native regions
rNativeBoundingRegion.Move( -aWinOffs.X(), -aWinOffs.Y() );
rNativeContentRegion.Move( -aWinOffs.X(), -aWinOffs.Y() );
}
// transform back ImplControlValue members
ImplMoveControlValue( nType, aValue, Point()-aWinOffs );
return bRet;
}
// -----------------------------------------------------------------------
WaitObject::~WaitObject()
{
if ( mpWindow )
mpWindow->LeaveWait();
}
<commit_msg>INTEGRATION: CWS mergesvp (1.9.2); FILE MERGED 2007/07/04 15:32:41 pl 1.9.2.1: #i79023# header moving<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: window3.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: rt $ $Date: 2007-07-24 10:23:32 $
*
* 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
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_vcl.hxx"
#define _SV_WINDOW_CXX
#ifndef _SV_SVSYS_HXX
#include <svsys.h>
#endif
#ifndef _SV_WINDOW_H
#include <vcl/window.h>
#endif
#ifndef _SV_WINDOW_HXX
#include <vcl/window.hxx>
#endif
#ifndef _SV_WAITOBJ_HXX
#include <vcl/waitobj.hxx>
#endif
#ifndef _SV_SALGDI_HXX
#include <vcl/salgdi.hxx>
#endif
#ifndef _SV_NATIVEWIDGETS_HXX
#include <vcl/salnativewidgets.hxx>
#endif
#ifndef _SV_SALCTRLHANDLE_HXX
#include <vcl/salctrlhandle.hxx>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
using namespace rtl;
// -----------------------------------------------------------------------
// These functions are mainly passthrough functions that allow access to
// the SalFrame behind a Window object for native widget rendering purposes.
// -----------------------------------------------------------------------
void Window::ImplInitSalControlHandle()
{
// create SalControlHandle on demand
// not needed for ordinary windows
// TODO: move creation to SalGraphics
//if( !ImplGetWinData()->mpSalControlHandle )
// ImplGetWinData()->mpSalControlHandle = new SalControlHandle;
}
// -----------------------------------------------------------------------
BOOL Window::IsNativeControlSupported( ControlType nType, ControlPart nPart )
{
if( !IsNativeWidgetEnabled() )
return FALSE;
if ( !mpGraphics )
if ( !ImplGetGraphics() )
return FALSE;
return( mpGraphics->IsNativeControlSupported(nType, nPart) );
}
// -----------------------------------------------------------------------
BOOL Window::HitTestNativeControl( ControlType nType,
ControlPart nPart,
const Region& rControlRegion,
const Point& aPos,
BOOL& rIsInside )
{
if( !IsNativeWidgetEnabled() )
return FALSE;
if ( !mpGraphics )
if ( !ImplGetGraphics() )
return FALSE;
ImplInitSalControlHandle();
Point aWinOffs;
aWinOffs = OutputToScreenPixel( aWinOffs );
Region screenRegion( rControlRegion );
screenRegion.Move( aWinOffs.X(), aWinOffs.Y());
return( mpGraphics->HitTestNativeControl(nType, nPart, screenRegion, OutputToScreenPixel( aPos ), *ImplGetWinData()->mpSalControlHandle, rIsInside, this ) );
}
// -----------------------------------------------------------------------
void Window::ImplMoveControlValue( ControlType nType, const ImplControlValue& aValue, const Point& rDelta ) const
{
if( aValue.getOptionalVal() )
{
switch( nType )
{
case CTRL_SCROLLBAR:
{
ScrollbarValue* pScVal = reinterpret_cast<ScrollbarValue*>(aValue.getOptionalVal());
pScVal->maThumbRect.Move( rDelta.X(), rDelta.Y() );
pScVal->maButton1Rect.Move( rDelta.X(), rDelta.Y() );
pScVal->maButton2Rect.Move( rDelta.X(), rDelta.Y() );
}
break;
case CTRL_SPINBOX:
case CTRL_SPINBUTTONS:
{
SpinbuttonValue* pSpVal = reinterpret_cast<SpinbuttonValue*>(aValue.getOptionalVal());
pSpVal->maUpperRect.Move( rDelta.X(), rDelta.Y() );
pSpVal->maLowerRect.Move( rDelta.X(), rDelta.Y() );
}
break;
case CTRL_TOOLBAR:
{
ToolbarValue* pTVal = reinterpret_cast<ToolbarValue*>(aValue.getOptionalVal());
pTVal->maGripRect.Move( rDelta.X(), rDelta.Y() );
}
break;
}
}
}
BOOL Window::DrawNativeControl( ControlType nType,
ControlPart nPart,
const Region& rControlRegion,
ControlState nState,
const ImplControlValue& aValue,
OUString aCaption )
{
if( !IsNativeWidgetEnabled() )
return FALSE;
/*
if( !IsInPaint() && IsPaintTransparent() )
{
// only required if called directly (ie, we're not in Paint() ):
// force redraw (Paint()) for transparent controls
// to trigger a repaint of the background
Region aClipRgn( GetClipRegion() );
if( !rControlRegion.IsEmpty() )
aClipRgn.Intersect( rControlRegion );
Invalidate( aClipRgn, INVALIDATE_UPDATE );
return TRUE;
}
*/
ImplInitSalControlHandle();
// make sure the current clip region is initialized correctly
if ( !mpGraphics )
if ( !ImplGetGraphics() )
return FALSE;
if ( mbInitClipRegion )
ImplInitClipRegion();
if ( mbOutputClipped )
return TRUE;
if ( mbInitLineColor )
ImplInitLineColor();
if ( mbInitFillColor )
ImplInitFillColor();
// Convert the coordinates from relative to Window-absolute, so we draw
// in the correct place in platform code
Point aWinOffs;
aWinOffs = OutputToScreenPixel( aWinOffs );
Region screenRegion( rControlRegion );
screenRegion.Move( aWinOffs.X(), aWinOffs.Y());
// do so for ImplControlValue members, also
ImplMoveControlValue( nType, aValue, aWinOffs );
Region aTestRegion( GetActiveClipRegion() );
aTestRegion.Intersect( rControlRegion );
if( aTestRegion == rControlRegion )
nState |= CTRL_CACHING_ALLOWED; // control is not clipped, caching allowed
BOOL bRet = mpGraphics->DrawNativeControl(nType, nPart, screenRegion, nState, aValue, *ImplGetWinData()->mpSalControlHandle, aCaption, this );
// transform back ImplControlValue members
ImplMoveControlValue( nType, aValue, Point()-aWinOffs );
return bRet;
}
// -----------------------------------------------------------------------
BOOL Window::DrawNativeControlText(ControlType nType,
ControlPart nPart,
const Region& rControlRegion,
ControlState nState,
const ImplControlValue& aValue,
OUString aCaption )
{
if( !IsNativeWidgetEnabled() )
return FALSE;
ImplInitSalControlHandle();
// make sure the current clip region is initialized correctly
if ( !mpGraphics )
if ( !ImplGetGraphics() )
return false;
if ( mbInitClipRegion )
ImplInitClipRegion();
if ( mbOutputClipped )
return true;
if ( mbInitLineColor )
ImplInitLineColor();
if ( mbInitFillColor )
ImplInitFillColor();
// Convert the coordinates from relative to Window-absolute, so we draw
// in the correct place in platform code
Point aWinOffs;
aWinOffs = OutputToScreenPixel( aWinOffs );
Region screenRegion( rControlRegion );
screenRegion.Move( aWinOffs.X(), aWinOffs.Y());
ImplMoveControlValue( nType, aValue, aWinOffs );
BOOL bRet = mpGraphics->DrawNativeControlText(nType, nPart, screenRegion, nState, aValue, *ImplGetWinData()->mpSalControlHandle, aCaption, this );
// transform back ImplControlValue members
ImplMoveControlValue( nType, aValue, Point()-aWinOffs );
return bRet;
}
// -----------------------------------------------------------------------
BOOL Window::GetNativeControlRegion( ControlType nType,
ControlPart nPart,
const Region& rControlRegion,
ControlState nState,
const ImplControlValue& aValue,
OUString aCaption,
Region &rNativeBoundingRegion,
Region &rNativeContentRegion )
{
if( !IsNativeWidgetEnabled() )
return FALSE;
if ( !mpGraphics )
if ( !ImplGetGraphics() )
return FALSE;
ImplInitSalControlHandle();
// Convert the coordinates from relative to Window-absolute, so we draw
// in the correct place in platform code
Point aWinOffs;
aWinOffs = OutputToScreenPixel( aWinOffs );
Region screenRegion( rControlRegion );
screenRegion.Move( aWinOffs.X(), aWinOffs.Y());
ImplMoveControlValue( nType, aValue, aWinOffs );
BOOL bRet = mpGraphics->GetNativeControlRegion(nType, nPart, screenRegion, nState, aValue,
*ImplGetWinData()->mpSalControlHandle, aCaption, rNativeBoundingRegion,
rNativeContentRegion, this );
if( bRet )
{
// transform back native regions
rNativeBoundingRegion.Move( -aWinOffs.X(), -aWinOffs.Y() );
rNativeContentRegion.Move( -aWinOffs.X(), -aWinOffs.Y() );
}
// transform back ImplControlValue members
ImplMoveControlValue( nType, aValue, Point()-aWinOffs );
return bRet;
}
// -----------------------------------------------------------------------
WaitObject::~WaitObject()
{
if ( mpWindow )
mpWindow->LeaveWait();
}
<|endoftext|>
|
<commit_before>#pragma once
#include "jsd_core.hpp"
#include "jsd_check.hpp"
#include "jsd_options.hpp"
namespace JSON
{
template <typename T>
void try_parse(T& obj, std::string const& name, PropertyTree const& tree, ParsingOptions const& options = DEFAULT_PARSER_OPTIONS,
typename std::enable_if <Internal::can_parse<T>::value, void>::type* = nullptr)
{
parse(obj, name, tree, options);
}
template <typename T>
void try_parse(T&, std::string const&, PropertyTree const&, ParsingOptions const& = DEFAULT_PARSER_OPTIONS,
typename std::enable_if <!Internal::can_parse<T>::value, int>::type* = nullptr)
{
static_assert (Internal::can_parse<T>::value, "the object you try to parse has no applicable interface");
}
template <typename T>
T make_from_json(std::istream& stream)
{
T res;
JSON::parse(res, "", JSON::parse_json(stream));
return res;
}
template <typename T>
T make_from_json(std::string const& str)
{
T res;
JSON::parse(res, "", JSON::parse_json(str));
return res;
}
}
#define json_deserialize(NAME) JSON::try_parse(#NAME, NAME)
#define json_deserialize_opt(NAME, OPTIONS) JSON::try_parse(#NAME, NAME, OPTIONS)
<commit_msg>Fixed for rvalues.<commit_after>#pragma once
#include "jsd_core.hpp"
#include "jsd_check.hpp"
#include "jsd_options.hpp"
namespace JSON
{
template <typename T>
void try_parse(T& obj, std::string const& name, PropertyTree const& tree, ParsingOptions const& options = DEFAULT_PARSER_OPTIONS,
typename std::enable_if <Internal::can_parse<T>::value, void>::type* = nullptr)
{
parse(obj, name, tree, options);
}
template <typename T>
void try_parse(T&, std::string const&, PropertyTree const&, ParsingOptions const& = DEFAULT_PARSER_OPTIONS,
typename std::enable_if <!Internal::can_parse<T>::value, int>::type* = nullptr)
{
static_assert (Internal::can_parse<T>::value, "the object you try to parse has no applicable interface");
}
template <typename T>
T make_from_json(std::istream&& stream)
{
T res;
JSON::parse(res, "", JSON::parse_json(stream));
return res;
}
template <typename T>
T make_from_json(std::istream& stream)
{
T res;
JSON::parse(res, "", JSON::parse_json(stream));
return res;
}
template <typename T>
T make_from_json(std::string const& str)
{
T res;
JSON::parse(res, "", JSON::parse_json(str));
return res;
}
}
#define json_deserialize(NAME) JSON::try_parse(#NAME, NAME)
#define json_deserialize_opt(NAME, OPTIONS) JSON::try_parse(#NAME, NAME, OPTIONS)
<|endoftext|>
|
<commit_before>/*
*
* Copyright (C) 2004 Mekensleep
*
* Mekensleep
* 24 rue vieille du temple
* 75004 Paris
* licensing@mekensleep.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* 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
*
* Author:
* Igor Kravtchenko <igor@obraz.net>
*
*/
#include "hdrloader.h"
#include <math.h>
#include <memory.h>
#include <stdio.h>
typedef unsigned char RGBE[4];
#define R 0
#define G 1
#define B 2
#define E 3
#define MINELEN 8 // minimum scanline length for encoding
#define MAXELEN 0x7fff // maximum scanline length for encoding
static void workOnRGBE(RGBE *scan, int len, float *cols);
static bool decrunch(RGBE *scanline, int len, FILE *file);
static bool oldDecrunch(RGBE *scanline, int len, FILE *file);
bool HDRLoader::isHDRFile(const char *_fileName)
{
FILE *file;
file = fopen(_fileName, "rb");
if (!file)
return false;
char str[10];
fread(str, 10, 1, file);
fclose(file);
if (memcmp(str, "#?RADIANCE", 10) && memcmp(str, "#?RGBE", 6))
return false;
return true;
}
bool HDRLoader::load(const char *_fileName, HDRLoaderResult &_res)
{
int i;
char str[200];
FILE *file;
file = fopen(_fileName, "rb");
if (!file)
return false;
fread(str, 10, 1, file);
if (memcmp(str, "#?RADIANCE", 10)) {
fseek(file, 0, SEEK_SET);
fread(str, 6, 1, file);
if (memcmp(str, "#?RGBE", 6)) {
fclose(file);
return false;
}
}
fseek(file, 1, SEEK_CUR);
char cmd[2000];
i = 0;
char c = 0, oldc;
while(true) {
oldc = c;
c = fgetc(file);
if (c == 0xa && oldc == 0xa)
break;
cmd[i++] = c;
}
char reso[2000];
i = 0;
while(true) {
c = fgetc(file);
reso[i++] = c;
if (c == 0xa)
break;
}
int w, h;
if (!sscanf(reso, "-Y %ld +X %ld", &h, &w)) {
fclose(file);
return false;
}
_res.width = w;
_res.height = h;
float *cols = new float[w * h * 3];
_res.cols = cols;
RGBE *scanline = new RGBE[w];
if (!scanline) {
fclose(file);
return false;
}
// convert image
cols += (h-1) * w * 3;
for (int y = h - 1; y >= 0; y--) {
if (decrunch(scanline, w, file) == false)
break;
workOnRGBE(scanline, w, cols);
cols -= w * 3;
}
delete [] scanline;
fclose(file);
return true;
}
float convertComponent(int _expo, int _val)
{
float v = _val / 256.0f;
float d = powf(2, _expo);
return v * d;
}
void workOnRGBE(RGBE *_scan, int _len, float *_cols)
{
int ii = 0;
while (_len-- > 0) {
int expo = _scan[0][E] - 128;
_cols[0] = convertComponent(expo, _scan[0][R]);
_cols[1] = convertComponent(expo, _scan[0][G]);
_cols[2] = convertComponent(expo, _scan[0][B]);
_cols += 3;
_scan++;
ii++;
}
}
bool decrunch(RGBE *_scanline, int _len, FILE *_file)
{
int i, j;
if (_len < MINELEN || _len > MAXELEN)
return oldDecrunch(_scanline, _len, _file);
i = fgetc(_file);
if (i != 2) {
fseek(_file, -1, SEEK_CUR);
return oldDecrunch(_scanline, _len, _file);
}
_scanline[0][G] = fgetc(_file);
_scanline[0][B] = fgetc(_file);
i = fgetc(_file);
if (_scanline[0][G] != 2 || _scanline[0][B] & 128) {
_scanline[0][R] = 2;
_scanline[0][E] = i;
return oldDecrunch(_scanline + 1, _len - 1, _file);
}
// read each component
for (i = 0; i < 4; i++) {
for (j = 0; j < _len; ) {
unsigned char code = fgetc(_file);
if (code > 128) { // run
code &= 127;
unsigned char val = fgetc(_file);
while (code--)
_scanline[j++][i] = val;
}
else { // non-run
while(code--)
_scanline[j++][i] = fgetc(_file);
}
}
}
return feof(_file) ? false : true;
}
bool oldDecrunch(RGBE *_scanline, int _len, FILE *_file)
{
int i;
int rshift = 0;
while (_len > 0) {
_scanline[0][R] = fgetc(_file);
_scanline[0][G] = fgetc(_file);
_scanline[0][B] = fgetc(_file);
_scanline[0][E] = fgetc(_file);
if (feof(_file))
return false;
if (_scanline[0][R] == 1 &&
_scanline[0][G] == 1 &&
_scanline[0][B] == 1) {
for (i = _scanline[0][E] << rshift; i > 0; i--) {
memcpy(&_scanline[0][0], &_scanline[-1][0], 4);
_scanline++;
_len--;
}
rshift += 8;
}
else {
_scanline++;
_len--;
rshift = 0;
}
}
return true;
}
<commit_msg>Warning fixes by Mike Weiblen + Robert Osfield<commit_after>/*
*
* Copyright (C) 2004 Mekensleep
*
* Mekensleep
* 24 rue vieille du temple
* 75004 Paris
* licensing@mekensleep.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* 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
*
* Author:
* Igor Kravtchenko <igor@obraz.net>
*
*/
#include "hdrloader.h"
#include <math.h>
#include <memory.h>
#include <stdio.h>
typedef unsigned char RGBE[4];
#define R 0
#define G 1
#define B 2
#define E 3
#define MINELEN 8 // minimum scanline length for encoding
#define MAXELEN 0x7fff // maximum scanline length for encoding
static void workOnRGBE(RGBE *scan, int len, float *cols);
static bool decrunch(RGBE *scanline, int len, FILE *file);
static bool oldDecrunch(RGBE *scanline, int len, FILE *file);
bool HDRLoader::isHDRFile(const char *_fileName)
{
FILE *file;
file = fopen(_fileName, "rb");
if (!file)
return false;
char str[10];
fread(str, 10, 1, file);
fclose(file);
if (memcmp(str, "#?RADIANCE", 10) && memcmp(str, "#?RGBE", 6))
return false;
return true;
}
bool HDRLoader::load(const char *_fileName, HDRLoaderResult &_res)
{
int i;
char str[200];
FILE *file;
file = fopen(_fileName, "rb");
if (!file)
return false;
fread(str, 10, 1, file);
if (memcmp(str, "#?RADIANCE", 10)) {
fseek(file, 0, SEEK_SET);
fread(str, 6, 1, file);
if (memcmp(str, "#?RGBE", 6)) {
fclose(file);
return false;
}
}
fseek(file, 1, SEEK_CUR);
char cmd[2000];
i = 0;
char c = 0, oldc;
while(true) {
oldc = c;
c = fgetc(file);
if (c == 0xa && oldc == 0xa)
break;
cmd[i++] = c;
}
char reso[2000];
i = 0;
while(true) {
c = fgetc(file);
reso[i++] = c;
if (c == 0xa)
break;
}
int w, h;
if (!sscanf(reso, "-Y %d +X %d", &h, &w)) {
fclose(file);
return false;
}
_res.width = w;
_res.height = h;
float *cols = new float[w * h * 3];
_res.cols = cols;
RGBE *scanline = new RGBE[w];
if (!scanline) {
fclose(file);
return false;
}
// convert image
cols += (h-1) * w * 3;
for (int y = h - 1; y >= 0; y--) {
if (decrunch(scanline, w, file) == false)
break;
workOnRGBE(scanline, w, cols);
cols -= w * 3;
}
delete [] scanline;
fclose(file);
return true;
}
float convertComponent(int _expo, int _val)
{
float v = _val / 256.0f;
float d = powf(2.0f, (float)_expo);
return v * d;
}
void workOnRGBE(RGBE *_scan, int _len, float *_cols)
{
int ii = 0;
while (_len-- > 0) {
int expo = _scan[0][E] - 128;
_cols[0] = convertComponent(expo, _scan[0][R]);
_cols[1] = convertComponent(expo, _scan[0][G]);
_cols[2] = convertComponent(expo, _scan[0][B]);
_cols += 3;
_scan++;
ii++;
}
}
bool decrunch(RGBE *_scanline, int _len, FILE *_file)
{
int i, j;
if (_len < MINELEN || _len > MAXELEN)
return oldDecrunch(_scanline, _len, _file);
i = fgetc(_file);
if (i != 2) {
fseek(_file, -1, SEEK_CUR);
return oldDecrunch(_scanline, _len, _file);
}
_scanline[0][G] = fgetc(_file);
_scanline[0][B] = fgetc(_file);
i = fgetc(_file);
if (_scanline[0][G] != 2 || _scanline[0][B] & 128) {
_scanline[0][R] = 2;
_scanline[0][E] = i;
return oldDecrunch(_scanline + 1, _len - 1, _file);
}
// read each component
for (i = 0; i < 4; i++) {
for (j = 0; j < _len; ) {
unsigned char code = fgetc(_file);
if (code > 128) { // run
code &= 127;
unsigned char val = fgetc(_file);
while (code--)
_scanline[j++][i] = val;
}
else { // non-run
while(code--)
_scanline[j++][i] = fgetc(_file);
}
}
}
return feof(_file) ? false : true;
}
bool oldDecrunch(RGBE *_scanline, int _len, FILE *_file)
{
int i;
int rshift = 0;
while (_len > 0) {
_scanline[0][R] = fgetc(_file);
_scanline[0][G] = fgetc(_file);
_scanline[0][B] = fgetc(_file);
_scanline[0][E] = fgetc(_file);
if (feof(_file))
return false;
if (_scanline[0][R] == 1 &&
_scanline[0][G] == 1 &&
_scanline[0][B] == 1) {
for (i = _scanline[0][E] << rshift; i > 0; i--) {
memcpy(&_scanline[0][0], &_scanline[-1][0], 4);
_scanline++;
_len--;
}
rshift += 8;
}
else {
_scanline++;
_len--;
rshift = 0;
}
}
return true;
}
<|endoftext|>
|
<commit_before>#include <testutilscxx.h>
#include <stdexcept>
void
assert_equals(CuTest *tc,
const Frame &f1,
const Frame &f2)
{
real pos = f1.position().distance(f2.position());
CuAssertDblEquals(tc, 0, pos, POINT_EPSILON);
real tan = f1.tangent().distance(f2.tangent());
CuAssertDblEquals(tc, 0, tan, POINT_EPSILON);
real norm = f1.normal().distance(f2.normal());
CuAssertDblEquals(tc, 0, tan, POINT_EPSILON);
real binorm = f1.binormal().distance(f2.binormal());
CuAssertDblEquals(tc, 0, binorm, POINT_EPSILON);
}
void
assert_equals(CuTest *tc,
const FrameSeq &fs1,
const FrameSeq &fs2)
{
CuAssertIntEquals(tc, (int) fs1.size(), (int) fs2.size());
for (size_t i = 0; i < fs1.size(); i++)
assert_equals(tc, fs1.at(i), fs2.at(i));
}
void
assert_orthogonal(CuTest *tc,
const Vec3 &v1,
const Vec3 &v2)
{
real angle = v1.angle(v2);
CuAssertDblEquals(tc, 90, angle, ANGLE_EPSILON);
}
void
frames_frameseq_copy_ctor(CuTest *tc)
{
// Given
BSpline spline(7, 2);
spline.setControlPoints({
120, 100, // P1
270, 40, // P2
370, 490, // P3
590, 40, // P4
570, 490, // P5
420, 480, // P6
220, 500 // P7
});
FrameSeq frames = spline.computeRMF(
spline.uniformKnotSeq(10));
// When
FrameSeq copy(frames);
// Then
assert_equals(tc, frames, copy);
}
void
frames_frameseq_move_ctor(CuTest *tc)
{
// Given
BSpline spline(7, 2);
spline.setControlPoints({
120, 100, // P1
270, 40, // P2
370, 490, // P3
590, 40, // P4
570, 490, // P5
420, 480, // P6
220, 500 // P7
});
FrameSeq frames = spline.computeRMF(
spline.uniformKnotSeq(10));
FrameSeq toBeMoved(frames);
// When
FrameSeq move(std::move(toBeMoved));
// Then
assert_equals(tc, frames, move);
CuAssertIntEquals(tc, 0, (int) toBeMoved.size());
}
void
frames_frameseq_copy_assign(CuTest *tc)
{
// Given
BSpline spline(7, 2);
spline.setControlPoints({
120, 100, // P1
270, 40, // P2
370, 490, // P3
590, 40, // P4
570, 490, // P5
420, 480, // P6
220, 500 // P7
});
FrameSeq frames = spline.computeRMF(
spline.uniformKnotSeq(10));
FrameSeq copy;
// When
copy = frames;
// Then
assert_equals(tc, frames, copy);
}
void
frames_frameseq_move_assign(CuTest *tc)
{
// Given
BSpline spline(7, 2);
spline.setControlPoints({
120, 100, // P1
270, 40, // P2
370, 490, // P3
590, 40, // P4
570, 490, // P5
420, 480, // P6
220, 500 // P7
});
FrameSeq frames = spline.computeRMF(
spline.uniformKnotSeq(10));
FrameSeq toBeMoved(frames);
FrameSeq move;
// When
move = std::move(toBeMoved);
// Then
assert_equals(tc, frames, move);
CuAssertIntEquals(tc, 0, (int) toBeMoved.size());
}
void
frames_vectors(CuTest *tc)
{
// Given
BSpline spline(7, 2);
spline.setControlPoints({
120, 100, // P1
270, 40, // P2
370, 490, // P3
590, 40, // P4
570, 490, // P5
420, 480, // P6
220, 500 // P7
});
vector<real> knots = spline.uniformKnotSeq(100);
// When
FrameSeq frames = spline.computeRMF(knots);
// Then
for (size_t i = 0; i < knots.size(); i++) {
Frame frame = frames.at(i);
real pos = spline(knots[i])
.resultVec3()
.distance(frame.position());
CuAssertDblEquals(tc, 0, pos, POINT_EPSILON);
real tan = spline.derive()(knots[i])
.resultVec3()
.normalize()
.distance(frame.tangent());
CuAssertDblEquals(tc, 0, tan, POINT_EPSILON);
assert_orthogonal(tc, frame.normal(), frame.tangent());
assert_orthogonal(tc, frame.normal(), frame.binormal());
assert_orthogonal(tc, frame.binormal(), frame.tangent());
}
}
void
frames_frameseq_invalid_idx(CuTest *tc)
{
FrameSeq frames;
try {
frames.at(1);
} catch (out_of_range &ex) {
string what(ex.what());
CuAssertTrue(tc, what.length() > 0);
return;
}
CuFail(tc, "Expected exception");
}
void
frames_frameseq_to_string(CuTest *tc)
{
// When
FrameSeq frames;
// When
string s = frames.toString();
// Then
CuAssertTrue(tc, s.length() > 0);
}
CuSuite *
get_frames_suite()
{
CuSuite* suite = CuSuiteNew();
SUITE_ADD_TEST(suite, frames_vectors);
SUITE_ADD_TEST(suite, frames_frameseq_copy_ctor);
SUITE_ADD_TEST(suite, frames_frameseq_move_ctor);
SUITE_ADD_TEST(suite, frames_frameseq_copy_assign);
SUITE_ADD_TEST(suite, frames_frameseq_move_assign);
SUITE_ADD_TEST(suite, frames_frameseq_invalid_idx);
SUITE_ADD_TEST(suite, frames_frameseq_to_string);
return suite;
}
<commit_msg>fixed test case for norm<commit_after>#include <testutilscxx.h>
#include <stdexcept>
void
assert_equals(CuTest *tc,
const Frame &f1,
const Frame &f2)
{
real pos = f1.position().distance(f2.position());
CuAssertDblEquals(tc, 0, pos, POINT_EPSILON);
real tan = f1.tangent().distance(f2.tangent());
CuAssertDblEquals(tc, 0, tan, POINT_EPSILON);
real norm = f1.normal().distance(f2.normal());
CuAssertDblEquals(tc, 0, norm, POINT_EPSILON);
real binorm = f1.binormal().distance(f2.binormal());
CuAssertDblEquals(tc, 0, binorm, POINT_EPSILON);
}
void
assert_equals(CuTest *tc,
const FrameSeq &fs1,
const FrameSeq &fs2)
{
CuAssertIntEquals(tc, (int) fs1.size(), (int) fs2.size());
for (size_t i = 0; i < fs1.size(); i++)
assert_equals(tc, fs1.at(i), fs2.at(i));
}
void
assert_orthogonal(CuTest *tc,
const Vec3 &v1,
const Vec3 &v2)
{
real angle = v1.angle(v2);
CuAssertDblEquals(tc, 90, angle, ANGLE_EPSILON);
}
void
frames_frameseq_copy_ctor(CuTest *tc)
{
// Given
BSpline spline(7, 2);
spline.setControlPoints({
120, 100, // P1
270, 40, // P2
370, 490, // P3
590, 40, // P4
570, 490, // P5
420, 480, // P6
220, 500 // P7
});
FrameSeq frames = spline.computeRMF(
spline.uniformKnotSeq(10));
// When
FrameSeq copy(frames);
// Then
assert_equals(tc, frames, copy);
}
void
frames_frameseq_move_ctor(CuTest *tc)
{
// Given
BSpline spline(7, 2);
spline.setControlPoints({
120, 100, // P1
270, 40, // P2
370, 490, // P3
590, 40, // P4
570, 490, // P5
420, 480, // P6
220, 500 // P7
});
FrameSeq frames = spline.computeRMF(
spline.uniformKnotSeq(10));
FrameSeq toBeMoved(frames);
// When
FrameSeq move(std::move(toBeMoved));
// Then
assert_equals(tc, frames, move);
CuAssertIntEquals(tc, 0, (int) toBeMoved.size());
}
void
frames_frameseq_copy_assign(CuTest *tc)
{
// Given
BSpline spline(7, 2);
spline.setControlPoints({
120, 100, // P1
270, 40, // P2
370, 490, // P3
590, 40, // P4
570, 490, // P5
420, 480, // P6
220, 500 // P7
});
FrameSeq frames = spline.computeRMF(
spline.uniformKnotSeq(10));
FrameSeq copy;
// When
copy = frames;
// Then
assert_equals(tc, frames, copy);
}
void
frames_frameseq_move_assign(CuTest *tc)
{
// Given
BSpline spline(7, 2);
spline.setControlPoints({
120, 100, // P1
270, 40, // P2
370, 490, // P3
590, 40, // P4
570, 490, // P5
420, 480, // P6
220, 500 // P7
});
FrameSeq frames = spline.computeRMF(
spline.uniformKnotSeq(10));
FrameSeq toBeMoved(frames);
FrameSeq move;
// When
move = std::move(toBeMoved);
// Then
assert_equals(tc, frames, move);
CuAssertIntEquals(tc, 0, (int) toBeMoved.size());
}
void
frames_vectors(CuTest *tc)
{
// Given
BSpline spline(7, 2);
spline.setControlPoints({
120, 100, // P1
270, 40, // P2
370, 490, // P3
590, 40, // P4
570, 490, // P5
420, 480, // P6
220, 500 // P7
});
vector<real> knots = spline.uniformKnotSeq(100);
// When
FrameSeq frames = spline.computeRMF(knots);
// Then
for (size_t i = 0; i < knots.size(); i++) {
Frame frame = frames.at(i);
real pos = spline(knots[i])
.resultVec3()
.distance(frame.position());
CuAssertDblEquals(tc, 0, pos, POINT_EPSILON);
real tan = spline.derive()(knots[i])
.resultVec3()
.normalize()
.distance(frame.tangent());
CuAssertDblEquals(tc, 0, tan, POINT_EPSILON);
assert_orthogonal(tc, frame.normal(), frame.tangent());
assert_orthogonal(tc, frame.normal(), frame.binormal());
assert_orthogonal(tc, frame.binormal(), frame.tangent());
}
}
void
frames_frameseq_invalid_idx(CuTest *tc)
{
FrameSeq frames;
try {
frames.at(1);
} catch (out_of_range &ex) {
string what(ex.what());
CuAssertTrue(tc, what.length() > 0);
return;
}
CuFail(tc, "Expected exception");
}
void
frames_frameseq_to_string(CuTest *tc)
{
// When
FrameSeq frames;
// When
string s = frames.toString();
// Then
CuAssertTrue(tc, s.length() > 0);
}
CuSuite *
get_frames_suite()
{
CuSuite* suite = CuSuiteNew();
SUITE_ADD_TEST(suite, frames_vectors);
SUITE_ADD_TEST(suite, frames_frameseq_copy_ctor);
SUITE_ADD_TEST(suite, frames_frameseq_move_ctor);
SUITE_ADD_TEST(suite, frames_frameseq_copy_assign);
SUITE_ADD_TEST(suite, frames_frameseq_move_assign);
SUITE_ADD_TEST(suite, frames_frameseq_invalid_idx);
SUITE_ADD_TEST(suite, frames_frameseq_to_string);
return suite;
}
<|endoftext|>
|
<commit_before>#include "IShader.h"
#include "common/Exception.h"
#include <gl/glew.h>
#include <stdio.h>
#include <assert.h>
namespace d2d
{
IShader::IShader()
{
m_prog = 0;
}
IShader::~IShader()
{
DeleteShader();
}
void IShader::InitShader(const char* VS, const char* FS)
{
GLuint prog = glCreateProgram();
GLuint vs = CompileShader(VS, GL_VERTEX_SHADER);
if (vs == 0) {
return;
} else {
glAttachShader(prog, vs);
}
GLuint fs = CompileShader(FS, GL_FRAGMENT_SHADER);
if (fs == 0) {
return;
} else {
glAttachShader(prog, fs);
}
BindAttrib(prog);
// link
GLint status;
glLinkProgram(prog);
glGetProgramiv(prog, GL_LINK_STATUS, &status);
if (status == GL_FALSE) {
char buf[1024];
glGetProgramInfoLog(prog, 1024, NULL, buf);
throw d2d::Exception("link failed:%s\n", buf);
}
// detatch
glDetachShader(prog, fs);
glDeleteShader(fs);
glDetachShader(prog, vs);
glDeleteShader(vs);
m_prog = prog;
}
void IShader::DeleteShader()
{
glUseProgram(0);
glDeleteProgram(m_prog);
}
GLuint IShader::CompileShader(const char* source, GLuint type)
{
GLint status;
GLuint shader = glCreateShader(type);
glShaderSource(shader, 1, &source, NULL);
glCompileShader(shader);
glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
if (status == GL_FALSE) {
char buf[1024];
glGetShaderInfoLog(shader, 1024, NULL, buf);
glDeleteShader(shader);
throw d2d::Exception("compile failed:%s\n, source:\n %s\n", buf, source);
}
return shader;
}
}<commit_msg>[FIXED] 调整调BindAttrib的时机<commit_after>#include "IShader.h"
#include "common/Exception.h"
#include <gl/glew.h>
#include <stdio.h>
#include <assert.h>
namespace d2d
{
IShader::IShader()
{
m_prog = 0;
}
IShader::~IShader()
{
DeleteShader();
}
void IShader::InitShader(const char* VS, const char* FS)
{
GLuint prog = glCreateProgram();
GLuint vs = CompileShader(VS, GL_VERTEX_SHADER);
if (vs == 0) {
return;
} else {
glAttachShader(prog, vs);
}
GLuint fs = CompileShader(FS, GL_FRAGMENT_SHADER);
if (fs == 0) {
return;
} else {
glAttachShader(prog, fs);
}
// BindAttrib(prog);
// link
GLint status;
glLinkProgram(prog);
glGetProgramiv(prog, GL_LINK_STATUS, &status);
if (status == GL_FALSE) {
char buf[1024];
glGetProgramInfoLog(prog, 1024, NULL, buf);
throw d2d::Exception("link failed:%s\n", buf);
}
// detatch
glDetachShader(prog, fs);
glDeleteShader(fs);
glDetachShader(prog, vs);
glDeleteShader(vs);
m_prog = prog;
BindAttrib(prog);
}
void IShader::DeleteShader()
{
glUseProgram(0);
glDeleteProgram(m_prog);
}
GLuint IShader::CompileShader(const char* source, GLuint type)
{
GLint status;
GLuint shader = glCreateShader(type);
glShaderSource(shader, 1, &source, NULL);
glCompileShader(shader);
glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
if (status == GL_FALSE) {
char buf[1024];
glGetShaderInfoLog(shader, 1024, NULL, buf);
glDeleteShader(shader);
throw d2d::Exception("compile failed:%s\n, source:\n %s\n", buf, source);
}
return shader;
}
}<|endoftext|>
|
<commit_before>/* dtkComposerNodeMatrixSquareRealOperatorBinary.cpp ---
*
* Author: slekout
* Copyright (C) 2011 - Babette lekouta, Inria.
* Created: Thu Apr 26 15:58:22 2012 (+0200)
* Version: $Id$
* Last-Updated:
* By:
* Update #:
*/
/* Commentary:
*
*/
/* Change log:
*
*/
#include "dtkComposerNodeMatrixSquareRealOperatorBinary.h"
#include "dtkComposerTransmitterEmitter.h"
#include "dtkComposerTransmitterReceiver.h"
#include <dtkMath>
#include <dtkLog/dtkLog>
// /////////////////////////////////////////////////////////////////
// dtkComposerNodeMatrixSquareRealOperatorBinary
// /////////////////////////////////////////////////////////////////
class dtkComposerNodeMatrixSquareRealOperatorBinaryPrivate
{
public:
dtkComposerTransmitterReceiver<dtkMatrixSquareReal> receiver_lhs;
dtkComposerTransmitterReceiver<dtkMatrixSquareReal> receiver_rhs;
public:
dtkComposerTransmitterEmitter<dtkMatrixSquareReal> emitter_matrix;
public:
dtkMatrixSquareReal *matrix;
};
dtkComposerNodeMatrixSquareRealOperatorBinary::dtkComposerNodeMatrixSquareRealOperatorBinary(void) : dtkComposerNodeLeaf(), d(new dtkComposerNodeMatrixSquareRealOperatorBinaryPrivate)
{
d->matrix = NULL;
this->appendReceiver(&d->receiver_lhs);
this->appendReceiver(&d->receiver_rhs);
this->appendEmitter(&d->emitter_matrix);
}
dtkComposerNodeMatrixSquareRealOperatorBinary::~dtkComposerNodeMatrixSquareRealOperatorBinary(void)
{
if (d->matrix)
delete d->matrix;
d->matrix = NULL;
delete d;
d = NULL;
}
// /////////////////////////////////////////////////////////////////
// dtkComposerNodeMatrixSquareRealOperatorBinaryProductMV
// /////////////////////////////////////////////////////////////////
class dtkComposerNodeMatrixSquareRealOperatorBinaryProductMVPrivate
{
public:
dtkComposerTransmitterReceiver<dtkMatrixSquareReal> receiver_matrix;
dtkComposerTransmitterReceiver<dtkVectorReal> receiver_vector;
public:
dtkComposerTransmitterEmitter<dtkVectorReal> emitter_vector;
public:
dtkVectorReal *vector;
};
dtkComposerNodeMatrixSquareRealOperatorBinaryProductMV::dtkComposerNodeMatrixSquareRealOperatorBinaryProductMV(void) : dtkComposerNodeLeaf(), d(new dtkComposerNodeMatrixSquareRealOperatorBinaryProductMVPrivate)
{
d->vector = NULL;
this->appendReceiver(&d->receiver_matrix);
this->appendReceiver(&d->receiver_vector);
this->appendEmitter(&d->emitter_vector);
}
dtkComposerNodeMatrixSquareRealOperatorBinaryProductMV::~dtkComposerNodeMatrixSquareRealOperatorBinaryProductMV(void)
{
if (d->vector)
delete d->vector;
d->vector = NULL;
delete d;
d = NULL;
}
// /////////////////////////////////////////////////////////////////////////////
// dtkComposerNodeMatrixSquareRealOperatorBinaryReplaceColAndRowMatrixByVector
// /////////////////////////////////////////////////////////////////////////////
class dtkComposerNodeMatrixSquareRealOperatorBinaryReplaceColAndRowMatrixByVectorPrivate
{
public:
dtkComposerTransmitterReceiver<dtkMatrixSquareReal> receiver_matrix;
dtkComposerTransmitterReceiver<dtkVectorReal> receiver_vector;
dtkComposerTransmitterVariant receiver_index;
public:
dtkComposerTransmitterEmitter<dtkMatrixSquareReal> emitter_matrix;
};
dtkComposerNodeMatrixSquareRealOperatorBinaryReplaceColAndRowMatrixByVector::dtkComposerNodeMatrixSquareRealOperatorBinaryReplaceColAndRowMatrixByVector(void) : dtkComposerNodeLeaf(), d(new dtkComposerNodeMatrixSquareRealOperatorBinaryReplaceColAndRowMatrixByVectorPrivate)
{
this->appendReceiver(&d->receiver_matrix);
this->appendReceiver(&d->receiver_vector);
QList<int> variant_list;
variant_list << QMetaType::LongLong;
d->receiver_index.setDataTypes(variant_list);
this->appendReceiver(&d->receiver_index);
this->appendEmitter(&d->emitter_matrix);
}
dtkComposerNodeMatrixSquareRealOperatorBinaryReplaceColAndRowMatrixByVector::~dtkComposerNodeMatrixSquareRealOperatorBinaryReplaceColAndRowMatrixByVector(void)
{
delete d;
d = NULL;
}
// /////////////////////////////////////////////////////////////////
// dtkComposerNodeMatrixSquareRealOperatorBinary - Sum
// /////////////////////////////////////////////////////////////////
void dtkComposerNodeMatrixSquareRealOperatorBinarySum::run(void)
{
if (d->receiver_lhs.isEmpty() || d->receiver_rhs.isEmpty()) {
dtkWarn() << "Inputs not specified. Nothing is done";
if (d->matrix)
d->matrix->deallocate();
} else {
if (!d->matrix) {
d->matrix = new dtkMatrixSquareReal();
d->emitter_matrix.setData(d->matrix);
}
dtkMatrixSquareReal *m_lhs = d->receiver_lhs.data();
dtkMatrixSquareReal *m_rhs = d->receiver_rhs.data();
if (m_lhs->size() != m_rhs->size()) {
dtkWarn()<< "Input matrices do not have the same size. Nothing is done";
d->matrix->deallocate();
} else {
*(d->matrix) = (*m_lhs + *m_rhs);
}
}
}
// /////////////////////////////////////////////////////////////////
// dtkComposerNodeMatrixSquareRealOperatorBinary - Substract
// /////////////////////////////////////////////////////////////////
void dtkComposerNodeMatrixSquareRealOperatorBinarySubstract::run(void)
{
if (d->receiver_lhs.isEmpty() || d->receiver_rhs.isEmpty()) {
dtkWarn() << "Inputs not specified. Nothing is done";
if (d->matrix)
d->matrix->deallocate();
} else {
if (!d->matrix) {
d->matrix = new dtkMatrixSquareReal();
d->emitter_matrix.setData(d->matrix);
}
dtkMatrixSquareReal *m_lhs = d->receiver_lhs.data();
dtkMatrixSquareReal *m_rhs = d->receiver_rhs.data();
if (m_lhs->size() != m_rhs->size()) {
dtkWarn()<< "Input matrices do not have the same size. Nothing is done";
d->matrix->deallocate();
} else {
*(d->matrix) = (*m_lhs - *m_rhs);
}
}
}
// /////////////////////////////////////////////////////////////////
// dtkComposerNodeMatrixSquareRealOperatorBinary - Mult
// /////////////////////////////////////////////////////////////////
void dtkComposerNodeMatrixSquareRealOperatorBinaryMult::run(void)
{
if (d->receiver_lhs.isEmpty() || d->receiver_rhs.isEmpty()) {
dtkWarn() << "Inputs not specified. Nothing is done";
if (d->matrix)
d->matrix->deallocate();
} else {
if (!d->matrix) {
d->matrix = new dtkMatrixSquareReal();
d->emitter_matrix.setData(d->matrix);
}
dtkMatrixSquareReal *m_lhs = d->receiver_lhs.data();
dtkMatrixSquareReal *m_rhs = d->receiver_rhs.data();
if (m_lhs->size() != m_rhs->size()) {
dtkWarn()<< "Input matrices do not have the same size. Nothing is done";
d->matrix->deallocate();
} else {
*(d->matrix) = (*m_lhs - *m_rhs);
}
}
}
// ///////////////////////////////////////////////////////////////////////////////////
// dtkComposerNodeMatrixSquareRealOperatorBinaryProductMV - Product Matrix Vector
// //////////////////////////////////////////////////////////////////////////////////
void dtkComposerNodeMatrixSquareRealOperatorBinaryRightProductMV::run(void)
{
if (d->receiver_matrix.isEmpty() || d->receiver_vector.isEmpty()) {
dtkWarn() << "Inputs not specified. Nothing is done";
if (d->vector)
d->vector->deallocate();
} else {
if (!d->vector) {
d->vector = new dtkVectorReal();
d->emitter_vector.setData(d->vector);
}
dtkMatrixSquareReal *matrix = d->receiver_matrix.data();
dtkVectorReal *vector = d->receiver_vector.data();
if ( matrix->size() != vector->size() ) {
dtkWarn() << "Matrix's row and vector's column are different size. Nothing is done";
d->vector->deallocate();
} else {
*d->vector = (*matrix) * (*vector);
}
}
}
// /////////////////////////////////////////////////////////////////////////////////////
// dtkComposerNodeMatrixSquareRealOperatorBinaryProductMV - Product Vector Matrix
// ////////////////////////////////////////////////////////////////////////////////////
void dtkComposerNodeMatrixSquareRealOperatorBinaryLeftProductVM::run(void)
{
if (d->receiver_matrix.isEmpty() || d->receiver_vector.isEmpty()) {
dtkWarn() << "Inputs not specified. Nothing is done";
if (d->vector)
d->vector->deallocate();
} else {
dtkMatrixSquareReal *matrix = d->receiver_matrix.data();
dtkVectorReal *vector = d->receiver_vector.data();
if (!d->vector) {
d->vector = new dtkVectorReal();
d->emitter_vector.setData(d->vector);
}
if ( matrix->size() != vector->size() ) {
dtkWarn() << "Matrix's row and vector's column are different size. Nothing is done";
d->vector->deallocate();
} else {
d->vector->allocate(vector->size());
for(qlonglong i = 0; i < matrix->size(); ++i) {
for(qlonglong j = 0; j < vector->size(); ++j) {
(*d->vector)[i] += (*vector)[j] * (*matrix)[j][i] ;
}
}
}
}
}
// ///////////////////////////////////////////////////////////////////////////////////////////////////
// dtkComposerNodeMatrixSquareRealOperatorBinaryReplaceRowAndColMatrixByVector Replace Row to Matrix
// ///////////////////////////////////////////////////////////////////////////////////////////////////
void dtkComposerNodeMatrixSquareRealOperatorBinaryReplaceRowMatrixByVector::run(void)
{
if (d->receiver_matrix.isEmpty() || d->receiver_vector.isEmpty()) {
dtkWarn() << "Inputs not specified. Nothing is done";
d->emitter_matrix.clearData();
} else {
qlonglong row_index = *d->receiver_index.data<qlonglong>();
dtkMatrixSquareReal *matrix = d->receiver_matrix.data();
if (row_index >= matrix->size()) {
dtkWarn() << "Row index = " << row_index << " >= matrix size = " << matrix->size() << ". Nothing is done.";
d->emitter_matrix.clearData();
} else {
dtkVectorReal *vector = d->receiver_vector.data();
for(qlonglong j = 0; j < matrix->size(); ++j)
(*matrix)[row_index][j] = (*vector)[j];
d->emitter_matrix.setData(matrix);
}
}
}
// ////////////////////////////////////////////////////////////////////////////////////////////////////
// dtkComposerNodeMatrixSquareRealOperatorBinaryReplaceRowAndColMatrixByVector - Replace Col to Matrix
// ////////////////////////////////////////////////////////////////////////////////////////////////////
void dtkComposerNodeMatrixSquareRealOperatorBinaryReplaceColMatrixByVector::run(void)
{
if (d->receiver_matrix.isEmpty() || d->receiver_vector.isEmpty()) {
dtkWarn() << "Inputs not specified. Nothing is done";
d->emitter_matrix.clearData();
} else {
qlonglong col_index = *d->receiver_index.data<qlonglong>();
dtkMatrixSquareReal *matrix = d->receiver_matrix.data();
if (col_index >= matrix->size()) {
dtkWarn() << "Column index = " << col_index << " >= matrix size = " << matrix->size() << ". Nothing is done.";
d->emitter_matrix.clearData();
} else {
dtkVectorReal *vector = d->receiver_vector.data();
for(qlonglong i = 0; i < matrix->size(); ++i)
(*matrix)[i][col_index] = (*vector)[i];
d->emitter_matrix.setData(matrix);
}
}
}
<commit_msg>Fix bugs.<commit_after>/* dtkComposerNodeMatrixSquareRealOperatorBinary.cpp ---
*
* Author: slekout
* Copyright (C) 2011 - Babette lekouta, Inria.
* Created: Thu Apr 26 15:58:22 2012 (+0200)
* Version: $Id$
* Last-Updated:
* By:
* Update #:
*/
/* Commentary:
*
*/
/* Change log:
*
*/
#include "dtkComposerNodeMatrixSquareRealOperatorBinary.h"
#include "dtkComposerTransmitterEmitter.h"
#include "dtkComposerTransmitterReceiver.h"
#include <dtkMath>
#include <dtkLog/dtkLog>
// /////////////////////////////////////////////////////////////////
// dtkComposerNodeMatrixSquareRealOperatorBinary
// /////////////////////////////////////////////////////////////////
class dtkComposerNodeMatrixSquareRealOperatorBinaryPrivate
{
public:
dtkComposerTransmitterReceiver<dtkMatrixSquareReal> receiver_lhs;
dtkComposerTransmitterReceiver<dtkMatrixSquareReal> receiver_rhs;
public:
dtkComposerTransmitterEmitter<dtkMatrixSquareReal> emitter_matrix;
public:
dtkMatrixSquareReal *matrix;
};
dtkComposerNodeMatrixSquareRealOperatorBinary::dtkComposerNodeMatrixSquareRealOperatorBinary(void) : dtkComposerNodeLeaf(), d(new dtkComposerNodeMatrixSquareRealOperatorBinaryPrivate)
{
d->matrix = NULL;
this->appendReceiver(&d->receiver_lhs);
this->appendReceiver(&d->receiver_rhs);
this->appendEmitter(&d->emitter_matrix);
}
dtkComposerNodeMatrixSquareRealOperatorBinary::~dtkComposerNodeMatrixSquareRealOperatorBinary(void)
{
if (d->matrix)
delete d->matrix;
d->matrix = NULL;
delete d;
d = NULL;
}
// /////////////////////////////////////////////////////////////////
// dtkComposerNodeMatrixSquareRealOperatorBinaryProductMV
// /////////////////////////////////////////////////////////////////
class dtkComposerNodeMatrixSquareRealOperatorBinaryProductMVPrivate
{
public:
dtkComposerTransmitterReceiver<dtkMatrixSquareReal> receiver_matrix;
dtkComposerTransmitterReceiver<dtkVectorReal> receiver_vector;
public:
dtkComposerTransmitterEmitter<dtkVectorReal> emitter_vector;
public:
dtkVectorReal *vector;
};
dtkComposerNodeMatrixSquareRealOperatorBinaryProductMV::dtkComposerNodeMatrixSquareRealOperatorBinaryProductMV(void) : dtkComposerNodeLeaf(), d(new dtkComposerNodeMatrixSquareRealOperatorBinaryProductMVPrivate)
{
d->vector = NULL;
this->appendReceiver(&d->receiver_matrix);
this->appendReceiver(&d->receiver_vector);
this->appendEmitter(&d->emitter_vector);
}
dtkComposerNodeMatrixSquareRealOperatorBinaryProductMV::~dtkComposerNodeMatrixSquareRealOperatorBinaryProductMV(void)
{
if (d->vector)
delete d->vector;
d->vector = NULL;
delete d;
d = NULL;
}
// /////////////////////////////////////////////////////////////////////////////
// dtkComposerNodeMatrixSquareRealOperatorBinaryReplaceColAndRowMatrixByVector
// /////////////////////////////////////////////////////////////////////////////
class dtkComposerNodeMatrixSquareRealOperatorBinaryReplaceColAndRowMatrixByVectorPrivate
{
public:
dtkComposerTransmitterReceiver<dtkMatrixSquareReal> receiver_matrix;
dtkComposerTransmitterReceiver<dtkVectorReal> receiver_vector;
dtkComposerTransmitterVariant receiver_index;
public:
dtkComposerTransmitterEmitter<dtkMatrixSquareReal> emitter_matrix;
};
dtkComposerNodeMatrixSquareRealOperatorBinaryReplaceColAndRowMatrixByVector::dtkComposerNodeMatrixSquareRealOperatorBinaryReplaceColAndRowMatrixByVector(void) : dtkComposerNodeLeaf(), d(new dtkComposerNodeMatrixSquareRealOperatorBinaryReplaceColAndRowMatrixByVectorPrivate)
{
this->appendReceiver(&d->receiver_matrix);
this->appendReceiver(&d->receiver_vector);
QList<int> variant_list;
variant_list << QMetaType::LongLong;
d->receiver_index.setDataTypes(variant_list);
this->appendReceiver(&d->receiver_index);
this->appendEmitter(&d->emitter_matrix);
}
dtkComposerNodeMatrixSquareRealOperatorBinaryReplaceColAndRowMatrixByVector::~dtkComposerNodeMatrixSquareRealOperatorBinaryReplaceColAndRowMatrixByVector(void)
{
delete d;
d = NULL;
}
// /////////////////////////////////////////////////////////////////
// dtkComposerNodeMatrixSquareRealOperatorBinary - Sum
// /////////////////////////////////////////////////////////////////
void dtkComposerNodeMatrixSquareRealOperatorBinarySum::run(void)
{
if (d->receiver_lhs.isEmpty() || d->receiver_rhs.isEmpty()) {
dtkWarn() << "Inputs not specified. Nothing is done";
if (d->matrix)
d->matrix->deallocate();
} else {
if (!d->matrix) {
d->matrix = new dtkMatrixSquareReal();
d->emitter_matrix.setData(d->matrix);
}
const dtkMatrixSquareReal *m_lhs = d->receiver_lhs.constData();
const dtkMatrixSquareReal *m_rhs = d->receiver_rhs.constData();
if (m_lhs->size() != m_rhs->size()) {
dtkWarn()<< "Input matrices do not have the same size. Nothing is done";
d->matrix->deallocate();
} else {
*(d->matrix) = (*m_lhs + *m_rhs);
}
}
}
// /////////////////////////////////////////////////////////////////
// dtkComposerNodeMatrixSquareRealOperatorBinary - Substract
// /////////////////////////////////////////////////////////////////
void dtkComposerNodeMatrixSquareRealOperatorBinarySubstract::run(void)
{
if (d->receiver_lhs.isEmpty() || d->receiver_rhs.isEmpty()) {
dtkWarn() << "Inputs not specified. Nothing is done";
if (d->matrix)
d->matrix->deallocate();
} else {
if (!d->matrix) {
d->matrix = new dtkMatrixSquareReal();
d->emitter_matrix.setData(d->matrix);
}
const dtkMatrixSquareReal *m_lhs = d->receiver_lhs.constData();
const dtkMatrixSquareReal *m_rhs = d->receiver_rhs.constData();
if (m_lhs->size() != m_rhs->size()) {
dtkWarn()<< "Input matrices do not have the same size. Nothing is done";
d->matrix->deallocate();
} else {
*(d->matrix) = (*m_lhs - *m_rhs);
}
}
}
// /////////////////////////////////////////////////////////////////
// dtkComposerNodeMatrixSquareRealOperatorBinary - Mult
// /////////////////////////////////////////////////////////////////
void dtkComposerNodeMatrixSquareRealOperatorBinaryMult::run(void)
{
if (d->receiver_lhs.isEmpty() || d->receiver_rhs.isEmpty()) {
dtkWarn() << "Inputs not specified. Nothing is done";
if (d->matrix)
d->matrix->deallocate();
} else {
if (!d->matrix) {
d->matrix = new dtkMatrixSquareReal();
d->emitter_matrix.setData(d->matrix);
}
const dtkMatrixSquareReal *m_lhs = d->receiver_lhs.constData();
const dtkMatrixSquareReal *m_rhs = d->receiver_rhs.constData();
if (m_lhs->size() != m_rhs->size()) {
dtkWarn()<< "Input matrices do not have the same size. Nothing is done";
d->matrix->deallocate();
} else {
*(d->matrix) = (*m_lhs * *m_rhs);
}
}
}
// ///////////////////////////////////////////////////////////////////////////////////
// dtkComposerNodeMatrixSquareRealOperatorBinaryProductMV - Product Matrix Vector
// //////////////////////////////////////////////////////////////////////////////////
void dtkComposerNodeMatrixSquareRealOperatorBinaryRightProductMV::run(void)
{
if (d->receiver_matrix.isEmpty() || d->receiver_vector.isEmpty()) {
dtkWarn() << "Inputs not specified. Nothing is done";
if (d->vector)
d->vector->deallocate();
} else {
if (!d->vector) {
d->vector = new dtkVectorReal();
d->emitter_vector.setData(d->vector);
}
const dtkMatrixSquareReal *matrix = d->receiver_matrix.constData();
const dtkVectorReal *vector = d->receiver_vector.constData();
if ( matrix->size() != vector->size() ) {
dtkWarn() << "Matrix's row and vector's column are different size. Nothing is done";
d->vector->deallocate();
} else {
*d->vector = (*matrix) * (*vector);
}
}
}
// /////////////////////////////////////////////////////////////////////////////////////
// dtkComposerNodeMatrixSquareRealOperatorBinaryProductMV - Product Vector Matrix
// ////////////////////////////////////////////////////////////////////////////////////
void dtkComposerNodeMatrixSquareRealOperatorBinaryLeftProductVM::run(void)
{
if (d->receiver_matrix.isEmpty() || d->receiver_vector.isEmpty()) {
dtkWarn() << "Inputs not specified. Nothing is done";
if (d->vector)
d->vector->deallocate();
} else {
const dtkMatrixSquareReal *matrix = d->receiver_matrix.constData();
const dtkVectorReal *vector = d->receiver_vector.constData();
if (!d->vector) {
d->vector = new dtkVectorReal();
d->emitter_vector.setData(d->vector);
}
if ( matrix->size() != vector->size() ) {
dtkWarn() << "Matrix's row and vector's column are different size. Nothing is done";
d->vector->deallocate();
} else {
d->vector->allocate(vector->size());
for(qlonglong i = 0; i < matrix->size(); ++i) {
for(qlonglong j = 0; j < vector->size(); ++j) {
(*d->vector)[i] += (*vector)[j] * (*matrix)[j][i] ;
}
}
}
}
}
// ///////////////////////////////////////////////////////////////////////////////////////////////////
// dtkComposerNodeMatrixSquareRealOperatorBinaryReplaceRowAndColMatrixByVector Replace Row to Matrix
// ///////////////////////////////////////////////////////////////////////////////////////////////////
void dtkComposerNodeMatrixSquareRealOperatorBinaryReplaceRowMatrixByVector::run(void)
{
if (d->receiver_matrix.isEmpty() || d->receiver_vector.isEmpty()) {
dtkWarn() << "Inputs not specified. Nothing is done";
d->emitter_matrix.clearData();
} else {
qlonglong row_index = *d->receiver_index.data<qlonglong>();
dtkMatrixSquareReal *matrix = d->receiver_matrix.data();
if (row_index >= matrix->size()) {
dtkWarn() << "Row index = " << row_index << " >= matrix size = " << matrix->size() << ". Nothing is done.";
d->emitter_matrix.clearData();
} else {
const dtkVectorReal *vector = d->receiver_vector.constData();
for(qlonglong j = 0; j < matrix->size(); ++j)
(*matrix)[row_index][j] = (*vector)[j];
d->emitter_matrix.setData(matrix);
}
}
}
// ////////////////////////////////////////////////////////////////////////////////////////////////////
// dtkComposerNodeMatrixSquareRealOperatorBinaryReplaceRowAndColMatrixByVector - Replace Col to Matrix
// ////////////////////////////////////////////////////////////////////////////////////////////////////
void dtkComposerNodeMatrixSquareRealOperatorBinaryReplaceColMatrixByVector::run(void)
{
if (d->receiver_matrix.isEmpty() || d->receiver_vector.isEmpty()) {
dtkWarn() << "Inputs not specified. Nothing is done";
d->emitter_matrix.clearData();
} else {
qlonglong col_index = *d->receiver_index.data<qlonglong>();
dtkMatrixSquareReal *matrix = d->receiver_matrix.data();
if (col_index >= matrix->size()) {
dtkWarn() << "Column index = " << col_index << " >= matrix size = " << matrix->size() << ". Nothing is done.";
d->emitter_matrix.clearData();
} else {
const dtkVectorReal *vector = d->receiver_vector.constData();
for(qlonglong i = 0; i < matrix->size(); ++i)
(*matrix)[i][col_index] = (*vector)[i];
d->emitter_matrix.setData(matrix);
}
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2009 Griffin Software
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "MetalScrollPCH.h"
#include "Connect.h"
#include "MetalBar.h"
#include "ColorChip.h"
extern CAddInModule _AtlModule;
CComPtr<EnvDTE80::DTE2> g_dte;
CComPtr<EnvDTE::AddIn> g_addInInstance;
CComPtr<IVsTextManager> g_textMgr;
// {454DB430-837D-4435-B7C1-F503B93EDA04} is the GUID for the marker service we register in MetalScrollPackage.rgs.
static const GUID g_markerServGUID = { 0x454DB430, 0x837D, 0x4435, { 0xB7, 0xC1, 0xF5, 0x03, 0xB9, 0x3E, 0xDA, 0x04 } };
// {FF447164-72F9-42ed-A767-C737B86BBD0B} is the GUID for the marker type.
static const GUID g_markerTypeGUID = { 0xFF447164, 0x72F9, 0x42ed, { 0xA7, 0x67, 0xC7, 0x37, 0xB8, 0x6B, 0xBD, 0x0B } };
CConnect::CConnect()
{
m_textMgrEventsCookie = 0;
}
bool CConnect::GetTextManagerEventsPlug(IConnectionPoint** connPt)
{
CComQIPtr<IConnectionPointContainer> connPoints = g_textMgr;
if(!connPoints)
return false;
HRESULT hr = connPoints->FindConnectionPoint(__uuidof(IVsTextManagerEvents), connPt);
return SUCCEEDED(hr) && *connPt;
}
bool CConnect::GetTextViewEventsPlug(IConnectionPoint** connPt, IVsTextView* view)
{
CComQIPtr<IConnectionPointContainer> connPoints = view;
if(!connPoints)
return false;
HRESULT hr = connPoints->FindConnectionPoint(__uuidof(IVsTextViewEvents), connPt);
return SUCCEEDED(hr) && *connPt;
}
STDMETHODIMP CConnect::OnConnection(IDispatch* application, ext_ConnectMode /*connectMode*/, IDispatch* addInInst, SAFEARRAY** /*custom*/)
{
HRESULT hr = application->QueryInterface(__uuidof(EnvDTE80::DTE2), (void**)&g_dte);
if(FAILED(hr))
return hr;
hr = addInInst->QueryInterface(__uuidof(EnvDTE::AddIn), (void**)&g_addInInstance);
if(FAILED(hr))
return hr;
CComQIPtr<IServiceProvider> sp = g_dte;
if(!sp)
return E_NOINTERFACE;
hr = sp->QueryService(SID_SVsTextManager, IID_IVsTextManager, (void**)&g_textMgr);
if(FAILED(hr) || !g_textMgr)
return E_NOINTERFACE;
CComPtr<IConnectionPoint> connPt;
if(!GetTextManagerEventsPlug(&connPt))
return E_NOINTERFACE;
hr = connPt->Advise((IVsTextManagerEvents*)this, &m_textMgrEventsCookie);
if(FAILED(hr))
return hr;
CComPtr<IProfferService> profferServ;
hr = sp->QueryService(SID_SProfferService, IID_IProfferService, (void**)&profferServ);
if(FAILED(hr) || !profferServ)
return E_NOINTERFACE;
DWORD cookie;
hr = profferServ->ProfferService(g_markerServGUID, (IServiceProvider*)this, &cookie);
if(FAILED(hr))
return hr;
MetalBar::ReadSettings();
ColorChip::Register();
return S_OK;
}
STDMETHODIMP CConnect::OnDisconnection(ext_DisconnectMode /*removeMode*/, SAFEARRAY** /*custom*/)
{
CComPtr<IConnectionPoint> textMgrEventsPlug;
if(m_textMgrEventsCookie && GetTextManagerEventsPlug(&textMgrEventsPlug))
{
textMgrEventsPlug->Unadvise(m_textMgrEventsCookie);
m_textMgrEventsCookie = 0;
}
MetalBar::RemoveAllBars();
ColorChip::Unregister();
// Give up the global pointers.
g_textMgr = 0;
g_addInInstance = 0;
g_dte = 0;
return S_OK;
}
void STDMETHODCALLTYPE CConnect::OnRegisterView(IVsTextView* view)
{
// Unfortunately, the window hasn't been created at this point yet, so we can't get the HWND
// here. Register an even handler to catch SetFocus(), and get the HWND from there. We'll remove
// the handler after the first SetFocus() as we don't care about getting more events once we
// have the HWND.
CComPtr<IConnectionPoint> connPt;
if(!GetTextViewEventsPlug(&connPt, view))
return;
DWORD cookie;
connPt->Advise((IVsTextViewEvents*)this, &cookie);
}
struct ScrollbarHandles
{
HWND vert;
HWND horiz;
};
static BOOL CALLBACK FindScrollbars(HWND hwnd, LPARAM param)
{
ScrollbarHandles* handles = (ScrollbarHandles*)param;
char className[64];
GetClassNameA(hwnd, className, _countof(className));
if(strcmp(className, "ScrollBar") == 0)
{
LONG styles = GetWindowLong(hwnd, GWL_STYLE);
if(styles & SBS_VERT)
handles->vert = hwnd;
else
handles->horiz = hwnd;
}
return TRUE;
}
static LRESULT FAR PASCAL ScrollBarProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam)
{
MetalBar* bar = (MetalBar*)GetWindowLongPtr(hwnd, GWL_USERDATA);
if(!bar)
return 0;
return bar->WndProc(hwnd, message, wparam, lparam);
}
void CConnect::HookScrollbar(IVsTextView* view)
{
HWND editorHwnd = view->GetWindowHandle();
if(!editorHwnd)
return;
ScrollbarHandles bars = { 0 };
EnumChildWindows(GetParent(editorHwnd), FindScrollbars, (LPARAM)&bars);
if(!bars.horiz || !bars.vert)
return;
if(GetWindowLongPtr(bars.vert, GWL_USERDATA) != 0)
return;
WNDPROC oldProc = (WNDPROC)SetWindowLongPtr(bars.vert, GWLP_WNDPROC, (::LONG_PTR)ScrollBarProc);
MetalBar* bar = new MetalBar(bars.vert, editorHwnd, bars.horiz, oldProc, view);
SetWindowLongPtr(bars.vert, GWL_USERDATA, (::LONG_PTR)bar);
}
void STDMETHODCALLTYPE CConnect::OnSetFocus(IVsTextView* view)
{
HookScrollbar(view);
// Remove ourselves from the event list. Since we can't store the cookie we got
// when we registered the event handler, we'll have to scan the event list looking
// for our pointer.
CComPtr<IConnectionPoint> connPt;
if(!GetTextViewEventsPlug(&connPt, view))
return;
CComPtr<IEnumConnections> enumerator;
HRESULT hr = connPt->EnumConnections(&enumerator);
if(FAILED(hr) || !enumerator)
return;
CONNECTDATA connData;
ULONG numRet;
bool found = false;
while( SUCCEEDED(enumerator->Next(1, &connData, &numRet)) && (numRet > 0) )
{
if(connData.pUnk == (IVsTextViewEvents*)this)
{
connPt->Unadvise(connData.dwCookie);
found = true;
}
connData.pUnk->Release();
}
}
STDMETHODIMP CConnect::QueryService(REFGUID guidService, REFIID riid, void** object)
{
if(!object)
return E_POINTER;
if(!InlineIsEqualGUID(guidService, g_markerServGUID))
return E_NOINTERFACE;
if(!IsEqualIID(riid, __uuidof(IVsTextMarkerTypeProvider)))
return E_NOINTERFACE;
*object = (IVsTextMarkerTypeProvider*)this;
((IVsTextMarkerTypeProvider*)this)->AddRef();
return S_OK;
}
STDMETHODIMP CConnect::GetTextMarkerType(GUID* guidMarker, IVsPackageDefinedTextMarkerType** markerType)
{
if(!markerType)
return E_POINTER;
if(!InlineIsEqualGUID(*guidMarker, g_markerTypeGUID))
return E_NOINTERFACE;
*markerType = (IVsPackageDefinedTextMarkerType*)this;
(*markerType)->AddRef();
return S_OK;
}
STDMETHODIMP CConnect::GetVisualStyle(DWORD* visualFlags)
{
*visualFlags = MV_COLOR_ALWAYS;
return S_OK;
}
STDMETHODIMP CConnect::GetDefaultColors(COLORINDEX* foreground, COLORINDEX* background)
{
*foreground = CI_BLACK;
*background = CI_CYAN;
return S_OK;
}
STDMETHODIMP CConnect::GetDefaultLineStyle(COLORINDEX* lineColor, LINESTYLE* lineIndex)
{
// This shouldn't be called because we haven't requested MV_LINE or MV_BORDER.
*lineColor = CI_BLACK;
*lineIndex = LI_SOLID;
return S_OK;
}
STDMETHODIMP CConnect::GetDefaultFontFlags(DWORD* fontFlags)
{
*fontFlags = FF_DEFAULT;
return S_OK;
}
STDMETHODIMP CConnect::DrawGlyphWithColors(HDC /*hdc*/, RECT* /*rect*/, long /*markerType*/, IVsTextMarkerColorSet* /*markerColors*/, DWORD /*glyphDrawFlags*/, long /*lineHeight*/)
{
// This shouldn't be called because we haven't requested MV_GLYPH.
return S_OK;
}
STDMETHODIMP CConnect::GetBehaviorFlags(DWORD* flags)
{
*flags = MB_DEFAULT;
return S_OK;
}
STDMETHODIMP CConnect::GetPriorityIndex(long* priorityIndex)
{
*priorityIndex = 100;
return S_OK;
}
<commit_msg>COM paranoia.<commit_after>/*
* Copyright 2009 Griffin Software
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "MetalScrollPCH.h"
#include "Connect.h"
#include "MetalBar.h"
#include "ColorChip.h"
extern CAddInModule _AtlModule;
CComPtr<EnvDTE80::DTE2> g_dte;
CComPtr<EnvDTE::AddIn> g_addInInstance;
CComPtr<IVsTextManager> g_textMgr;
// {454DB430-837D-4435-B7C1-F503B93EDA04} is the GUID for the marker service we register in MetalScrollPackage.rgs.
static const GUID g_markerServGUID = { 0x454DB430, 0x837D, 0x4435, { 0xB7, 0xC1, 0xF5, 0x03, 0xB9, 0x3E, 0xDA, 0x04 } };
// {FF447164-72F9-42ed-A767-C737B86BBD0B} is the GUID for the marker type.
static const GUID g_markerTypeGUID = { 0xFF447164, 0x72F9, 0x42ed, { 0xA7, 0x67, 0xC7, 0x37, 0xB8, 0x6B, 0xBD, 0x0B } };
CConnect::CConnect()
{
m_textMgrEventsCookie = 0;
}
bool CConnect::GetTextManagerEventsPlug(IConnectionPoint** connPt)
{
CComQIPtr<IConnectionPointContainer> connPoints = g_textMgr;
if(!connPoints)
return false;
HRESULT hr = connPoints->FindConnectionPoint(__uuidof(IVsTextManagerEvents), connPt);
return SUCCEEDED(hr) && *connPt;
}
bool CConnect::GetTextViewEventsPlug(IConnectionPoint** connPt, IVsTextView* view)
{
CComQIPtr<IConnectionPointContainer> connPoints = view;
if(!connPoints)
return false;
HRESULT hr = connPoints->FindConnectionPoint(__uuidof(IVsTextViewEvents), connPt);
return SUCCEEDED(hr) && *connPt;
}
STDMETHODIMP CConnect::OnConnection(IDispatch* application, ext_ConnectMode /*connectMode*/, IDispatch* addInInst, SAFEARRAY** /*custom*/)
{
HRESULT hr = application->QueryInterface(__uuidof(EnvDTE80::DTE2), (void**)&g_dte);
if(FAILED(hr))
return hr;
hr = addInInst->QueryInterface(__uuidof(EnvDTE::AddIn), (void**)&g_addInInstance);
if(FAILED(hr))
return hr;
CComQIPtr<IServiceProvider> sp = g_dte;
if(!sp)
return E_NOINTERFACE;
hr = sp->QueryService(SID_SVsTextManager, IID_IVsTextManager, (void**)&g_textMgr);
if(FAILED(hr) || !g_textMgr)
return E_NOINTERFACE;
CComPtr<IConnectionPoint> connPt;
if(!GetTextManagerEventsPlug(&connPt))
return E_NOINTERFACE;
hr = connPt->Advise((IVsTextManagerEvents*)this, &m_textMgrEventsCookie);
if(FAILED(hr))
return hr;
CComPtr<IProfferService> profferServ;
hr = sp->QueryService(SID_SProfferService, IID_IProfferService, (void**)&profferServ);
if(FAILED(hr) || !profferServ)
return E_NOINTERFACE;
DWORD cookie;
hr = profferServ->ProfferService(g_markerServGUID, (IServiceProvider*)this, &cookie);
if(FAILED(hr))
return hr;
MetalBar::ReadSettings();
ColorChip::Register();
return S_OK;
}
STDMETHODIMP CConnect::OnDisconnection(ext_DisconnectMode /*removeMode*/, SAFEARRAY** /*custom*/)
{
CComPtr<IConnectionPoint> textMgrEventsPlug;
if(m_textMgrEventsCookie && GetTextManagerEventsPlug(&textMgrEventsPlug))
{
textMgrEventsPlug->Unadvise(m_textMgrEventsCookie);
m_textMgrEventsCookie = 0;
}
MetalBar::RemoveAllBars();
ColorChip::Unregister();
// Give up the global pointers.
g_textMgr = 0;
g_addInInstance = 0;
g_dte = 0;
return S_OK;
}
void STDMETHODCALLTYPE CConnect::OnRegisterView(IVsTextView* view)
{
// Unfortunately, the window hasn't been created at this point yet, so we can't get the HWND
// here. Register an even handler to catch SetFocus(), and get the HWND from there. We'll remove
// the handler after the first SetFocus() as we don't care about getting more events once we
// have the HWND.
CComPtr<IConnectionPoint> connPt;
if(!GetTextViewEventsPlug(&connPt, view))
return;
DWORD cookie;
connPt->Advise((IVsTextViewEvents*)this, &cookie);
}
struct ScrollbarHandles
{
HWND vert;
HWND horiz;
};
static BOOL CALLBACK FindScrollbars(HWND hwnd, LPARAM param)
{
ScrollbarHandles* handles = (ScrollbarHandles*)param;
char className[64];
GetClassNameA(hwnd, className, _countof(className));
if(strcmp(className, "ScrollBar") == 0)
{
LONG styles = GetWindowLong(hwnd, GWL_STYLE);
if(styles & SBS_VERT)
handles->vert = hwnd;
else
handles->horiz = hwnd;
}
return TRUE;
}
static LRESULT FAR PASCAL ScrollBarProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam)
{
MetalBar* bar = (MetalBar*)GetWindowLongPtr(hwnd, GWL_USERDATA);
if(!bar)
return 0;
return bar->WndProc(hwnd, message, wparam, lparam);
}
void CConnect::HookScrollbar(IVsTextView* view)
{
HWND editorHwnd = view->GetWindowHandle();
if(!editorHwnd)
return;
ScrollbarHandles bars = { 0 };
EnumChildWindows(GetParent(editorHwnd), FindScrollbars, (LPARAM)&bars);
if(!bars.horiz || !bars.vert)
return;
if(GetWindowLongPtr(bars.vert, GWL_USERDATA) != 0)
return;
WNDPROC oldProc = (WNDPROC)SetWindowLongPtr(bars.vert, GWLP_WNDPROC, (::LONG_PTR)ScrollBarProc);
MetalBar* bar = new MetalBar(bars.vert, editorHwnd, bars.horiz, oldProc, view);
SetWindowLongPtr(bars.vert, GWL_USERDATA, (::LONG_PTR)bar);
}
void STDMETHODCALLTYPE CConnect::OnSetFocus(IVsTextView* view)
{
HookScrollbar(view);
// Remove ourselves from the event list. Since we can't store the cookie we got
// when we registered the event handler, we'll have to scan the event list looking
// for our pointer.
CComPtr<IConnectionPoint> connPt;
if(!GetTextViewEventsPlug(&connPt, view))
return;
CComPtr<IEnumConnections> enumerator;
HRESULT hr = connPt->EnumConnections(&enumerator);
if(FAILED(hr) || !enumerator)
return;
CONNECTDATA connData;
ULONG numRet;
bool found = false;
while( SUCCEEDED(enumerator->Next(1, &connData, &numRet)) && (numRet > 0) )
{
if(connData.pUnk == (IVsTextViewEvents*)this)
{
connPt->Unadvise(connData.dwCookie);
found = true;
}
connData.pUnk->Release();
}
}
STDMETHODIMP CConnect::QueryService(REFGUID guidService, REFIID riid, void** object)
{
if(!object)
return E_POINTER;
if(!InlineIsEqualGUID(guidService, g_markerServGUID))
return E_NOINTERFACE;
if(!IsEqualIID(riid, __uuidof(IVsTextMarkerTypeProvider)))
return E_NOINTERFACE;
*object = (IVsTextMarkerTypeProvider*)this;
((IVsTextMarkerTypeProvider*)this)->AddRef();
return S_OK;
}
STDMETHODIMP CConnect::GetTextMarkerType(GUID* guidMarker, IVsPackageDefinedTextMarkerType** markerType)
{
if(!markerType)
return E_POINTER;
if(!InlineIsEqualGUID(*guidMarker, g_markerTypeGUID))
return E_NOINTERFACE;
*markerType = (IVsPackageDefinedTextMarkerType*)this;
(*markerType)->AddRef();
return S_OK;
}
STDMETHODIMP CConnect::GetVisualStyle(DWORD* visualFlags)
{
if(!visualFlags)
return E_POINTER;
*visualFlags = MV_COLOR_ALWAYS;
return S_OK;
}
STDMETHODIMP CConnect::GetDefaultColors(COLORINDEX* foreground, COLORINDEX* background)
{
if(!foreground || !background)
return E_POINTER;
*foreground = CI_BLACK;
*background = CI_CYAN;
return S_OK;
}
STDMETHODIMP CConnect::GetDefaultLineStyle(COLORINDEX* lineColor, LINESTYLE* lineIndex)
{
// This shouldn't be called because we haven't requested MV_LINE or MV_BORDER.
if(!lineColor || !lineIndex)
return E_POINTER;
*lineColor = CI_BLACK;
*lineIndex = LI_SOLID;
return S_OK;
}
STDMETHODIMP CConnect::GetDefaultFontFlags(DWORD* fontFlags)
{
if(!fontFlags)
return E_POINTER;
*fontFlags = FF_DEFAULT;
return S_OK;
}
STDMETHODIMP CConnect::DrawGlyphWithColors(HDC /*hdc*/, RECT* /*rect*/, long /*markerType*/, IVsTextMarkerColorSet* /*markerColors*/, DWORD /*glyphDrawFlags*/, long /*lineHeight*/)
{
// This shouldn't be called because we haven't requested MV_GLYPH.
return S_OK;
}
STDMETHODIMP CConnect::GetBehaviorFlags(DWORD* flags)
{
if(!flags)
return E_POINTER;
*flags = MB_DEFAULT;
return S_OK;
}
STDMETHODIMP CConnect::GetPriorityIndex(long* priorityIndex)
{
if(!priorityIndex)
return E_POINTER;
*priorityIndex = 100;
return S_OK;
}
<|endoftext|>
|
<commit_before><commit_msg>Dead function prototypes gone.<commit_after><|endoftext|>
|
<commit_before>// This file is part of Parsito <http://github.com/ufal/parsito/>.
//
// Copyright 2015 Institute of Formal and Applied Linguistics, Faculty of
// Mathematics and Physics, Charles University in Prague, Czech Republic.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include <algorithm>
#include <atomic>
#include <fstream>
#include <limits>
#include <random>
#include <thread>
#include <unordered_set>
#include "network/neural_network_trainer.h"
#include "parser_nn.h"
#include "parser_nn_trainer.h"
#include "utils/parse_double.h"
#include "utils/parse_int.h"
#include "utils/split.h"
namespace ufal {
namespace parsito {
void parser_nn_trainer::train(const string& transition_system_name, const string& transition_oracle_name,
const string& embeddings_description, const string& nodes_description, const network_parameters& parameters,
unsigned number_of_threads, const vector<tree>& train, const vector<tree>& heldout, binary_encoder& enc) {
if (train.empty()) runtime_failure("No training data was given!");
// Random generator with fixed seed for reproducibility
mt19937 generator(42);
// Check that all non-root nodes have heads and nonempty deprel
for (auto&& tree : train)
for (auto&& node : tree.nodes)
if (node.id) {
if (node.head < 0) runtime_failure("The node '" << node.form << "' with id " << node.id << " has no head set!");
if (node.deprel.empty()) runtime_failure("The node '" << node.form << "' with id " << node.id << " has no deprel set!");
}
// Generate labels for transition system
parser_nn parser;
unordered_set<string> labels_set;
for (auto&& tree : train)
for (auto&& node : tree.nodes)
if (node.id && !labels_set.count(node.deprel)) {
labels_set.insert(node.deprel);
parser.labels.push_back(node.deprel);
}
// Create transition system and transition oracle
parser.system.reset(transition_system::create(transition_system_name, parser.labels));
if (!parser.system) runtime_failure("Cannot create transition system '" << transition_system_name << "'!");
unique_ptr<transition_oracle> oracle(parser.system->oracle(transition_oracle_name));
if (!oracle) runtime_failure("Cannot create transition oracle '" << transition_oracle_name << "' for transition system '" << transition_system_name << "'!");
// Create node_extractor
string error;
if (!parser.nodes.create(nodes_description, error)) runtime_failure(error);
// Load value_extractors and embeddings
vector<string> value_names;
vector<string_piece> lines, tokens;
split(embeddings_description, '\n', lines);
for (auto&& line : lines) {
// Ignore empty lines and comments
if (!line.len || line.str[0] == '#') continue;
split(line, ' ', tokens);
if (!(tokens.size() >= 3 && tokens.size() <= 6))
runtime_failure("Expected 3 to 6 columns on embedding description line '" << line << "'!");
value_names.emplace_back(string(tokens[0].str, tokens[0].len));
parser.values.emplace_back();
if (!parser.values.back().create(tokens[0], error)) runtime_failure(error);
int dimension = parse_int(tokens[1], "embedding dimension");
int min_count = parse_int(tokens[2], "minimum frequency count");
unsigned updatable_index = 0;
unsigned embeddings_from_file = 0;
string embeddings_from_file_comment;
vector<pair<string, vector<float>>> weights;
unordered_set<string> weights_set;
// Compute words and counts present in the training data
string word;
unordered_map<string, int> word_counts;
for (auto&& tree : train)
for (auto&& node : tree.nodes)
if (node.id) {
parser.values.back().extract(node, word);
word_counts[word]++;
}
// Load embedding if it was given
if (tokens.size() >= 4) {
int update_weights = tokens.size() >= 5 ? parse_int(tokens[4], "update weights") : 1;
int max_embeddings = tokens.size() >= 6 ? parse_int(tokens[5], "maximum embeddings count") : numeric_limits<int>::max();
ifstream in(string(tokens[3].str, tokens[3].len));
if (!in.is_open()) runtime_failure("Cannot load '" << tokens[0] << "' embedding from file '" << tokens[3] << "'!");
// Load first line containing dictionary size and dimensions
string line;
vector<string_piece> parts;
if (!getline(in, line)) runtime_failure("Cannot read first line from embedding file '" << tokens[3] << "'!");
split(line, ' ', parts);
if (parts.size() != 2) runtime_failure("Expected two numbers on the first line of embedding file '" << tokens[3] << "'!");
int file_dimension = parse_int(parts[1], "embedding file dimension");
if (file_dimension < dimension) runtime_failure("The embedding file '" << tokens[3] << "' has lower dimension than required!");
// Generate random projection when smaller dimension is required
vector<vector<float>> projection;
if (file_dimension > dimension) {
embeddings_from_file_comment = "[dim" + to_string(file_dimension) + "->" + to_string(dimension) + "]";
uniform_real_distribution<double> uniform(0, 1);
projection.resize(dimension);
for (auto&& row : projection) {
row.resize(file_dimension);
for (auto&& weight : row) weight = uniform(generator);
double sum = 0;
for (auto&& weight : row) sum += weight;
for (auto&& weight : row) weight /= sum;
}
}
// Load input embedding
vector<double> input_weights(file_dimension);
vector<float> projected_weights(dimension);
while (getline(in, line) && int(weights.size()) < max_embeddings) {
split(line, ' ', parts);
if (!parts.empty() && !parts.back().len) parts.pop_back(); // Ignore space at the end of line
if (int(parts.size()) != file_dimension + 1) runtime_failure("Wrong number of values on line '" << line << "' of embedding file '" << tokens[3]);
for (int i = 0; i < file_dimension; i++)
input_weights[i] = parse_double(parts[1 + i], "embedding weight");
string word(parts[0].str, parts[0].len);
// For update_weights == 2, ignore embeddings for unknown words
if (update_weights == 2 && !word_counts.count(word))
continue;
for (int i = 0; i < dimension; i++)
if (file_dimension == dimension) {
projected_weights[i] = input_weights[i];
} else {
projected_weights[i] = 0;
for (int j = 0; j < file_dimension; j++)
projected_weights[i] += projection[i][j] * input_weights[j];
}
if (!weights_set.count(word)) {
weights.emplace_back(word, projected_weights);
weights_set.insert(word);
}
}
embeddings_from_file = weights.size();
updatable_index = update_weights ? 0 : embeddings_from_file;
}
// Add embedding for non-present word with min_count
{
vector<float> word_weights(dimension);
uniform_real_distribution<float> uniform(-1, 1);
for (auto&& word_count : word_counts)
if (word_count.second >= min_count && !weights_set.count(word_count.first)) {
for (auto&& word_weight : word_weights)
word_weight = uniform(generator);
weights.emplace_back(word_count.first, word_weights);
}
}
// If there are unknown words in the training data, create initial embedding
vector<float> unknown_weights(dimension);
if (min_count > 1) {
uniform_real_distribution<float> uniform(-1, 1);
for (auto&& weight : unknown_weights)
weight = uniform(generator);
}
// Add the embedding
parser.embeddings.emplace_back();
parser.embeddings.back().create(dimension, updatable_index, weights, unknown_weights);
// Count the cover of this embedding
string buffer;
unsigned words_total = 0, words_covered = 0, words_covered_from_file = 0;
for (auto&& tree : train)
for (auto&& node : tree.nodes)
if (node.id) {
parser.values.back().extract(node, word);
words_total++;
int word_id = parser.embeddings.back().lookup_word(word, buffer);
words_covered += word_id != parser.embeddings.back().unknown_word();
words_covered_from_file += word_id != parser.embeddings.back().unknown_word() && unsigned(word_id) < embeddings_from_file;
}
cerr << "Initialized '" << tokens[0] << "' embedding with " << embeddings_from_file << embeddings_from_file_comment
<< "," << weights.size() << " words and " << fixed << setprecision(1) << 100. * words_covered_from_file / words_total
<< "%," << 100. * words_covered / words_total << "% coverage." << endl;
}
// Train the network
unsigned total_dimension = 0, total_nodes = 0;
for (auto&& embedding : parser.embeddings) total_dimension += embedding.dimension;
for (auto&& tree : train) total_nodes += tree.nodes.size() - 1;
auto scaled_parameters = parameters;
scaled_parameters.l1_regularization /= train.size();
scaled_parameters.l2_regularization /= total_nodes;
neural_network_trainer network_trainer(parser.network, total_dimension * parser.nodes.node_count(), parser.system->transition_count(), scaled_parameters, generator);
vector<int> permutation;
for (size_t i = 0; i < train.size(); i++)
permutation.push_back(permutation.size());
for (int iteration = 1; network_trainer.next_iteration(); iteration++) {
// Train on training data
shuffle(permutation.begin(), permutation.end(), generator);
atomic<unsigned> atomic_index(0);
atomic<double> atomic_logprob(0);
auto training = [&]() {
tree t;
configuration conf;
string word, word_buffer;
vector<vector<int>> nodes_embeddings;
vector<int> extracted_nodes;
vector<const vector<int>*> extracted_embeddings;
neural_network_trainer::workspace workspace;
double logprob = 0;
for (unsigned current_index; (current_index = atomic_index++) < permutation.size();) {
const tree& gold = train[permutation[current_index]];
t = gold;
t.unlink_all_nodes();
conf.init(&t);
// Compute embeddings
if (t.nodes.size() > nodes_embeddings.size()) nodes_embeddings.resize(t.nodes.size());
for (size_t i = 0; i < t.nodes.size(); i++) {
nodes_embeddings[i].resize(parser.embeddings.size());
for (size_t j = 0; j < parser.embeddings.size(); j++) {
parser.values[j].extract(t.nodes[i], word);
nodes_embeddings[i][j] = parser.embeddings[j].lookup_word(word, word_buffer);
}
}
// Train the network
while (!conf.final()) {
// Extract nodes
parser.nodes.extract(conf, extracted_nodes);
extracted_embeddings.resize(extracted_nodes.size());
for (size_t i = 0; i < extracted_nodes.size(); i++)
extracted_embeddings[i] = extracted_nodes[i] >= 0 ? &nodes_embeddings[extracted_nodes[i]] : nullptr;
// Propagate
network_trainer.propagate(parser.embeddings, extracted_embeddings, workspace);
// Find most probable applicable transition
int network_best = -1;
for (unsigned i = 0; i < workspace.outcomes.size(); i++)
if (parser.system->applicable(conf, i) && (network_best < 0 || workspace.outcomes[i] > workspace.outcomes[network_best]))
network_best = i;
// Apply the oracle
auto prediction = oracle->predict(conf, gold, network_best);
// Update logprob
if (workspace.outcomes[prediction.best])
logprob += log(workspace.outcomes[prediction.best]);
// Backpropagate the chosen outcome
network_trainer.backpropagate(parser.embeddings, extracted_embeddings, prediction.best, workspace);
// Follow the chosen outcome
int child = parser.system->perform(conf, prediction.to_follow);
// If a node was linked, recompute its embeddings as deprel has changed
if (child >= 0)
for (size_t i = 0; i < parser.embeddings.size(); i++) {
parser.values[i].extract(t.nodes[child], word);
nodes_embeddings[child][i] = parser.embeddings[i].lookup_word(word, word_buffer);
}
}
network_trainer.finalize_sentence();
}
for (double old_atomic_logprob = atomic_logprob; atomic_logprob.compare_exchange_weak(old_atomic_logprob, old_atomic_logprob + logprob); ) {}
};
cerr << "Iteration " << iteration << ": ";
if (number_of_threads > 1) {
vector<thread> threads;
for (unsigned i = 0; i < number_of_threads; i++) threads.emplace_back(training);
for (; !threads.empty(); threads.pop_back()) threads.back().join();
} else {
training();
}
cerr << "training logprob " << scientific << setprecision(4) << atomic_logprob;
// Evaluate heldout data if present
if (!heldout.empty()) {
network_trainer.finalize_dropout_weights();
tree t;
unsigned total = 0, correct_unlabelled = 0, correct_labelled = 0;
for (auto&& gold : heldout) {
t = gold;
t.unlink_all_nodes();
parser.parse(t);
for (size_t i = 1; i < t.nodes.size(); i++) {
total++;
correct_unlabelled += t.nodes[i].head == gold.nodes[i].head;
correct_labelled += t.nodes[i].head == gold.nodes[i].head && t.nodes[i].deprel == gold.nodes[i].deprel;
}
}
network_trainer.finalize_dropout_weights(false);
cerr << ", heldout UAS " << fixed << setprecision(2) << (100. * correct_unlabelled / total) << "%, LAS " << (100. * correct_labelled / total) << "%";
}
cerr << endl;
}
network_trainer.finalize_dropout_weights();
// Encode transition system
enc.add_2B(parser.labels.size());
for (auto&& label : parser.labels)
enc.add_str(label);
enc.add_str(transition_system_name);
// Encode nodes selector
enc.add_str(nodes_description);
// Encode value extractors and embeddings
enc.add_2B(value_names.size());
for (auto&& value_name : value_names)
enc.add_str(value_name);
for (auto&& embedding : parser.embeddings)
embedding.save(enc);
// Encode the network
network_trainer.save_network(enc);
}
} // namespace parsito
} // namespace ufal
<commit_msg>Allow oracle to return inapplicable transition.<commit_after>// This file is part of Parsito <http://github.com/ufal/parsito/>.
//
// Copyright 2015 Institute of Formal and Applied Linguistics, Faculty of
// Mathematics and Physics, Charles University in Prague, Czech Republic.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include <algorithm>
#include <atomic>
#include <fstream>
#include <limits>
#include <random>
#include <thread>
#include <unordered_set>
#include "network/neural_network_trainer.h"
#include "parser_nn.h"
#include "parser_nn_trainer.h"
#include "utils/parse_double.h"
#include "utils/parse_int.h"
#include "utils/split.h"
namespace ufal {
namespace parsito {
void parser_nn_trainer::train(const string& transition_system_name, const string& transition_oracle_name,
const string& embeddings_description, const string& nodes_description, const network_parameters& parameters,
unsigned number_of_threads, const vector<tree>& train, const vector<tree>& heldout, binary_encoder& enc) {
if (train.empty()) runtime_failure("No training data was given!");
// Random generator with fixed seed for reproducibility
mt19937 generator(42);
// Check that all non-root nodes have heads and nonempty deprel
for (auto&& tree : train)
for (auto&& node : tree.nodes)
if (node.id) {
if (node.head < 0) runtime_failure("The node '" << node.form << "' with id " << node.id << " has no head set!");
if (node.deprel.empty()) runtime_failure("The node '" << node.form << "' with id " << node.id << " has no deprel set!");
}
// Generate labels for transition system
parser_nn parser;
unordered_set<string> labels_set;
for (auto&& tree : train)
for (auto&& node : tree.nodes)
if (node.id && !labels_set.count(node.deprel)) {
labels_set.insert(node.deprel);
parser.labels.push_back(node.deprel);
}
// Create transition system and transition oracle
parser.system.reset(transition_system::create(transition_system_name, parser.labels));
if (!parser.system) runtime_failure("Cannot create transition system '" << transition_system_name << "'!");
unique_ptr<transition_oracle> oracle(parser.system->oracle(transition_oracle_name));
if (!oracle) runtime_failure("Cannot create transition oracle '" << transition_oracle_name << "' for transition system '" << transition_system_name << "'!");
// Create node_extractor
string error;
if (!parser.nodes.create(nodes_description, error)) runtime_failure(error);
// Load value_extractors and embeddings
vector<string> value_names;
vector<string_piece> lines, tokens;
split(embeddings_description, '\n', lines);
for (auto&& line : lines) {
// Ignore empty lines and comments
if (!line.len || line.str[0] == '#') continue;
split(line, ' ', tokens);
if (!(tokens.size() >= 3 && tokens.size() <= 6))
runtime_failure("Expected 3 to 6 columns on embedding description line '" << line << "'!");
value_names.emplace_back(string(tokens[0].str, tokens[0].len));
parser.values.emplace_back();
if (!parser.values.back().create(tokens[0], error)) runtime_failure(error);
int dimension = parse_int(tokens[1], "embedding dimension");
int min_count = parse_int(tokens[2], "minimum frequency count");
unsigned updatable_index = 0;
unsigned embeddings_from_file = 0;
string embeddings_from_file_comment;
vector<pair<string, vector<float>>> weights;
unordered_set<string> weights_set;
// Compute words and counts present in the training data
string word;
unordered_map<string, int> word_counts;
for (auto&& tree : train)
for (auto&& node : tree.nodes)
if (node.id) {
parser.values.back().extract(node, word);
word_counts[word]++;
}
// Load embedding if it was given
if (tokens.size() >= 4) {
int update_weights = tokens.size() >= 5 ? parse_int(tokens[4], "update weights") : 1;
int max_embeddings = tokens.size() >= 6 ? parse_int(tokens[5], "maximum embeddings count") : numeric_limits<int>::max();
ifstream in(string(tokens[3].str, tokens[3].len));
if (!in.is_open()) runtime_failure("Cannot load '" << tokens[0] << "' embedding from file '" << tokens[3] << "'!");
// Load first line containing dictionary size and dimensions
string line;
vector<string_piece> parts;
if (!getline(in, line)) runtime_failure("Cannot read first line from embedding file '" << tokens[3] << "'!");
split(line, ' ', parts);
if (parts.size() != 2) runtime_failure("Expected two numbers on the first line of embedding file '" << tokens[3] << "'!");
int file_dimension = parse_int(parts[1], "embedding file dimension");
if (file_dimension < dimension) runtime_failure("The embedding file '" << tokens[3] << "' has lower dimension than required!");
// Generate random projection when smaller dimension is required
vector<vector<float>> projection;
if (file_dimension > dimension) {
embeddings_from_file_comment = "[dim" + to_string(file_dimension) + "->" + to_string(dimension) + "]";
uniform_real_distribution<double> uniform(0, 1);
projection.resize(dimension);
for (auto&& row : projection) {
row.resize(file_dimension);
for (auto&& weight : row) weight = uniform(generator);
double sum = 0;
for (auto&& weight : row) sum += weight;
for (auto&& weight : row) weight /= sum;
}
}
// Load input embedding
vector<double> input_weights(file_dimension);
vector<float> projected_weights(dimension);
while (getline(in, line) && int(weights.size()) < max_embeddings) {
split(line, ' ', parts);
if (!parts.empty() && !parts.back().len) parts.pop_back(); // Ignore space at the end of line
if (int(parts.size()) != file_dimension + 1) runtime_failure("Wrong number of values on line '" << line << "' of embedding file '" << tokens[3]);
for (int i = 0; i < file_dimension; i++)
input_weights[i] = parse_double(parts[1 + i], "embedding weight");
string word(parts[0].str, parts[0].len);
// For update_weights == 2, ignore embeddings for unknown words
if (update_weights == 2 && !word_counts.count(word))
continue;
for (int i = 0; i < dimension; i++)
if (file_dimension == dimension) {
projected_weights[i] = input_weights[i];
} else {
projected_weights[i] = 0;
for (int j = 0; j < file_dimension; j++)
projected_weights[i] += projection[i][j] * input_weights[j];
}
if (!weights_set.count(word)) {
weights.emplace_back(word, projected_weights);
weights_set.insert(word);
}
}
embeddings_from_file = weights.size();
updatable_index = update_weights ? 0 : embeddings_from_file;
}
// Add embedding for non-present word with min_count
{
vector<float> word_weights(dimension);
uniform_real_distribution<float> uniform(-1, 1);
for (auto&& word_count : word_counts)
if (word_count.second >= min_count && !weights_set.count(word_count.first)) {
for (auto&& word_weight : word_weights)
word_weight = uniform(generator);
weights.emplace_back(word_count.first, word_weights);
}
}
// If there are unknown words in the training data, create initial embedding
vector<float> unknown_weights(dimension);
if (min_count > 1) {
uniform_real_distribution<float> uniform(-1, 1);
for (auto&& weight : unknown_weights)
weight = uniform(generator);
}
// Add the embedding
parser.embeddings.emplace_back();
parser.embeddings.back().create(dimension, updatable_index, weights, unknown_weights);
// Count the cover of this embedding
string buffer;
unsigned words_total = 0, words_covered = 0, words_covered_from_file = 0;
for (auto&& tree : train)
for (auto&& node : tree.nodes)
if (node.id) {
parser.values.back().extract(node, word);
words_total++;
int word_id = parser.embeddings.back().lookup_word(word, buffer);
words_covered += word_id != parser.embeddings.back().unknown_word();
words_covered_from_file += word_id != parser.embeddings.back().unknown_word() && unsigned(word_id) < embeddings_from_file;
}
cerr << "Initialized '" << tokens[0] << "' embedding with " << embeddings_from_file << embeddings_from_file_comment
<< "," << weights.size() << " words and " << fixed << setprecision(1) << 100. * words_covered_from_file / words_total
<< "%," << 100. * words_covered / words_total << "% coverage." << endl;
}
// Train the network
unsigned total_dimension = 0, total_nodes = 0;
for (auto&& embedding : parser.embeddings) total_dimension += embedding.dimension;
for (auto&& tree : train) total_nodes += tree.nodes.size() - 1;
auto scaled_parameters = parameters;
scaled_parameters.l1_regularization /= train.size();
scaled_parameters.l2_regularization /= total_nodes;
neural_network_trainer network_trainer(parser.network, total_dimension * parser.nodes.node_count(), parser.system->transition_count(), scaled_parameters, generator);
vector<int> permutation;
for (size_t i = 0; i < train.size(); i++)
permutation.push_back(permutation.size());
for (int iteration = 1; network_trainer.next_iteration(); iteration++) {
// Train on training data
shuffle(permutation.begin(), permutation.end(), generator);
atomic<unsigned> atomic_index(0);
atomic<double> atomic_logprob(0);
auto training = [&]() {
tree t;
configuration conf;
string word, word_buffer;
vector<vector<int>> nodes_embeddings;
vector<int> extracted_nodes;
vector<const vector<int>*> extracted_embeddings;
neural_network_trainer::workspace workspace;
double logprob = 0;
for (unsigned current_index; (current_index = atomic_index++) < permutation.size();) {
const tree& gold = train[permutation[current_index]];
t = gold;
t.unlink_all_nodes();
conf.init(&t);
// Compute embeddings
if (t.nodes.size() > nodes_embeddings.size()) nodes_embeddings.resize(t.nodes.size());
for (size_t i = 0; i < t.nodes.size(); i++) {
nodes_embeddings[i].resize(parser.embeddings.size());
for (size_t j = 0; j < parser.embeddings.size(); j++) {
parser.values[j].extract(t.nodes[i], word);
nodes_embeddings[i][j] = parser.embeddings[j].lookup_word(word, word_buffer);
}
}
// Train the network
while (!conf.final()) {
// Extract nodes
parser.nodes.extract(conf, extracted_nodes);
extracted_embeddings.resize(extracted_nodes.size());
for (size_t i = 0; i < extracted_nodes.size(); i++)
extracted_embeddings[i] = extracted_nodes[i] >= 0 ? &nodes_embeddings[extracted_nodes[i]] : nullptr;
// Propagate
network_trainer.propagate(parser.embeddings, extracted_embeddings, workspace);
// Find most probable applicable transition
int network_best = -1;
for (unsigned i = 0; i < workspace.outcomes.size(); i++)
if (parser.system->applicable(conf, i) && (network_best < 0 || workspace.outcomes[i] > workspace.outcomes[network_best]))
network_best = i;
// Apply the oracle
auto prediction = oracle->predict(conf, gold, network_best);
// If the best transition is applicable, train on it
if (parser.system->applicable(conf, prediction.best)) {
// Update logprob
if (workspace.outcomes[prediction.best])
logprob += log(workspace.outcomes[prediction.best]);
// Backpropagate the chosen outcome
network_trainer.backpropagate(parser.embeddings, extracted_embeddings, prediction.best, workspace);
}
// Emergency break if the to_follow transition is not applicable
if (!parser.system->applicable(conf, prediction.to_follow))
break;
// Follow the chosen outcome
int child = parser.system->perform(conf, prediction.to_follow);
// If a node was linked, recompute its embeddings as deprel has changed
if (child >= 0)
for (size_t i = 0; i < parser.embeddings.size(); i++) {
parser.values[i].extract(t.nodes[child], word);
nodes_embeddings[child][i] = parser.embeddings[i].lookup_word(word, word_buffer);
}
}
network_trainer.finalize_sentence();
}
for (double old_atomic_logprob = atomic_logprob; atomic_logprob.compare_exchange_weak(old_atomic_logprob, old_atomic_logprob + logprob); ) {}
};
cerr << "Iteration " << iteration << ": ";
if (number_of_threads > 1) {
vector<thread> threads;
for (unsigned i = 0; i < number_of_threads; i++) threads.emplace_back(training);
for (; !threads.empty(); threads.pop_back()) threads.back().join();
} else {
training();
}
cerr << "training logprob " << scientific << setprecision(4) << atomic_logprob;
// Evaluate heldout data if present
if (!heldout.empty()) {
network_trainer.finalize_dropout_weights();
tree t;
unsigned total = 0, correct_unlabelled = 0, correct_labelled = 0;
for (auto&& gold : heldout) {
t = gold;
t.unlink_all_nodes();
parser.parse(t);
for (size_t i = 1; i < t.nodes.size(); i++) {
total++;
correct_unlabelled += t.nodes[i].head == gold.nodes[i].head;
correct_labelled += t.nodes[i].head == gold.nodes[i].head && t.nodes[i].deprel == gold.nodes[i].deprel;
}
}
network_trainer.finalize_dropout_weights(false);
cerr << ", heldout UAS " << fixed << setprecision(2) << (100. * correct_unlabelled / total) << "%, LAS " << (100. * correct_labelled / total) << "%";
}
cerr << endl;
}
network_trainer.finalize_dropout_weights();
// Encode transition system
enc.add_2B(parser.labels.size());
for (auto&& label : parser.labels)
enc.add_str(label);
enc.add_str(transition_system_name);
// Encode nodes selector
enc.add_str(nodes_description);
// Encode value extractors and embeddings
enc.add_2B(value_names.size());
for (auto&& value_name : value_names)
enc.add_str(value_name);
for (auto&& embedding : parser.embeddings)
embedding.save(enc);
// Encode the network
network_trainer.save_network(enc);
}
} // namespace parsito
} // namespace ufal
<|endoftext|>
|
<commit_before>#include "prefixedoutstream.h"
#include <string>
#include <iostream>
#include <streambuf>
#include <string.h>
using namespace mlpack::io;
PrefixedOutStream& PrefixedOutStream::operator<< (bool& val) {
BaseLogic<bool&>(val);
return *this;
}
PrefixedOutStream& PrefixedOutStream::operator<< (short& val) {
BaseLogic<short&>(val);
return *this;
}
PrefixedOutStream& PrefixedOutStream::operator<< (unsigned short& val) {
BaseLogic<unsigned short&>(val);
return *this;
}
PrefixedOutStream& PrefixedOutStream::operator<< (int& val) {
BaseLogic<int&>(val);
return *this;
}
PrefixedOutStream& PrefixedOutStream::operator<< (unsigned int& val) {
BaseLogic<unsigned int&>(val);
return *this;
}
PrefixedOutStream& PrefixedOutStream::operator<< (long& val) {
BaseLogic<long&>(val);
return *this;
}
PrefixedOutStream& PrefixedOutStream::operator<< (unsigned long& val) {
BaseLogic<unsigned long&>(val);
return *this;
}
PrefixedOutStream& PrefixedOutStream::operator<< (float& val) {
BaseLogic<float&>(val);
return *this;
}
PrefixedOutStream& PrefixedOutStream::operator<< (double& val) {
BaseLogic<double&>(val);
return *this;
}
PrefixedOutStream& PrefixedOutStream::operator<< (long double& val) {
BaseLogic<long double&>(val);
return *this;
}
PrefixedOutStream& PrefixedOutStream::operator<< (void* val) {
BaseLogic<void*>(val);
return *this;
}
PrefixedOutStream& PrefixedOutStream::operator<< (const char* str) {
BaseLogic<const char*>(str);
// No need to worry about platform-independent newline characters; because
// stdout and stderr are text-mode streams, they do the relevant conversions
// automatically.
if (strstr(str, "\n") != NULL) {
carriageReturned = true;
if (fatal) // Terminate application.
exit(1);
}
return *this;
}
PrefixedOutStream& PrefixedOutStream::operator<< (std::string& str) {
BaseLogic<std::string&>(str);
// No need to worry about platform-independent newline characters; because
// stdout and stderr are text-mode streams, they do the relevant conversions
// automatically.
if (str.find("\n") != std::string::npos) {
carriageReturned = true;
if (fatal) // Terminate application.
exit(1);
}
return *this;
}
PrefixedOutStream& PrefixedOutStream::operator<< (std::streambuf* sb) {
destination << sb;
return *this;
}
PrefixedOutStream& PrefixedOutStream::operator<<
(std::ostream& (*pf) (std::ostream&)) {
// We don't want to prefix on what will show up as empty lines.
destination << pf;
carriageReturned = true;
if (fatal) // Terminate application.
exit(1);
return *this;
}
PrefixedOutStream& PrefixedOutStream::operator<< (std::ios& (*pf) (std::ios&)) {
BaseLogic<std::ios& (*) (std::ios&)>(pf);
return *this;
}
PrefixedOutStream& PrefixedOutStream::operator<<
(std::ios_base& (*pf) (std::ios_base&)) {
BaseLogic<std::ios_base& (*) (std::ios_base&)>(pf);
return *this;
}
<commit_msg>Oops, this isn't included by default.<commit_after>#include "prefixedoutstream.h"
#include <string>
#include <iostream>
#include <streambuf>
#include <string.h>
#include <stdlib.h>
using namespace mlpack::io;
PrefixedOutStream& PrefixedOutStream::operator<< (bool& val) {
BaseLogic<bool&>(val);
return *this;
}
PrefixedOutStream& PrefixedOutStream::operator<< (short& val) {
BaseLogic<short&>(val);
return *this;
}
PrefixedOutStream& PrefixedOutStream::operator<< (unsigned short& val) {
BaseLogic<unsigned short&>(val);
return *this;
}
PrefixedOutStream& PrefixedOutStream::operator<< (int& val) {
BaseLogic<int&>(val);
return *this;
}
PrefixedOutStream& PrefixedOutStream::operator<< (unsigned int& val) {
BaseLogic<unsigned int&>(val);
return *this;
}
PrefixedOutStream& PrefixedOutStream::operator<< (long& val) {
BaseLogic<long&>(val);
return *this;
}
PrefixedOutStream& PrefixedOutStream::operator<< (unsigned long& val) {
BaseLogic<unsigned long&>(val);
return *this;
}
PrefixedOutStream& PrefixedOutStream::operator<< (float& val) {
BaseLogic<float&>(val);
return *this;
}
PrefixedOutStream& PrefixedOutStream::operator<< (double& val) {
BaseLogic<double&>(val);
return *this;
}
PrefixedOutStream& PrefixedOutStream::operator<< (long double& val) {
BaseLogic<long double&>(val);
return *this;
}
PrefixedOutStream& PrefixedOutStream::operator<< (void* val) {
BaseLogic<void*>(val);
return *this;
}
PrefixedOutStream& PrefixedOutStream::operator<< (const char* str) {
BaseLogic<const char*>(str);
// No need to worry about platform-independent newline characters; because
// stdout and stderr are text-mode streams, they do the relevant conversions
// automatically.
if (strstr(str, "\n") != NULL) {
carriageReturned = true;
if (fatal) // Terminate application.
exit(1);
}
return *this;
}
PrefixedOutStream& PrefixedOutStream::operator<< (std::string& str) {
BaseLogic<std::string&>(str);
// No need to worry about platform-independent newline characters; because
// stdout and stderr are text-mode streams, they do the relevant conversions
// automatically.
if (str.find("\n") != std::string::npos) {
carriageReturned = true;
if (fatal) // Terminate application.
exit(1);
}
return *this;
}
PrefixedOutStream& PrefixedOutStream::operator<< (std::streambuf* sb) {
destination << sb;
return *this;
}
PrefixedOutStream& PrefixedOutStream::operator<<
(std::ostream& (*pf) (std::ostream&)) {
// We don't want to prefix on what will show up as empty lines.
destination << pf;
carriageReturned = true;
if (fatal) // Terminate application.
exit(1);
return *this;
}
PrefixedOutStream& PrefixedOutStream::operator<< (std::ios& (*pf) (std::ios&)) {
BaseLogic<std::ios& (*) (std::ios&)>(pf);
return *this;
}
PrefixedOutStream& PrefixedOutStream::operator<<
(std::ios_base& (*pf) (std::ios_base&)) {
BaseLogic<std::ios_base& (*) (std::ios_base&)>(pf);
return *this;
}
<|endoftext|>
|
<commit_before>#include "continuous_fmm.h"
int main(int argc, char *argv[]) {
// Initialize FastExec (parameter handling stuff).
fx_init(argc, argv, NULL);
////////// READING PARAMETERS AND LOADING DATA /////////////////////
// FASTexec organizes parameters and results into submodules. Think
// of this as creating a new folder named "cfmm_module" under the
// root directory (NULL) for the continuous FMM object to work
// inside. Here, we initialize it with all parameters defined
// "--cfmm/...=...".
struct datanode* cfmm_module = fx_submodule(fx_root, "cfmm");
// The reference data file is a required parameter.
const char* references_file_name = fx_param_str_req(fx_root, "data");
// The query data file defaults to the references.
const char* queries_file_name =
fx_param_str(fx_root, "query", references_file_name);
// Query and reference datasets, reference weight dataset, and the
// reference bandwidth dataset.
Matrix references;
Matrix reference_weights;
Matrix reference_bandwidths;
Matrix queries;
// Flag for telling whether references are equal to queries
bool queries_equal_references =
!strcmp(queries_file_name, references_file_name);
// data::Load inits a matrix with the contents of a .csv or .arff.
data::Load(references_file_name, &references);
la::Scale(100.0, &references);
if(queries_equal_references) {
queries.Alias(references);
}
else {
data::Load(queries_file_name, &queries);
}
// If the reference weight file name is specified, then read in,
// otherwise, initialize to uniform weights.
if(fx_param_exists(fx_root, "dwgts")) {
data::Load(fx_param_str(fx_root, "dwgts", NULL), &reference_weights);
}
else {
reference_weights.Init(1, references.n_cols());
reference_weights.SetAll(1);
}
// Read in the bandwidth for each point.
if(fx_param_exists(fx_root, "bandwidths")) {
data::Load(fx_param_str(fx_root, "bandwidths", NULL),
&reference_bandwidths);
}
else {
reference_bandwidths.Init(1, references.n_cols());
reference_bandwidths.SetAll(1);
}
// Declare the fast multipole method object and initialize it.
ContinuousFmm cfmm_algorithm;
cfmm_algorithm.Init(queries, references, reference_weights,
reference_bandwidths, queries_equal_references,
cfmm_module);
// Start computation.
cfmm_algorithm.Compute();
// Compute naively.
Vector naive_results;
cfmm_algorithm.NaiveCompute(&naive_results);
fx_done(NULL);
return 0;
}
<commit_msg>Final commit of CFMM.<commit_after>#include "continuous_fmm.h"
int main(int argc, char *argv[]) {
// Initialize FastExec (parameter handling stuff).
fx_init(argc, argv, NULL);
////////// READING PARAMETERS AND LOADING DATA /////////////////////
// FASTexec organizes parameters and results into submodules. Think
// of this as creating a new folder named "cfmm_module" under the
// root directory (NULL) for the continuous FMM object to work
// inside. Here, we initialize it with all parameters defined
// "--cfmm/...=...".
struct datanode* cfmm_module = fx_submodule(fx_root, "cfmm");
// The reference data file is a required parameter.
const char* references_file_name = fx_param_str_req(fx_root, "data");
// The query data file defaults to the references.
const char* queries_file_name =
fx_param_str(fx_root, "query", references_file_name);
// Query and reference datasets, reference weight dataset, and the
// reference bandwidth dataset.
Matrix references;
Matrix reference_weights;
Matrix reference_bandwidths;
Matrix queries;
// Flag for telling whether references are equal to queries
bool queries_equal_references =
!strcmp(queries_file_name, references_file_name);
// data::Load inits a matrix with the contents of a .csv or .arff.
data::Load(references_file_name, &references);
if(queries_equal_references) {
queries.Alias(references);
}
else {
data::Load(queries_file_name, &queries);
}
// If the reference weight file name is specified, then read in,
// otherwise, initialize to uniform weights.
if(fx_param_exists(fx_root, "dwgts")) {
data::Load(fx_param_str(fx_root, "dwgts", NULL), &reference_weights);
}
else {
reference_weights.Init(1, references.n_cols());
reference_weights.SetAll(1);
}
// Read in the bandwidth for each point.
if(fx_param_exists(fx_root, "bandwidths")) {
data::Load(fx_param_str(fx_root, "bandwidths", NULL),
&reference_bandwidths);
}
else {
reference_bandwidths.Init(1, references.n_cols());
reference_bandwidths.SetAll(1);
}
// Declare the fast multipole method object and initialize it.
ContinuousFmm cfmm_algorithm;
cfmm_algorithm.Init(queries, references, reference_weights,
reference_bandwidths, queries_equal_references,
cfmm_module);
// Start computation.
cfmm_algorithm.Compute();
// Compute naively.
Vector naive_results;
cfmm_algorithm.NaiveCompute(&naive_results);
fx_done(NULL);
return 0;
}
<|endoftext|>
|
<commit_before>#include <cvd/config.h>
#include <cvd/image_convert.h>
#include <cvd/utility.h>
#include <arm_neon.h>
namespace CVD {
namespace Internal {
void convert_rgb_to_grey_NEON(const SubImage<Rgb<byte> >& from, SubImage<byte>& to, const unsigned r, const unsigned g, const unsigned b) {
const uint8x8_t red = vdup_n_u8(r);
const uint8x8_t green = vdup_n_u8(g);
const uint8x8_t blue = vdup_n_u8(b);
for( int y = 0; y < from.size().y; ++y){
const Rgb<byte> * in = from[y];
byte * out = to[y];
for( int x = 0; x < from.size().x; x+=8, in += 8, out += 8){
uint8x8x3_t in_data = vld3_u8((const uint8_t *)in);
uint16x8_t sum = vmull_u8(in_data.val[0], red);
sum = vmlal_u8(sum, in_data.val[1], green);
sum = vmlal_u8(sum, in_data.val[2], blue);
uint8x8_t final_sum = vshrn_n_u16(sum, 8); // divide by 256
vst1_u8(out, final_sum);
}
}
}
}
void ConvertImage<Rgb<byte>, byte, Pixel::CIE<Rgb<byte>, byte>, 1>::convert(const SubImage<Rgb<byte> >& from, SubImage<byte>& to)
{
if((from.size().x % 8) == 0){
// red (77) + green (150) + blue (29) = 256
Internal::convert_rgb_to_grey_NEON( from, to, 77, 150, 29);
} else {
const int multiple_of_8_width = (from.size().x / 8) * 8;
const ImageRef end_fast(multiple_of_8_width, from.size().y);
// red (77) + green (150) + blue (29) = 256
Internal::convert_rgb_to_grey_NEON( from.sub_image(ImageRef_zero, end_fast), to.sub_image(ImageRef_zero, end_fast).ref(), 77, 150, 29);
for(int y = 0; y < from.size().y; ++y){
const Rgb<byte> * in = from[y]+multiple_of_8_width;
byte * out = to[y]+multiple_of_8_width;
for(int x = multiple_of_8_width; x < from.size().x; ++x, ++in, ++out){
Pixel::CIE<Rgb<byte>,byte>::convert(*in, *out);
}
}
}
}
}
<commit_msg>cleanup<commit_after>#include <cvd/image_convert.h>
#include <arm_neon.h>
namespace CVD {
namespace Internal {
void convert_rgb_to_grey_NEON(const SubImage<Rgb<byte> >& from, SubImage<byte>& to, const unsigned r, const unsigned g, const unsigned b) {
const uint8x8_t red = vdup_n_u8(r);
const uint8x8_t green = vdup_n_u8(g);
const uint8x8_t blue = vdup_n_u8(b);
for( int y = 0; y < from.size().y; ++y){
const Rgb<byte> * in = from[y];
byte * out = to[y];
for( int x = 0; x < from.size().x; x+=8, in += 8, out += 8){
uint8x8x3_t in_data = vld3_u8((const uint8_t *)in);
uint16x8_t sum = vmull_u8(in_data.val[0], red);
sum = vmlal_u8(sum, in_data.val[1], green);
sum = vmlal_u8(sum, in_data.val[2], blue);
uint8x8_t final_sum = vshrn_n_u16(sum, 8); // divide by 256
vst1_u8(out, final_sum);
}
}
}
}
void ConvertImage<Rgb<byte>, byte, Pixel::CIE<Rgb<byte>, byte>, 1>::convert(const SubImage<Rgb<byte> >& from, SubImage<byte>& to)
{
if((from.size().x % 8) == 0){
// red (77) + green (150) + blue (29) = 256
Internal::convert_rgb_to_grey_NEON( from, to, 77, 150, 29);
} else {
const int multiple_of_8_width = (from.size().x / 8) * 8;
const ImageRef end_fast(multiple_of_8_width, from.size().y);
// red (77) + green (150) + blue (29) = 256
Internal::convert_rgb_to_grey_NEON( from.sub_image(ImageRef_zero, end_fast), to.sub_image(ImageRef_zero, end_fast).ref(), 77, 150, 29);
for(int y = 0; y < from.size().y; ++y){
const Rgb<byte> * in = from[y]+multiple_of_8_width;
byte * out = to[y]+multiple_of_8_width;
for(int x = multiple_of_8_width; x < from.size().x; ++x, ++in, ++out){
Pixel::CIE<Rgb<byte>,byte>::convert(*in, *out);
}
}
}
}
}
<|endoftext|>
|
<commit_before>/*
* #%L
* %%
* Copyright (C) 2011 - 2017 BMW Car IT GmbH
* %%
* 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.
* #L%
*/
#include "joynr/MulticastReceiverDirectory.h"
namespace joynr
{
INIT_LOGGER(MulticastReceiverDirectory);
MulticastReceiverDirectory::~MulticastReceiverDirectory()
{
JOYNR_LOG_TRACE(logger, "destructor: number of entries = {}", multicastReceivers.size());
multicastReceivers.clear();
}
void MulticastReceiverDirectory::registerMulticastReceiver(const std::string& multicastId,
const std::string& receiverId)
{
JOYNR_LOG_TRACE(logger,
"register multicast receiver: multicastId={}, receiverId={}",
multicastId,
receiverId);
std::lock_guard<std::recursive_mutex> lock(mutex);
MulticastMatcher matcher(multicastId);
multicastReceivers[matcher].insert(receiverId);
}
bool MulticastReceiverDirectory::unregisterMulticastReceiver(const std::string& multicastId,
const std::string& receiverId)
{
JOYNR_LOG_TRACE(logger,
"unregister multicast receiver: multicastId={}, receiverId={}",
multicastId,
receiverId);
std::lock_guard<std::recursive_mutex> lock(mutex);
if (contains(multicastId)) {
MulticastMatcher matcher(multicastId);
std::unordered_set<std::string>& receivers = multicastReceivers[matcher];
receivers.erase(receiverId);
JOYNR_LOG_TRACE(logger,
"removed multicast receiver: multicastId={}, receiverId={}",
multicastId,
receiverId);
if (receivers.empty()) {
JOYNR_LOG_TRACE(logger, "removed last multicast receiver: multicastId={}", multicastId);
multicastReceivers.erase(matcher);
}
return true;
}
return false;
}
std::unordered_set<std::string> MulticastReceiverDirectory::getReceivers(
const std::string& multicastId)
{
JOYNR_LOG_TRACE(logger, "get multicast receivers: multicastId={}", multicastId);
std::lock_guard<std::recursive_mutex> lock(mutex);
std::unordered_set<std::string> foundReceivers;
for (const std::pair<MulticastMatcher, std::unordered_set<std::string>>& pair :
multicastReceivers) {
if (pair.first.doesMatch(multicastId)) {
foundReceivers.insert(pair.second.cbegin(), pair.second.cend());
}
}
return foundReceivers;
}
std::vector<std::string> MulticastReceiverDirectory::getMulticastIds() const
{
std::vector<std::string> multicastIds;
for (const auto& multicastReceiver : multicastReceivers) {
multicastIds.push_back(multicastReceiver.first.multicastId);
}
return multicastIds;
}
bool MulticastReceiverDirectory::contains(const std::string& multicastId)
{
std::lock_guard<std::recursive_mutex> lock(mutex);
MulticastMatcher matcher(multicastId);
return multicastReceivers.find(matcher) != multicastReceivers.cend();
}
bool MulticastReceiverDirectory::contains(const std::string& multicastId,
const std::string& receiverId)
{
std::lock_guard<std::recursive_mutex> lock(mutex);
auto receivers = getReceivers(multicastId);
return receivers.find(receiverId) != receivers.cend();
}
} // namespace joynr
<commit_msg>[C++] avoid implicit cast<commit_after>/*
* #%L
* %%
* Copyright (C) 2011 - 2017 BMW Car IT GmbH
* %%
* 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.
* #L%
*/
#include "joynr/MulticastReceiverDirectory.h"
namespace joynr
{
INIT_LOGGER(MulticastReceiverDirectory);
MulticastReceiverDirectory::~MulticastReceiverDirectory()
{
JOYNR_LOG_TRACE(logger, "destructor: number of entries = {}", multicastReceivers.size());
multicastReceivers.clear();
}
void MulticastReceiverDirectory::registerMulticastReceiver(const std::string& multicastId,
const std::string& receiverId)
{
JOYNR_LOG_TRACE(logger,
"register multicast receiver: multicastId={}, receiverId={}",
multicastId,
receiverId);
std::lock_guard<std::recursive_mutex> lock(mutex);
MulticastMatcher matcher(multicastId);
multicastReceivers[matcher].insert(receiverId);
}
bool MulticastReceiverDirectory::unregisterMulticastReceiver(const std::string& multicastId,
const std::string& receiverId)
{
JOYNR_LOG_TRACE(logger,
"unregister multicast receiver: multicastId={}, receiverId={}",
multicastId,
receiverId);
std::lock_guard<std::recursive_mutex> lock(mutex);
if (contains(multicastId)) {
MulticastMatcher matcher(multicastId);
std::unordered_set<std::string>& receivers = multicastReceivers[matcher];
receivers.erase(receiverId);
JOYNR_LOG_TRACE(logger,
"removed multicast receiver: multicastId={}, receiverId={}",
multicastId,
receiverId);
if (receivers.empty()) {
JOYNR_LOG_TRACE(logger, "removed last multicast receiver: multicastId={}", multicastId);
multicastReceivers.erase(matcher);
}
return true;
}
return false;
}
std::unordered_set<std::string> MulticastReceiverDirectory::getReceivers(
const std::string& multicastId)
{
JOYNR_LOG_TRACE(logger, "get multicast receivers: multicastId={}", multicastId);
std::lock_guard<std::recursive_mutex> lock(mutex);
std::unordered_set<std::string> foundReceivers;
for (const auto& entry : multicastReceivers) {
if (entry.first.doesMatch(multicastId)) {
foundReceivers.insert(entry.second.cbegin(), entry.second.cend());
}
}
return foundReceivers;
}
std::vector<std::string> MulticastReceiverDirectory::getMulticastIds() const
{
std::vector<std::string> multicastIds;
for (const auto& multicastReceiver : multicastReceivers) {
multicastIds.push_back(multicastReceiver.first.multicastId);
}
return multicastIds;
}
bool MulticastReceiverDirectory::contains(const std::string& multicastId)
{
std::lock_guard<std::recursive_mutex> lock(mutex);
MulticastMatcher matcher(multicastId);
return multicastReceivers.find(matcher) != multicastReceivers.cend();
}
bool MulticastReceiverDirectory::contains(const std::string& multicastId,
const std::string& receiverId)
{
std::lock_guard<std::recursive_mutex> lock(mutex);
auto receivers = getReceivers(multicastId);
return receivers.find(receiverId) != receivers.cend();
}
} // namespace joynr
<|endoftext|>
|
<commit_before>//===-- SIMachineFunctionInfo.cpp - SI Machine Function Info -------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
/// \file
//===----------------------------------------------------------------------===//
#include "SIMachineFunctionInfo.h"
#include "AMDGPUSubtarget.h"
#include "SIInstrInfo.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/LLVMContext.h"
#define MAX_LANES 64
using namespace llvm;
// Pin the vtable to this file.
void SIMachineFunctionInfo::anchor() {}
SIMachineFunctionInfo::SIMachineFunctionInfo(const MachineFunction &MF)
: AMDGPUMachineFunction(MF),
TIDReg(AMDGPU::NoRegister),
ScratchRSrcReg(AMDGPU::NoRegister),
ScratchWaveOffsetReg(AMDGPU::NoRegister),
PrivateSegmentBufferUserSGPR(AMDGPU::NoRegister),
DispatchPtrUserSGPR(AMDGPU::NoRegister),
QueuePtrUserSGPR(AMDGPU::NoRegister),
KernargSegmentPtrUserSGPR(AMDGPU::NoRegister),
DispatchIDUserSGPR(AMDGPU::NoRegister),
FlatScratchInitUserSGPR(AMDGPU::NoRegister),
PrivateSegmentSizeUserSGPR(AMDGPU::NoRegister),
GridWorkGroupCountXUserSGPR(AMDGPU::NoRegister),
GridWorkGroupCountYUserSGPR(AMDGPU::NoRegister),
GridWorkGroupCountZUserSGPR(AMDGPU::NoRegister),
WorkGroupIDXSystemSGPR(AMDGPU::NoRegister),
WorkGroupIDYSystemSGPR(AMDGPU::NoRegister),
WorkGroupIDZSystemSGPR(AMDGPU::NoRegister),
WorkGroupInfoSystemSGPR(AMDGPU::NoRegister),
PrivateSegmentWaveByteOffsetSystemSGPR(AMDGPU::NoRegister),
PSInputAddr(0),
ReturnsVoid(true),
MaximumWorkGroupSize(0),
DebuggerReservedVGPRCount(0),
LDSWaveSpillSize(0),
PSInputEna(0),
NumUserSGPRs(0),
NumSystemSGPRs(0),
HasSpilledSGPRs(false),
HasSpilledVGPRs(false),
HasNonSpillStackObjects(false),
HasFlatInstructions(false),
PrivateSegmentBuffer(false),
DispatchPtr(false),
QueuePtr(false),
DispatchID(false),
KernargSegmentPtr(false),
FlatScratchInit(false),
GridWorkgroupCountX(false),
GridWorkgroupCountY(false),
GridWorkgroupCountZ(false),
WorkGroupIDX(false),
WorkGroupIDY(false),
WorkGroupIDZ(false),
WorkGroupInfo(false),
PrivateSegmentWaveByteOffset(false),
WorkItemIDX(false),
WorkItemIDY(false),
WorkItemIDZ(false) {
const AMDGPUSubtarget &ST = MF.getSubtarget<AMDGPUSubtarget>();
const Function *F = MF.getFunction();
PSInputAddr = AMDGPU::getInitialPSInputAddr(*F);
const MachineFrameInfo *FrameInfo = MF.getFrameInfo();
if (!AMDGPU::isShader(F->getCallingConv())) {
KernargSegmentPtr = true;
WorkGroupIDX = true;
WorkItemIDX = true;
}
if (F->hasFnAttribute("amdgpu-work-group-id-y"))
WorkGroupIDY = true;
if (F->hasFnAttribute("amdgpu-work-group-id-z"))
WorkGroupIDZ = true;
if (F->hasFnAttribute("amdgpu-work-item-id-y"))
WorkItemIDY = true;
if (F->hasFnAttribute("amdgpu-work-item-id-z"))
WorkItemIDZ = true;
// X, XY, and XYZ are the only supported combinations, so make sure Y is
// enabled if Z is.
if (WorkItemIDZ)
WorkItemIDY = true;
bool MaySpill = ST.isVGPRSpillingEnabled(*F);
bool HasStackObjects = FrameInfo->hasStackObjects();
if (HasStackObjects || MaySpill)
PrivateSegmentWaveByteOffset = true;
if (ST.isAmdHsaOS()) {
if (HasStackObjects || MaySpill)
PrivateSegmentBuffer = true;
if (F->hasFnAttribute("amdgpu-dispatch-ptr"))
DispatchPtr = true;
if (F->hasFnAttribute("amdgpu-queue-ptr"))
QueuePtr = true;
}
// We don't need to worry about accessing spills with flat instructions.
// TODO: On VI where we must use flat for global, we should be able to omit
// this if it is never used for generic access.
if (HasStackObjects && ST.getGeneration() >= AMDGPUSubtarget::SEA_ISLANDS &&
ST.isAmdHsaOS())
FlatScratchInit = true;
if (AMDGPU::isCompute(F->getCallingConv()))
MaximumWorkGroupSize = AMDGPU::getMaximumWorkGroupSize(*F);
else
MaximumWorkGroupSize = ST.getWavefrontSize();
if (ST.debuggerReserveRegs())
DebuggerReservedVGPRCount = 4;
}
unsigned SIMachineFunctionInfo::addPrivateSegmentBuffer(
const SIRegisterInfo &TRI) {
PrivateSegmentBufferUserSGPR = TRI.getMatchingSuperReg(
getNextUserSGPR(), AMDGPU::sub0, &AMDGPU::SReg_128RegClass);
NumUserSGPRs += 4;
return PrivateSegmentBufferUserSGPR;
}
unsigned SIMachineFunctionInfo::addDispatchPtr(const SIRegisterInfo &TRI) {
DispatchPtrUserSGPR = TRI.getMatchingSuperReg(
getNextUserSGPR(), AMDGPU::sub0, &AMDGPU::SReg_64RegClass);
NumUserSGPRs += 2;
return DispatchPtrUserSGPR;
}
unsigned SIMachineFunctionInfo::addQueuePtr(const SIRegisterInfo &TRI) {
QueuePtrUserSGPR = TRI.getMatchingSuperReg(
getNextUserSGPR(), AMDGPU::sub0, &AMDGPU::SReg_64RegClass);
NumUserSGPRs += 2;
return QueuePtrUserSGPR;
}
unsigned SIMachineFunctionInfo::addKernargSegmentPtr(const SIRegisterInfo &TRI) {
KernargSegmentPtrUserSGPR = TRI.getMatchingSuperReg(
getNextUserSGPR(), AMDGPU::sub0, &AMDGPU::SReg_64RegClass);
NumUserSGPRs += 2;
return KernargSegmentPtrUserSGPR;
}
unsigned SIMachineFunctionInfo::addFlatScratchInit(const SIRegisterInfo &TRI) {
FlatScratchInitUserSGPR = TRI.getMatchingSuperReg(
getNextUserSGPR(), AMDGPU::sub0, &AMDGPU::SReg_64RegClass);
NumUserSGPRs += 2;
return FlatScratchInitUserSGPR;
}
SIMachineFunctionInfo::SpilledReg SIMachineFunctionInfo::getSpilledReg(
MachineFunction *MF,
unsigned FrameIndex,
unsigned SubIdx) {
MachineFrameInfo *FrameInfo = MF->getFrameInfo();
const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(
MF->getSubtarget<AMDGPUSubtarget>().getRegisterInfo());
MachineRegisterInfo &MRI = MF->getRegInfo();
int64_t Offset = FrameInfo->getObjectOffset(FrameIndex);
Offset += SubIdx * 4;
unsigned LaneVGPRIdx = Offset / (64 * 4);
unsigned Lane = (Offset / 4) % 64;
struct SpilledReg Spill;
Spill.Lane = Lane;
if (!LaneVGPRs.count(LaneVGPRIdx)) {
unsigned LaneVGPR = TRI->findUnusedRegister(MRI, &AMDGPU::VGPR_32RegClass);
if (LaneVGPR == AMDGPU::NoRegister)
// We have no VGPRs left for spilling SGPRs.
return Spill;
LaneVGPRs[LaneVGPRIdx] = LaneVGPR;
// Add this register as live-in to all blocks to avoid machine verifer
// complaining about use of an undefined physical register.
for (MachineFunction::iterator BI = MF->begin(), BE = MF->end();
BI != BE; ++BI) {
BI->addLiveIn(LaneVGPR);
}
}
Spill.VGPR = LaneVGPRs[LaneVGPRIdx];
return Spill;
}
unsigned SIMachineFunctionInfo::getMaximumWorkGroupSize(
const MachineFunction &MF) const {
return MaximumWorkGroupSize;
}
<commit_msg>AMDGPU: Add option to disable spilling SGPRs to VGPRs.<commit_after>//===-- SIMachineFunctionInfo.cpp -------- SI Machine Function Info -------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "SIMachineFunctionInfo.h"
#include "AMDGPUSubtarget.h"
#include "SIInstrInfo.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/LLVMContext.h"
#define MAX_LANES 64
using namespace llvm;
static cl::opt<bool> EnableSpillSGPRToVGPR(
"amdgpu-spill-sgpr-to-vgpr",
cl::desc("Enable spilling VGPRs to SGPRs"),
cl::ReallyHidden,
cl::init(true));
// Pin the vtable to this file.
void SIMachineFunctionInfo::anchor() {}
SIMachineFunctionInfo::SIMachineFunctionInfo(const MachineFunction &MF)
: AMDGPUMachineFunction(MF),
TIDReg(AMDGPU::NoRegister),
ScratchRSrcReg(AMDGPU::NoRegister),
ScratchWaveOffsetReg(AMDGPU::NoRegister),
PrivateSegmentBufferUserSGPR(AMDGPU::NoRegister),
DispatchPtrUserSGPR(AMDGPU::NoRegister),
QueuePtrUserSGPR(AMDGPU::NoRegister),
KernargSegmentPtrUserSGPR(AMDGPU::NoRegister),
DispatchIDUserSGPR(AMDGPU::NoRegister),
FlatScratchInitUserSGPR(AMDGPU::NoRegister),
PrivateSegmentSizeUserSGPR(AMDGPU::NoRegister),
GridWorkGroupCountXUserSGPR(AMDGPU::NoRegister),
GridWorkGroupCountYUserSGPR(AMDGPU::NoRegister),
GridWorkGroupCountZUserSGPR(AMDGPU::NoRegister),
WorkGroupIDXSystemSGPR(AMDGPU::NoRegister),
WorkGroupIDYSystemSGPR(AMDGPU::NoRegister),
WorkGroupIDZSystemSGPR(AMDGPU::NoRegister),
WorkGroupInfoSystemSGPR(AMDGPU::NoRegister),
PrivateSegmentWaveByteOffsetSystemSGPR(AMDGPU::NoRegister),
PSInputAddr(0),
ReturnsVoid(true),
MaximumWorkGroupSize(0),
DebuggerReservedVGPRCount(0),
LDSWaveSpillSize(0),
PSInputEna(0),
NumUserSGPRs(0),
NumSystemSGPRs(0),
HasSpilledSGPRs(false),
HasSpilledVGPRs(false),
HasNonSpillStackObjects(false),
HasFlatInstructions(false),
PrivateSegmentBuffer(false),
DispatchPtr(false),
QueuePtr(false),
DispatchID(false),
KernargSegmentPtr(false),
FlatScratchInit(false),
GridWorkgroupCountX(false),
GridWorkgroupCountY(false),
GridWorkgroupCountZ(false),
WorkGroupIDX(false),
WorkGroupIDY(false),
WorkGroupIDZ(false),
WorkGroupInfo(false),
PrivateSegmentWaveByteOffset(false),
WorkItemIDX(false),
WorkItemIDY(false),
WorkItemIDZ(false) {
const AMDGPUSubtarget &ST = MF.getSubtarget<AMDGPUSubtarget>();
const Function *F = MF.getFunction();
PSInputAddr = AMDGPU::getInitialPSInputAddr(*F);
const MachineFrameInfo *FrameInfo = MF.getFrameInfo();
if (!AMDGPU::isShader(F->getCallingConv())) {
KernargSegmentPtr = true;
WorkGroupIDX = true;
WorkItemIDX = true;
}
if (F->hasFnAttribute("amdgpu-work-group-id-y"))
WorkGroupIDY = true;
if (F->hasFnAttribute("amdgpu-work-group-id-z"))
WorkGroupIDZ = true;
if (F->hasFnAttribute("amdgpu-work-item-id-y"))
WorkItemIDY = true;
if (F->hasFnAttribute("amdgpu-work-item-id-z"))
WorkItemIDZ = true;
// X, XY, and XYZ are the only supported combinations, so make sure Y is
// enabled if Z is.
if (WorkItemIDZ)
WorkItemIDY = true;
bool MaySpill = ST.isVGPRSpillingEnabled(*F);
bool HasStackObjects = FrameInfo->hasStackObjects();
if (HasStackObjects || MaySpill)
PrivateSegmentWaveByteOffset = true;
if (ST.isAmdHsaOS()) {
if (HasStackObjects || MaySpill)
PrivateSegmentBuffer = true;
if (F->hasFnAttribute("amdgpu-dispatch-ptr"))
DispatchPtr = true;
if (F->hasFnAttribute("amdgpu-queue-ptr"))
QueuePtr = true;
}
// We don't need to worry about accessing spills with flat instructions.
// TODO: On VI where we must use flat for global, we should be able to omit
// this if it is never used for generic access.
if (HasStackObjects && ST.getGeneration() >= AMDGPUSubtarget::SEA_ISLANDS &&
ST.isAmdHsaOS())
FlatScratchInit = true;
if (AMDGPU::isCompute(F->getCallingConv()))
MaximumWorkGroupSize = AMDGPU::getMaximumWorkGroupSize(*F);
else
MaximumWorkGroupSize = ST.getWavefrontSize();
if (ST.debuggerReserveRegs())
DebuggerReservedVGPRCount = 4;
}
unsigned SIMachineFunctionInfo::addPrivateSegmentBuffer(
const SIRegisterInfo &TRI) {
PrivateSegmentBufferUserSGPR = TRI.getMatchingSuperReg(
getNextUserSGPR(), AMDGPU::sub0, &AMDGPU::SReg_128RegClass);
NumUserSGPRs += 4;
return PrivateSegmentBufferUserSGPR;
}
unsigned SIMachineFunctionInfo::addDispatchPtr(const SIRegisterInfo &TRI) {
DispatchPtrUserSGPR = TRI.getMatchingSuperReg(
getNextUserSGPR(), AMDGPU::sub0, &AMDGPU::SReg_64RegClass);
NumUserSGPRs += 2;
return DispatchPtrUserSGPR;
}
unsigned SIMachineFunctionInfo::addQueuePtr(const SIRegisterInfo &TRI) {
QueuePtrUserSGPR = TRI.getMatchingSuperReg(
getNextUserSGPR(), AMDGPU::sub0, &AMDGPU::SReg_64RegClass);
NumUserSGPRs += 2;
return QueuePtrUserSGPR;
}
unsigned SIMachineFunctionInfo::addKernargSegmentPtr(const SIRegisterInfo &TRI) {
KernargSegmentPtrUserSGPR = TRI.getMatchingSuperReg(
getNextUserSGPR(), AMDGPU::sub0, &AMDGPU::SReg_64RegClass);
NumUserSGPRs += 2;
return KernargSegmentPtrUserSGPR;
}
unsigned SIMachineFunctionInfo::addFlatScratchInit(const SIRegisterInfo &TRI) {
FlatScratchInitUserSGPR = TRI.getMatchingSuperReg(
getNextUserSGPR(), AMDGPU::sub0, &AMDGPU::SReg_64RegClass);
NumUserSGPRs += 2;
return FlatScratchInitUserSGPR;
}
SIMachineFunctionInfo::SpilledReg SIMachineFunctionInfo::getSpilledReg(
MachineFunction *MF,
unsigned FrameIndex,
unsigned SubIdx) {
if (!EnableSpillSGPRToVGPR)
return SpilledReg();
MachineFrameInfo *FrameInfo = MF->getFrameInfo();
const SIRegisterInfo *TRI = static_cast<const SIRegisterInfo *>(
MF->getSubtarget<AMDGPUSubtarget>().getRegisterInfo());
MachineRegisterInfo &MRI = MF->getRegInfo();
int64_t Offset = FrameInfo->getObjectOffset(FrameIndex);
Offset += SubIdx * 4;
unsigned LaneVGPRIdx = Offset / (64 * 4);
unsigned Lane = (Offset / 4) % 64;
struct SpilledReg Spill;
Spill.Lane = Lane;
if (!LaneVGPRs.count(LaneVGPRIdx)) {
unsigned LaneVGPR = TRI->findUnusedRegister(MRI, &AMDGPU::VGPR_32RegClass);
if (LaneVGPR == AMDGPU::NoRegister)
// We have no VGPRs left for spilling SGPRs.
return Spill;
LaneVGPRs[LaneVGPRIdx] = LaneVGPR;
// Add this register as live-in to all blocks to avoid machine verifer
// complaining about use of an undefined physical register.
for (MachineFunction::iterator BI = MF->begin(), BE = MF->end();
BI != BE; ++BI) {
BI->addLiveIn(LaneVGPR);
}
}
Spill.VGPR = LaneVGPRs[LaneVGPRIdx];
return Spill;
}
unsigned SIMachineFunctionInfo::getMaximumWorkGroupSize(
const MachineFunction &MF) const {
return MaximumWorkGroupSize;
}
<|endoftext|>
|
<commit_before>//===- BreakCriticalEdges.cpp - Critical Edge Elimination Pass ------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// BreakCriticalEdges pass - Break all of the critical edges in the CFG by
// inserting a dummy basic block. This pass may be "required" by passes that
// cannot deal with critical edges. For this usage, the structure type is
// forward declared. This pass obviously invalidates the CFG, but can update
// dominator trees.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Scalar.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Analysis/CFG.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/IR/CFG.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Type.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
using namespace llvm;
#define DEBUG_TYPE "break-crit-edges"
STATISTIC(NumBroken, "Number of blocks inserted");
namespace {
struct BreakCriticalEdges : public FunctionPass {
static char ID; // Pass identification, replacement for typeid
BreakCriticalEdges() : FunctionPass(ID) {
initializeBreakCriticalEdgesPass(*PassRegistry::getPassRegistry());
}
bool runOnFunction(Function &F) override {
unsigned N = SplitAllCriticalEdges(F, this);
NumBroken += N;
return N > 0;
}
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addPreserved<DominatorTreeWrapperPass>();
AU.addPreserved<LoopInfoWrapperPass>();
// No loop canonicalization guarantees are broken by this pass.
AU.addPreservedID(LoopSimplifyID);
}
};
}
char BreakCriticalEdges::ID = 0;
INITIALIZE_PASS(BreakCriticalEdges, "break-crit-edges",
"Break critical edges in CFG", false, false)
// Publicly exposed interface to pass...
char &llvm::BreakCriticalEdgesID = BreakCriticalEdges::ID;
FunctionPass *llvm::createBreakCriticalEdgesPass() {
return new BreakCriticalEdges();
}
//===----------------------------------------------------------------------===//
// Implementation of the external critical edge manipulation functions
//===----------------------------------------------------------------------===//
/// createPHIsForSplitLoopExit - When a loop exit edge is split, LCSSA form
/// may require new PHIs in the new exit block. This function inserts the
/// new PHIs, as needed. Preds is a list of preds inside the loop, SplitBB
/// is the new loop exit block, and DestBB is the old loop exit, now the
/// successor of SplitBB.
static void createPHIsForSplitLoopExit(ArrayRef<BasicBlock *> Preds,
BasicBlock *SplitBB,
BasicBlock *DestBB) {
// SplitBB shouldn't have anything non-trivial in it yet.
assert((SplitBB->getFirstNonPHI() == SplitBB->getTerminator() ||
SplitBB->isLandingPad()) && "SplitBB has non-PHI nodes!");
// For each PHI in the destination block.
for (BasicBlock::iterator I = DestBB->begin();
PHINode *PN = dyn_cast<PHINode>(I); ++I) {
unsigned Idx = PN->getBasicBlockIndex(SplitBB);
Value *V = PN->getIncomingValue(Idx);
// If the input is a PHI which already satisfies LCSSA, don't create
// a new one.
if (const PHINode *VP = dyn_cast<PHINode>(V))
if (VP->getParent() == SplitBB)
continue;
// Otherwise a new PHI is needed. Create one and populate it.
PHINode *NewPN =
PHINode::Create(PN->getType(), Preds.size(), "split",
SplitBB->isLandingPad() ?
SplitBB->begin() : SplitBB->getTerminator());
for (unsigned i = 0, e = Preds.size(); i != e; ++i)
NewPN->addIncoming(V, Preds[i]);
// Update the original PHI.
PN->setIncomingValue(Idx, NewPN);
}
}
/// SplitCriticalEdge - If this edge is a critical edge, insert a new node to
/// split the critical edge. This will update DominatorTree information if it
/// is available, thus calling this pass will not invalidate either of them.
/// This returns the new block if the edge was split, null otherwise.
///
/// If MergeIdenticalEdges is true (not the default), *all* edges from TI to the
/// specified successor will be merged into the same critical edge block.
/// This is most commonly interesting with switch instructions, which may
/// have many edges to any one destination. This ensures that all edges to that
/// dest go to one block instead of each going to a different block, but isn't
/// the standard definition of a "critical edge".
///
/// It is invalid to call this function on a critical edge that starts at an
/// IndirectBrInst. Splitting these edges will almost always create an invalid
/// program because the address of the new block won't be the one that is jumped
/// to.
///
BasicBlock *llvm::SplitCriticalEdge(TerminatorInst *TI, unsigned SuccNum,
Pass *P, bool MergeIdenticalEdges,
bool DontDeleteUselessPhis,
bool SplitLandingPads) {
if (!isCriticalEdge(TI, SuccNum, MergeIdenticalEdges)) return nullptr;
assert(!isa<IndirectBrInst>(TI) &&
"Cannot split critical edge from IndirectBrInst");
BasicBlock *TIBB = TI->getParent();
BasicBlock *DestBB = TI->getSuccessor(SuccNum);
// Splitting the critical edge to a landing pad block is non-trivial. Don't do
// it in this generic function.
if (DestBB->isLandingPad()) return nullptr;
// Create a new basic block, linking it into the CFG.
BasicBlock *NewBB = BasicBlock::Create(TI->getContext(),
TIBB->getName() + "." + DestBB->getName() + "_crit_edge");
// Create our unconditional branch.
BranchInst *NewBI = BranchInst::Create(DestBB, NewBB);
NewBI->setDebugLoc(TI->getDebugLoc());
// Branch to the new block, breaking the edge.
TI->setSuccessor(SuccNum, NewBB);
// Insert the block into the function... right after the block TI lives in.
Function &F = *TIBB->getParent();
Function::iterator FBBI = TIBB;
F.getBasicBlockList().insert(++FBBI, NewBB);
// If there are any PHI nodes in DestBB, we need to update them so that they
// merge incoming values from NewBB instead of from TIBB.
{
unsigned BBIdx = 0;
for (BasicBlock::iterator I = DestBB->begin(); isa<PHINode>(I); ++I) {
// We no longer enter through TIBB, now we come in through NewBB.
// Revector exactly one entry in the PHI node that used to come from
// TIBB to come from NewBB.
PHINode *PN = cast<PHINode>(I);
// Reuse the previous value of BBIdx if it lines up. In cases where we
// have multiple phi nodes with *lots* of predecessors, this is a speed
// win because we don't have to scan the PHI looking for TIBB. This
// happens because the BB list of PHI nodes are usually in the same
// order.
if (PN->getIncomingBlock(BBIdx) != TIBB)
BBIdx = PN->getBasicBlockIndex(TIBB);
PN->setIncomingBlock(BBIdx, NewBB);
}
}
// If there are any other edges from TIBB to DestBB, update those to go
// through the split block, making those edges non-critical as well (and
// reducing the number of phi entries in the DestBB if relevant).
if (MergeIdenticalEdges) {
for (unsigned i = SuccNum+1, e = TI->getNumSuccessors(); i != e; ++i) {
if (TI->getSuccessor(i) != DestBB) continue;
// Remove an entry for TIBB from DestBB phi nodes.
DestBB->removePredecessor(TIBB, DontDeleteUselessPhis);
// We found another edge to DestBB, go to NewBB instead.
TI->setSuccessor(i, NewBB);
}
}
// If we don't have a pass object, we can't update anything...
if (!P) return NewBB;
auto *AA = P->getAnalysisIfAvailable<AliasAnalysis>();
DominatorTreeWrapperPass *DTWP =
P->getAnalysisIfAvailable<DominatorTreeWrapperPass>();
DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
auto *LIWP = P->getAnalysisIfAvailable<LoopInfoWrapperPass>();
LoopInfo *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
bool PreserveLCSSA = P->mustPreserveAnalysisID(LCSSAID);
// If we have nothing to update, just return.
if (!DT && !LI)
return NewBB;
// Now update analysis information. Since the only predecessor of NewBB is
// the TIBB, TIBB clearly dominates NewBB. TIBB usually doesn't dominate
// anything, as there are other successors of DestBB. However, if all other
// predecessors of DestBB are already dominated by DestBB (e.g. DestBB is a
// loop header) then NewBB dominates DestBB.
SmallVector<BasicBlock*, 8> OtherPreds;
// If there is a PHI in the block, loop over predecessors with it, which is
// faster than iterating pred_begin/end.
if (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
if (PN->getIncomingBlock(i) != NewBB)
OtherPreds.push_back(PN->getIncomingBlock(i));
} else {
for (pred_iterator I = pred_begin(DestBB), E = pred_end(DestBB);
I != E; ++I) {
BasicBlock *P = *I;
if (P != NewBB)
OtherPreds.push_back(P);
}
}
bool NewBBDominatesDestBB = true;
// Should we update DominatorTree information?
if (DT) {
DomTreeNode *TINode = DT->getNode(TIBB);
// The new block is not the immediate dominator for any other nodes, but
// TINode is the immediate dominator for the new node.
//
if (TINode) { // Don't break unreachable code!
DomTreeNode *NewBBNode = DT->addNewBlock(NewBB, TIBB);
DomTreeNode *DestBBNode = nullptr;
// If NewBBDominatesDestBB hasn't been computed yet, do so with DT.
if (!OtherPreds.empty()) {
DestBBNode = DT->getNode(DestBB);
while (!OtherPreds.empty() && NewBBDominatesDestBB) {
if (DomTreeNode *OPNode = DT->getNode(OtherPreds.back()))
NewBBDominatesDestBB = DT->dominates(DestBBNode, OPNode);
OtherPreds.pop_back();
}
OtherPreds.clear();
}
// If NewBBDominatesDestBB, then NewBB dominates DestBB, otherwise it
// doesn't dominate anything.
if (NewBBDominatesDestBB) {
if (!DestBBNode) DestBBNode = DT->getNode(DestBB);
DT->changeImmediateDominator(DestBBNode, NewBBNode);
}
}
}
// Update LoopInfo if it is around.
if (LI) {
if (Loop *TIL = LI->getLoopFor(TIBB)) {
// If one or the other blocks were not in a loop, the new block is not
// either, and thus LI doesn't need to be updated.
if (Loop *DestLoop = LI->getLoopFor(DestBB)) {
if (TIL == DestLoop) {
// Both in the same loop, the NewBB joins loop.
DestLoop->addBasicBlockToLoop(NewBB, *LI);
} else if (TIL->contains(DestLoop)) {
// Edge from an outer loop to an inner loop. Add to the outer loop.
TIL->addBasicBlockToLoop(NewBB, *LI);
} else if (DestLoop->contains(TIL)) {
// Edge from an inner loop to an outer loop. Add to the outer loop.
DestLoop->addBasicBlockToLoop(NewBB, *LI);
} else {
// Edge from two loops with no containment relation. Because these
// are natural loops, we know that the destination block must be the
// header of its loop (adding a branch into a loop elsewhere would
// create an irreducible loop).
assert(DestLoop->getHeader() == DestBB &&
"Should not create irreducible loops!");
if (Loop *P = DestLoop->getParentLoop())
P->addBasicBlockToLoop(NewBB, *LI);
}
}
// If TIBB is in a loop and DestBB is outside of that loop, we may need
// to update LoopSimplify form and LCSSA form.
if (!TIL->contains(DestBB) &&
P->mustPreserveAnalysisID(LoopSimplifyID)) {
assert(!TIL->contains(NewBB) &&
"Split point for loop exit is contained in loop!");
// Update LCSSA form in the newly created exit block.
if (PreserveLCSSA)
createPHIsForSplitLoopExit(TIBB, NewBB, DestBB);
// The only that we can break LoopSimplify form by splitting a critical
// edge is if after the split there exists some edge from TIL to DestBB
// *and* the only edge into DestBB from outside of TIL is that of
// NewBB. If the first isn't true, then LoopSimplify still holds, NewBB
// is the new exit block and it has no non-loop predecessors. If the
// second isn't true, then DestBB was not in LoopSimplify form prior to
// the split as it had a non-loop predecessor. In both of these cases,
// the predecessor must be directly in TIL, not in a subloop, or again
// LoopSimplify doesn't hold.
SmallVector<BasicBlock *, 4> LoopPreds;
for (pred_iterator I = pred_begin(DestBB), E = pred_end(DestBB); I != E;
++I) {
BasicBlock *P = *I;
if (P == NewBB)
continue; // The new block is known.
if (LI->getLoopFor(P) != TIL) {
// No need to re-simplify, it wasn't to start with.
LoopPreds.clear();
break;
}
LoopPreds.push_back(P);
}
if (!LoopPreds.empty()) {
assert(!DestBB->isLandingPad() &&
"We don't split edges to landing pads!");
BasicBlock *NewExitBB = SplitBlockPredecessors(
DestBB, LoopPreds, "split", AA, DT, LI, PreserveLCSSA);
if (PreserveLCSSA)
createPHIsForSplitLoopExit(LoopPreds, NewExitBB, DestBB);
}
}
// LCSSA form was updated above for the case where LoopSimplify is
// available, which means that all predecessors of loop exit blocks
// are within the loop. Without LoopSimplify form, it would be
// necessary to insert a new phi.
assert((!PreserveLCSSA || P->mustPreserveAnalysisID(LoopSimplifyID)) &&
"SplitCriticalEdge doesn't know how to update LCCSA form "
"without LoopSimplify!");
}
}
return NewBB;
}
<commit_msg>[PM] Relax asserts and always try to reconstruct loop simplify form when we can while splitting critical edges.<commit_after>//===- BreakCriticalEdges.cpp - Critical Edge Elimination Pass ------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// BreakCriticalEdges pass - Break all of the critical edges in the CFG by
// inserting a dummy basic block. This pass may be "required" by passes that
// cannot deal with critical edges. For this usage, the structure type is
// forward declared. This pass obviously invalidates the CFG, but can update
// dominator trees.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Scalar.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Analysis/CFG.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/IR/CFG.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Type.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
using namespace llvm;
#define DEBUG_TYPE "break-crit-edges"
STATISTIC(NumBroken, "Number of blocks inserted");
namespace {
struct BreakCriticalEdges : public FunctionPass {
static char ID; // Pass identification, replacement for typeid
BreakCriticalEdges() : FunctionPass(ID) {
initializeBreakCriticalEdgesPass(*PassRegistry::getPassRegistry());
}
bool runOnFunction(Function &F) override {
unsigned N = SplitAllCriticalEdges(F, this);
NumBroken += N;
return N > 0;
}
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addPreserved<DominatorTreeWrapperPass>();
AU.addPreserved<LoopInfoWrapperPass>();
// No loop canonicalization guarantees are broken by this pass.
AU.addPreservedID(LoopSimplifyID);
}
};
}
char BreakCriticalEdges::ID = 0;
INITIALIZE_PASS(BreakCriticalEdges, "break-crit-edges",
"Break critical edges in CFG", false, false)
// Publicly exposed interface to pass...
char &llvm::BreakCriticalEdgesID = BreakCriticalEdges::ID;
FunctionPass *llvm::createBreakCriticalEdgesPass() {
return new BreakCriticalEdges();
}
//===----------------------------------------------------------------------===//
// Implementation of the external critical edge manipulation functions
//===----------------------------------------------------------------------===//
/// createPHIsForSplitLoopExit - When a loop exit edge is split, LCSSA form
/// may require new PHIs in the new exit block. This function inserts the
/// new PHIs, as needed. Preds is a list of preds inside the loop, SplitBB
/// is the new loop exit block, and DestBB is the old loop exit, now the
/// successor of SplitBB.
static void createPHIsForSplitLoopExit(ArrayRef<BasicBlock *> Preds,
BasicBlock *SplitBB,
BasicBlock *DestBB) {
// SplitBB shouldn't have anything non-trivial in it yet.
assert((SplitBB->getFirstNonPHI() == SplitBB->getTerminator() ||
SplitBB->isLandingPad()) && "SplitBB has non-PHI nodes!");
// For each PHI in the destination block.
for (BasicBlock::iterator I = DestBB->begin();
PHINode *PN = dyn_cast<PHINode>(I); ++I) {
unsigned Idx = PN->getBasicBlockIndex(SplitBB);
Value *V = PN->getIncomingValue(Idx);
// If the input is a PHI which already satisfies LCSSA, don't create
// a new one.
if (const PHINode *VP = dyn_cast<PHINode>(V))
if (VP->getParent() == SplitBB)
continue;
// Otherwise a new PHI is needed. Create one and populate it.
PHINode *NewPN =
PHINode::Create(PN->getType(), Preds.size(), "split",
SplitBB->isLandingPad() ?
SplitBB->begin() : SplitBB->getTerminator());
for (unsigned i = 0, e = Preds.size(); i != e; ++i)
NewPN->addIncoming(V, Preds[i]);
// Update the original PHI.
PN->setIncomingValue(Idx, NewPN);
}
}
/// SplitCriticalEdge - If this edge is a critical edge, insert a new node to
/// split the critical edge. This will update DominatorTree information if it
/// is available, thus calling this pass will not invalidate either of them.
/// This returns the new block if the edge was split, null otherwise.
///
/// If MergeIdenticalEdges is true (not the default), *all* edges from TI to the
/// specified successor will be merged into the same critical edge block.
/// This is most commonly interesting with switch instructions, which may
/// have many edges to any one destination. This ensures that all edges to that
/// dest go to one block instead of each going to a different block, but isn't
/// the standard definition of a "critical edge".
///
/// It is invalid to call this function on a critical edge that starts at an
/// IndirectBrInst. Splitting these edges will almost always create an invalid
/// program because the address of the new block won't be the one that is jumped
/// to.
///
BasicBlock *llvm::SplitCriticalEdge(TerminatorInst *TI, unsigned SuccNum,
Pass *P, bool MergeIdenticalEdges,
bool DontDeleteUselessPhis,
bool SplitLandingPads) {
if (!isCriticalEdge(TI, SuccNum, MergeIdenticalEdges)) return nullptr;
assert(!isa<IndirectBrInst>(TI) &&
"Cannot split critical edge from IndirectBrInst");
BasicBlock *TIBB = TI->getParent();
BasicBlock *DestBB = TI->getSuccessor(SuccNum);
// Splitting the critical edge to a landing pad block is non-trivial. Don't do
// it in this generic function.
if (DestBB->isLandingPad()) return nullptr;
// Create a new basic block, linking it into the CFG.
BasicBlock *NewBB = BasicBlock::Create(TI->getContext(),
TIBB->getName() + "." + DestBB->getName() + "_crit_edge");
// Create our unconditional branch.
BranchInst *NewBI = BranchInst::Create(DestBB, NewBB);
NewBI->setDebugLoc(TI->getDebugLoc());
// Branch to the new block, breaking the edge.
TI->setSuccessor(SuccNum, NewBB);
// Insert the block into the function... right after the block TI lives in.
Function &F = *TIBB->getParent();
Function::iterator FBBI = TIBB;
F.getBasicBlockList().insert(++FBBI, NewBB);
// If there are any PHI nodes in DestBB, we need to update them so that they
// merge incoming values from NewBB instead of from TIBB.
{
unsigned BBIdx = 0;
for (BasicBlock::iterator I = DestBB->begin(); isa<PHINode>(I); ++I) {
// We no longer enter through TIBB, now we come in through NewBB.
// Revector exactly one entry in the PHI node that used to come from
// TIBB to come from NewBB.
PHINode *PN = cast<PHINode>(I);
// Reuse the previous value of BBIdx if it lines up. In cases where we
// have multiple phi nodes with *lots* of predecessors, this is a speed
// win because we don't have to scan the PHI looking for TIBB. This
// happens because the BB list of PHI nodes are usually in the same
// order.
if (PN->getIncomingBlock(BBIdx) != TIBB)
BBIdx = PN->getBasicBlockIndex(TIBB);
PN->setIncomingBlock(BBIdx, NewBB);
}
}
// If there are any other edges from TIBB to DestBB, update those to go
// through the split block, making those edges non-critical as well (and
// reducing the number of phi entries in the DestBB if relevant).
if (MergeIdenticalEdges) {
for (unsigned i = SuccNum+1, e = TI->getNumSuccessors(); i != e; ++i) {
if (TI->getSuccessor(i) != DestBB) continue;
// Remove an entry for TIBB from DestBB phi nodes.
DestBB->removePredecessor(TIBB, DontDeleteUselessPhis);
// We found another edge to DestBB, go to NewBB instead.
TI->setSuccessor(i, NewBB);
}
}
// If we don't have a pass object, we can't update anything...
if (!P) return NewBB;
auto *AA = P->getAnalysisIfAvailable<AliasAnalysis>();
DominatorTreeWrapperPass *DTWP =
P->getAnalysisIfAvailable<DominatorTreeWrapperPass>();
DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
auto *LIWP = P->getAnalysisIfAvailable<LoopInfoWrapperPass>();
LoopInfo *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
bool PreserveLCSSA = P->mustPreserveAnalysisID(LCSSAID);
// If we have nothing to update, just return.
if (!DT && !LI)
return NewBB;
// Now update analysis information. Since the only predecessor of NewBB is
// the TIBB, TIBB clearly dominates NewBB. TIBB usually doesn't dominate
// anything, as there are other successors of DestBB. However, if all other
// predecessors of DestBB are already dominated by DestBB (e.g. DestBB is a
// loop header) then NewBB dominates DestBB.
SmallVector<BasicBlock*, 8> OtherPreds;
// If there is a PHI in the block, loop over predecessors with it, which is
// faster than iterating pred_begin/end.
if (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
if (PN->getIncomingBlock(i) != NewBB)
OtherPreds.push_back(PN->getIncomingBlock(i));
} else {
for (pred_iterator I = pred_begin(DestBB), E = pred_end(DestBB);
I != E; ++I) {
BasicBlock *P = *I;
if (P != NewBB)
OtherPreds.push_back(P);
}
}
bool NewBBDominatesDestBB = true;
// Should we update DominatorTree information?
if (DT) {
DomTreeNode *TINode = DT->getNode(TIBB);
// The new block is not the immediate dominator for any other nodes, but
// TINode is the immediate dominator for the new node.
//
if (TINode) { // Don't break unreachable code!
DomTreeNode *NewBBNode = DT->addNewBlock(NewBB, TIBB);
DomTreeNode *DestBBNode = nullptr;
// If NewBBDominatesDestBB hasn't been computed yet, do so with DT.
if (!OtherPreds.empty()) {
DestBBNode = DT->getNode(DestBB);
while (!OtherPreds.empty() && NewBBDominatesDestBB) {
if (DomTreeNode *OPNode = DT->getNode(OtherPreds.back()))
NewBBDominatesDestBB = DT->dominates(DestBBNode, OPNode);
OtherPreds.pop_back();
}
OtherPreds.clear();
}
// If NewBBDominatesDestBB, then NewBB dominates DestBB, otherwise it
// doesn't dominate anything.
if (NewBBDominatesDestBB) {
if (!DestBBNode) DestBBNode = DT->getNode(DestBB);
DT->changeImmediateDominator(DestBBNode, NewBBNode);
}
}
}
// Update LoopInfo if it is around.
if (LI) {
if (Loop *TIL = LI->getLoopFor(TIBB)) {
// If one or the other blocks were not in a loop, the new block is not
// either, and thus LI doesn't need to be updated.
if (Loop *DestLoop = LI->getLoopFor(DestBB)) {
if (TIL == DestLoop) {
// Both in the same loop, the NewBB joins loop.
DestLoop->addBasicBlockToLoop(NewBB, *LI);
} else if (TIL->contains(DestLoop)) {
// Edge from an outer loop to an inner loop. Add to the outer loop.
TIL->addBasicBlockToLoop(NewBB, *LI);
} else if (DestLoop->contains(TIL)) {
// Edge from an inner loop to an outer loop. Add to the outer loop.
DestLoop->addBasicBlockToLoop(NewBB, *LI);
} else {
// Edge from two loops with no containment relation. Because these
// are natural loops, we know that the destination block must be the
// header of its loop (adding a branch into a loop elsewhere would
// create an irreducible loop).
assert(DestLoop->getHeader() == DestBB &&
"Should not create irreducible loops!");
if (Loop *P = DestLoop->getParentLoop())
P->addBasicBlockToLoop(NewBB, *LI);
}
}
// If TIBB is in a loop and DestBB is outside of that loop, we may need
// to update LoopSimplify form and LCSSA form.
if (!TIL->contains(DestBB)) {
assert(!TIL->contains(NewBB) &&
"Split point for loop exit is contained in loop!");
// Update LCSSA form in the newly created exit block.
if (PreserveLCSSA) {
createPHIsForSplitLoopExit(TIBB, NewBB, DestBB);
}
// The only that we can break LoopSimplify form by splitting a critical
// edge is if after the split there exists some edge from TIL to DestBB
// *and* the only edge into DestBB from outside of TIL is that of
// NewBB. If the first isn't true, then LoopSimplify still holds, NewBB
// is the new exit block and it has no non-loop predecessors. If the
// second isn't true, then DestBB was not in LoopSimplify form prior to
// the split as it had a non-loop predecessor. In both of these cases,
// the predecessor must be directly in TIL, not in a subloop, or again
// LoopSimplify doesn't hold.
SmallVector<BasicBlock *, 4> LoopPreds;
for (pred_iterator I = pred_begin(DestBB), E = pred_end(DestBB); I != E;
++I) {
BasicBlock *P = *I;
if (P == NewBB)
continue; // The new block is known.
if (LI->getLoopFor(P) != TIL) {
// No need to re-simplify, it wasn't to start with.
LoopPreds.clear();
break;
}
LoopPreds.push_back(P);
}
if (!LoopPreds.empty()) {
assert(!DestBB->isLandingPad() &&
"We don't split edges to landing pads!");
BasicBlock *NewExitBB = SplitBlockPredecessors(
DestBB, LoopPreds, "split", AA, DT, LI, PreserveLCSSA);
if (PreserveLCSSA)
createPHIsForSplitLoopExit(LoopPreds, NewExitBB, DestBB);
}
}
}
}
return NewBB;
}
<|endoftext|>
|
<commit_before>// recycle result vector
on_all_cores([=] {
swap_refs({{symsrc}}.data, {{symsink}}.data);
{{symsink}}.data->vector.clear();
});
<commit_msg>newline<commit_after>// recycle result vector
on_all_cores([=] {
swap_refs({{symsrc}}.data, {{symsink}}.data);
{{symsink}}.data->vector.clear();
});
<|endoftext|>
|
<commit_before>#include "Engine.hpp"
int ProcessMudFunctions() {
// -- Handle our server protocols
if(!System.Server->ResetPollDescriptors()) { return PROCESS_FAILED; }
if(!System.Server->ResetFDControllers()) { return PROCESS_FAILED; }
if(!System.Server->SelectAndPoll()) { return PROCESS_FAILED; }
System.EventManager->processEvents(EV_BEFORE_INPUT);
// -- TODO: add input handling Server call here
System.EventManager->processEvents(EV_BEFORE_OUTPUT);
// -- TODO: add output handling Server call here
return PROCESS_SUCCESS;
}
int MainLoop() {
struct timeval last_time;
int processRetValue;
signal( SIGPIPE, SIG_IGN );
gettimeofday( &last_time, NULL );
System.CurrentSystemTime = (time_t) last_time.tv_sec;
while((processRetValue = ProcessMudFunctions()) != PROCESS_FAILED) {
// --------------------------------------------------------------------------------------------
// -- process End of Process functions
System.EventManager->processEvents(EV_POST_OUTPUT);
// -- TODO: add output handling Server call here (so we send any updates that have occurred before input)
// --------------------------------------------------------------------------------------------
// -- Process time management and system speed adjustments
// -- Need to figure out a better way to do this
struct timeval now_time;
long secDelta;
long usecDelta;
gettimeofday( &now_time, NULL );
usecDelta = ((int) last_time.tv_usec) - ((int) now_time.tv_usec) + 1000000 / 4;
secDelta = ((int) last_time.tv_sec ) - ((int) now_time.tv_sec );
while ( usecDelta < 0 )
{
usecDelta += 1000000;
secDelta -= 1;
}
while ( usecDelta >= 1000000 )
{
usecDelta -= 1000000;
secDelta += 1;
}
if ( secDelta > 0 || ( secDelta == 0 && usecDelta > 0 ) )
{
struct timeval stall_time;
stall_time.tv_usec = usecDelta;
stall_time.tv_sec = secDelta;
if ( select( 0, NULL, NULL, NULL, &stall_time ) < 0 )
{
// -- TODO: insert logging mechanism
kill(getpid(), SIGSEGV);
}
}
gettimeofday( &last_time, NULL );
System.CurrentSystemTime = (time_t) last_time.tv_sec;
// --------------------------------------------------------------------------------------------
} // -- end while loop
// -- generate a core file
if(processRetValue == PROCESS_FAILED) {
kill(getpid(), SIGSEGV);
}
return processRetValue;
}
// -- EOF
<commit_msg>Update Engine.cpp<commit_after>#include "Engine.hpp"
int ProcessMudFunctions() {
// -- Handle our server protocols
if(!System.mServer->ResetPollDescriptors()) { return PROCESS_FAILED; }
if(!System.mServer->ResetFDControllers()) { return PROCESS_FAILED; }
if(!System.mServer->SelectAndPoll()) { return PROCESS_FAILED; }
System.mEventManager->processEvents(EV_BEFORE_INPUT);
// -- TODO: add input handling Server call here
System.mEventManager->processEvents(EV_BEFORE_OUTPUT);
// -- TODO: add output handling Server call here
return PROCESS_SUCCESS;
}
int MainLoop() {
struct timeval last_time;
int processRetValue;
signal( SIGPIPE, SIG_IGN );
gettimeofday( &last_time, NULL );
System.CurrentSystemTime = (time_t) last_time.tv_sec;
while((processRetValue = ProcessMudFunctions()) != PROCESS_FAILED) {
// --------------------------------------------------------------------------------------------
// -- process End of Process functions
System.mEventManager->processEvents(EV_POST_OUTPUT);
// -- TODO: add output handling Server call here (so we send any updates that have occurred before input)
// --------------------------------------------------------------------------------------------
// -- Process time management and system speed adjustments
// -- Need to figure out a better way to do this
struct timeval now_time;
long secDelta;
long usecDelta;
gettimeofday( &now_time, NULL );
usecDelta = ((int) last_time.tv_usec) - ((int) now_time.tv_usec) + 1000000 / 4;
secDelta = ((int) last_time.tv_sec ) - ((int) now_time.tv_sec );
while ( usecDelta < 0 )
{
usecDelta += 1000000;
secDelta -= 1;
}
while ( usecDelta >= 1000000 )
{
usecDelta -= 1000000;
secDelta += 1;
}
if ( secDelta > 0 || ( secDelta == 0 && usecDelta > 0 ) )
{
struct timeval stall_time;
stall_time.tv_usec = usecDelta;
stall_time.tv_sec = secDelta;
if ( select( 0, NULL, NULL, NULL, &stall_time ) < 0 )
{
// -- TODO: insert logging mechanism
kill(getpid(), SIGSEGV);
}
}
gettimeofday( &last_time, NULL );
System.CurrentSystemTime = (time_t) last_time.tv_sec;
// --------------------------------------------------------------------------------------------
} // -- end while loop
// -- generate a core file
if(processRetValue == PROCESS_FAILED) {
kill(getpid(), SIGSEGV);
}
return processRetValue;
}
// -- EOF
<|endoftext|>
|
<commit_before>#include "Engine.hpp"
Server::Server() {
};
Server::~Server() {
}
bool Server::InitiatePort(int portNum) {
static struct sockaddr_in sa_zero;
struct sockaddr_in sa;
int x = 1;
int fd;
if ( ( fd = socket( AF_INET, SOCK_STREAM, 0 ) ) < 0 )
{
// -- TODO: insert logging mechanism
return false;
}
if ( setsockopt( fd, SOL_SOCKET, SO_REUSEADDR, (char *) &x, sizeof(x) ) < 0 )
{
// -- TODO: insert logging mechanism
close(fd);
exit( 1 );
}
#if defined(SO_DONTLINGER) && !defined(SYSV)
{
struct linger ld;
ld.l_onoff = 1;
ld.l_linger = 1000;
if ( setsockopt( fd, SOL_SOCKET, SO_DONTLINGER, (char *) &ld, sizeof(ld) ) < 0 ) {
// -- TODO: insert logging mechanism
close(fd);
return false;
}
}
#endif
sa = sa_zero;
sa.sin_family = AF_INET;
sa.sin_port = htons( port );
if ( bind( fd, (struct sockaddr *) &sa, sizeof(sa) ) < 0 )
{
// -- TODO: insert logging mechanism
close(fd);
return false;
}
if ( listen( fd, 3 ) < 0 )
{
// -- TODO: insert logging mechanism
close(fd);
exit(1);
}
mControl = fd;
return true;
}
bool Server::ResetPollDescriptors() {
FD_ZERO( &mRead );
FD_ZERO( &mWrite );
FD_ZERO( &mError );
FD_SET( mControl, &mRead );
maxedConnection = mControl;
return true;
}
bool Server::ResetFDControllers() {
std::list<Socket *>::iterator iter, itern;
for(iter = System.mSocketList.begin(); iter != System.mSocketList.end(); iter = itern) {
Socket *s = (*iter);
itern = ++iter;
maxedConnection = Maximum<int>( maxedConnection, s->getFileDescriptor() );
FD_SET( s->getFileDescriptor(), &mRead );
FD_SET( s->getFileDescriptor(), &mWrite );
FD_SET( s->getFileDescriptor(), &mError );
}
return;
}
bool Server::SelectAndPoll() {
static struct timeval base_time;
if ( select( maxedConnection+1, &mRead, &mWrite, &mError, &base_time ) < 0 )
{
return false;
}
if ( FD_ISSET( mControl, &mRead ) )
startNewSocket( mControl );
return true;
}
void Server::startNewSocket(int ctrl) {
Socket *s;
struct sockaddr_in sock;
int desc;
socklen_t size;
size = sizeof(sock);
getsockname( ctrl, (struct sockaddr *) &sock, &size );
if ( ( desc = accept( ctrl, (struct sockaddr *) &sock, &size) ) < 0 )
{
// -- TODO: insert log mechanism here
return;
}
#if !defined(FNDELAY)
#define FNDELAY O_NDELAY
#endif
if ( fcntl( desc, F_SETFL, FNDELAY ) == -1 )
{
// -- TODO: insert log mechanism here
return;
}
s = new Socket();
// -- attempt to glean the host address/ip
size = sizeof(sock);
if ( getpeername( desc, (struct sockaddr *) &sock, &size ) < 0 )
{
// -- TODO: insert logging mechanism
s->setHost("UNKNOWN");
s->setIpAddress("UNKNOWN");
} else {
struct hostent *from = gethostbyaddr( (char *) &sock.sin_addr, sizeof(sock.sin_addr), AF_INET );
s->setHost(from ? from->h_name : "UNKNOWN");
h->setIpAddress(inet_ntoa(sock.sin_addr));
}
System.mSocketList.push_back(s);
s->sendGreeting();
return;
}
bool Server::ReadFromSockets() {
std::list<Socket *>::iterator iter, itern;
for(iter = System.mSocketList.begin(); iter != System.mSocketList.end(); iter = itern) {
Socket *s = (*iter);
itern = ++iter;
if(FD_ISSET(s->getFileDescriptor(), &mRead)) {
if(!s->Read()) {
CloseSocket(s, true);
}
}
}
}
bool Server::ProcessInput() {
std::list<Socket *>::iterator iter, itern;
for(iter = System.mSocketList.begin(); iter != System.mSocketList.end(); iter = itern) {
Socket *s = (*iter);
itern = ++iter;
if(!s->getInputBuffer().empty()) {
// -- handle processing of the input buffer here.
// -- here we will attempt to process commands/functions
}
s->clearInputBuffer();
}
return true;
}
bool Server::FlushSockets() {
std::list<Socket *>::iterator iter, itern;
for(iter = System.mSocketList.begin(); iter != System.mSocketList.end(); iter = itern) {
Socket *s = (*iter);
itern = ++iter;
if(!s->Flush()) {
CloseSocket(s, true);
}
}
return true;
}
void Server::CloseSocket(Socket *s, bool forced) {
// -- attempt to dump any remaining data to the socket
if(!forced) {
// -- we don't attempt to trap errors here, if it returns false we just don't
// -- care as they were disconnecting anyways.
s->Flush();
}
// -- strip the socket from the socket-list
System.mSocketList.remove(s);
// -- reset the control values for said socket to CLR status.
FD_CLR(s->getFileDescriptor(), &mRead);
FD_CLR(s->getFileDescriptor(), &mWrite);
FD_CLR(s->getFileDescriptor(), &mError);
// -- handle accounts/players here
// -- close out the descriptor
close(s->getFileDescriptor());
// -- delete the actual socket-data (kill any lingering data)
delete s;
}
<commit_msg>Update Server.cpp<commit_after>#include "Engine.hpp"
Server::Server() {
};
Server::~Server() {
}
bool Server::InitiatePort(int portNum) {
static struct sockaddr_in sa_zero;
struct sockaddr_in sa;
int x = 1;
int fd;
if ( ( fd = socket( AF_INET, SOCK_STREAM, 0 ) ) < 0 )
{
// -- TODO: insert logging mechanism
return false;
}
if ( setsockopt( fd, SOL_SOCKET, SO_REUSEADDR, (char *) &x, sizeof(x) ) < 0 )
{
// -- TODO: insert logging mechanism
close(fd);
exit( 1 );
}
#if defined(SO_DONTLINGER) && !defined(SYSV)
{
struct linger ld;
ld.l_onoff = 1;
ld.l_linger = 1000;
if ( setsockopt( fd, SOL_SOCKET, SO_DONTLINGER, (char *) &ld, sizeof(ld) ) < 0 ) {
// -- TODO: insert logging mechanism
close(fd);
return false;
}
}
#endif
sa = sa_zero;
sa.sin_family = AF_INET;
sa.sin_port = htons( port );
if ( bind( fd, (struct sockaddr *) &sa, sizeof(sa) ) < 0 )
{
// -- TODO: insert logging mechanism
close(fd);
return false;
}
if ( listen( fd, 3 ) < 0 )
{
// -- TODO: insert logging mechanism
close(fd);
return false;
}
mControl = fd;
return true;
}
bool Server::ResetPollDescriptors() {
FD_ZERO( &mRead );
FD_ZERO( &mWrite );
FD_ZERO( &mError );
FD_SET( mControl, &mRead );
maxedConnection = mControl;
return true;
}
bool Server::ResetFDControllers() {
std::list<Socket *>::iterator iter, itern;
for(iter = System.mSocketList.begin(); iter != System.mSocketList.end(); iter = itern) {
Socket *s = (*iter);
itern = ++iter;
maxedConnection = Maximum<int>( maxedConnection, s->getFileDescriptor() );
FD_SET( s->getFileDescriptor(), &mRead );
FD_SET( s->getFileDescriptor(), &mWrite );
FD_SET( s->getFileDescriptor(), &mError );
}
return;
}
bool Server::SelectAndPoll() {
static struct timeval base_time;
if ( select( maxedConnection+1, &mRead, &mWrite, &mError, &base_time ) < 0 )
{
return false;
}
if ( FD_ISSET( mControl, &mRead ) )
startNewSocket( mControl );
return true;
}
void Server::startNewSocket(int ctrl) {
Socket *s;
struct sockaddr_in sock;
int desc;
socklen_t size;
size = sizeof(sock);
getsockname( ctrl, (struct sockaddr *) &sock, &size );
if ( ( desc = accept( ctrl, (struct sockaddr *) &sock, &size) ) < 0 )
{
// -- TODO: insert log mechanism here
return;
}
#if !defined(FNDELAY)
#define FNDELAY O_NDELAY
#endif
if ( fcntl( desc, F_SETFL, FNDELAY ) == -1 )
{
// -- TODO: insert log mechanism here
return;
}
s = new Socket();
// -- attempt to glean the host address/ip
size = sizeof(sock);
if ( getpeername( desc, (struct sockaddr *) &sock, &size ) < 0 )
{
// -- TODO: insert logging mechanism
s->setHost("UNKNOWN");
s->setIpAddress("UNKNOWN");
} else {
struct hostent *from = gethostbyaddr( (char *) &sock.sin_addr, sizeof(sock.sin_addr), AF_INET );
s->setHost(from ? from->h_name : "UNKNOWN");
h->setIpAddress(inet_ntoa(sock.sin_addr));
}
System.mSocketList.push_back(s);
s->sendGreeting();
return;
}
bool Server::ReadFromSockets() {
std::list<Socket *>::iterator iter, itern;
for(iter = System.mSocketList.begin(); iter != System.mSocketList.end(); iter = itern) {
Socket *s = (*iter);
itern = ++iter;
if(FD_ISSET(s->getFileDescriptor(), &mRead)) {
if(!s->Read()) {
CloseSocket(s, true);
}
}
}
}
bool Server::ProcessInput() {
std::list<Socket *>::iterator iter, itern;
for(iter = System.mSocketList.begin(); iter != System.mSocketList.end(); iter = itern) {
Socket *s = (*iter);
itern = ++iter;
if(!s->getInputBuffer().empty()) {
// -- handle processing of the input buffer here.
// -- here we will attempt to process commands/functions
}
s->clearInputBuffer();
}
return true;
}
bool Server::FlushSockets() {
std::list<Socket *>::iterator iter, itern;
for(iter = System.mSocketList.begin(); iter != System.mSocketList.end(); iter = itern) {
Socket *s = (*iter);
itern = ++iter;
if(!s->Flush()) {
CloseSocket(s, true);
}
}
return true;
}
void Server::CloseSocket(Socket *s, bool forced) {
// -- attempt to dump any remaining data to the socket
if(!forced) {
// -- we don't attempt to trap errors here, if it returns false we just don't
// -- care as they were disconnecting anyways.
s->Flush();
}
// -- strip the socket from the socket-list
System.mSocketList.remove(s);
// -- reset the control values for said socket to CLR status.
FD_CLR(s->getFileDescriptor(), &mRead);
FD_CLR(s->getFileDescriptor(), &mWrite);
FD_CLR(s->getFileDescriptor(), &mError);
// -- handle accounts/players here
// -- close out the descriptor
close(s->getFileDescriptor());
// -- delete the actual socket-data (kill any lingering data)
delete s;
}
<|endoftext|>
|
<commit_before>#ifndef ECL_ISTREAM_HPP
#define ECL_ISTREAM_HPP
#include <cstddef>
#include <cstdint>
namespace ecl {
template< class IO_device >
class istream
{
public:
// Provides type information of the underlaying device
using device_type = IO_device;
// Initializes a stream with given device
// NOTE: device must be initialized and opened already
istream(IO_device *device);
~istream();
istream& operator>>(int& value);
istream& operator>>(unsigned int& value);
istream& operator>>(char& character);
istream& operator>>(char *string);
// For I\O manipulators
istream& operator>>(istream& (*func)(istream< IO_device >&));
// NOTE: this will be used later with different manipulators,
// such that used for hex or octal output of integers
// unformatted input
int get();
istream& get(char& c);
private:
// Simply, a device driver object
IO_device *m_device;
};
//------------------------------------------------------------------------------
template< class IO_device >
istream< IO_device >::istream(IO_device *device)
:m_device{device}
{
}
template< class IO_device >
istream< IO_device >::~istream()
{
}
template< class IO_device >
istream<IO_device>& istream< IO_device >::operator>>(int& value)
{
value = 0;
char in_character;
char in_char_for_spaces;
int symbol_code;
bool sign = false; //TRUE is used to indicate negative number
bool first = true; //TRUE indicates the first round of cycle
do{
if(m_device->read((uint8_t*) &in_char_for_spaces, 1) < 0) {
break;
}
} while(in_char_for_spaces == ' ');
in_character = in_char_for_spaces;
do{
symbol_code = in_character;
if(symbol_code >= 48 && symbol_code <= 58) {
value = value * 10 + (symbol_code - 48);
}
else if(symbol_code == 45 && first == true) {
sign = true;
first = false;
}
else if (in_character != '\n') {
break; //FIXME: add error handling
}
if(m_device->read((uint8_t*) &in_character, 1) < 0) {
break;
}
} while(in_character != '\n' && in_character != ' ');
if(sign == true) {
value *= -1;
}
return *this;
}
template< class IO_device >
istream<IO_device>& istream< IO_device >::operator>>(unsigned int& value)
{
value = 0;
char in_character;
char in_char_for_spaces;
int symbol_code;
do{
if(m_device->read((uint8_t*) &in_char_for_spaces, 1) < 0) {
break;
}
} while(in_char_for_spaces == ' ');
in_character = in_char_for_spaces;
do{
symbol_code = in_character;
if(symbol_code >= 48 && symbol_code <= 58) {
value = value * 10 + (symbol_code - 48);
}
else if (in_character != '\n') {
break; //FIXME: add error handling
}
if(m_device->read((uint8_t*) &in_character, 1) < 0) {
break; //FIXME: add error handling
}
} while(in_character != '\n' && in_character != ' ');
return *this;
}
template< class IO_device >
istream<IO_device>& istream< IO_device >::operator>>(char& character)
{
char in_char_for_spaces;
do{
if(m_device->read((uint8_t*) &in_char_for_spaces, 1) < 0) {
break;
}
} while(in_char_for_spaces == ' ');
character = in_char_for_spaces;
return *this;
}
template< class IO_device >
istream<IO_device>& istream< IO_device >::operator>>(char *string)
{
size_t i = 1;
char in_char_for_spaces;
do{
if(m_device->read((uint8_t*) &in_char_for_spaces, 1) < 0) {
break;
}
} while(in_char_for_spaces == ' ');
string[0] = in_char_for_spaces;
do {
if(m_device->read((uint8_t *) &string[i], 1) < 0) {
break; //FIXME: add error handling
}
}
while(string[i] != '\n' && string[i++] != ' ');
return *this;
}
template< class IO_device >
istream<IO_device>& istream< IO_device >::operator>>(
istream& (*func)(istream< IO_device >&))
{
return func(*this);
}
template< class IO_device >
int istream< IO_device >::get()
{
int c = 0;
if(m_device->read((uint8_t *) &c, 1) < 0) {
return -1;
}
return c;
}
template< class IO_device >
istream<IO_device>& istream< IO_device >::get(char& character)
{
m_device->read((uint8_t *) &character, 1);
return *this;
}
}
#endif // ECL_istream_HPP
<commit_msg>Tabs substituted with sapces<commit_after>#ifndef ECL_ISTREAM_HPP
#define ECL_ISTREAM_HPP
#include <cstddef>
#include <cstdint>
namespace ecl {
template< class IO_device >
class istream
{
public:
// Provides type information of the underlaying device
using device_type = IO_device;
// Initializes a stream with given device
// NOTE: device must be initialized and opened already
istream(IO_device *device);
~istream();
istream& operator>>(int& value);
istream& operator>>(unsigned int& value);
istream& operator>>(char& character);
istream& operator>>(char *string);
// For I\O manipulators
istream& operator>>(istream& (*func)(istream< IO_device >&));
// NOTE: this will be used later with different manipulators,
// such that used for hex or octal output of integers
// unformatted input
int get();
istream& get(char& c);
private:
// Simply, a device driver object
IO_device *m_device;
};
//------------------------------------------------------------------------------
template< class IO_device >
istream< IO_device >::istream(IO_device *device)
:m_device{device}
{
}
template< class IO_device >
istream< IO_device >::~istream()
{
}
template< class IO_device >
istream<IO_device>& istream< IO_device >::operator>>(int& value)
{
value = 0;
char in_character;
char in_char_for_spaces;
int symbol_code;
bool sign = false; //TRUE is used to indicate negative number
bool first = true; //TRUE indicates the first round of cycle
do{
if(m_device->read((uint8_t*) &in_char_for_spaces, 1) < 0) {
break;
}
} while(in_char_for_spaces == ' ');
in_character = in_char_for_spaces;
do{
symbol_code = in_character;
if(symbol_code >= 48 && symbol_code <= 58) {
value = value * 10 + (symbol_code - 48);
}
else if(symbol_code == 45 && first == true) {
sign = true;
first = false;
}
else if (in_character != '\n') {
break; //FIXME: add error handling
}
if(m_device->read((uint8_t*) &in_character, 1) < 0) {
break;
}
} while(in_character != '\n' && in_character != ' ');
if(sign == true) {
value *= -1;
}
return *this;
}
template< class IO_device >
istream<IO_device>& istream< IO_device >::operator>>(unsigned int& value)
{
value = 0;
char in_character;
char in_char_for_spaces;
int symbol_code;
do{
if(m_device->read((uint8_t*) &in_char_for_spaces, 1) < 0) {
break;
}
} while(in_char_for_spaces == ' ');
in_character = in_char_for_spaces;
do{
symbol_code = in_character;
if(symbol_code >= 48 && symbol_code <= 58) {
value = value * 10 + (symbol_code - 48);
}
else if (in_character != '\n') {
break; //FIXME: add error handling
}
if(m_device->read((uint8_t*) &in_character, 1) < 0) {
break; //FIXME: add error handling
}
} while(in_character != '\n' && in_character != ' ');
return *this;
}
template< class IO_device >
istream<IO_device>& istream< IO_device >::operator>>(char& character)
{
char in_char_for_spaces;
do{
if(m_device->read((uint8_t*) &in_char_for_spaces, 1) < 0) {
break;
}
} while(in_char_for_spaces == ' ');
character = in_char_for_spaces;
return *this;
}
template< class IO_device >
istream<IO_device>& istream< IO_device >::operator>>(char *string)
{
size_t i = 1;
char in_char_for_spaces;
do{
if(m_device->read((uint8_t*) &in_char_for_spaces, 1) < 0) {
break;
}
} while(in_char_for_spaces == ' ');
string[0] = in_char_for_spaces;
do {
if(m_device->read((uint8_t *) &string[i], 1) < 0) {
break; //FIXME: add error handling
}
}
while(string[i] != '\n' && string[i++] != ' ');
return *this;
}
template< class IO_device >
istream<IO_device>& istream< IO_device >::operator>>(
istream& (*func)(istream< IO_device >&))
{
return func(*this);
}
template< class IO_device >
int istream< IO_device >::get()
{
int c = 0;
if(m_device->read((uint8_t *) &c, 1) < 0) {
return -1;
}
return c;
}
template< class IO_device >
istream<IO_device>& istream< IO_device >::get(char& character)
{
m_device->read((uint8_t *) &character, 1);
return *this;
}
}
#endif // ECL_istream_HPP
<|endoftext|>
|
<commit_before>/*******************************************************************************
* Copyright (c) 2009-2014, MAV'RIC Development Team
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
/*******************************************************************************
* \file tasks.c
*
* \author MAV'RIC Team
*
* \brief Definition of the tasks executed on the autopilot
*
******************************************************************************/
#include "tasks.hpp"
#include "central_data.hpp"
extern "C"
{
#include "led.h"
#include "pwm_servos.h"
}
void tasks_run_imu_update(Central_data* central_data)
{
central_data->imu.update();
qfilter_update(¢ral_data->attitude_filter);
position_estimation_update(¢ral_data->position_estimation);
}
bool tasks_run_stabilisation(Central_data* central_data)
{
tasks_run_imu_update(central_data);
mav_mode_t mode = central_data->state.mav_mode;
if ( mav_modes_is_armed(mode) )
{
if ( mav_modes_is_auto(mode) )
{
central_data->controls = central_data->controls_nav;
central_data->controls.control_mode = VELOCITY_COMMAND_MODE;
// if no waypoints are set, we do position hold therefore the yaw mode is absolute
if (((central_data->state.nav_plan_active&&(!central_data->navigation.auto_takeoff)&&(!central_data->navigation.auto_landing)&&(!central_data->navigation.stop_nav)))||((central_data->state.mav_state == MAV_STATE_CRITICAL)&&(central_data->navigation.critical_behavior == FLY_TO_HOME_WP)))
//if (((central_data->state.nav_plan_active&&(!central_data->navigation.auto_takeoff)&&(!central_data->navigation.auto_landing)))||((central_data->state.mav_state == MAV_STATE_CRITICAL)&&(central_data->navigation.critical_behavior == FLY_TO_HOME_WP)))
{
central_data->controls.yaw_mode = YAW_RELATIVE;
}
else
{
central_data->controls.yaw_mode = YAW_ABSOLUTE;
}
if (central_data->state.in_the_air || central_data->navigation.auto_takeoff)
{
stabilisation_copter_cascade_stabilise(¢ral_data->stabilisation_copter);
servos_mix_quadcopter_diag_update( ¢ral_data->servo_mix );
}
}
else if ( mav_modes_is_guided(mode) )
{
central_data->controls = central_data->controls_nav;
central_data->controls.control_mode = VELOCITY_COMMAND_MODE;
if ((central_data->state.mav_state == MAV_STATE_CRITICAL) && (central_data->navigation.critical_behavior == FLY_TO_HOME_WP))
{
central_data->controls.yaw_mode = YAW_RELATIVE;
}
else
{
central_data->controls.yaw_mode = YAW_ABSOLUTE;
}
if (central_data->state.in_the_air || central_data->navigation.auto_takeoff)
{
stabilisation_copter_cascade_stabilise(¢ral_data->stabilisation_copter);
servos_mix_quadcopter_diag_update( ¢ral_data->servo_mix );
}
}
else if ( mav_modes_is_stabilise(mode) )
{
manual_control_get_velocity_vector(¢ral_data->manual_control, ¢ral_data->controls);
central_data->controls.control_mode = VELOCITY_COMMAND_MODE;
central_data->controls.yaw_mode = YAW_RELATIVE;
if (central_data->state.in_the_air || central_data->navigation.auto_takeoff)
{
stabilisation_copter_cascade_stabilise(¢ral_data->stabilisation_copter);
servos_mix_quadcopter_diag_update( ¢ral_data->servo_mix );
}
}
else if ( mav_modes_is_manual(mode) )
{
manual_control_get_control_command(¢ral_data->manual_control, ¢ral_data->controls);
central_data->controls.control_mode = ATTITUDE_COMMAND_MODE;
central_data->controls.yaw_mode=YAW_RELATIVE;
stabilisation_copter_cascade_stabilise(¢ral_data->stabilisation_copter);
servos_mix_quadcopter_diag_update( ¢ral_data->servo_mix );
}
else
{
servos_set_value_failsafe( ¢ral_data->servos );
}
}
else
{
servos_set_value_failsafe( ¢ral_data->servos );
}
return true;
}
bool tasks_run_stabilisation_quaternion(Central_data* central_data);
bool tasks_run_stabilisation_quaternion(Central_data* central_data)
{
tasks_run_imu_update(central_data);
mav_mode_t mode = central_data->state.mav_mode;
if( mav_modes_is_armed(mode) == false )
{
// Set command to current heading
central_data->command.attitude.rpy[2] = coord_conventions_quat_to_aero(central_data->ahrs.qe).rpy[2];
servos_set_value_failsafe( ¢ral_data->servos );
}
else if( mav_modes_is_auto(mode) )
{
vector_field_waypoint_update( ¢ral_data->vector_field_waypoint );
velocity_controller_copter_update( ¢ral_data->velocity_controller );
attitude_controller_update( ¢ral_data->attitude_controller );
servos_mix_quadcopter_diag_update( ¢ral_data->servo_mix );
}
else if( mav_modes_is_manual(mode) && mav_modes_is_guided(mode) )
{
manual_control_get_velocity_command(¢ral_data->manual_control, ¢ral_data->command.velocity, 1.0f);
velocity_controller_copter_update( ¢ral_data->velocity_controller );
attitude_controller_update( ¢ral_data->attitude_controller );
servos_mix_quadcopter_diag_update( ¢ral_data->servo_mix );
}
else if( mav_modes_is_manual(mode) && mav_modes_is_stabilise(mode) )
{
manual_control_get_attitude_command(¢ral_data->manual_control, 0.02f, ¢ral_data->command.attitude, 1.0f);
manual_control_get_thrust_command(¢ral_data->manual_control, ¢ral_data->command.thrust);
attitude_controller_update( ¢ral_data->attitude_controller );
servos_mix_quadcopter_diag_update( ¢ral_data->servo_mix );
}
else
{
servos_set_value_failsafe( ¢ral_data->servos );
}
return true;
}
bool tasks_run_gps_update(Central_data* central_data)
{
central_data->gps.update();
return true;
}
bool tasks_run_barometer_update(Central_data* central_data)
{
central_data->barometer.update();
return true;
}
bool tasks_run_sonar_update(Central_data* central_data)
{
central_data->sonar.update();
return true;
}
#include <unistd.h>
bool tasks_sleep(Central_data* central_data)
{
usleep(3900);
return true;
}
bool tasks_create_tasks(Central_data* central_data)
{
bool init_success = true;
scheduler_t* scheduler = ¢ral_data->scheduler;
// init_success &= scheduler_add_task(scheduler, 4000, RUN_REGULAR, PERIODIC_ABSOLUTE, PRIORITY_HIGHEST, (task_function_t)&tasks_run_stabilisation , (task_argument_t)central_data , 0);
init_success &= scheduler_add_task(scheduler, 4000, RUN_REGULAR, PERIODIC_ABSOLUTE, PRIORITY_HIGHEST, (task_function_t)&tasks_run_stabilisation_quaternion , (task_argument_t)central_data , 0);
init_success &= scheduler_add_task(scheduler, 15000, RUN_REGULAR, PERIODIC_RELATIVE, PRIORITY_HIGH , (task_function_t)&tasks_run_barometer_update , (task_argument_t)central_data , 2);
init_success &= scheduler_add_task(scheduler, 100000, RUN_REGULAR, PERIODIC_ABSOLUTE, PRIORITY_HIGH , (task_function_t)&tasks_run_gps_update , (task_argument_t)central_data , 3);
// init_success &= scheduler_add_task(scheduler, 10000, RUN_REGULAR, PERIODIC_ABSOLUTE, PRIORITY_HIGH , (task_function_t)&navigation_update , (task_argument_t)¢ral_data->navigation , 4);
init_success &= scheduler_add_task(scheduler, 10000, RUN_REGULAR, PERIODIC_ABSOLUTE, PRIORITY_HIGH , (task_function_t)&vector_field_waypoint_update , (task_argument_t)¢ral_data->vector_field_waypoint , 4);
init_success &= scheduler_add_task(scheduler, 200000, RUN_REGULAR, PERIODIC_ABSOLUTE, PRIORITY_NORMAL , (task_function_t)&state_machine_update , (task_argument_t)¢ral_data->state_machine , 5);
init_success &= scheduler_add_task(scheduler, 4000, RUN_REGULAR, PERIODIC_ABSOLUTE, PRIORITY_NORMAL , (task_function_t)&mavlink_communication_update , (task_argument_t)¢ral_data->mavlink_communication , 6);
init_success &= scheduler_add_task(scheduler, 10000, RUN_REGULAR, PERIODIC_ABSOLUTE, PRIORITY_LOW , (task_function_t)&waypoint_handler_control_time_out_waypoint_msg , (task_argument_t)¢ral_data->waypoint_handler , 8);
init_success &= scheduler_add_task(scheduler, 20000, RUN_REGULAR, PERIODIC_ABSOLUTE, PRIORITY_HIGH , (task_function_t)&remote_update , (task_argument_t)¢ral_data->manual_control.remote , 12);
init_success &= scheduler_add_task(scheduler, 500000, RUN_REGULAR, PERIODIC_ABSOLUTE, PRIORITY_LOW , (task_function_t)&tasks_run_sonar_update , (task_argument_t)central_data , 13);
init_success &= scheduler_add_task(scheduler, 4000, RUN_REGULAR, PERIODIC_ABSOLUTE, PRIORITY_LOWEST , (task_function_t)&tasks_sleep , (task_argument_t)central_data , 14);
scheduler_sort_tasks(scheduler);
return init_success;
}
<commit_msg>Roll back to gps navigation for test<commit_after>/*******************************************************************************
* Copyright (c) 2009-2014, MAV'RIC Development Team
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
/*******************************************************************************
* \file tasks.c
*
* \author MAV'RIC Team
*
* \brief Definition of the tasks executed on the autopilot
*
******************************************************************************/
#include "tasks.hpp"
#include "central_data.hpp"
extern "C"
{
#include "led.h"
#include "pwm_servos.h"
}
void tasks_run_imu_update(Central_data* central_data)
{
central_data->imu.update();
qfilter_update(¢ral_data->attitude_filter);
position_estimation_update(¢ral_data->position_estimation);
}
bool tasks_run_stabilisation(Central_data* central_data)
{
tasks_run_imu_update(central_data);
mav_mode_t mode = central_data->state.mav_mode;
if ( mav_modes_is_armed(mode) )
{
if ( mav_modes_is_auto(mode) )
{
central_data->controls = central_data->controls_nav;
central_data->controls.control_mode = VELOCITY_COMMAND_MODE;
// if no waypoints are set, we do position hold therefore the yaw mode is absolute
if (((central_data->state.nav_plan_active&&(!central_data->navigation.auto_takeoff)&&(!central_data->navigation.auto_landing)&&(!central_data->navigation.stop_nav)))||((central_data->state.mav_state == MAV_STATE_CRITICAL)&&(central_data->navigation.critical_behavior == FLY_TO_HOME_WP)))
//if (((central_data->state.nav_plan_active&&(!central_data->navigation.auto_takeoff)&&(!central_data->navigation.auto_landing)))||((central_data->state.mav_state == MAV_STATE_CRITICAL)&&(central_data->navigation.critical_behavior == FLY_TO_HOME_WP)))
{
central_data->controls.yaw_mode = YAW_RELATIVE;
}
else
{
central_data->controls.yaw_mode = YAW_ABSOLUTE;
}
if (central_data->state.in_the_air || central_data->navigation.auto_takeoff)
{
stabilisation_copter_cascade_stabilise(¢ral_data->stabilisation_copter);
servos_mix_quadcopter_diag_update( ¢ral_data->servo_mix );
}
}
else if ( mav_modes_is_guided(mode) )
{
central_data->controls = central_data->controls_nav;
central_data->controls.control_mode = VELOCITY_COMMAND_MODE;
if ((central_data->state.mav_state == MAV_STATE_CRITICAL) && (central_data->navigation.critical_behavior == FLY_TO_HOME_WP))
{
central_data->controls.yaw_mode = YAW_RELATIVE;
}
else
{
central_data->controls.yaw_mode = YAW_ABSOLUTE;
}
if (central_data->state.in_the_air || central_data->navigation.auto_takeoff)
{
stabilisation_copter_cascade_stabilise(¢ral_data->stabilisation_copter);
servos_mix_quadcopter_diag_update( ¢ral_data->servo_mix );
}
}
else if ( mav_modes_is_stabilise(mode) )
{
manual_control_get_velocity_vector(¢ral_data->manual_control, ¢ral_data->controls);
central_data->controls.control_mode = VELOCITY_COMMAND_MODE;
central_data->controls.yaw_mode = YAW_RELATIVE;
if (central_data->state.in_the_air || central_data->navigation.auto_takeoff)
{
stabilisation_copter_cascade_stabilise(¢ral_data->stabilisation_copter);
servos_mix_quadcopter_diag_update( ¢ral_data->servo_mix );
}
}
else if ( mav_modes_is_manual(mode) )
{
manual_control_get_control_command(¢ral_data->manual_control, ¢ral_data->controls);
central_data->controls.control_mode = ATTITUDE_COMMAND_MODE;
central_data->controls.yaw_mode=YAW_RELATIVE;
stabilisation_copter_cascade_stabilise(¢ral_data->stabilisation_copter);
servos_mix_quadcopter_diag_update( ¢ral_data->servo_mix );
}
else
{
servos_set_value_failsafe( ¢ral_data->servos );
}
}
else
{
servos_set_value_failsafe( ¢ral_data->servos );
}
return true;
}
bool tasks_run_stabilisation_quaternion(Central_data* central_data);
bool tasks_run_stabilisation_quaternion(Central_data* central_data)
{
tasks_run_imu_update(central_data);
mav_mode_t mode = central_data->state.mav_mode;
if( mav_modes_is_armed(mode) == false )
{
// Set command to current heading
central_data->command.attitude.rpy[2] = coord_conventions_quat_to_aero(central_data->ahrs.qe).rpy[2];
servos_set_value_failsafe( ¢ral_data->servos );
}
else if( mav_modes_is_auto(mode) )
{
vector_field_waypoint_update( ¢ral_data->vector_field_waypoint );
velocity_controller_copter_update( ¢ral_data->velocity_controller );
attitude_controller_update( ¢ral_data->attitude_controller );
servos_mix_quadcopter_diag_update( ¢ral_data->servo_mix );
}
else if( mav_modes_is_manual(mode) && mav_modes_is_guided(mode) )
{
manual_control_get_velocity_command(¢ral_data->manual_control, ¢ral_data->command.velocity, 1.0f);
velocity_controller_copter_update( ¢ral_data->velocity_controller );
attitude_controller_update( ¢ral_data->attitude_controller );
servos_mix_quadcopter_diag_update( ¢ral_data->servo_mix );
}
else if( mav_modes_is_manual(mode) && mav_modes_is_stabilise(mode) )
{
manual_control_get_attitude_command(¢ral_data->manual_control, 0.02f, ¢ral_data->command.attitude, 1.0f);
manual_control_get_thrust_command(¢ral_data->manual_control, ¢ral_data->command.thrust);
attitude_controller_update( ¢ral_data->attitude_controller );
servos_mix_quadcopter_diag_update( ¢ral_data->servo_mix );
}
else
{
servos_set_value_failsafe( ¢ral_data->servos );
}
return true;
}
bool tasks_run_gps_update(Central_data* central_data)
{
central_data->gps.update();
return true;
}
bool tasks_run_barometer_update(Central_data* central_data)
{
central_data->barometer.update();
return true;
}
bool tasks_run_sonar_update(Central_data* central_data)
{
central_data->sonar.update();
return true;
}
#include <unistd.h>
bool tasks_sleep(Central_data* central_data)
{
usleep(3900);
return true;
}
bool tasks_create_tasks(Central_data* central_data)
{
bool init_success = true;
scheduler_t* scheduler = ¢ral_data->scheduler;
init_success &= scheduler_add_task(scheduler, 4000, RUN_REGULAR, PERIODIC_ABSOLUTE, PRIORITY_HIGHEST, (task_function_t)&tasks_run_stabilisation , (task_argument_t)central_data , 0);
// init_success &= scheduler_add_task(scheduler, 4000, RUN_REGULAR, PERIODIC_ABSOLUTE, PRIORITY_HIGHEST, (task_function_t)&tasks_run_stabilisation_quaternion , (task_argument_t)central_data , 0);
init_success &= scheduler_add_task(scheduler, 15000, RUN_REGULAR, PERIODIC_RELATIVE, PRIORITY_HIGH , (task_function_t)&tasks_run_barometer_update , (task_argument_t)central_data , 2);
init_success &= scheduler_add_task(scheduler, 100000, RUN_REGULAR, PERIODIC_ABSOLUTE, PRIORITY_HIGH , (task_function_t)&tasks_run_gps_update , (task_argument_t)central_data , 3);
init_success &= scheduler_add_task(scheduler, 10000, RUN_REGULAR, PERIODIC_ABSOLUTE, PRIORITY_HIGH , (task_function_t)&navigation_update , (task_argument_t)¢ral_data->navigation , 4);
// init_success &= scheduler_add_task(scheduler, 10000, RUN_REGULAR, PERIODIC_ABSOLUTE, PRIORITY_HIGH , (task_function_t)&vector_field_waypoint_update , (task_argument_t)¢ral_data->vector_field_waypoint , 4);
init_success &= scheduler_add_task(scheduler, 200000, RUN_REGULAR, PERIODIC_ABSOLUTE, PRIORITY_NORMAL , (task_function_t)&state_machine_update , (task_argument_t)¢ral_data->state_machine , 5);
init_success &= scheduler_add_task(scheduler, 4000, RUN_REGULAR, PERIODIC_ABSOLUTE, PRIORITY_NORMAL , (task_function_t)&mavlink_communication_update , (task_argument_t)¢ral_data->mavlink_communication , 6);
init_success &= scheduler_add_task(scheduler, 10000, RUN_REGULAR, PERIODIC_ABSOLUTE, PRIORITY_LOW , (task_function_t)&waypoint_handler_control_time_out_waypoint_msg , (task_argument_t)¢ral_data->waypoint_handler , 8);
init_success &= scheduler_add_task(scheduler, 20000, RUN_REGULAR, PERIODIC_ABSOLUTE, PRIORITY_HIGH , (task_function_t)&remote_update , (task_argument_t)¢ral_data->manual_control.remote , 12);
init_success &= scheduler_add_task(scheduler, 500000, RUN_REGULAR, PERIODIC_ABSOLUTE, PRIORITY_LOW , (task_function_t)&tasks_run_sonar_update , (task_argument_t)central_data , 13);
init_success &= scheduler_add_task(scheduler, 4000, RUN_REGULAR, PERIODIC_ABSOLUTE, PRIORITY_LOWEST , (task_function_t)&tasks_sleep , (task_argument_t)central_data , 14);
scheduler_sort_tasks(scheduler);
return init_success;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2018 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include <boost/range/adaptor/map.hpp>
#include "view_update_generator.hh"
#include "service/priority_manager.hh"
#include "utils/error_injection.hh"
static logging::logger vug_logger("view_update_generator");
static inline void inject_failure(std::string_view operation) {
utils::get_local_injector().inject(operation,
[operation] { throw std::runtime_error(std::string(operation)); });
}
namespace db::view {
future<> view_update_generator::start() {
thread_attributes attr;
attr.sched_group = _db.get_streaming_scheduling_group();
_started = seastar::async(std::move(attr), [this]() mutable {
auto drop_sstable_references = defer([&] {
// Clear sstable references so sstables_manager::stop() doesn't hang.
vug_logger.info("leaving {} unstaged sstables unprocessed",
_sstables_to_move.size(), _sstables_with_tables.size());
_sstables_to_move.clear();
_sstables_with_tables.clear();
});
while (!_as.abort_requested()) {
if (_sstables_with_tables.empty()) {
_pending_sstables.wait().get();
}
// To ensure we don't race with updates, move the entire content
// into a local variable.
auto sstables_with_tables = std::exchange(_sstables_with_tables, {});
// If we got here, we will process all tables we know about so far eventually so there
// is no starvation
for (auto table_it = sstables_with_tables.begin(); table_it != sstables_with_tables.end(); table_it = sstables_with_tables.erase(table_it)) {
auto& [t, sstables] = *table_it;
schema_ptr s = t->schema();
vug_logger.trace("Processing {}.{}: {} sstables", s->ks_name(), s->cf_name(), sstables.size());
const auto num_sstables = sstables.size();
try {
// Exploit the fact that sstables in the staging directory
// are usually non-overlapping and use a partitioned set for
// the read.
auto ssts = make_lw_shared<sstables::sstable_set>(sstables::make_partitioned_sstable_set(s, make_lw_shared<sstable_list>(sstable_list{}), false));
for (auto& sst : sstables) {
ssts->insert(sst);
}
auto permit = _db.get_reader_concurrency_semaphore().make_permit(s.get(), "view_update_generator");
auto ms = mutation_source([this, ssts] (
schema_ptr s,
reader_permit permit,
const dht::partition_range& pr,
const query::partition_slice& ps,
const io_priority_class& pc,
tracing::trace_state_ptr ts,
streamed_mutation::forwarding fwd_ms,
mutation_reader::forwarding fwd_mr) {
return make_restricted_range_sstable_reader(std::move(ssts), s, std::move(permit), pr, ps, pc, std::move(ts), fwd_ms, fwd_mr);
});
auto [staging_sstable_reader, staging_sstable_reader_handle] = make_manually_paused_evictable_reader(
std::move(ms),
s,
permit,
query::full_partition_range,
s->full_slice(),
service::get_local_streaming_priority(),
nullptr,
::mutation_reader::forwarding::no);
inject_failure("view_update_generator_consume_staging_sstable");
auto result = staging_sstable_reader.consume_in_thread(view_updating_consumer(s, std::move(permit), *t, sstables, _as, staging_sstable_reader_handle), db::no_timeout);
if (result == stop_iteration::yes) {
break;
}
} catch (...) {
vug_logger.warn("Processing {} failed for table {}:{}. Will retry...", s->ks_name(), s->cf_name(), std::current_exception());
// Need to add sstables back to the set so we can retry later. By now it may
// have had other updates.
std::move(sstables.begin(), sstables.end(), std::back_inserter(_sstables_with_tables[t]));
break;
}
try {
inject_failure("view_update_generator_collect_consumed_sstables");
// collect all staging sstables to move in a map, grouped by table.
std::move(sstables.begin(), sstables.end(), std::back_inserter(_sstables_to_move[t]));
} catch (...) {
// Move from staging will be retried upon restart.
vug_logger.warn("Moving {} from staging failed: {}:{}. Ignoring...", s->ks_name(), s->cf_name(), std::current_exception());
}
_registration_sem.signal(num_sstables);
}
// For each table, move the processed staging sstables into the table's base dir.
for (auto it = _sstables_to_move.begin(); it != _sstables_to_move.end(); ) {
auto& [t, sstables] = *it;
try {
inject_failure("view_update_generator_move_staging_sstable");
t->move_sstables_from_staging(sstables).get();
} catch (...) {
// Move from staging will be retried upon restart.
vug_logger.warn("Moving some sstable from staging failed: {}. Ignoring...", std::current_exception());
}
it = _sstables_to_move.erase(it);
}
}
});
return make_ready_future<>();
}
future<> view_update_generator::stop() {
_as.request_abort();
_pending_sstables.signal();
return std::move(_started).then([this] {
_registration_sem.broken();
});
}
bool view_update_generator::should_throttle() const {
return !_started.available();
}
future<> view_update_generator::register_staging_sstable(sstables::shared_sstable sst, lw_shared_ptr<table> table) {
if (_as.abort_requested()) {
return make_ready_future<>();
}
inject_failure("view_update_generator_registering_staging_sstable");
_sstables_with_tables[table].push_back(std::move(sst));
_pending_sstables.signal();
if (should_throttle()) {
return _registration_sem.wait(1);
} else {
_registration_sem.consume(1);
return make_ready_future<>();
}
}
void view_update_generator::setup_metrics() {
namespace sm = seastar::metrics;
_metrics.add_group("view_update_generator", {
sm::make_gauge("pending_registrations", sm::description("Number of tasks waiting to register staging sstables"),
[this] { return _registration_sem.waiters(); }),
sm::make_gauge("queued_batches_count",
sm::description("Number of sets of sstables queued for view update generation"),
[this] { return _sstables_with_tables.size(); }),
sm::make_gauge("sstables_to_move_count",
sm::description("Number of sets of sstables which are already processed and wait to be moved from their staging directory"),
[this] { return _sstables_to_move.size(); })
});
}
}
<commit_msg>view_update_generator: start: close staging_sstable_reader when done<commit_after>/*
* Copyright (C) 2018 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include <boost/range/adaptor/map.hpp>
#include "view_update_generator.hh"
#include "service/priority_manager.hh"
#include "utils/error_injection.hh"
static logging::logger vug_logger("view_update_generator");
static inline void inject_failure(std::string_view operation) {
utils::get_local_injector().inject(operation,
[operation] { throw std::runtime_error(std::string(operation)); });
}
namespace db::view {
future<> view_update_generator::start() {
thread_attributes attr;
attr.sched_group = _db.get_streaming_scheduling_group();
_started = seastar::async(std::move(attr), [this]() mutable {
auto drop_sstable_references = defer([&] {
// Clear sstable references so sstables_manager::stop() doesn't hang.
vug_logger.info("leaving {} unstaged sstables unprocessed",
_sstables_to_move.size(), _sstables_with_tables.size());
_sstables_to_move.clear();
_sstables_with_tables.clear();
});
while (!_as.abort_requested()) {
if (_sstables_with_tables.empty()) {
_pending_sstables.wait().get();
}
// To ensure we don't race with updates, move the entire content
// into a local variable.
auto sstables_with_tables = std::exchange(_sstables_with_tables, {});
// If we got here, we will process all tables we know about so far eventually so there
// is no starvation
for (auto table_it = sstables_with_tables.begin(); table_it != sstables_with_tables.end(); table_it = sstables_with_tables.erase(table_it)) {
auto& [t, sstables] = *table_it;
schema_ptr s = t->schema();
vug_logger.trace("Processing {}.{}: {} sstables", s->ks_name(), s->cf_name(), sstables.size());
const auto num_sstables = sstables.size();
try {
// Exploit the fact that sstables in the staging directory
// are usually non-overlapping and use a partitioned set for
// the read.
auto ssts = make_lw_shared<sstables::sstable_set>(sstables::make_partitioned_sstable_set(s, make_lw_shared<sstable_list>(sstable_list{}), false));
for (auto& sst : sstables) {
ssts->insert(sst);
}
auto permit = _db.get_reader_concurrency_semaphore().make_permit(s.get(), "view_update_generator");
auto ms = mutation_source([this, ssts] (
schema_ptr s,
reader_permit permit,
const dht::partition_range& pr,
const query::partition_slice& ps,
const io_priority_class& pc,
tracing::trace_state_ptr ts,
streamed_mutation::forwarding fwd_ms,
mutation_reader::forwarding fwd_mr) {
return make_restricted_range_sstable_reader(std::move(ssts), s, std::move(permit), pr, ps, pc, std::move(ts), fwd_ms, fwd_mr);
});
auto [staging_sstable_reader, staging_sstable_reader_handle] = make_manually_paused_evictable_reader(
std::move(ms),
s,
permit,
query::full_partition_range,
s->full_slice(),
service::get_local_streaming_priority(),
nullptr,
::mutation_reader::forwarding::no);
inject_failure("view_update_generator_consume_staging_sstable");
auto result = staging_sstable_reader.consume_in_thread(view_updating_consumer(s, std::move(permit), *t, sstables, _as, staging_sstable_reader_handle), db::no_timeout);
staging_sstable_reader.close().get();
if (result == stop_iteration::yes) {
break;
}
} catch (...) {
vug_logger.warn("Processing {} failed for table {}:{}. Will retry...", s->ks_name(), s->cf_name(), std::current_exception());
// Need to add sstables back to the set so we can retry later. By now it may
// have had other updates.
std::move(sstables.begin(), sstables.end(), std::back_inserter(_sstables_with_tables[t]));
break;
}
try {
inject_failure("view_update_generator_collect_consumed_sstables");
// collect all staging sstables to move in a map, grouped by table.
std::move(sstables.begin(), sstables.end(), std::back_inserter(_sstables_to_move[t]));
} catch (...) {
// Move from staging will be retried upon restart.
vug_logger.warn("Moving {} from staging failed: {}:{}. Ignoring...", s->ks_name(), s->cf_name(), std::current_exception());
}
_registration_sem.signal(num_sstables);
}
// For each table, move the processed staging sstables into the table's base dir.
for (auto it = _sstables_to_move.begin(); it != _sstables_to_move.end(); ) {
auto& [t, sstables] = *it;
try {
inject_failure("view_update_generator_move_staging_sstable");
t->move_sstables_from_staging(sstables).get();
} catch (...) {
// Move from staging will be retried upon restart.
vug_logger.warn("Moving some sstable from staging failed: {}. Ignoring...", std::current_exception());
}
it = _sstables_to_move.erase(it);
}
}
});
return make_ready_future<>();
}
future<> view_update_generator::stop() {
_as.request_abort();
_pending_sstables.signal();
return std::move(_started).then([this] {
_registration_sem.broken();
});
}
bool view_update_generator::should_throttle() const {
return !_started.available();
}
future<> view_update_generator::register_staging_sstable(sstables::shared_sstable sst, lw_shared_ptr<table> table) {
if (_as.abort_requested()) {
return make_ready_future<>();
}
inject_failure("view_update_generator_registering_staging_sstable");
_sstables_with_tables[table].push_back(std::move(sst));
_pending_sstables.signal();
if (should_throttle()) {
return _registration_sem.wait(1);
} else {
_registration_sem.consume(1);
return make_ready_future<>();
}
}
void view_update_generator::setup_metrics() {
namespace sm = seastar::metrics;
_metrics.add_group("view_update_generator", {
sm::make_gauge("pending_registrations", sm::description("Number of tasks waiting to register staging sstables"),
[this] { return _registration_sem.waiters(); }),
sm::make_gauge("queued_batches_count",
sm::description("Number of sets of sstables queued for view update generation"),
[this] { return _sstables_with_tables.size(); }),
sm::make_gauge("sstables_to_move_count",
sm::description("Number of sets of sstables which are already processed and wait to be moved from their staging directory"),
[this] { return _sstables_to_move.size(); })
});
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2013, Matthew Harvey. All rights reserved.
#include "reconciliation_entry_list_ctrl.hpp"
#include "entry.hpp"
#include "filtered_entry_list_ctrl.hpp"
#include "finformat.hpp"
#include "locale.hpp"
#include "ordinary_journal.hpp"
#include "reconciliation_status_marker.hpp"
#include "summary_datum.hpp"
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/optional.hpp>
#include <jewel/decimal.hpp>
#include <jewel/optional.hpp>
#include <wx/listctrl.h>
#include <vector>
using boost::optional;
using jewel::Decimal;
using jewel::value;
using std::vector;
// For debugging
#include <jewel/debug_log.hpp>
#include <iostream>
using std::endl;
namespace gregorian = boost::gregorian;
namespace phatbooks
{
namespace gui
{
// TODO We can use "EVT_LIST_ITEM_COL_CLICK" to activate this
// on left click of the "Reconciled" column - which is more intuitive.
BEGIN_EVENT_TABLE(ReconciliationEntryListCtrl, FilteredEntryListCtrl)
EVT_LIST_ITEM_RIGHT_CLICK
( wxID_ANY,
ReconciliationEntryListCtrl::on_item_right_click
)
END_EVENT_TABLE()
namespace
{
int comment_col_num()
{
return 1;
}
int amount_col_num()
{
return 2;
}
int reconciled_col_num()
{
return 3;
}
int anon_num_columns()
{
return 4;
}
} // end anonymous namespace
ReconciliationEntryListCtrl::ReconciliationEntryListCtrl
( ReconciliationListPanel* p_parent,
wxSize const& p_size,
Account const& p_account,
gregorian::date const& p_min_date,
gregorian::date const& p_max_date
):
FilteredEntryListCtrl
( p_parent,
p_size,
p_account,
optional<gregorian::date>(p_min_date),
optional<gregorian::date>(p_max_date)
),
m_max_date(p_max_date),
m_summary_data(0),
m_closing_balance(0, p_account.commodity().precision()),
m_reconciled_closing_balance(0, p_account.commodity().precision())
{
}
ReconciliationEntryListCtrl::~ReconciliationEntryListCtrl()
{
delete m_summary_data;
m_summary_data = 0;
}
void
ReconciliationEntryListCtrl::do_set_non_date_columns
( long p_row,
Entry const& p_entry
)
{
SetItem
( p_row,
comment_col_num(),
bstring_to_wx(p_entry.comment())
);
SetItem
( p_row,
amount_col_num(),
finformat_wx(p_entry.amount(), locale(), false)
);
SetItem
( p_row,
reconciled_col_num(),
reconciliation_status_marker(p_entry.is_reconciled())
);
assert (num_columns() == 4);
return;
}
void
ReconciliationEntryListCtrl::do_insert_non_date_columns()
{
InsertColumn
( comment_col_num(),
wxString("Memo"),
wxLIST_FORMAT_LEFT
);
InsertColumn
( amount_col_num(),
wxString("Amount"),
wxLIST_FORMAT_RIGHT
);
InsertColumn
( reconciled_col_num(),
wxString("Reconciled?"),
wxLIST_FORMAT_RIGHT
);
assert (num_columns() == 4);
return;
}
bool
ReconciliationEntryListCtrl::do_approve_entry(Entry const& p_entry) const
{
if (p_entry.account() != account())
{
return false;
}
gregorian::date const date = p_entry.date();
if (date > max_date())
{
return false;
}
if (date < min_date())
{
// We include unreconciled Entries even if they're prior to the
// min_date(), providing they're not later than max_date().
assert (date <= max_date());
assert
( (date > database_connection().opening_balance_journal_date()) ||
p_entry.is_reconciled()
);
return !p_entry.is_reconciled();
}
assert (p_entry.account() == account());
assert (date >= min_date());
assert (date <= max_date());
return true;
}
int
ReconciliationEntryListCtrl::do_get_comment_col_num() const
{
return comment_col_num();
}
int
ReconciliationEntryListCtrl::do_get_num_columns() const
{
return anon_num_columns();
}
vector<SummaryDatum> const&
ReconciliationEntryListCtrl::do_get_summary_data() const
{
assert (!m_summary_data->empty());
m_summary_data->at(0).set_amount(m_closing_balance);
m_summary_data->at(1).set_amount(m_reconciled_closing_balance);
return *m_summary_data;
}
void
ReconciliationEntryListCtrl::do_initialize_summary_data()
{
m_closing_balance = Decimal(0, account().commodity().precision());
m_reconciled_closing_balance =
Decimal(0, account().commodity().precision());
assert (!m_summary_data);
m_summary_data = new std::vector<SummaryDatum>;
SummaryDatum a
( wxString("Closing balance"),
m_closing_balance
);
m_summary_data->push_back(a);
SummaryDatum b
( wxString("Reconciled balance"),
m_reconciled_closing_balance
);
m_summary_data->push_back(b);
return;
}
void
ReconciliationEntryListCtrl::do_process_candidate_entry_for_summary
( Entry const& p_entry
)
{
if (p_entry.account() != account())
{
return;
}
assert (p_entry.account() == account());
jewel::Decimal const amount = p_entry.amount();
if (p_entry.date() <= max_date())
{
m_closing_balance += amount;
if (p_entry.is_reconciled()) m_reconciled_closing_balance += amount;
}
return;
}
void
ReconciliationEntryListCtrl::do_process_removal_for_summary(long p_row)
{
Decimal const amount = amount_for_row(p_row);
m_closing_balance -= amount;
# ifndef NDEBUG
wxListItem item;
item.SetId(p_row);
item.SetColumn(reconciled_col_num());
GetItem(item);
// TODO HIGH PRIORITY This assertion can fail!
assert (item.GetText() == reconciliation_status_marker(false));
// as we don't allow user to delete reconciled Entries.
// so we don't need to adjust m_reconciled_closing_balance here.
# endif
return;
}
void
ReconciliationEntryListCtrl::on_item_right_click(wxListEvent& event)
{
int const col = reconciled_col_num();
Entry::Id const entry_id = event.GetData();
long const pos = event.GetIndex();
assert (FindItem(-1, entry_id) == pos);
assert (entry_id >= 0);
assert (GetItemData(pos) == static_cast<size_t>(entry_id));
Entry entry(database_connection(), entry_id);
bool const old_reconciliation_status = entry.is_reconciled();
entry.set_whether_reconciled(!old_reconciliation_status);
SetItem(pos, col, reconciliation_status_marker(entry.is_reconciled()));
if (entry.is_reconciled())
{
m_reconciled_closing_balance += entry.amount();
}
else
{
m_reconciled_closing_balance -= entry.amount();
}
entry.save();
ReconciliationListPanel* parent =
dynamic_cast<ReconciliationListPanel*>(GetParent());
assert (parent);
parent->postconfigure_summary();
return;
}
Decimal
ReconciliationEntryListCtrl::amount_for_row(long p_row) const
{
wxListItem item;
item.SetId(p_row);
item.SetColumn(amount_col_num());
GetItem(item);
Decimal ret = wx_to_decimal(item.GetText(), locale());
return ret;
}
boost::gregorian::date
ReconciliationEntryListCtrl::max_date() const
{
return m_max_date;
}
} // namespace gui
} // namespace phatbooks
<commit_msg>Fixed ReconciliationEntryListCtrl::do_process_removal_for_summary(long) to account for the fact that on occasion reconciled Entries are in fact removed from the displayed list (albeit only to be immediately reinserted), viz. during the process of responding to a "journal edited" event.<commit_after>// Copyright (c) 2013, Matthew Harvey. All rights reserved.
#include "reconciliation_entry_list_ctrl.hpp"
#include "entry.hpp"
#include "filtered_entry_list_ctrl.hpp"
#include "finformat.hpp"
#include "locale.hpp"
#include "ordinary_journal.hpp"
#include "reconciliation_status_marker.hpp"
#include "summary_datum.hpp"
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/optional.hpp>
#include <jewel/decimal.hpp>
#include <jewel/optional.hpp>
#include <wx/listctrl.h>
#include <vector>
using boost::optional;
using jewel::Decimal;
using jewel::value;
using std::vector;
// For debugging
#include <jewel/debug_log.hpp>
#include <iostream>
using std::endl;
namespace gregorian = boost::gregorian;
namespace phatbooks
{
namespace gui
{
// TODO We can use "EVT_LIST_ITEM_COL_CLICK" to activate this
// on left click of the "Reconciled" column - which is more intuitive.
BEGIN_EVENT_TABLE(ReconciliationEntryListCtrl, FilteredEntryListCtrl)
EVT_LIST_ITEM_RIGHT_CLICK
( wxID_ANY,
ReconciliationEntryListCtrl::on_item_right_click
)
END_EVENT_TABLE()
namespace
{
int comment_col_num()
{
return 1;
}
int amount_col_num()
{
return 2;
}
int reconciled_col_num()
{
return 3;
}
int anon_num_columns()
{
return 4;
}
} // end anonymous namespace
ReconciliationEntryListCtrl::ReconciliationEntryListCtrl
( ReconciliationListPanel* p_parent,
wxSize const& p_size,
Account const& p_account,
gregorian::date const& p_min_date,
gregorian::date const& p_max_date
):
FilteredEntryListCtrl
( p_parent,
p_size,
p_account,
optional<gregorian::date>(p_min_date),
optional<gregorian::date>(p_max_date)
),
m_max_date(p_max_date),
m_summary_data(0),
m_closing_balance(0, p_account.commodity().precision()),
m_reconciled_closing_balance(0, p_account.commodity().precision())
{
}
ReconciliationEntryListCtrl::~ReconciliationEntryListCtrl()
{
delete m_summary_data;
m_summary_data = 0;
}
void
ReconciliationEntryListCtrl::do_set_non_date_columns
( long p_row,
Entry const& p_entry
)
{
SetItem
( p_row,
comment_col_num(),
bstring_to_wx(p_entry.comment())
);
SetItem
( p_row,
amount_col_num(),
finformat_wx(p_entry.amount(), locale(), false)
);
SetItem
( p_row,
reconciled_col_num(),
reconciliation_status_marker(p_entry.is_reconciled())
);
assert (num_columns() == 4);
return;
}
void
ReconciliationEntryListCtrl::do_insert_non_date_columns()
{
InsertColumn
( comment_col_num(),
wxString("Memo"),
wxLIST_FORMAT_LEFT
);
InsertColumn
( amount_col_num(),
wxString("Amount"),
wxLIST_FORMAT_RIGHT
);
InsertColumn
( reconciled_col_num(),
wxString("Reconciled?"),
wxLIST_FORMAT_RIGHT
);
assert (num_columns() == 4);
return;
}
bool
ReconciliationEntryListCtrl::do_approve_entry(Entry const& p_entry) const
{
if (p_entry.account() != account())
{
return false;
}
gregorian::date const date = p_entry.date();
if (date > max_date())
{
return false;
}
if (date < min_date())
{
// We include unreconciled Entries even if they're prior to the
// min_date(), providing they're not later than max_date().
assert (date <= max_date());
assert
( (date > database_connection().opening_balance_journal_date()) ||
p_entry.is_reconciled()
);
return !p_entry.is_reconciled();
}
assert (p_entry.account() == account());
assert (date >= min_date());
assert (date <= max_date());
return true;
}
int
ReconciliationEntryListCtrl::do_get_comment_col_num() const
{
return comment_col_num();
}
int
ReconciliationEntryListCtrl::do_get_num_columns() const
{
return anon_num_columns();
}
vector<SummaryDatum> const&
ReconciliationEntryListCtrl::do_get_summary_data() const
{
assert (!m_summary_data->empty());
m_summary_data->at(0).set_amount(m_closing_balance);
m_summary_data->at(1).set_amount(m_reconciled_closing_balance);
return *m_summary_data;
}
void
ReconciliationEntryListCtrl::do_initialize_summary_data()
{
m_closing_balance = Decimal(0, account().commodity().precision());
m_reconciled_closing_balance =
Decimal(0, account().commodity().precision());
assert (!m_summary_data);
m_summary_data = new std::vector<SummaryDatum>;
SummaryDatum a
( wxString("Closing balance"),
m_closing_balance
);
m_summary_data->push_back(a);
SummaryDatum b
( wxString("Reconciled balance"),
m_reconciled_closing_balance
);
m_summary_data->push_back(b);
return;
}
void
ReconciliationEntryListCtrl::do_process_candidate_entry_for_summary
( Entry const& p_entry
)
{
if (p_entry.account() != account())
{
return;
}
assert (p_entry.account() == account());
jewel::Decimal const amount = p_entry.amount();
if (p_entry.date() <= max_date())
{
m_closing_balance += amount;
if (p_entry.is_reconciled()) m_reconciled_closing_balance += amount;
}
return;
}
void
ReconciliationEntryListCtrl::do_process_removal_for_summary(long p_row)
{
// Item is in the visible list so must be removed from m_closing_balance
Decimal const amount = amount_for_row(p_row);
m_closing_balance -= amount;
// Check whether the item is marked as reconciled in the visible list.
// If it is, then its removal should impact m_reconciled_closing_balance.
wxListItem item;
item.SetId(p_row);
item.SetColumn(reconciled_col_num());
GetItem(item);
if (item.GetText() == reconciliation_status_marker(true))
{
m_reconciled_closing_balance -= amount;
}
return;
}
void
ReconciliationEntryListCtrl::on_item_right_click(wxListEvent& event)
{
int const col = reconciled_col_num();
Entry::Id const entry_id = event.GetData();
long const pos = event.GetIndex();
assert (FindItem(-1, entry_id) == pos);
assert (entry_id >= 0);
assert (GetItemData(pos) == static_cast<size_t>(entry_id));
Entry entry(database_connection(), entry_id);
bool const old_reconciliation_status = entry.is_reconciled();
entry.set_whether_reconciled(!old_reconciliation_status);
SetItem(pos, col, reconciliation_status_marker(entry.is_reconciled()));
if (entry.is_reconciled())
{
m_reconciled_closing_balance += entry.amount();
}
else
{
m_reconciled_closing_balance -= entry.amount();
}
entry.save();
ReconciliationListPanel* parent =
dynamic_cast<ReconciliationListPanel*>(GetParent());
assert (parent);
parent->postconfigure_summary();
return;
}
Decimal
ReconciliationEntryListCtrl::amount_for_row(long p_row) const
{
wxListItem item;
item.SetId(p_row);
item.SetColumn(amount_col_num());
GetItem(item);
Decimal ret = wx_to_decimal(item.GetText(), locale());
return ret;
}
boost::gregorian::date
ReconciliationEntryListCtrl::max_date() const
{
return m_max_date;
}
} // namespace gui
} // namespace phatbooks
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: dbwiz.cxx,v $
*
* $Revision: 1.20 $
*
* last change: $Author: kz $ $Date: 2008-03-06 18:18: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
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_dbaccess.hxx"
#ifndef DBAUI_DBWIZ_HXX
#include "dbwiz.hxx"
#endif
#ifndef _DBAUI_DBADMIN_HRC_
#include "dbadmin.hrc"
#endif
#ifndef _DBU_DLG_HRC_
#include "dbu_dlg.hrc"
#endif
#ifndef _DBAUI_DATASOURCEITEMS_HXX_
#include "dsitems.hxx"
#endif
#ifndef _SFXSTRITEM_HXX
#include <svtools/stritem.hxx>
#endif
#ifndef _SFXENUMITEM_HXX
#include <svtools/eitem.hxx>
#endif
#ifndef _SFXINTITEM_HXX
#include <svtools/intitem.hxx>
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
#ifndef DBACCESS_SHARED_DBUSTRINGS_HRC
#include "dbustrings.hrc"
#endif
#ifndef _DBAUI_ADMINPAGES_HXX_
#include "adminpages.hxx"
#endif
#ifndef _DBAUI_GENERALPAGE_HXX_
#include "generalpage.hxx"
#endif
#ifndef _DBAUI_LOCALRESACCESS_HXX_
#include "localresaccess.hxx"
#endif
#ifndef _DBAUI_STRINGLISTITEM_HXX_
#include "stringlistitem.hxx"
#endif
#ifndef _DBAUI_PROPERTYSETITEM_HXX_
#include "propertysetitem.hxx"
#endif
#ifndef _UNOTOOLS_CONFIGNODE_HXX_
#include <unotools/confignode.hxx>
#endif
#ifndef DBAUI_CONNECTIONPAGE_HXX
#include "ConnectionPage.hxx"
#endif
#ifndef DBAUI_DRIVERSETTINGS_HXX
#include "DriverSettings.hxx"
#endif
#ifndef _DBAUI_DBADMINIMPL_HXX_
#include "DbAdminImpl.hxx"
#endif
#ifndef _DBA_DBACCESS_HELPID_HRC_
#include "dbaccess_helpid.hrc"
#endif
//.........................................................................
namespace dbaui
{
//.........................................................................
using namespace svt;
using namespace com::sun::star::uno;
using namespace com::sun::star::sdbc;
using namespace com::sun::star::lang;
using namespace com::sun::star::util;
using namespace com::sun::star::beans;
using namespace com::sun::star::container;
#define START_PAGE 0
#define CONNECTION_PAGE 1
#define ADDITIONAL_PAGE_DBASE 2
#define ADDITIONAL_PAGE_FLAT 3
#define ADDITIONAL_PAGE_LDAP 4
#define ADDITIONAL_PAGE_ADABAS 5
#define ADDITIONAL_PAGE_MYSQL_JDBC 6
#define ADDITIONAL_PAGE_MYSQL_ODBC 7
#define ADDITIONAL_PAGE_ORACLE_JDBC 8
#define ADDITIONAL_PAGE_ADO 9
#define ADDITIONAL_PAGE_ODBC 10
#define ADDITIONAL_USERDEFINED 11
#define ADDITIONAL_PAGE_MYSQL_NATIVE 12
DBG_NAME(ODbTypeWizDialog)
//=========================================================================
//= ODbTypeWizDialog
//=========================================================================
//-------------------------------------------------------------------------
ODbTypeWizDialog::ODbTypeWizDialog(Window* _pParent
,SfxItemSet* _pItems
,const Reference< XMultiServiceFactory >& _rxORB
,const ::com::sun::star::uno::Any& _aDataSourceName
)
:OWizardMachine(_pParent, ModuleRes(DLG_DATABASE_TYPE_CHANGE), WZB_NEXT | WZB_PREVIOUS | WZB_FINISH | WZB_CANCEL | WZB_HELP )
,m_pOutSet(NULL)
,m_bResetting(sal_False)
,m_bApplied(sal_False)
,m_bUIEnabled( sal_True )
{
DBG_CTOR(ODbTypeWizDialog,NULL);
m_pImpl = ::std::auto_ptr<ODbDataSourceAdministrationHelper>(new ODbDataSourceAdministrationHelper(_rxORB,this,this));
m_pImpl->setDataSourceOrName(_aDataSourceName);
Reference< XPropertySet > xDatasource = m_pImpl->getCurrentDataSource();
m_pOutSet = new SfxItemSet( *_pItems->GetPool(), _pItems->GetRanges() );
m_pImpl->translateProperties(xDatasource, *m_pOutSet);
m_eType = m_pImpl->getDatasourceType(*m_pOutSet);
SetPageSizePixel(LogicToPixel(::Size(PAGE_X, PAGE_Y), MAP_APPFONT));
ShowButtonFixedLine(sal_True);
defaultButton(WZB_NEXT);
enableButtons(WZB_FINISH, sal_False);
enableAutomaticNextButtonState( true );
m_pPrevPage->SetHelpId(HID_DBWIZ_PREVIOUS);
m_pNextPage->SetHelpId(HID_DBWIZ_NEXT);
m_pCancel->SetHelpId(HID_DBWIZ_CANCEL);
m_pFinish->SetHelpId(HID_DBWIZ_FINISH);
m_pHelp->SetUniqueId(UID_DBWIZ_HELP);
// no local resources needed anymore
FreeResource();
ActivatePage();
}
//-------------------------------------------------------------------------
ODbTypeWizDialog::~ODbTypeWizDialog()
{
DBG_DTOR(ODbTypeWizDialog,NULL);
delete m_pOutSet;
}
//-------------------------------------------------------------------------
IMPL_LINK(ODbTypeWizDialog, OnTypeSelected, OGeneralPage*, _pTabPage)
{
m_eType = _pTabPage->GetSelectedType();
switch(m_eType)
{
case DST_MOZILLA:
case DST_OUTLOOK:
case DST_OUTLOOKEXP:
case DST_EVOLUTION:
case DST_KAB:
case DST_MACAB:
enableButtons(WZB_NEXT,sal_False);
enableButtons(WZB_FINISH,sal_True);
break;
default:
enableButtons(WZB_NEXT,sal_True);
enableButtons(WZB_FINISH,sal_False);
break;
}
return 1L;
}
//-------------------------------------------------------------------------
WizardTypes::WizardState ODbTypeWizDialog::determineNextState( WizardState _nCurrentState ) const
{
WizardTypes::WizardState nNextState = WZS_INVALID_STATE;
switch(_nCurrentState)
{
case START_PAGE:
switch(m_eType)
{
case DST_MOZILLA:
case DST_OUTLOOK:
case DST_OUTLOOKEXP:
case DST_EVOLUTION:
case DST_KAB:
case DST_MACAB:
nNextState = WZS_INVALID_STATE;
break;
default:
nNextState = CONNECTION_PAGE;
break;
}
break;
case CONNECTION_PAGE:
switch(m_eType)
{
case DST_MOZILLA:
case DST_THUNDERBIRD:
case DST_OUTLOOK:
case DST_OUTLOOKEXP:
case DST_EVOLUTION:
case DST_KAB:
case DST_MACAB:
case DST_MSACCESS:
case DST_MSACCESS_2007:
case DST_JDBC:
case DST_CALC:
nNextState = WZS_INVALID_STATE;
break;
case DST_DBASE:
nNextState = ADDITIONAL_PAGE_DBASE;
break;
case DST_FLAT:
nNextState = ADDITIONAL_PAGE_FLAT;
break;
case DST_LDAP:
nNextState = ADDITIONAL_PAGE_LDAP;
break;
case DST_ADABAS:
nNextState = ADDITIONAL_PAGE_ADABAS;
break;
case DST_MYSQL_NATIVE:
nNextState = ADDITIONAL_PAGE_MYSQL_NATIVE;
break;
case DST_MYSQL_JDBC:
nNextState = ADDITIONAL_PAGE_MYSQL_JDBC;
break;
case DST_MYSQL_ODBC:
nNextState = ADDITIONAL_PAGE_MYSQL_ODBC;
break;
case DST_ORACLE_JDBC:
nNextState = ADDITIONAL_PAGE_ORACLE_JDBC;
break;
case DST_ADO:
nNextState = ADDITIONAL_PAGE_ADO;
break;
case DST_ODBC:
nNextState = ADDITIONAL_PAGE_ODBC;
break;
default:
nNextState = WZS_INVALID_STATE;
break;
}
break;
}
return nNextState;
}
// -----------------------------------------------------------------------------
const SfxItemSet* ODbTypeWizDialog::getOutputSet() const
{
return m_pOutSet;
}
// -----------------------------------------------------------------------------
SfxItemSet* ODbTypeWizDialog::getWriteOutputSet()
{
return m_pOutSet;
}
// -----------------------------------------------------------------------------
::std::pair< Reference<XConnection>,sal_Bool> ODbTypeWizDialog::createConnection()
{
return m_pImpl->createConnection();
}
// -----------------------------------------------------------------------------
Reference< XMultiServiceFactory > ODbTypeWizDialog::getORB() const
{
return m_pImpl->getORB();
}
// -----------------------------------------------------------------------------
Reference< XDriver > ODbTypeWizDialog::getDriver()
{
return m_pImpl->getDriver();
}
// -----------------------------------------------------------------------------
DATASOURCE_TYPE ODbTypeWizDialog::getDatasourceType(const SfxItemSet& _rSet) const
{
return m_pImpl->getDatasourceType(_rSet);
}
// -----------------------------------------------------------------------------
void ODbTypeWizDialog::clearPassword()
{
m_pImpl->clearPassword();
}
// -----------------------------------------------------------------------------
TabPage* ODbTypeWizDialog::createPage(WizardState _nState)
{
USHORT nStringId = STR_PAGETITLE_ADVANCED;
TabPage* pPage = NULL;
switch(_nState)
{
case START_PAGE: // start state
{
pPage = OGeneralPage::Create(this,*m_pOutSet);
OGeneralPage* pGeneralPage = static_cast< OGeneralPage* >( pPage );
pGeneralPage->SetTypeSelectHandler( LINK( this, ODbTypeWizDialog, OnTypeSelected));
// pGeneralPage->SetCreationModeHandler( LINK( this, ODbTypeWizDialog, TODO ) );
nStringId = STR_PAGETITLE_GENERAL;
}
break;
case CONNECTION_PAGE:
pPage = OConnectionTabPage::Create(this,*m_pOutSet);
nStringId = STR_PAGETITLE_CONNECTION;
break;
case ADDITIONAL_PAGE_DBASE:
pPage = ODriversSettings::CreateDbase(this,*m_pOutSet);
break;
case ADDITIONAL_PAGE_FLAT:
pPage = ODriversSettings::CreateText(this,*m_pOutSet);
break;
case ADDITIONAL_PAGE_LDAP:
pPage = ODriversSettings::CreateLDAP(this,*m_pOutSet);
break;
case ADDITIONAL_PAGE_ADABAS:
pPage = ODriversSettings::CreateAdabas(this,*m_pOutSet);
break;
case ADDITIONAL_PAGE_MYSQL_JDBC:
pPage = ODriversSettings::CreateMySQLJDBC(this,*m_pOutSet);
break;
case ADDITIONAL_PAGE_MYSQL_NATIVE:
pPage = ODriversSettings::CreateMySQLNATIVE(this,*m_pOutSet);
break;
case ADDITIONAL_PAGE_MYSQL_ODBC:
pPage = ODriversSettings::CreateMySQLODBC(this,*m_pOutSet);
break;
case ADDITIONAL_PAGE_ORACLE_JDBC:
pPage = ODriversSettings::CreateOracleJDBC(this,*m_pOutSet);
break;
case ADDITIONAL_PAGE_ADO:
pPage = ODriversSettings::CreateAdo(this,*m_pOutSet);
break;
case ADDITIONAL_PAGE_ODBC:
pPage = ODriversSettings::CreateODBC(this,*m_pOutSet);
break;
case ADDITIONAL_USERDEFINED:
pPage = ODriversSettings::CreateUser(this,*m_pOutSet);
break;
default:
OSL_ENSURE(0,"Wrong state!");
break;
}
// register ourself as modified listener
if ( pPage )
{
static_cast<OGenericAdministrationPage*>(pPage)->SetServiceFactory(m_pImpl->getORB());
static_cast<OGenericAdministrationPage*>(pPage)->SetAdminDialog(this,this);
// open our own resource block, as the page titles are strings local to this block
LocalResourceAccess aDummy(DLG_DATABASE_ADMINISTRATION, RSC_TABDIALOG);
pPage->SetText(String(ModuleRes(nStringId)));
defaultButton( _nState == START_PAGE ? WZB_NEXT : WZB_FINISH );
enableButtons( WZB_FINISH, _nState == START_PAGE ? sal_False : sal_True);
pPage->Show();
}
return pPage;
}
// -----------------------------------------------------------------------------
sal_Bool ODbTypeWizDialog::leaveState(WizardState _nState)
{
SfxTabPage* pPage = static_cast<SfxTabPage*>(WizardDialog::GetPage(_nState));
if ( pPage )
pPage->FillItemSet(*m_pOutSet);
return sal_True;
}
// -----------------------------------------------------------------------------
void ODbTypeWizDialog::setTitle(const ::rtl::OUString& _sTitle)
{
SetText(_sTitle);
}
//-------------------------------------------------------------------------
void ODbTypeWizDialog::enableConfirmSettings( bool _bEnable )
{
enableButtons( WZB_FINISH, _bEnable );
// TODO:
// this is hacky. At the moment, this method is used in only one case (#b6532894#).
// As soon as it is to be used more wide-spread, we should find a proper concept
// for enabling both the Next and Finish buttons, depending on the current page state.
// Plus, the concept must also care for the case where those pages are embedded into
// anormal tab dialog.
}
//-------------------------------------------------------------------------
sal_Bool ODbTypeWizDialog::saveDatasource()
{
SfxTabPage* pPage = static_cast<SfxTabPage*>(WizardDialog::GetPage(getCurrentState()));
if ( pPage )
pPage->FillItemSet(*m_pOutSet);
return sal_True;
}
// -----------------------------------------------------------------------------
IWizardPage* ODbTypeWizDialog::getWizardPage(TabPage* _pCurrentPage) const
{
OGenericAdministrationPage* pPage = static_cast<OGenericAdministrationPage*>(_pCurrentPage);
return pPage;
}
// -----------------------------------------------------------------------------
sal_Bool ODbTypeWizDialog::onFinish(sal_Int32 _nResult)
{
saveDatasource();
return m_pImpl->saveChanges(*m_pOutSet) ? OWizardMachine::onFinish(_nResult) : sal_False;
}
//.........................................................................
} // namespace dbaui
//.........................................................................
<commit_msg>INTEGRATION: CWS changefileheader (1.20.12); FILE MERGED 2008/03/31 13:27:16 rt 1.20.12.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: dbwiz.cxx,v $
* $Revision: 1.21 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org 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 version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_dbaccess.hxx"
#ifndef DBAUI_DBWIZ_HXX
#include "dbwiz.hxx"
#endif
#ifndef _DBAUI_DBADMIN_HRC_
#include "dbadmin.hrc"
#endif
#ifndef _DBU_DLG_HRC_
#include "dbu_dlg.hrc"
#endif
#ifndef _DBAUI_DATASOURCEITEMS_HXX_
#include "dsitems.hxx"
#endif
#ifndef _SFXSTRITEM_HXX
#include <svtools/stritem.hxx>
#endif
#ifndef _SFXENUMITEM_HXX
#include <svtools/eitem.hxx>
#endif
#ifndef _SFXINTITEM_HXX
#include <svtools/intitem.hxx>
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
#ifndef DBACCESS_SHARED_DBUSTRINGS_HRC
#include "dbustrings.hrc"
#endif
#ifndef _DBAUI_ADMINPAGES_HXX_
#include "adminpages.hxx"
#endif
#ifndef _DBAUI_GENERALPAGE_HXX_
#include "generalpage.hxx"
#endif
#ifndef _DBAUI_LOCALRESACCESS_HXX_
#include "localresaccess.hxx"
#endif
#ifndef _DBAUI_STRINGLISTITEM_HXX_
#include "stringlistitem.hxx"
#endif
#ifndef _DBAUI_PROPERTYSETITEM_HXX_
#include "propertysetitem.hxx"
#endif
#ifndef _UNOTOOLS_CONFIGNODE_HXX_
#include <unotools/confignode.hxx>
#endif
#ifndef DBAUI_CONNECTIONPAGE_HXX
#include "ConnectionPage.hxx"
#endif
#ifndef DBAUI_DRIVERSETTINGS_HXX
#include "DriverSettings.hxx"
#endif
#ifndef _DBAUI_DBADMINIMPL_HXX_
#include "DbAdminImpl.hxx"
#endif
#ifndef _DBA_DBACCESS_HELPID_HRC_
#include "dbaccess_helpid.hrc"
#endif
//.........................................................................
namespace dbaui
{
//.........................................................................
using namespace svt;
using namespace com::sun::star::uno;
using namespace com::sun::star::sdbc;
using namespace com::sun::star::lang;
using namespace com::sun::star::util;
using namespace com::sun::star::beans;
using namespace com::sun::star::container;
#define START_PAGE 0
#define CONNECTION_PAGE 1
#define ADDITIONAL_PAGE_DBASE 2
#define ADDITIONAL_PAGE_FLAT 3
#define ADDITIONAL_PAGE_LDAP 4
#define ADDITIONAL_PAGE_ADABAS 5
#define ADDITIONAL_PAGE_MYSQL_JDBC 6
#define ADDITIONAL_PAGE_MYSQL_ODBC 7
#define ADDITIONAL_PAGE_ORACLE_JDBC 8
#define ADDITIONAL_PAGE_ADO 9
#define ADDITIONAL_PAGE_ODBC 10
#define ADDITIONAL_USERDEFINED 11
#define ADDITIONAL_PAGE_MYSQL_NATIVE 12
DBG_NAME(ODbTypeWizDialog)
//=========================================================================
//= ODbTypeWizDialog
//=========================================================================
//-------------------------------------------------------------------------
ODbTypeWizDialog::ODbTypeWizDialog(Window* _pParent
,SfxItemSet* _pItems
,const Reference< XMultiServiceFactory >& _rxORB
,const ::com::sun::star::uno::Any& _aDataSourceName
)
:OWizardMachine(_pParent, ModuleRes(DLG_DATABASE_TYPE_CHANGE), WZB_NEXT | WZB_PREVIOUS | WZB_FINISH | WZB_CANCEL | WZB_HELP )
,m_pOutSet(NULL)
,m_bResetting(sal_False)
,m_bApplied(sal_False)
,m_bUIEnabled( sal_True )
{
DBG_CTOR(ODbTypeWizDialog,NULL);
m_pImpl = ::std::auto_ptr<ODbDataSourceAdministrationHelper>(new ODbDataSourceAdministrationHelper(_rxORB,this,this));
m_pImpl->setDataSourceOrName(_aDataSourceName);
Reference< XPropertySet > xDatasource = m_pImpl->getCurrentDataSource();
m_pOutSet = new SfxItemSet( *_pItems->GetPool(), _pItems->GetRanges() );
m_pImpl->translateProperties(xDatasource, *m_pOutSet);
m_eType = m_pImpl->getDatasourceType(*m_pOutSet);
SetPageSizePixel(LogicToPixel(::Size(PAGE_X, PAGE_Y), MAP_APPFONT));
ShowButtonFixedLine(sal_True);
defaultButton(WZB_NEXT);
enableButtons(WZB_FINISH, sal_False);
enableAutomaticNextButtonState( true );
m_pPrevPage->SetHelpId(HID_DBWIZ_PREVIOUS);
m_pNextPage->SetHelpId(HID_DBWIZ_NEXT);
m_pCancel->SetHelpId(HID_DBWIZ_CANCEL);
m_pFinish->SetHelpId(HID_DBWIZ_FINISH);
m_pHelp->SetUniqueId(UID_DBWIZ_HELP);
// no local resources needed anymore
FreeResource();
ActivatePage();
}
//-------------------------------------------------------------------------
ODbTypeWizDialog::~ODbTypeWizDialog()
{
DBG_DTOR(ODbTypeWizDialog,NULL);
delete m_pOutSet;
}
//-------------------------------------------------------------------------
IMPL_LINK(ODbTypeWizDialog, OnTypeSelected, OGeneralPage*, _pTabPage)
{
m_eType = _pTabPage->GetSelectedType();
switch(m_eType)
{
case DST_MOZILLA:
case DST_OUTLOOK:
case DST_OUTLOOKEXP:
case DST_EVOLUTION:
case DST_KAB:
case DST_MACAB:
enableButtons(WZB_NEXT,sal_False);
enableButtons(WZB_FINISH,sal_True);
break;
default:
enableButtons(WZB_NEXT,sal_True);
enableButtons(WZB_FINISH,sal_False);
break;
}
return 1L;
}
//-------------------------------------------------------------------------
WizardTypes::WizardState ODbTypeWizDialog::determineNextState( WizardState _nCurrentState ) const
{
WizardTypes::WizardState nNextState = WZS_INVALID_STATE;
switch(_nCurrentState)
{
case START_PAGE:
switch(m_eType)
{
case DST_MOZILLA:
case DST_OUTLOOK:
case DST_OUTLOOKEXP:
case DST_EVOLUTION:
case DST_KAB:
case DST_MACAB:
nNextState = WZS_INVALID_STATE;
break;
default:
nNextState = CONNECTION_PAGE;
break;
}
break;
case CONNECTION_PAGE:
switch(m_eType)
{
case DST_MOZILLA:
case DST_THUNDERBIRD:
case DST_OUTLOOK:
case DST_OUTLOOKEXP:
case DST_EVOLUTION:
case DST_KAB:
case DST_MACAB:
case DST_MSACCESS:
case DST_MSACCESS_2007:
case DST_JDBC:
case DST_CALC:
nNextState = WZS_INVALID_STATE;
break;
case DST_DBASE:
nNextState = ADDITIONAL_PAGE_DBASE;
break;
case DST_FLAT:
nNextState = ADDITIONAL_PAGE_FLAT;
break;
case DST_LDAP:
nNextState = ADDITIONAL_PAGE_LDAP;
break;
case DST_ADABAS:
nNextState = ADDITIONAL_PAGE_ADABAS;
break;
case DST_MYSQL_NATIVE:
nNextState = ADDITIONAL_PAGE_MYSQL_NATIVE;
break;
case DST_MYSQL_JDBC:
nNextState = ADDITIONAL_PAGE_MYSQL_JDBC;
break;
case DST_MYSQL_ODBC:
nNextState = ADDITIONAL_PAGE_MYSQL_ODBC;
break;
case DST_ORACLE_JDBC:
nNextState = ADDITIONAL_PAGE_ORACLE_JDBC;
break;
case DST_ADO:
nNextState = ADDITIONAL_PAGE_ADO;
break;
case DST_ODBC:
nNextState = ADDITIONAL_PAGE_ODBC;
break;
default:
nNextState = WZS_INVALID_STATE;
break;
}
break;
}
return nNextState;
}
// -----------------------------------------------------------------------------
const SfxItemSet* ODbTypeWizDialog::getOutputSet() const
{
return m_pOutSet;
}
// -----------------------------------------------------------------------------
SfxItemSet* ODbTypeWizDialog::getWriteOutputSet()
{
return m_pOutSet;
}
// -----------------------------------------------------------------------------
::std::pair< Reference<XConnection>,sal_Bool> ODbTypeWizDialog::createConnection()
{
return m_pImpl->createConnection();
}
// -----------------------------------------------------------------------------
Reference< XMultiServiceFactory > ODbTypeWizDialog::getORB() const
{
return m_pImpl->getORB();
}
// -----------------------------------------------------------------------------
Reference< XDriver > ODbTypeWizDialog::getDriver()
{
return m_pImpl->getDriver();
}
// -----------------------------------------------------------------------------
DATASOURCE_TYPE ODbTypeWizDialog::getDatasourceType(const SfxItemSet& _rSet) const
{
return m_pImpl->getDatasourceType(_rSet);
}
// -----------------------------------------------------------------------------
void ODbTypeWizDialog::clearPassword()
{
m_pImpl->clearPassword();
}
// -----------------------------------------------------------------------------
TabPage* ODbTypeWizDialog::createPage(WizardState _nState)
{
USHORT nStringId = STR_PAGETITLE_ADVANCED;
TabPage* pPage = NULL;
switch(_nState)
{
case START_PAGE: // start state
{
pPage = OGeneralPage::Create(this,*m_pOutSet);
OGeneralPage* pGeneralPage = static_cast< OGeneralPage* >( pPage );
pGeneralPage->SetTypeSelectHandler( LINK( this, ODbTypeWizDialog, OnTypeSelected));
// pGeneralPage->SetCreationModeHandler( LINK( this, ODbTypeWizDialog, TODO ) );
nStringId = STR_PAGETITLE_GENERAL;
}
break;
case CONNECTION_PAGE:
pPage = OConnectionTabPage::Create(this,*m_pOutSet);
nStringId = STR_PAGETITLE_CONNECTION;
break;
case ADDITIONAL_PAGE_DBASE:
pPage = ODriversSettings::CreateDbase(this,*m_pOutSet);
break;
case ADDITIONAL_PAGE_FLAT:
pPage = ODriversSettings::CreateText(this,*m_pOutSet);
break;
case ADDITIONAL_PAGE_LDAP:
pPage = ODriversSettings::CreateLDAP(this,*m_pOutSet);
break;
case ADDITIONAL_PAGE_ADABAS:
pPage = ODriversSettings::CreateAdabas(this,*m_pOutSet);
break;
case ADDITIONAL_PAGE_MYSQL_JDBC:
pPage = ODriversSettings::CreateMySQLJDBC(this,*m_pOutSet);
break;
case ADDITIONAL_PAGE_MYSQL_NATIVE:
pPage = ODriversSettings::CreateMySQLNATIVE(this,*m_pOutSet);
break;
case ADDITIONAL_PAGE_MYSQL_ODBC:
pPage = ODriversSettings::CreateMySQLODBC(this,*m_pOutSet);
break;
case ADDITIONAL_PAGE_ORACLE_JDBC:
pPage = ODriversSettings::CreateOracleJDBC(this,*m_pOutSet);
break;
case ADDITIONAL_PAGE_ADO:
pPage = ODriversSettings::CreateAdo(this,*m_pOutSet);
break;
case ADDITIONAL_PAGE_ODBC:
pPage = ODriversSettings::CreateODBC(this,*m_pOutSet);
break;
case ADDITIONAL_USERDEFINED:
pPage = ODriversSettings::CreateUser(this,*m_pOutSet);
break;
default:
OSL_ENSURE(0,"Wrong state!");
break;
}
// register ourself as modified listener
if ( pPage )
{
static_cast<OGenericAdministrationPage*>(pPage)->SetServiceFactory(m_pImpl->getORB());
static_cast<OGenericAdministrationPage*>(pPage)->SetAdminDialog(this,this);
// open our own resource block, as the page titles are strings local to this block
LocalResourceAccess aDummy(DLG_DATABASE_ADMINISTRATION, RSC_TABDIALOG);
pPage->SetText(String(ModuleRes(nStringId)));
defaultButton( _nState == START_PAGE ? WZB_NEXT : WZB_FINISH );
enableButtons( WZB_FINISH, _nState == START_PAGE ? sal_False : sal_True);
pPage->Show();
}
return pPage;
}
// -----------------------------------------------------------------------------
sal_Bool ODbTypeWizDialog::leaveState(WizardState _nState)
{
SfxTabPage* pPage = static_cast<SfxTabPage*>(WizardDialog::GetPage(_nState));
if ( pPage )
pPage->FillItemSet(*m_pOutSet);
return sal_True;
}
// -----------------------------------------------------------------------------
void ODbTypeWizDialog::setTitle(const ::rtl::OUString& _sTitle)
{
SetText(_sTitle);
}
//-------------------------------------------------------------------------
void ODbTypeWizDialog::enableConfirmSettings( bool _bEnable )
{
enableButtons( WZB_FINISH, _bEnable );
// TODO:
// this is hacky. At the moment, this method is used in only one case (#b6532894#).
// As soon as it is to be used more wide-spread, we should find a proper concept
// for enabling both the Next and Finish buttons, depending on the current page state.
// Plus, the concept must also care for the case where those pages are embedded into
// anormal tab dialog.
}
//-------------------------------------------------------------------------
sal_Bool ODbTypeWizDialog::saveDatasource()
{
SfxTabPage* pPage = static_cast<SfxTabPage*>(WizardDialog::GetPage(getCurrentState()));
if ( pPage )
pPage->FillItemSet(*m_pOutSet);
return sal_True;
}
// -----------------------------------------------------------------------------
IWizardPage* ODbTypeWizDialog::getWizardPage(TabPage* _pCurrentPage) const
{
OGenericAdministrationPage* pPage = static_cast<OGenericAdministrationPage*>(_pCurrentPage);
return pPage;
}
// -----------------------------------------------------------------------------
sal_Bool ODbTypeWizDialog::onFinish(sal_Int32 _nResult)
{
saveDatasource();
return m_pImpl->saveChanges(*m_pOutSet) ? OWizardMachine::onFinish(_nResult) : sal_False;
}
//.........................................................................
} // namespace dbaui
//.........................................................................
<|endoftext|>
|
<commit_before>// Copyright (c) 2013, Matthew Harvey. All rights reserved.
#include "reconciliation_entry_list_ctrl.hpp"
#include "entry.hpp"
#include "filtered_entry_list_ctrl.hpp"
#include "finformat.hpp"
#include "locale.hpp"
#include "ordinary_journal.hpp"
#include "summary_datum.hpp"
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/optional.hpp>
#include <jewel/decimal.hpp>
#include <jewel/optional.hpp>
#include <wx/listctrl.h>
#include <vector>
using boost::optional;
using jewel::Decimal;
using jewel::value;
using std::vector;
// For debugging
#include <jewel/debug_log.hpp>
#include <iostream>
using std::endl;
namespace gregorian = boost::gregorian;
namespace phatbooks
{
namespace gui
{
// TODO We can use "EVT_LIST_ITEM_COL_CLICK" to activate this
// on left click of the "Reconciled" column - which is more intuitive.
BEGIN_EVENT_TABLE(ReconciliationEntryListCtrl, FilteredEntryListCtrl)
EVT_LIST_ITEM_RIGHT_CLICK
( wxID_ANY,
ReconciliationEntryListCtrl::on_item_right_click
)
END_EVENT_TABLE()
namespace
{
int comment_col_num()
{
return 1;
}
int amount_col_num()
{
return 2;
}
int reconciled_col_num()
{
return 3;
}
int anon_num_columns()
{
return 4;
}
} // end anonymous namespace
ReconciliationEntryListCtrl::ReconciliationEntryListCtrl
( ReconciliationListPanel* p_parent,
wxSize const& p_size,
Account const& p_account,
gregorian::date const& p_min_date,
gregorian::date const& p_max_date
):
FilteredEntryListCtrl
( p_parent,
p_size,
p_account,
optional<gregorian::date>(p_min_date),
optional<gregorian::date>(p_max_date)
),
m_max_date(p_max_date),
m_summary_data(0),
m_closing_balance(0, p_account.commodity().precision()),
m_reconciled_closing_balance(0, p_account.commodity().precision())
{
}
ReconciliationEntryListCtrl::~ReconciliationEntryListCtrl()
{
delete m_summary_data;
m_summary_data = 0;
}
void
ReconciliationEntryListCtrl::do_set_non_date_columns
( long p_row,
Entry const& p_entry
)
{
SetItem
( p_row,
comment_col_num(),
bstring_to_wx(p_entry.comment())
);
SetItem
( p_row,
amount_col_num(),
finformat_wx(p_entry.amount(), locale(), false)
);
SetItem
( p_row,
reconciled_col_num(),
(p_entry.is_reconciled()? wxString("Y"): wxString("N"))
);
assert (num_columns() == 4);
return;
}
void
ReconciliationEntryListCtrl::do_insert_non_date_columns()
{
InsertColumn
( comment_col_num(),
wxString("Memo"),
wxLIST_FORMAT_LEFT
);
InsertColumn
( amount_col_num(),
wxString("Amount"),
wxLIST_FORMAT_RIGHT
);
InsertColumn
( reconciled_col_num(),
wxString("Reconciled?"),
wxLIST_FORMAT_RIGHT
);
assert (num_columns() == 4);
return;
}
bool
ReconciliationEntryListCtrl::do_approve_entry(Entry const& p_entry) const
{
if (p_entry.account() != account())
{
return false;
}
gregorian::date const date = p_entry.date();
if (date > max_date())
{
return false;
}
if (date < min_date())
{
// We include unreconciled Entries even if they're prior to the
// min_date(), providing they're not later than max_date().
assert (date <= max_date());
assert
( (date > database_connection().opening_balance_journal_date()) ||
p_entry.is_reconciled()
);
return !p_entry.is_reconciled();
}
assert (p_entry.account() == account());
assert (date >= min_date());
assert (date <= max_date());
return true;
}
int
ReconciliationEntryListCtrl::do_get_comment_col_num() const
{
return comment_col_num();
}
int
ReconciliationEntryListCtrl::do_get_num_columns() const
{
return anon_num_columns();
}
vector<SummaryDatum> const&
ReconciliationEntryListCtrl::do_get_summary_data() const
{
assert (!m_summary_data->empty());
m_summary_data->at(0).set_amount(m_closing_balance);
m_summary_data->at(1).set_amount(m_reconciled_closing_balance);
return *m_summary_data;
}
void
ReconciliationEntryListCtrl::do_initialize_summary_data()
{
m_closing_balance = Decimal(0, account().commodity().precision());
m_reconciled_closing_balance =
Decimal(0, account().commodity().precision());
assert (!m_summary_data);
m_summary_data = new std::vector<SummaryDatum>;
SummaryDatum a
( wxString("Closing balance"),
m_closing_balance
);
m_summary_data->push_back(a);
SummaryDatum b
( wxString("Reconciled balance"),
m_reconciled_closing_balance
);
m_summary_data->push_back(b);
return;
}
void
ReconciliationEntryListCtrl::do_process_candidate_entry_for_summary
( Entry const& p_entry
)
{
if (p_entry.account() != account())
{
return;
}
assert (p_entry.account() == account());
jewel::Decimal const amount = p_entry.amount();
if (p_entry.date() <= max_date())
{
m_closing_balance += amount;
if (p_entry.is_reconciled()) m_reconciled_closing_balance += amount;
}
return;
}
void
ReconciliationEntryListCtrl::do_process_removal_for_summary(long p_row)
{
Decimal const amount = amount_for_row(p_row);
m_closing_balance -= amount;
# ifndef NDEBUG
wxListItem item;
item.SetId(p_row);
item.SetColumn(reconciled_col_num());
GetItem(item);
// TODO HIGH PRIORITY This assertion can fail!
assert (item.GetText() == wxString("N"));
// as we don't allow user to delete reconciled Entries.
// so we don't need to adjust m_reconciled_closing_balance here.
# endif
return;
}
void
ReconciliationEntryListCtrl::on_item_right_click(wxListEvent& event)
{
int const col = reconciled_col_num();
Entry::Id const entry_id = event.GetData();
long const pos = event.GetIndex();
assert (FindItem(-1, entry_id) == pos);
assert (entry_id >= 0);
assert (GetItemData(pos) == static_cast<size_t>(entry_id));
Entry entry(database_connection(), entry_id);
bool const old_reconciliation_status = entry.is_reconciled();
entry.set_whether_reconciled(!old_reconciliation_status);
SetItem(pos, col, entry.is_reconciled()? wxString("Y"): wxString("N"));
if (entry.is_reconciled())
{
m_reconciled_closing_balance += entry.amount();
}
else
{
m_reconciled_closing_balance -= entry.amount();
}
entry.save();
ReconciliationListPanel* parent =
dynamic_cast<ReconciliationListPanel*>(GetParent());
assert (parent);
parent->postconfigure_summary();
return;
}
Decimal
ReconciliationEntryListCtrl::amount_for_row(long p_row) const
{
wxListItem item;
item.SetId(p_row);
item.SetColumn(amount_col_num());
GetItem(item);
Decimal ret = wx_to_decimal(item.GetText(), locale());
return ret;
}
boost::gregorian::date
ReconciliationEntryListCtrl::max_date() const
{
return m_max_date;
}
} // namespace gui
} // namespace phatbooks
<commit_msg>In ReconciliationEntryListCtrl, instead of using "Y" and "N" to indicate reconciliation status, now using a the unicode "thick check" mark and an empty string, respectively. Did some refactoring so that the relationship between the reconciliation status and the particular string that represents it, is located within a single function.<commit_after>// Copyright (c) 2013, Matthew Harvey. All rights reserved.
#include "reconciliation_entry_list_ctrl.hpp"
#include "entry.hpp"
#include "filtered_entry_list_ctrl.hpp"
#include "finformat.hpp"
#include "locale.hpp"
#include "ordinary_journal.hpp"
#include "summary_datum.hpp"
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/optional.hpp>
#include <jewel/decimal.hpp>
#include <jewel/optional.hpp>
#include <wx/listctrl.h>
#include <vector>
using boost::optional;
using jewel::Decimal;
using jewel::value;
using std::vector;
// For debugging
#include <jewel/debug_log.hpp>
#include <iostream>
using std::endl;
namespace gregorian = boost::gregorian;
namespace phatbooks
{
namespace gui
{
// TODO We can use "EVT_LIST_ITEM_COL_CLICK" to activate this
// on left click of the "Reconciled" column - which is more intuitive.
BEGIN_EVENT_TABLE(ReconciliationEntryListCtrl, FilteredEntryListCtrl)
EVT_LIST_ITEM_RIGHT_CLICK
( wxID_ANY,
ReconciliationEntryListCtrl::on_item_right_click
)
END_EVENT_TABLE()
namespace
{
int comment_col_num()
{
return 1;
}
int amount_col_num()
{
return 2;
}
int reconciled_col_num()
{
return 3;
}
int anon_num_columns()
{
return 4;
}
wxString reconciliation_status_mark(bool p_is_reconciled)
{
return
p_is_reconciled?
wxString("\u2714"): // TODO HIGH PRIORITY Check that this "thick check" mark displays properly on Windows.
wxString();
}
} // end anonymous namespace
ReconciliationEntryListCtrl::ReconciliationEntryListCtrl
( ReconciliationListPanel* p_parent,
wxSize const& p_size,
Account const& p_account,
gregorian::date const& p_min_date,
gregorian::date const& p_max_date
):
FilteredEntryListCtrl
( p_parent,
p_size,
p_account,
optional<gregorian::date>(p_min_date),
optional<gregorian::date>(p_max_date)
),
m_max_date(p_max_date),
m_summary_data(0),
m_closing_balance(0, p_account.commodity().precision()),
m_reconciled_closing_balance(0, p_account.commodity().precision())
{
}
ReconciliationEntryListCtrl::~ReconciliationEntryListCtrl()
{
delete m_summary_data;
m_summary_data = 0;
}
void
ReconciliationEntryListCtrl::do_set_non_date_columns
( long p_row,
Entry const& p_entry
)
{
SetItem
( p_row,
comment_col_num(),
bstring_to_wx(p_entry.comment())
);
SetItem
( p_row,
amount_col_num(),
finformat_wx(p_entry.amount(), locale(), false)
);
SetItem
( p_row,
reconciled_col_num(),
reconciliation_status_mark(p_entry.is_reconciled())
);
assert (num_columns() == 4);
return;
}
void
ReconciliationEntryListCtrl::do_insert_non_date_columns()
{
InsertColumn
( comment_col_num(),
wxString("Memo"),
wxLIST_FORMAT_LEFT
);
InsertColumn
( amount_col_num(),
wxString("Amount"),
wxLIST_FORMAT_RIGHT
);
InsertColumn
( reconciled_col_num(),
wxString("Reconciled?"),
wxLIST_FORMAT_RIGHT
);
assert (num_columns() == 4);
return;
}
bool
ReconciliationEntryListCtrl::do_approve_entry(Entry const& p_entry) const
{
if (p_entry.account() != account())
{
return false;
}
gregorian::date const date = p_entry.date();
if (date > max_date())
{
return false;
}
if (date < min_date())
{
// We include unreconciled Entries even if they're prior to the
// min_date(), providing they're not later than max_date().
assert (date <= max_date());
assert
( (date > database_connection().opening_balance_journal_date()) ||
p_entry.is_reconciled()
);
return !p_entry.is_reconciled();
}
assert (p_entry.account() == account());
assert (date >= min_date());
assert (date <= max_date());
return true;
}
int
ReconciliationEntryListCtrl::do_get_comment_col_num() const
{
return comment_col_num();
}
int
ReconciliationEntryListCtrl::do_get_num_columns() const
{
return anon_num_columns();
}
vector<SummaryDatum> const&
ReconciliationEntryListCtrl::do_get_summary_data() const
{
assert (!m_summary_data->empty());
m_summary_data->at(0).set_amount(m_closing_balance);
m_summary_data->at(1).set_amount(m_reconciled_closing_balance);
return *m_summary_data;
}
void
ReconciliationEntryListCtrl::do_initialize_summary_data()
{
m_closing_balance = Decimal(0, account().commodity().precision());
m_reconciled_closing_balance =
Decimal(0, account().commodity().precision());
assert (!m_summary_data);
m_summary_data = new std::vector<SummaryDatum>;
SummaryDatum a
( wxString("Closing balance"),
m_closing_balance
);
m_summary_data->push_back(a);
SummaryDatum b
( wxString("Reconciled balance"),
m_reconciled_closing_balance
);
m_summary_data->push_back(b);
return;
}
void
ReconciliationEntryListCtrl::do_process_candidate_entry_for_summary
( Entry const& p_entry
)
{
if (p_entry.account() != account())
{
return;
}
assert (p_entry.account() == account());
jewel::Decimal const amount = p_entry.amount();
if (p_entry.date() <= max_date())
{
m_closing_balance += amount;
if (p_entry.is_reconciled()) m_reconciled_closing_balance += amount;
}
return;
}
void
ReconciliationEntryListCtrl::do_process_removal_for_summary(long p_row)
{
Decimal const amount = amount_for_row(p_row);
m_closing_balance -= amount;
# ifndef NDEBUG
wxListItem item;
item.SetId(p_row);
item.SetColumn(reconciled_col_num());
GetItem(item);
// TODO HIGH PRIORITY This assertion can fail!
assert (item.GetText() == reconciliation_status_mark(false));
// as we don't allow user to delete reconciled Entries.
// so we don't need to adjust m_reconciled_closing_balance here.
# endif
return;
}
void
ReconciliationEntryListCtrl::on_item_right_click(wxListEvent& event)
{
int const col = reconciled_col_num();
Entry::Id const entry_id = event.GetData();
long const pos = event.GetIndex();
assert (FindItem(-1, entry_id) == pos);
assert (entry_id >= 0);
assert (GetItemData(pos) == static_cast<size_t>(entry_id));
Entry entry(database_connection(), entry_id);
bool const old_reconciliation_status = entry.is_reconciled();
entry.set_whether_reconciled(!old_reconciliation_status);
SetItem(pos, col, reconciliation_status_mark(entry.is_reconciled()));
if (entry.is_reconciled())
{
m_reconciled_closing_balance += entry.amount();
}
else
{
m_reconciled_closing_balance -= entry.amount();
}
entry.save();
ReconciliationListPanel* parent =
dynamic_cast<ReconciliationListPanel*>(GetParent());
assert (parent);
parent->postconfigure_summary();
return;
}
Decimal
ReconciliationEntryListCtrl::amount_for_row(long p_row) const
{
wxListItem item;
item.SetId(p_row);
item.SetColumn(amount_col_num());
GetItem(item);
Decimal ret = wx_to_decimal(item.GetText(), locale());
return ret;
}
boost::gregorian::date
ReconciliationEntryListCtrl::max_date() const
{
return m_max_date;
}
} // namespace gui
} // namespace phatbooks
<|endoftext|>
|
<commit_before>// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "google/cloud/storage/benchmarks/aggregate_throughput_options.h"
#include "google/cloud/storage/benchmarks/benchmark_utils.h"
#include "google/cloud/storage/client.h"
#include "google/cloud/storage/grpc_plugin.h"
#include "google/cloud/grpc_options.h"
#include "google/cloud/internal/build_info.h"
#include "google/cloud/internal/getenv.h"
#include "google/cloud/internal/random.h"
#include "google/cloud/options.h"
#include "google/cloud/testing_util/command_line_parsing.h"
#include "google/cloud/testing_util/timer.h"
#include "absl/time/time.h"
#include <algorithm>
#include <atomic>
#include <future>
#include <iomanip>
#include <random>
#include <sstream>
#include <thread>
#include <vector>
namespace {
using ::google::cloud::storage_experimental::DefaultGrpcClient;
using ::google::cloud::testing_util::FormatSize;
using ::google::cloud::testing_util::Timer;
namespace gcs = google::cloud::storage;
namespace gcs_bm = google::cloud::storage_benchmarks;
using gcs_bm::AggregateThroughputOptions;
using gcs_bm::ApiName;
char const kDescription[] = R"""(A benchmark for aggregated throughput.
This program is used to evaluate the combined performance of GCS (the service)
and the C++ client library for GCS. It is not recommended as a benchmark for
the client library, as it introduces too many sources of performance variation.
It is useful when the C++ client library team collaborates with the GCS team to
measure changes in the service's performance.
The program measures the observed download throughput given a fixed "dataset",
that is, a collection of GCS objects contained in the same bucket, with a common
prefix. If needed, synthetic datasets can be created using the
`create_dataset.cc` in this directory. Given a dataset and some configuration
parameters the program will:
- Read the list of available objects in the dataset.
- Launch `thread-count` *download threads*, see below for their description.
- Every `reporting-interval` seconds the main thread will report the current
wall time and the total number of bytes downloaded by all the download
threads.
- After `running-time` seconds the main thread ask all other threads to
terminate.
- The main thread then waits for all the "download threads", collects any
metrics they choose to report, prints these metrics, and then exits.
While running, each download thread performs the following loop:
1) Create a gcs::Client object, see the `AggregateThroughputOptions` struct for
details about how this client object can be configured.
2) Check if the program is shutting down. If so, just return some metrics.
3) Pick one of the objects in the dataset at random.
4) If so configured, pick a random portion of the object to download, otherwise
simply download the full object.
5) Download the object, requesting `read-buffer-size` bytes from the client
library at a time.
6) Once the requested buffer is received, increment a per-thread counter with
the number of bytes received so far.
7) Keep track of the number of files downloaded, the gRPC peer used to download
the object (if applicable) and other counters.
8) Go back to step (2) in this list.
)""";
google::cloud::StatusOr<AggregateThroughputOptions> ParseArgs(int argc,
char* argv[]);
struct ThreadConfig {
std::atomic<std::int64_t> bytes_received{0};
std::seed_seq::result_type seed;
};
using Counters = std::map<std::string, std::int64_t>;
Counters RunThread(gcs::Client client,
AggregateThroughputOptions const& options,
std::vector<gcs::ObjectMetadata> const& objects,
ThreadConfig& config);
template <typename Rep, typename Period>
std::string FormatBandwidthGbPerSecond(
std::uintmax_t bytes, std::chrono::duration<Rep, Period> elapsed) {
using ns = ::std::chrono::nanoseconds;
auto const elapsed_ns = std::chrono::duration_cast<ns>(elapsed);
if (elapsed_ns == ns(0)) return "NaN";
auto const bandwidth =
8 * static_cast<double>(bytes) / static_cast<double>(elapsed_ns.count());
std::ostringstream os;
os << std::fixed << std::setprecision(2) << bandwidth;
return std::move(os).str();
}
template <typename Rep, typename Period>
std::string FormatBandwidthGiBPerSecond(
std::uintmax_t bytes, std::chrono::duration<Rep, Period> elapsed) {
using ::std::chrono::seconds;
auto const elapsed_s = std::chrono::duration_cast<seconds>(elapsed);
if (elapsed_s == seconds(0)) return "NaN";
auto const bandwidth = static_cast<double>(bytes) / gcs_bm::kGiB /
static_cast<double>(elapsed_s.count());
std::ostringstream os;
os << std::fixed << std::setprecision(2) << bandwidth;
return std::move(os).str();
}
} // namespace
int main(int argc, char* argv[]) {
auto options = ParseArgs(argc, argv);
if (!options) {
std::cerr << options.status() << "\n";
return 1;
}
if (options->exit_after_parse) return 1;
auto client = gcs::Client();
#if GOOGLE_CLOUD_CPP_STORAGE_HAVE_GRPC
if (options->api == ApiName::kApiGrpc) {
auto channels = options->grpc_channel_count;
if (channels == 0) channels = (std::max)(options->thread_count / 4, 4);
client = DefaultGrpcClient(
google::cloud::Options{}.set<google::cloud::GrpcNumChannelsOption>(
channels));
}
#endif // GOOGLE_CLOUD_CPP_STORAGE_HAVE_GRPC
std::vector<gcs::ObjectMetadata> objects;
std::uint64_t dataset_size = 0;
for (auto& o : client.ListObjects(options->bucket_name,
gcs::Prefix(options->object_prefix))) {
if (!o) break;
dataset_size += o->size();
objects.push_back(*std::move(o));
}
if (objects.empty()) {
std::cerr << "No objects found in bucket " << options->bucket_name
<< " starting with prefix " << options->object_prefix << "\n"
<< "Cannot run the benchmark with an empty dataset\n";
return 1;
}
std::string notes = google::cloud::storage::version_string() + ";" +
google::cloud::internal::compiler() + ";" +
google::cloud::internal::compiler_flags();
std::transform(notes.begin(), notes.end(), notes.begin(),
[](char c) { return c == '\n' ? ';' : c; });
auto current_time = [] {
auto constexpr kFormat = "%E4Y-%m-%dT%H:%M:%E*SZ";
auto const t = absl::FromChrono(std::chrono::system_clock::now());
return absl::FormatTime(kFormat, t, absl::UTCTimeZone());
};
std::cout << "# Start time: " << current_time()
<< "\n# Bucket Name: " << options->bucket_name
<< "\n# Object Prefix: " << options->object_prefix
<< "\n# Thread Count: " << options->thread_count
<< "\n# Reporting Interval: "
<< absl::FromChrono(options->reporting_interval)
<< "\n# Running Time: " << absl::FromChrono(options->running_time)
<< "\n# Read Size: " << options->read_size
<< "\n# Read Buffer Size: " << options->read_buffer_size
<< "\n# API: " << gcs_bm::ToString(options->api)
<< "\n# gRPC Channel Count: " << options->grpc_channel_count
<< "\n# Build Info: " << notes
<< "\n# Object Count: " << objects.size()
<< "\n# Dataset size: " << FormatSize(dataset_size) << std::endl;
auto configs = [](std::size_t count) {
std::random_device rd;
std::vector<std::seed_seq::result_type> seeds(count);
std::seed_seq({rd(), rd(), rd()}).generate(seeds.begin(), seeds.end());
std::vector<ThreadConfig> config(seeds.size());
for (std::size_t i = 0; i != config.size(); ++i) config[i].seed = seeds[i];
return config;
}(options->thread_count);
std::cout << "CurrentTime,BytesReceived,CpuTimeMicroseconds\n"
<< current_time() << ",0,0\n";
std::vector<std::future<Counters>> tasks(configs.size());
std::transform(configs.begin(), configs.end(), tasks.begin(),
[&](ThreadConfig& c) {
return std::async(std::launch::async, RunThread, client,
*options, objects, std::ref(c));
});
auto accumulate_bytes_received = [&] {
std::int64_t bytes_received = 0;
for (auto const& t : configs) bytes_received += t.bytes_received.load();
return bytes_received;
};
auto timer = Timer::PerProcess();
auto usage = timer.Sample();
while (usage.elapsed_time < options->running_time) {
std::this_thread::sleep_for(options->reporting_interval);
usage = timer.Sample();
std::cout << current_time() << "," << accumulate_bytes_received() << ","
<< usage.cpu_time.count() << std::endl;
}
auto const bytes_received = accumulate_bytes_received();
std::cout << "# Bytes Received: " << FormatSize(bytes_received)
<< "\n# Elapsed Time: " << absl::FromChrono(usage.elapsed_time)
<< "\n# Bandwidth: "
<< FormatBandwidthGbPerSecond(bytes_received, usage.elapsed_time)
<< "Gbit/s "
<< FormatBandwidthGiBPerSecond(bytes_received, usage.elapsed_time)
<< "GiB/s\n";
Counters accumulated;
for (auto& t : tasks) {
auto counters = t.get();
for (auto const& kv : counters) accumulated[kv.first] += kv.second;
}
for (auto& kv : accumulated) {
std::cout << "# counter " << kv.first << ": " << kv.second << "\n";
}
return 0;
}
namespace {
Counters RunThread(gcs::Client client,
AggregateThroughputOptions const& options,
std::vector<gcs::ObjectMetadata> const& objects,
ThreadConfig& config) {
using clock = std::chrono::steady_clock;
auto const deadline = clock::now() + options.running_time;
auto generator = std::mt19937_64(config.seed);
auto index =
std::uniform_int_distribution<std::size_t>(0, objects.size() - 1);
std::vector<char> buffer(options.read_buffer_size);
auto const buffer_size = static_cast<std::streamsize>(buffer.size());
Counters counters{{"download-count", 0}};
// Using IfGenerationNotMatch(0) triggers JSON, as this feature is not
// supported by XML. Using IfGenerationNotMatch() -- without a value -- has
// no effect.
auto xml_hack = options.api == ApiName::kApiJson
? gcs::IfGenerationNotMatch(0)
: gcs::IfGenerationNotMatch();
while (clock::now() < deadline) {
auto const& object = objects[index(generator)];
auto const object_size = static_cast<std::int64_t>(object.size());
auto range = gcs::ReadRange();
if (options.read_size != 0 && options.read_size < object_size) {
auto start = std::uniform_int_distribution<std::int64_t>(
0, object_size - options.read_size);
range = gcs::ReadRange(start(generator), options.read_size);
}
auto stream = client.ReadObject(object.bucket(), object.name(),
gcs::Generation(object.generation()), range,
xml_hack);
while (stream.read(buffer.data(), buffer_size)) {
config.bytes_received += stream.gcount();
}
stream.Close();
++counters["download-count"];
auto peer = stream.headers().find(":grpc-context-peer");
if (peer != stream.headers().end()) {
++counters[peer->first + "/" + peer->second];
}
}
return counters;
}
using ::google::cloud::internal::GetEnv;
google::cloud::StatusOr<AggregateThroughputOptions> SelfTest(
char const* argv0) {
using google::cloud::internal::Sample;
for (auto const& var : {"GOOGLE_CLOUD_CPP_STORAGE_TEST_BUCKET_NAME"}) {
auto const value = GetEnv(var).value_or("");
if (!value.empty()) continue;
std::ostringstream os;
os << "The environment variable " << var << " is not set or empty";
return google::cloud::Status(google::cloud::StatusCode::kUnknown,
std::move(os).str());
}
auto bucket_name =
GetEnv("GOOGLE_CLOUD_CPP_STORAGE_TEST_BUCKET_NAME").value();
auto client = gcs::Client{};
(void)client.InsertObject(bucket_name,
"aggregate-throughput-benchmark/32KiB.bin",
std::string(32 * gcs_bm::kKiB, 'A'));
return gcs_bm::ParseAggregateThroughputOptions(
{
argv0,
"--bucket-name=" + bucket_name,
"--object-prefix=aggregate-throughput-benchmark/",
"--thread-count=1",
"--reporting-interval=5s",
"--running-time=15s",
"--read-size=32KiB",
"--read-buffer-size=16KiB",
"--api=JSON",
},
kDescription);
}
google::cloud::StatusOr<AggregateThroughputOptions> ParseArgs(int argc,
char* argv[]) {
bool auto_run =
google::cloud::internal::GetEnv("GOOGLE_CLOUD_CPP_AUTO_RUN_EXAMPLES")
.value_or("") == "yes";
if (auto_run) return SelfTest(argv[0]);
return gcs_bm::ParseAggregateThroughputOptions({argv, argv + argc},
kDescription);
}
} // namespace
<commit_msg>feat(storage): more accurate aggregate bandwidth results (#6953)<commit_after>// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "google/cloud/storage/benchmarks/aggregate_throughput_options.h"
#include "google/cloud/storage/benchmarks/benchmark_utils.h"
#include "google/cloud/storage/client.h"
#include "google/cloud/storage/grpc_plugin.h"
#include "google/cloud/grpc_options.h"
#include "google/cloud/internal/build_info.h"
#include "google/cloud/internal/getenv.h"
#include "google/cloud/internal/random.h"
#include "google/cloud/options.h"
#include "google/cloud/testing_util/command_line_parsing.h"
#include "google/cloud/testing_util/timer.h"
#include "absl/time/time.h"
#include <algorithm>
#include <atomic>
#include <future>
#include <iomanip>
#include <random>
#include <sstream>
#include <thread>
#include <vector>
namespace {
using ::google::cloud::storage_experimental::DefaultGrpcClient;
using ::google::cloud::testing_util::FormatSize;
using ::google::cloud::testing_util::Timer;
namespace gcs = google::cloud::storage;
namespace gcs_bm = google::cloud::storage_benchmarks;
using gcs_bm::AggregateThroughputOptions;
using gcs_bm::ApiName;
char const kDescription[] = R"""(A benchmark for aggregated throughput.
This program is used to evaluate the combined performance of GCS (the service)
and the C++ client library for GCS. It is not recommended as a benchmark for
the client library, as it introduces too many sources of performance variation.
It is useful when the C++ client library team collaborates with the GCS team to
measure changes in the service's performance.
The program measures the observed download throughput given a fixed "dataset",
that is, a collection of GCS objects contained in the same bucket, with a common
prefix. If needed, synthetic datasets can be created using the
`create_dataset.cc` in this directory. Given a dataset and some configuration
parameters the program will:
- Read the list of available objects in the dataset.
- Launch `thread-count` *download threads*, see below for their description.
- Every `reporting-interval` seconds the main thread will report the current
wall time and the total number of bytes downloaded by all the download
threads.
- After `running-time` seconds the main thread ask all other threads to
terminate.
- The main thread then waits for all the "download threads", collects any
metrics they choose to report, prints these metrics, and then exits.
While running, each download thread performs the following loop:
1) Create a gcs::Client object, see the `AggregateThroughputOptions` struct for
details about how this client object can be configured.
2) Check if the program is shutting down. If so, just return some metrics.
3) Pick one of the objects in the dataset at random.
4) If so configured, pick a random portion of the object to download, otherwise
simply download the full object.
5) Download the object, requesting `read-buffer-size` bytes from the client
library at a time.
6) Once the requested buffer is received, increment a per-thread counter with
the number of bytes received so far.
7) Keep track of the number of files downloaded, the gRPC peer used to download
the object (if applicable) and other counters.
8) Go back to step (2) in this list.
)""";
google::cloud::StatusOr<AggregateThroughputOptions> ParseArgs(int argc,
char* argv[]);
struct ThreadConfig {
std::atomic<std::int64_t> bytes_received{0};
std::seed_seq::result_type seed;
};
using Counters = std::map<std::string, std::int64_t>;
Counters RunThread(gcs::Client client,
AggregateThroughputOptions const& options,
std::vector<gcs::ObjectMetadata> const& objects,
ThreadConfig& config);
template <typename Rep, typename Period>
std::string FormatBandwidthGbPerSecond(
std::uintmax_t bytes, std::chrono::duration<Rep, Period> elapsed) {
using ns = ::std::chrono::nanoseconds;
auto const elapsed_ns = std::chrono::duration_cast<ns>(elapsed);
if (elapsed_ns == ns(0)) return "NaN";
auto const bandwidth =
8 * static_cast<double>(bytes) / static_cast<double>(elapsed_ns.count());
std::ostringstream os;
os << std::fixed << std::setprecision(2) << bandwidth;
return std::move(os).str();
}
template <typename Rep, typename Period>
std::string FormatBandwidthGiBPerSecond(
std::uintmax_t bytes, std::chrono::duration<Rep, Period> elapsed) {
using ::std::chrono::seconds;
auto const elapsed_s = std::chrono::duration_cast<seconds>(elapsed);
if (elapsed_s == seconds(0)) return "NaN";
auto const bandwidth = static_cast<double>(bytes) / gcs_bm::kGiB /
static_cast<double>(elapsed_s.count());
std::ostringstream os;
os << std::fixed << std::setprecision(2) << bandwidth;
return std::move(os).str();
}
} // namespace
int main(int argc, char* argv[]) {
auto options = ParseArgs(argc, argv);
if (!options) {
std::cerr << options.status() << "\n";
return 1;
}
if (options->exit_after_parse) return 1;
auto client = gcs::Client();
#if GOOGLE_CLOUD_CPP_STORAGE_HAVE_GRPC
if (options->api == ApiName::kApiGrpc) {
auto channels = options->grpc_channel_count;
if (channels == 0) channels = (std::max)(options->thread_count / 4, 4);
client = DefaultGrpcClient(
google::cloud::Options{}.set<google::cloud::GrpcNumChannelsOption>(
channels));
}
#endif // GOOGLE_CLOUD_CPP_STORAGE_HAVE_GRPC
std::vector<gcs::ObjectMetadata> objects;
std::uint64_t dataset_size = 0;
for (auto& o : client.ListObjects(options->bucket_name,
gcs::Prefix(options->object_prefix))) {
if (!o) break;
dataset_size += o->size();
objects.push_back(*std::move(o));
}
if (objects.empty()) {
std::cerr << "No objects found in bucket " << options->bucket_name
<< " starting with prefix " << options->object_prefix << "\n"
<< "Cannot run the benchmark with an empty dataset\n";
return 1;
}
std::string notes = google::cloud::storage::version_string() + ";" +
google::cloud::internal::compiler() + ";" +
google::cloud::internal::compiler_flags();
std::transform(notes.begin(), notes.end(), notes.begin(),
[](char c) { return c == '\n' ? ';' : c; });
auto current_time = [] {
auto constexpr kFormat = "%E4Y-%m-%dT%H:%M:%E*SZ";
auto const t = absl::FromChrono(std::chrono::system_clock::now());
return absl::FormatTime(kFormat, t, absl::UTCTimeZone());
};
std::cout << "# Start time: " << current_time()
<< "\n# Bucket Name: " << options->bucket_name
<< "\n# Object Prefix: " << options->object_prefix
<< "\n# Thread Count: " << options->thread_count
<< "\n# Reporting Interval: "
<< absl::FromChrono(options->reporting_interval)
<< "\n# Running Time: " << absl::FromChrono(options->running_time)
<< "\n# Read Size: " << options->read_size
<< "\n# Read Buffer Size: " << options->read_buffer_size
<< "\n# API: " << gcs_bm::ToString(options->api)
<< "\n# gRPC Channel Count: " << options->grpc_channel_count
<< "\n# Build Info: " << notes
<< "\n# Object Count: " << objects.size()
<< "\n# Dataset size: " << FormatSize(dataset_size) << std::endl;
auto configs = [](std::size_t count) {
std::random_device rd;
std::vector<std::seed_seq::result_type> seeds(count);
std::seed_seq({rd(), rd(), rd()}).generate(seeds.begin(), seeds.end());
std::vector<ThreadConfig> config(seeds.size());
for (std::size_t i = 0; i != config.size(); ++i) config[i].seed = seeds[i];
return config;
}(options->thread_count);
std::cout << "CurrentTime,BytesReceived,CpuTimeMicroseconds\n"
<< current_time() << ",0,0\n";
std::vector<std::future<Counters>> tasks(configs.size());
std::transform(configs.begin(), configs.end(), tasks.begin(),
[&](ThreadConfig& c) {
return std::async(std::launch::async, RunThread, client,
*options, objects, std::ref(c));
});
auto accumulate_bytes_received = [&] {
std::int64_t bytes_received = 0;
for (auto const& t : configs) bytes_received += t.bytes_received.load();
return bytes_received;
};
using clock = std::chrono::steady_clock;
auto deadline = clock::now() + options->running_time;
auto timer = Timer::PerProcess();
for (auto now = clock::now(); now < deadline; now = clock::now()) {
std::this_thread::sleep_until(
(std::min)(now + options->reporting_interval, deadline));
auto const usage = timer.Sample();
std::cout << current_time() << "," << accumulate_bytes_received() << ","
<< usage.cpu_time.count() << std::endl;
}
Counters accumulated;
for (auto& t : tasks) {
auto counters = t.get();
for (auto const& kv : counters) accumulated[kv.first] += kv.second;
}
auto const usage = timer.Sample();
auto const bytes_received = accumulate_bytes_received();
std::cout << "# Bytes Received: " << FormatSize(bytes_received)
<< "\n# Elapsed Time: " << absl::FromChrono(usage.elapsed_time)
<< "\n# CPU Time: " << absl::FromChrono(usage.cpu_time)
<< "\n# Bandwidth: "
<< FormatBandwidthGbPerSecond(bytes_received, usage.elapsed_time)
<< "Gbit/s "
<< FormatBandwidthGiBPerSecond(bytes_received, usage.elapsed_time)
<< "GiB/s\n";
for (auto& kv : accumulated) {
std::cout << "# counter " << kv.first << ": " << kv.second << "\n";
}
return 0;
}
namespace {
Counters RunThread(gcs::Client client,
AggregateThroughputOptions const& options,
std::vector<gcs::ObjectMetadata> const& objects,
ThreadConfig& config) {
using clock = std::chrono::steady_clock;
auto const deadline = clock::now() + options.running_time;
auto generator = std::mt19937_64(config.seed);
auto index =
std::uniform_int_distribution<std::size_t>(0, objects.size() - 1);
std::vector<char> buffer(options.read_buffer_size);
auto const buffer_size = static_cast<std::streamsize>(buffer.size());
Counters counters{{"download-count", 0}};
// Using IfGenerationNotMatch(0) triggers JSON, as this feature is not
// supported by XML. Using IfGenerationNotMatch() -- without a value -- has
// no effect.
auto xml_hack = options.api == ApiName::kApiJson
? gcs::IfGenerationNotMatch(0)
: gcs::IfGenerationNotMatch();
while (clock::now() < deadline) {
auto const& object = objects[index(generator)];
auto const object_size = static_cast<std::int64_t>(object.size());
auto range = gcs::ReadRange();
if (options.read_size != 0 && options.read_size < object_size) {
auto start = std::uniform_int_distribution<std::int64_t>(
0, object_size - options.read_size);
range = gcs::ReadRange(start(generator), options.read_size);
}
auto stream = client.ReadObject(object.bucket(), object.name(),
gcs::Generation(object.generation()), range,
xml_hack);
while (stream.read(buffer.data(), buffer_size)) {
config.bytes_received += stream.gcount();
}
stream.Close();
++counters["download-count"];
auto peer = stream.headers().find(":grpc-context-peer");
if (peer != stream.headers().end()) {
++counters[peer->first + "/" + peer->second];
}
}
return counters;
}
using ::google::cloud::internal::GetEnv;
google::cloud::StatusOr<AggregateThroughputOptions> SelfTest(
char const* argv0) {
using google::cloud::internal::Sample;
for (auto const& var : {"GOOGLE_CLOUD_CPP_STORAGE_TEST_BUCKET_NAME"}) {
auto const value = GetEnv(var).value_or("");
if (!value.empty()) continue;
std::ostringstream os;
os << "The environment variable " << var << " is not set or empty";
return google::cloud::Status(google::cloud::StatusCode::kUnknown,
std::move(os).str());
}
auto bucket_name =
GetEnv("GOOGLE_CLOUD_CPP_STORAGE_TEST_BUCKET_NAME").value();
auto client = gcs::Client{};
(void)client.InsertObject(bucket_name,
"aggregate-throughput-benchmark/32KiB.bin",
std::string(32 * gcs_bm::kKiB, 'A'));
return gcs_bm::ParseAggregateThroughputOptions(
{
argv0,
"--bucket-name=" + bucket_name,
"--object-prefix=aggregate-throughput-benchmark/",
"--thread-count=1",
"--reporting-interval=5s",
"--running-time=15s",
"--read-size=32KiB",
"--read-buffer-size=16KiB",
"--api=JSON",
},
kDescription);
}
google::cloud::StatusOr<AggregateThroughputOptions> ParseArgs(int argc,
char* argv[]) {
bool auto_run =
google::cloud::internal::GetEnv("GOOGLE_CLOUD_CPP_AUTO_RUN_EXAMPLES")
.value_or("") == "yes";
if (auto_run) return SelfTest(argv[0]);
return gcs_bm::ParseAggregateThroughputOptions({argv, argv + argc},
kDescription);
}
} // namespace
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2004-2008 Marc Boris Duerner
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* As a special exception, you may use this file as part of a free
* software library without restriction. Specifically, if other files
* instantiate templates or use macros or inline functions from this
* file, or you compile this file and link it with other files to
* produce an executable, this file does not by itself cause the
* resulting executable to be covered by the GNU General Public
* License. This exception does not however invalidate any other
* reasons why the executable file might be covered by the GNU Library
* General Public License.
*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "cxxtools/streambuffer.h"
#include <algorithm>
#include <stdexcept>
#include <cstring>
#include <cxxtools/log.h>
log_define("cxxtools.streambuffer")
namespace cxxtools {
StreamBuffer::StreamBuffer(IODevice& ioDevice, size_t bufferSize, bool extend)
: _ioDevice(&ioDevice),
_ibufferSize(bufferSize+4),
_ibuffer(0),
_obufferSize(bufferSize),
_obuffer(0),
_pbmax(4),
_oextend(extend)
{
this->setg(0, 0, 0);
this->setp(0, 0);
this->attach(ioDevice);
}
StreamBuffer::StreamBuffer(size_t bufferSize, bool extend)
: _ioDevice(0),
_ibufferSize(bufferSize+4),
_ibuffer(0),
_obufferSize(bufferSize),
_obuffer(0),
_pbmax(4),
_oextend(extend)
{
this->setg(0, 0, 0);
this->setp(0, 0);
}
StreamBuffer::~StreamBuffer()
{
delete[] _ibuffer;
delete[] _obuffer;
}
void StreamBuffer::attach(IODevice& ioDevice)
{
if( ioDevice.busy() )
throw IOPending("IODevice in use");
if(_ioDevice)
{
if( _ioDevice->busy() )
throw IOPending("IODevice in use");
disconnect(ioDevice.inputReady, *this, &StreamBuffer::onRead);
disconnect(ioDevice.outputReady, *this, &StreamBuffer::onWrite);
}
_ioDevice = &ioDevice;
connect(ioDevice.inputReady, *this, &StreamBuffer::onRead);
connect(ioDevice.outputReady, *this, &StreamBuffer::onWrite);
}
IODevice* StreamBuffer::device()
{
return _ioDevice;
}
void StreamBuffer::beginRead()
{
if(_ioDevice == 0 || _ioDevice->reading())
return;
if( ! _ibuffer )
{
_ibuffer = new char[_ibufferSize];
}
size_t putback = _pbmax;
size_t leftover = 0;
// keep chars for putback
if( this->gptr() )
{
putback = std::min<size_t>( gptr() - eback(), _pbmax);
char* to = _ibuffer + _pbmax - putback;
char* from = this->gptr() - putback;
leftover = egptr() - gptr();
std::memmove( to, from, putback + leftover );
}
size_t used = _pbmax + leftover;
if( _ibufferSize == used )
throw std::logic_error("StreamBuffer is full");
_ioDevice->beginRead( _ibuffer + used, _ibufferSize - used );
this->setg( _ibuffer + (_pbmax - putback), // start of get area
_ibuffer + used, // gptr position
_ibuffer + used ); // end of get area
}
void StreamBuffer::onRead(IODevice& dev)
{
inputReady.send(*this);
}
void StreamBuffer::endRead()
{
size_t readSize = _ioDevice->endRead();
this->setg( this->eback(), // start of get area
this->gptr(), // gptr position
this->egptr() + readSize ); // end of get area
}
StreamBuffer::int_type StreamBuffer::underflow()
{
log_trace("underflow");
if( ! _ioDevice )
return traits_type::eof();
if(_ioDevice->reading())
this->endRead();
if( this->gptr() < this->egptr() )
return traits_type::to_int_type( *(this->gptr()) );
if( _ioDevice->eof() )
return traits_type::eof();
if( ! _ibuffer )
{
_ibuffer = new char[_ibufferSize];
}
size_t putback = _pbmax;
if( this->gptr() )
{
putback = std::min<size_t>(this->gptr() - this->eback(), _pbmax);
std::memmove( _ibuffer + (_pbmax - putback),
this->gptr() - putback,
putback );
}
size_t readSize = _ioDevice->read( _ibuffer + _pbmax, _ibufferSize - _pbmax );
this->setg( _ibuffer + _pbmax - putback, // start of get area
_ibuffer + _pbmax, // gptr position
_ibuffer + _pbmax + readSize ); // end of get area
if( _ioDevice->eof() )
return traits_type::eof();
return traits_type::to_int_type( *(this->gptr()) );
}
std::streamsize StreamBuffer::showfull()
{
return 0;
}
size_t StreamBuffer::beginWrite()
{
log_trace("beginWrite; out_avail=" << out_avail());
if(_ioDevice == 0 || _ioDevice->writing())
return 0;
if( this->pptr() )
{
size_t avail = this->pptr() - this->pbase();
if(avail > 0)
{
return _ioDevice->beginWrite(_obuffer, avail);
}
}
return 0;
}
void StreamBuffer::discard()
{
if (_ioDevice && (_ioDevice->reading() || _ioDevice->writing()))
throw IOPending("discard failed - streambuffer is in use");
if (gptr())
this->setg(_ibuffer, _ibuffer + _ibufferSize, _ibuffer + _ibufferSize);
if (pptr())
this->setp(_obuffer, _obuffer + _obufferSize);
}
void StreamBuffer::onWrite(IODevice& dev)
{
outputReady.send(*this);
}
size_t StreamBuffer::endWrite()
{
log_trace("endWrite; out_avail=" << out_avail());
size_t leftover = 0;
size_t written = 0;
if( this->pptr() )
{
size_t avail = this->pptr() - this->pbase();
written = _ioDevice->endWrite();
leftover = avail - written;
if(leftover > 0)
{
traits_type::move(_obuffer, _obuffer + written, leftover);
}
}
this->setp(_obuffer, _obuffer + _obufferSize);
this->pbump( leftover );
return written;
}
StreamBuffer::int_type StreamBuffer::overflow(int_type ch)
{
log_trace("overflow(" << ch << ')');
if( ! _ioDevice )
return traits_type::eof();
if( ! _obuffer )
{
_obuffer = new char[_obufferSize];
this->setp(_obuffer, _obuffer + _obufferSize);
}
else if(_ioDevice->writing()) // beginWrite is unfinished
{
this->endWrite();
}
else if (traits_type::eq_int_type( ch, traits_type::eof() ) || !_oextend)
{
// normal blocking overflow case
size_t avail = this->pptr() - _obuffer;
size_t written = _ioDevice->write(_obuffer, avail);
size_t leftover = avail - written;
if(leftover > 0)
{
traits_type::move(_obuffer, _obuffer + written, leftover);
}
this->setp(_obuffer, _obuffer + _obufferSize);
this->pbump( leftover );
}
else
{
// if the buffer area is extensible and overflow is not called by
// sync/flush we copy the output buffer to a larger one
size_t bufsize = _obufferSize + (_obufferSize/2);
char* buf = new char[ bufsize ];
traits_type::copy(buf, _obuffer, _obufferSize);
std::swap(_obuffer, buf);
this->setp(_obuffer, _obuffer + bufsize);
this->pbump( _obufferSize );
_obufferSize = bufsize;
delete [] buf;
}
// if the overflow char is not EOF put it in buffer
if( traits_type::eq_int_type(ch, traits_type::eof()) == false )
{
*this->pptr() = traits_type::to_char_type(ch);
this->pbump(1);
}
return traits_type::not_eof(ch);
}
StreamBuffer::int_type StreamBuffer::pbackfail(StreamBuffer::int_type)
{
return traits_type::eof();
}
int StreamBuffer::sync()
{
log_trace("sync");
if( ! _ioDevice )
return 0;
if( pptr() )
{
while( this->pptr() > this->pbase() )
{
const int_type ch = this->overflow( traits_type::eof() );
if( ch == traits_type::eof() )
{
return -1;
}
_ioDevice->sync();
}
}
return 0;
}
std::streamsize StreamBuffer::xspeekn(char* buffer, std::streamsize size)
{
if( traits_type::eof() == this->underflow() )
return 0;
const std::streamsize avail = this->egptr() - this->gptr();
size = std::min(avail, size);
if(size == 0) {
return 0;
}
std::memcpy(buffer, this->gptr(), sizeof(char) * size);
return size;
}
StreamBuffer::pos_type
StreamBuffer::seekoff(off_type off, std::ios::seekdir dir, std::ios::openmode)
{
pos_type ret = pos_type( off_type(-1) );
if ( ! _ioDevice || ! _ioDevice->enabled() ||
! _ioDevice->seekable() || off == 0)
{
return ret;
}
if(_ioDevice->writing())
{
this->endWrite();
}
if(_ioDevice->reading())
{
this->endRead();
}
ret = _ioDevice->seek(off, dir);
// eliminate currently buffered sequence
discard();
return ret;
}
StreamBuffer::pos_type
StreamBuffer::seekpos(pos_type p, std::ios::openmode mode)
{
return this->seekoff(p, std::ios::beg, mode);
}
}
<commit_msg>fix a bug where the streambuffer may block when non blocking I/O is used<commit_after>/*
* Copyright (C) 2004-2008 Marc Boris Duerner
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* As a special exception, you may use this file as part of a free
* software library without restriction. Specifically, if other files
* instantiate templates or use macros or inline functions from this
* file, or you compile this file and link it with other files to
* produce an executable, this file does not by itself cause the
* resulting executable to be covered by the GNU General Public
* License. This exception does not however invalidate any other
* reasons why the executable file might be covered by the GNU Library
* General Public License.
*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "cxxtools/streambuffer.h"
#include <algorithm>
#include <stdexcept>
#include <cstring>
#include <cxxtools/log.h>
log_define("cxxtools.streambuffer")
namespace cxxtools {
StreamBuffer::StreamBuffer(IODevice& ioDevice, size_t bufferSize, bool extend)
: _ioDevice(&ioDevice),
_ibufferSize(bufferSize+4),
_ibuffer(0),
_obufferSize(bufferSize),
_obuffer(0),
_pbmax(4),
_oextend(extend)
{
this->setg(0, 0, 0);
this->setp(0, 0);
this->attach(ioDevice);
}
StreamBuffer::StreamBuffer(size_t bufferSize, bool extend)
: _ioDevice(0),
_ibufferSize(bufferSize+4),
_ibuffer(0),
_obufferSize(bufferSize),
_obuffer(0),
_pbmax(4),
_oextend(extend)
{
this->setg(0, 0, 0);
this->setp(0, 0);
}
StreamBuffer::~StreamBuffer()
{
delete[] _ibuffer;
delete[] _obuffer;
}
void StreamBuffer::attach(IODevice& ioDevice)
{
if( ioDevice.busy() )
throw IOPending("IODevice in use");
if(_ioDevice)
{
if( _ioDevice->busy() )
throw IOPending("IODevice in use");
disconnect(ioDevice.inputReady, *this, &StreamBuffer::onRead);
disconnect(ioDevice.outputReady, *this, &StreamBuffer::onWrite);
}
_ioDevice = &ioDevice;
connect(ioDevice.inputReady, *this, &StreamBuffer::onRead);
connect(ioDevice.outputReady, *this, &StreamBuffer::onWrite);
}
IODevice* StreamBuffer::device()
{
return _ioDevice;
}
void StreamBuffer::beginRead()
{
if(_ioDevice == 0 || _ioDevice->reading())
return;
if( ! _ibuffer )
{
_ibuffer = new char[_ibufferSize];
}
size_t putback = _pbmax;
size_t leftover = 0;
// keep chars for putback
if( this->gptr() )
{
putback = std::min<size_t>( gptr() - eback(), _pbmax);
char* to = _ibuffer + _pbmax - putback;
char* from = this->gptr() - putback;
leftover = egptr() - gptr();
std::memmove( to, from, putback + leftover );
}
size_t used = _pbmax + leftover;
if( _ibufferSize == used )
throw std::logic_error("StreamBuffer is full");
_ioDevice->beginRead( _ibuffer + used, _ibufferSize - used );
this->setg( _ibuffer + (_pbmax - putback), // start of get area
_ibuffer + used, // gptr position
_ibuffer + used ); // end of get area
}
void StreamBuffer::onRead(IODevice& dev)
{
inputReady.send(*this);
}
void StreamBuffer::endRead()
{
size_t readSize = _ioDevice->endRead();
this->setg( this->eback(), // start of get area
this->gptr(), // gptr position
this->egptr() + readSize ); // end of get area
}
StreamBuffer::int_type StreamBuffer::underflow()
{
log_trace("underflow");
if( ! _ioDevice )
return traits_type::eof();
if(_ioDevice->reading())
this->endRead();
if( this->gptr() < this->egptr() )
return traits_type::to_int_type( *(this->gptr()) );
if( _ioDevice->eof() )
return traits_type::eof();
if( ! _ibuffer )
{
_ibuffer = new char[_ibufferSize];
}
size_t putback = _pbmax;
if( this->gptr() )
{
putback = std::min<size_t>(this->gptr() - this->eback(), _pbmax);
std::memmove( _ibuffer + (_pbmax - putback),
this->gptr() - putback,
putback );
}
size_t readSize = _ioDevice->read( _ibuffer + _pbmax, _ibufferSize - _pbmax );
this->setg( _ibuffer + _pbmax - putback, // start of get area
_ibuffer + _pbmax, // gptr position
_ibuffer + _pbmax + readSize ); // end of get area
if( _ioDevice->eof() )
return traits_type::eof();
return traits_type::to_int_type( *(this->gptr()) );
}
std::streamsize StreamBuffer::showfull()
{
return 0;
}
size_t StreamBuffer::beginWrite()
{
log_trace("beginWrite; out_avail=" << out_avail());
if(_ioDevice == 0 || _ioDevice->writing())
return 0;
if( this->pptr() )
{
size_t avail = this->pptr() - this->pbase();
if(avail > 0)
{
return _ioDevice->beginWrite(_obuffer, avail);
}
}
return 0;
}
void StreamBuffer::discard()
{
if (_ioDevice && (_ioDevice->reading() || _ioDevice->writing()))
throw IOPending("discard failed - streambuffer is in use");
if (gptr())
this->setg(_ibuffer, _ibuffer + _ibufferSize, _ibuffer + _ibufferSize);
if (pptr())
this->setp(_obuffer, _obuffer + _obufferSize);
}
void StreamBuffer::onWrite(IODevice& dev)
{
outputReady.send(*this);
}
size_t StreamBuffer::endWrite()
{
log_trace("endWrite; out_avail=" << out_avail());
size_t leftover = 0;
size_t written = 0;
if( this->pptr() )
{
size_t avail = this->pptr() - this->pbase();
written = _ioDevice->endWrite();
leftover = avail - written;
if(leftover > 0)
{
traits_type::move(_obuffer, _obuffer + written, leftover);
}
}
this->setp(_obuffer, _obuffer + _obufferSize);
this->pbump( leftover );
return written;
}
StreamBuffer::int_type StreamBuffer::overflow(int_type ch)
{
log_trace("overflow(" << ch << ')');
if( ! _ioDevice )
return traits_type::eof();
if( ! _obuffer )
{
_obuffer = new char[_obufferSize];
this->setp(_obuffer, _obuffer + _obufferSize);
}
else if (_oextend && !traits_type::eq_int_type( ch, traits_type::eof() ))
{
// if the buffer area is extensible and overflow is not called by
// sync/flush we copy the output buffer to a larger one
size_t bufsize = _obufferSize + (_obufferSize/2);
char* buf = new char[ bufsize ];
traits_type::copy(buf, _obuffer, _obufferSize);
std::swap(_obuffer, buf);
this->setp(_obuffer, _obuffer + bufsize);
this->pbump( _obufferSize );
_obufferSize = bufsize;
delete [] buf;
}
else if (_ioDevice->writing()) // beginWrite is unfinished
{
this->endWrite();
}
else
{
// normal blocking overflow case
size_t avail = this->pptr() - _obuffer;
size_t written = _ioDevice->write(_obuffer, avail);
size_t leftover = avail - written;
if (leftover > 0)
{
traits_type::move(_obuffer, _obuffer + written, leftover);
}
this->setp(_obuffer, _obuffer + _obufferSize);
this->pbump( leftover );
}
// if the overflow char is not EOF put it in buffer
if ( traits_type::eq_int_type(ch, traits_type::eof()) == false )
{
*this->pptr() = traits_type::to_char_type(ch);
this->pbump(1);
}
return traits_type::not_eof(ch);
}
StreamBuffer::int_type StreamBuffer::pbackfail(StreamBuffer::int_type)
{
return traits_type::eof();
}
int StreamBuffer::sync()
{
log_trace("sync");
if( ! _ioDevice )
return 0;
if( pptr() )
{
while( this->pptr() > this->pbase() )
{
const int_type ch = this->overflow( traits_type::eof() );
if( ch == traits_type::eof() )
{
return -1;
}
_ioDevice->sync();
}
}
return 0;
}
std::streamsize StreamBuffer::xspeekn(char* buffer, std::streamsize size)
{
if( traits_type::eof() == this->underflow() )
return 0;
const std::streamsize avail = this->egptr() - this->gptr();
size = std::min(avail, size);
if(size == 0) {
return 0;
}
std::memcpy(buffer, this->gptr(), sizeof(char) * size);
return size;
}
StreamBuffer::pos_type
StreamBuffer::seekoff(off_type off, std::ios::seekdir dir, std::ios::openmode)
{
pos_type ret = pos_type( off_type(-1) );
if ( ! _ioDevice || ! _ioDevice->enabled() ||
! _ioDevice->seekable() || off == 0)
{
return ret;
}
if(_ioDevice->writing())
{
this->endWrite();
}
if(_ioDevice->reading())
{
this->endRead();
}
ret = _ioDevice->seek(off, dir);
// eliminate currently buffered sequence
discard();
return ret;
}
StreamBuffer::pos_type
StreamBuffer::seekpos(pos_type p, std::ios::openmode mode)
{
return this->seekoff(p, std::ios::beg, mode);
}
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.