text
stringlengths 54
60.6k
|
---|
<commit_before>Int_t AliITStestV2(Char_t SlowOrFast='f') {
Int_t rc=0;
if (gAlice) {delete gAlice; gAlice=0;}
TFile *in=TFile::Open("galice.root");
if (!in->IsOpen()) {
cerr<<"Can't open galice.root !\n";
return 1;
}
if (!(gAlice=(AliRun*)in->Get("gAlice"))) {
cerr<<"Can't find gAlice !\n";
return 2;
}
AliKalmanTrack::SetConvConst(1000/0.299792458/gAlice->Field()->SolenoidField());
delete gAlice; gAlice=0;
in->Close();
if (SlowOrFast=='f') {
cerr<<"Fast AliITSRecPoint(s) !\n";
gROOT->LoadMacro("$(ALICE_ROOT)/ITS/AliITSHits2FastRecPoints.C");
AliITSHits2FastRecPoints();
} else {
cerr<<"Slow AliITSRecPoint(s) !\n";
gROOT->LoadMacro("$(ALICE_ROOT)/ITS/AliITSHits2SDigits.C");
AliITSHits2SDigits();
gROOT->LoadMacro("$(ALICE_ROOT)/ITS/AliITSSDigits2Digits.C");
AliITSSDigits2Digits();
gROOT->LoadMacro("$(ALICE_ROOT)/ITS/AliITSDigits2RecPoints.C");
AliITSDigits2RecPoints();
}
gROOT->LoadMacro("$(ALICE_ROOT)/ITS/AliITSFindClustersV2.C");
if (rc=AliITSFindClustersV2(SlowOrFast)) return rc;
gROOT->LoadMacro("$(ALICE_ROOT)/ITS/AliITSFindTracksV2.C");
if (rc=AliITSFindTracksV2()) return rc;
gROOT->LoadMacro("$(ALICE_ROOT)/ITS/AliITSComparisonV2.C");
if (rc=AliITSComparisonV2()) return rc;
return rc;
}
<commit_msg>Default ITS simulation reverted to slow<commit_after>Int_t AliITStestV2(Char_t SlowOrFast='s') {
Int_t rc=0;
if (gAlice) {delete gAlice; gAlice=0;}
TFile *in=TFile::Open("galice.root");
if (!in->IsOpen()) {
cerr<<"Can't open galice.root !\n";
return 1;
}
if (!(gAlice=(AliRun*)in->Get("gAlice"))) {
cerr<<"Can't find gAlice !\n";
return 2;
}
AliKalmanTrack::SetConvConst(1000/0.299792458/gAlice->Field()->SolenoidField());
delete gAlice; gAlice=0;
in->Close();
if (SlowOrFast=='f') {
cerr<<"Fast AliITSRecPoint(s) !\n";
gROOT->LoadMacro("$(ALICE_ROOT)/ITS/AliITSHits2FastRecPoints.C");
AliITSHits2FastRecPoints();
} else {
cerr<<"Slow AliITSRecPoint(s) !\n";
gROOT->LoadMacro("$(ALICE_ROOT)/ITS/AliITSHits2SDigits.C");
AliITSHits2SDigits();
gROOT->LoadMacro("$(ALICE_ROOT)/ITS/AliITSSDigits2Digits.C");
AliITSSDigits2Digits();
gROOT->LoadMacro("$(ALICE_ROOT)/ITS/AliITSDigits2RecPoints.C");
AliITSDigits2RecPoints();
}
gROOT->LoadMacro("$(ALICE_ROOT)/ITS/AliITSFindClustersV2.C");
if (rc=AliITSFindClustersV2(SlowOrFast)) return rc;
gROOT->LoadMacro("$(ALICE_ROOT)/ITS/AliITSFindTracksV2.C");
if (rc=AliITSFindTracksV2()) return rc;
gROOT->LoadMacro("$(ALICE_ROOT)/ITS/AliITSComparisonV2.C");
if (rc=AliITSComparisonV2()) return rc;
return rc;
}
<|endoftext|> |
<commit_before><commit_msg>CID#1078757 nOfs <= nPersistPtrAnz<commit_after><|endoftext|> |
<commit_before>#include <QGraphicsView>
#include "fish_annotator/common/annotation_scene.h"
namespace fish_annotator {
AnnotationScene::AnnotationScene(QObject *parent)
: QGraphicsScene(parent)
, mode_(kDoNothing)
, type_(kBox)
, start_pos_()
, rect_item_(nullptr)
, line_item_(nullptr)
, dot_item_(nullptr) {
}
void AnnotationScene::setToolWidget(AnnotationWidget *widget) {
QObject::connect(widget, &AnnotationWidget::setAnnotation,
this, &AnnotationScene::setAnnotationType);
}
void AnnotationScene::setMode(Mode mode) {
mode_ = mode;
QGraphicsView::DragMode drag;
if(mode == kDraw) {
makeItemsControllable(false);
drag = QGraphicsView::NoDrag;
}
else if(mode == kSelect) {
makeItemsControllable(true);
drag = QGraphicsView::RubberBandDrag;
}
auto view = views().at(0);
if(view != nullptr) view->setDragMode(drag);
}
void AnnotationScene::setAnnotationType(AnnotationType type) {
type_ = type;
}
namespace {
// Define pen width in anonymous namespace.
static const int pen_width = 7;
}
void AnnotationScene::mousePressEvent(QGraphicsSceneMouseEvent *event) {
if(mode_ == kDraw) {
start_pos_ = event->scenePos();
switch(type_) {
case kBox:
rect_item_ = new QGraphicsRectItem(
start_pos_.x(), start_pos_.y(), 0, 0);
rect_item_->setPen(QPen(Qt::black, pen_width, Qt::SolidLine));
addItem(rect_item_);
break;
case kLine:
line_item_ = new QGraphicsLineItem(QLineF(
start_pos_, start_pos_));
line_item_->setPen(QPen(Qt::black, pen_width, Qt::SolidLine));
addItem(line_item_);
break;
case kDot:
dot_item_ = new QGraphicsEllipseItem(
start_pos_.x() - pen_width,
start_pos_.y() - pen_width,
2 * pen_width, 2 * pen_width);
dot_item_->setPen(QPen(Qt::black, pen_width, Qt::SolidLine));
addItem(dot_item_);
break;
}
}
QGraphicsScene::mousePressEvent(event);
}
void AnnotationScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
if(mode_ == kDraw) {
auto update_pos = event->scenePos();
switch(type_) {
case kBox:
if(rect_item_ != nullptr) {
auto left = qMin(start_pos_.x(), update_pos.x());
auto top = qMin(start_pos_.y(), update_pos.y());
auto width = qAbs(start_pos_.x() - update_pos.x());
auto height = qAbs(start_pos_.y() - update_pos.y());
rect_item_->setRect(QRectF(left, top, width, height));
}
break;
case kLine:
if(line_item_ != nullptr) {
line_item_->setLine(QLineF(start_pos_, update_pos));
}
break;
case kDot:
if(dot_item_ != nullptr) {
dot_item_->setRect(QRectF(
update_pos.x() - pen_width,
update_pos.y() - pen_width,
2 * pen_width, 2 * pen_width));
}
break;
}
}
}
void AnnotationScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
if(mode_ == kDraw) {
switch(type_) {
case kBox:
if(rect_item_ != nullptr) {
emit boxFinished(rect_item_->rect());
}
break;
case kLine:
if(line_item_ != nullptr) {
emit lineFinished(line_item_->line());
}
break;
case kDot:
if(dot_item_ != nullptr) {
emit dotFinished(dot_item_->rect().topLeft());
}
break;
}
}
}
void AnnotationScene::makeItemsControllable(bool controllable) {
foreach(QGraphicsItem *item, items()) {
item->setFlag(QGraphicsItem::ItemIsSelectable, controllable);
item->setFlag(QGraphicsItem::ItemIsMovable, controllable);
}
}
} // namespace fish_annotator
<commit_msg>Add moc include<commit_after>#include <QGraphicsView>
#include "fish_annotator/common/annotation_scene.h"
namespace fish_annotator {
AnnotationScene::AnnotationScene(QObject *parent)
: QGraphicsScene(parent)
, mode_(kDoNothing)
, type_(kBox)
, start_pos_()
, rect_item_(nullptr)
, line_item_(nullptr)
, dot_item_(nullptr) {
}
void AnnotationScene::setToolWidget(AnnotationWidget *widget) {
QObject::connect(widget, &AnnotationWidget::setAnnotation,
this, &AnnotationScene::setAnnotationType);
}
void AnnotationScene::setMode(Mode mode) {
mode_ = mode;
QGraphicsView::DragMode drag;
if(mode == kDraw) {
makeItemsControllable(false);
drag = QGraphicsView::NoDrag;
}
else if(mode == kSelect) {
makeItemsControllable(true);
drag = QGraphicsView::RubberBandDrag;
}
auto view = views().at(0);
if(view != nullptr) view->setDragMode(drag);
}
void AnnotationScene::setAnnotationType(AnnotationType type) {
type_ = type;
}
namespace {
// Define pen width in anonymous namespace.
static const int pen_width = 7;
}
void AnnotationScene::mousePressEvent(QGraphicsSceneMouseEvent *event) {
if(mode_ == kDraw) {
start_pos_ = event->scenePos();
switch(type_) {
case kBox:
rect_item_ = new QGraphicsRectItem(
start_pos_.x(), start_pos_.y(), 0, 0);
rect_item_->setPen(QPen(Qt::black, pen_width, Qt::SolidLine));
addItem(rect_item_);
break;
case kLine:
line_item_ = new QGraphicsLineItem(QLineF(
start_pos_, start_pos_));
line_item_->setPen(QPen(Qt::black, pen_width, Qt::SolidLine));
addItem(line_item_);
break;
case kDot:
dot_item_ = new QGraphicsEllipseItem(
start_pos_.x() - pen_width,
start_pos_.y() - pen_width,
2 * pen_width, 2 * pen_width);
dot_item_->setPen(QPen(Qt::black, pen_width, Qt::SolidLine));
addItem(dot_item_);
break;
}
}
QGraphicsScene::mousePressEvent(event);
}
void AnnotationScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
if(mode_ == kDraw) {
auto update_pos = event->scenePos();
switch(type_) {
case kBox:
if(rect_item_ != nullptr) {
auto left = qMin(start_pos_.x(), update_pos.x());
auto top = qMin(start_pos_.y(), update_pos.y());
auto width = qAbs(start_pos_.x() - update_pos.x());
auto height = qAbs(start_pos_.y() - update_pos.y());
rect_item_->setRect(QRectF(left, top, width, height));
}
break;
case kLine:
if(line_item_ != nullptr) {
line_item_->setLine(QLineF(start_pos_, update_pos));
}
break;
case kDot:
if(dot_item_ != nullptr) {
dot_item_->setRect(QRectF(
update_pos.x() - pen_width,
update_pos.y() - pen_width,
2 * pen_width, 2 * pen_width));
}
break;
}
}
}
void AnnotationScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
if(mode_ == kDraw) {
switch(type_) {
case kBox:
if(rect_item_ != nullptr) {
emit boxFinished(rect_item_->rect());
}
break;
case kLine:
if(line_item_ != nullptr) {
emit lineFinished(line_item_->line());
}
break;
case kDot:
if(dot_item_ != nullptr) {
emit dotFinished(dot_item_->rect().topLeft());
}
break;
}
}
}
void AnnotationScene::makeItemsControllable(bool controllable) {
foreach(QGraphicsItem *item, items()) {
item->setFlag(QGraphicsItem::ItemIsSelectable, controllable);
item->setFlag(QGraphicsItem::ItemIsMovable, controllable);
}
}
#include "../../include/fish_annotator/common/moc_annotation_scene.cpp"
} // namespace fish_annotator
<|endoftext|> |
<commit_before>#include "./scene.h"
#include <QDebug>
#include <Eigen/Core>
#include <Eigen/Geometry>
#include <string>
#include <vector>
#include "./gl.h"
#include "./input/invoke_manager.h"
#include "./mesh.h"
#include "./mesh_node.h"
#include "./label_node.h"
#include "./render_data.h"
#include "./importer.h"
#include "./camera_controller.h"
#include "./camera_rotation_controller.h"
#include "./camera_zoom_controller.h"
#include "./camera_move_controller.h"
#include "./nodes.h"
#include "./quad.h"
#include "./frame_buffer_object.h"
#include "./utils/persister.h"
#include "./forces/labeller_frame_data.h"
BOOST_CLASS_EXPORT_GUID(LabelNode, "LabelNode")
BOOST_CLASS_EXPORT_GUID(MeshNode, "MeshNode")
Scene::Scene(std::shared_ptr<InvokeManager> invokeManager,
std::shared_ptr<Nodes> nodes,
std::shared_ptr<Forces::Labeller> labeller)
: nodes(nodes), labeller(labeller)
{
cameraController = std::make_shared<CameraController>(camera);
cameraRotationController = std::make_shared<CameraRotationController>(camera);
cameraZoomController = std::make_shared<CameraZoomController>(camera);
cameraMoveController = std::make_shared<CameraMoveController>(camera);
invokeManager->addHandler("cam", cameraController.get());
invokeManager->addHandler("cameraRotation", cameraRotationController.get());
invokeManager->addHandler("cameraZoom", cameraZoomController.get());
invokeManager->addHandler("cameraMove", cameraMoveController.get());
fbo = std::unique_ptr<FrameBufferObject>(new FrameBufferObject());
}
Scene::~Scene()
{
}
void Scene::initialize()
{
glAssert(gl->glClearColor(0.9f, 0.9f, 0.8f, 1.0f));
const std::string filename = "assets/assets.dae";
Importer importer;
std::vector<std::shared_ptr<Node>> meshNodes;
for (unsigned int meshIndex = 0; meshIndex < 2; ++meshIndex)
{
auto mesh = importer.import(filename, meshIndex);
auto node =
new MeshNode(filename, meshIndex, mesh, Eigen::Matrix4f::Identity());
meshNodes.push_back(std::unique_ptr<MeshNode>(node));
}
auto label = Label(1, "Shoulder", Eigen::Vector3f(0.174f, 0.553f, 0.02f));
meshNodes.push_back(std::make_shared<LabelNode>(label));
auto label2 = Label(2, "Ellbow", Eigen::Vector3f(0.334f, 0.317f, -0.013f));
meshNodes.push_back(std::make_shared<LabelNode>(label2));
auto label3 = Label(3, "Wound", Eigen::Vector3f(0.262f, 0.422f, 0.058f),
Eigen::Vector2f(0.14f, 0.14f));
meshNodes.push_back(std::make_shared<LabelNode>(label3));
auto label4 = Label(4, "Wound 2", Eigen::Vector3f(0.034f, 0.373f, 0.141f));
meshNodes.push_back(std::make_shared<LabelNode>(label4));
Persister::save(meshNodes, "config/scene.xml");
nodes->addSceneNodesFrom("config/scene.xml");
for (auto &labelNode : nodes->getLabelNodes())
{
auto label = labelNode->getLabel();
labeller->addLabel(label.id, label.text, label.anchorPosition, label.size);
}
quad = std::make_shared<Quad>();
fbo->initialize(gl, width, height);
}
void Scene::update(double frameTime, QSet<Qt::Key> keysPressed)
{
this->frameTime = frameTime;
cameraController->setFrameTime(frameTime);
cameraRotationController->setFrameTime(frameTime);
cameraZoomController->setFrameTime(frameTime);
cameraMoveController->setFrameTime(frameTime);
auto newPositions = labeller->update(Forces::LabellerFrameData(
frameTime, camera.getProjectionMatrix(), camera.getViewMatrix()));
for (auto &labelNode : nodes->getLabelNodes())
{
labelNode->labelPosition = newPositions[labelNode->getLabel().id];
}
}
void Scene::render()
{
if (shouldResize)
{
camera.resize(width, height);
fbo->resize(gl, width, height);
shouldResize = false;
}
glAssert(gl->glViewport(0, 0, width, height));
glAssert(gl->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT));
fbo->bind();
glAssert(gl->glViewport(0, 0, width, height));
glAssert(gl->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT));
RenderData renderData;
renderData.projectionMatrix = camera.getProjectionMatrix();
renderData.viewMatrix = camera.getViewMatrix();
renderData.cameraPosition = camera.getPosition();
renderData.modelMatrix = Eigen::Matrix4f::Identity();
nodes->render(gl, renderData);
fbo->unbind();
renderScreenQuad();
}
void Scene::renderScreenQuad()
{
RenderData renderData;
renderData.projectionMatrix = Eigen::Matrix4f::Identity();
renderData.viewMatrix = Eigen::Matrix4f::Identity();
renderData.modelMatrix =
Eigen::Affine3f(Eigen::AlignedScaling3f(1, -1, 1)).matrix();
fbo->bindColorTexture(GL_TEXTURE0);
// fbo->bindDepthTexture(GL_TEXTURE0);
quad->render(gl, renderData);
}
void Scene::resize(int width, int height)
{
this->width = width;
this->height = height;
shouldResize = true;
}
<commit_msg>Picking every frame for center position.<commit_after>#include "./scene.h"
#include <QDebug>
#include <Eigen/Core>
#include <Eigen/Geometry>
#include <string>
#include <vector>
#include "./gl.h"
#include "./input/invoke_manager.h"
#include "./mesh.h"
#include "./mesh_node.h"
#include "./label_node.h"
#include "./render_data.h"
#include "./importer.h"
#include "./camera_controller.h"
#include "./camera_rotation_controller.h"
#include "./camera_zoom_controller.h"
#include "./camera_move_controller.h"
#include "./nodes.h"
#include "./quad.h"
#include "./frame_buffer_object.h"
#include "./utils/persister.h"
#include "./forces/labeller_frame_data.h"
BOOST_CLASS_EXPORT_GUID(LabelNode, "LabelNode")
BOOST_CLASS_EXPORT_GUID(MeshNode, "MeshNode")
Scene::Scene(std::shared_ptr<InvokeManager> invokeManager,
std::shared_ptr<Nodes> nodes,
std::shared_ptr<Forces::Labeller> labeller)
: nodes(nodes), labeller(labeller)
{
cameraController = std::make_shared<CameraController>(camera);
cameraRotationController = std::make_shared<CameraRotationController>(camera);
cameraZoomController = std::make_shared<CameraZoomController>(camera);
cameraMoveController = std::make_shared<CameraMoveController>(camera);
invokeManager->addHandler("cam", cameraController.get());
invokeManager->addHandler("cameraRotation", cameraRotationController.get());
invokeManager->addHandler("cameraZoom", cameraZoomController.get());
invokeManager->addHandler("cameraMove", cameraMoveController.get());
fbo = std::unique_ptr<FrameBufferObject>(new FrameBufferObject());
}
Scene::~Scene()
{
}
void Scene::initialize()
{
glAssert(gl->glClearColor(0.9f, 0.9f, 0.8f, 1.0f));
const std::string filename = "assets/assets.dae";
Importer importer;
std::vector<std::shared_ptr<Node>> meshNodes;
for (unsigned int meshIndex = 0; meshIndex < 2; ++meshIndex)
{
auto mesh = importer.import(filename, meshIndex);
auto node =
new MeshNode(filename, meshIndex, mesh, Eigen::Matrix4f::Identity());
meshNodes.push_back(std::unique_ptr<MeshNode>(node));
}
auto label = Label(1, "Shoulder", Eigen::Vector3f(0.174f, 0.553f, 0.02f));
meshNodes.push_back(std::make_shared<LabelNode>(label));
auto label2 = Label(2, "Ellbow", Eigen::Vector3f(0.334f, 0.317f, -0.013f));
meshNodes.push_back(std::make_shared<LabelNode>(label2));
auto label3 = Label(3, "Wound", Eigen::Vector3f(0.262f, 0.422f, 0.058f),
Eigen::Vector2f(0.14f, 0.14f));
meshNodes.push_back(std::make_shared<LabelNode>(label3));
auto label4 = Label(4, "Wound 2", Eigen::Vector3f(0.034f, 0.373f, 0.141f));
meshNodes.push_back(std::make_shared<LabelNode>(label4));
Persister::save(meshNodes, "config/scene.xml");
nodes->addSceneNodesFrom("config/scene.xml");
for (auto &labelNode : nodes->getLabelNodes())
{
auto label = labelNode->getLabel();
labeller->addLabel(label.id, label.text, label.anchorPosition, label.size);
}
quad = std::make_shared<Quad>();
fbo->initialize(gl, width, height);
}
void Scene::update(double frameTime, QSet<Qt::Key> keysPressed)
{
this->frameTime = frameTime;
cameraController->setFrameTime(frameTime);
cameraRotationController->setFrameTime(frameTime);
cameraZoomController->setFrameTime(frameTime);
cameraMoveController->setFrameTime(frameTime);
auto newPositions = labeller->update(Forces::LabellerFrameData(
frameTime, camera.getProjectionMatrix(), camera.getViewMatrix()));
for (auto &labelNode : nodes->getLabelNodes())
{
labelNode->labelPosition = newPositions[labelNode->getLabel().id];
}
}
void Scene::render()
{
if (shouldResize)
{
camera.resize(width, height);
fbo->resize(gl, width, height);
shouldResize = false;
}
glAssert(gl->glViewport(0, 0, width, height));
glAssert(gl->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT));
fbo->bind();
glAssert(gl->glViewport(0, 0, width, height));
glAssert(gl->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT));
RenderData renderData;
renderData.projectionMatrix = camera.getProjectionMatrix();
renderData.viewMatrix = camera.getViewMatrix();
renderData.cameraPosition = camera.getPosition();
renderData.modelMatrix = Eigen::Matrix4f::Identity();
nodes->render(gl, renderData);
int x = 640;
int y = 360;
float depth = -1.0f;
glAssert(gl->glReadPixels(x, y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &depth));
qWarning() << depth;
fbo->unbind();
renderScreenQuad();
}
void Scene::renderScreenQuad()
{
RenderData renderData;
renderData.projectionMatrix = Eigen::Matrix4f::Identity();
renderData.viewMatrix = Eigen::Matrix4f::Identity();
renderData.modelMatrix =
Eigen::Affine3f(Eigen::AlignedScaling3f(1, -1, 1)).matrix();
fbo->bindColorTexture(GL_TEXTURE0);
//fbo->bindDepthTexture(GL_TEXTURE0);
quad->render(gl, renderData);
}
void Scene::resize(int width, int height)
{
this->width = width;
this->height = height;
shouldResize = true;
}
<|endoftext|> |
<commit_before>/***************************************************************************
* Copyright (C) 2006 by Tobias Koenig <[email protected]> *
* *
* 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 "store.h"
#include "akonadi.h"
#include "akonadiconnection.h"
#include "handlerhelper.h"
#include "response.h"
#include "storage/datastore.h"
#include "storage/transaction.h"
#include "storage/itemqueryhelper.h"
#include "storage/selectquerybuilder.h"
#include "storage/parthelper.h"
#include "storage/dbconfig.h"
#include "storage/itemretriever.h"
#include "libs/imapparser_p.h"
#include "libs/protocol_p.h"
#include "imapstreamparser.h"
#include <QtCore/QStringList>
#include <QLocale>
#include <QDebug>
#include <QFile>
#include <algorithm>
#include <functional>
using namespace Akonadi;
Store::Store( Scope::SelectionScope scope )
: Handler()
, mScope( scope )
, mPos( 0 )
, mPreviousRevision( -1 )
, mSize( 0 )
, mCheckRevision( false )
{
}
bool Store::replaceFlags( const PimItem &item, const QList<QByteArray> &flags )
{
Flag::List flagList = HandlerHelper::resolveFlags( flags );
DataStore *store = connection()->storageBackend();
Flag::List currentFlags = item.flags();
std::sort( flagList.begin(), flagList.end(), _detail::ById<std::less>() );
std::sort( currentFlags.begin(), currentFlags.end(), _detail::ById<std::less>() );
if ( flagList == currentFlags )
return false;
if ( !store->setItemFlags( item, flagList ) )
throw HandlerException( "Store::replaceFlags: Unable to set new item flags" );
return true;
}
bool Store::addFlags( const PimItem &item, const QList<QByteArray> &flags, bool& flagsChanged )
{
const Flag::List flagList = HandlerHelper::resolveFlags( flags );
DataStore *store = connection()->storageBackend();
if ( !store->appendItemFlags( item, flagList, flagsChanged ) ) {
qDebug( "Store::addFlags: Unable to add new item flags" );
return false;
}
return true;
}
bool Store::deleteFlags( const PimItem &item, const QList<QByteArray> &flags )
{
DataStore *store = connection()->storageBackend();
QVector<Flag> flagList;
flagList.reserve( flags.size() );
for ( int i = 0; i < flags.count(); ++i ) {
Flag flag = Flag::retrieveByName( QString::fromUtf8( flags[ i ] ) );
if ( !flag.isValid() )
continue;
flagList.append( flag );
}
if ( !store->removeItemFlags( item, flagList ) ) {
qDebug( "Store::deleteFlags: Unable to remove item flags" );
return false;
}
return true;
}
bool Store::parseStream()
{
parseCommand();
DataStore *store = connection()->storageBackend();
Transaction transaction( store );
// Set the same modification time for each item.
const QDateTime modificationtime = QDateTime::currentDateTime().toUTC();
// retrieve selected items
SelectQueryBuilder<PimItem> qb;
ItemQueryHelper::scopeToQuery( mScope, connection(), qb );
if ( !qb.exec() )
return failureResponse( "Unable to retrieve items" );
PimItem::List pimItems = qb.result();
if ( pimItems.isEmpty() )
return failureResponse( "No items found" );
for ( int i = 0; i < pimItems.size(); ++i ) {
if ( mCheckRevision ) {
// check for conflicts if a resources tries to overwrite an item with dirty payload
// FIXME: STORE is also used to mark items as no longer dirty by the resource!
/* if ( connection()->isOwnerResource( pimItems.at( i ) ) ) {
if ( pimItems.at( i ).dirty() )
throw HandlerException( "[LRCONFLICT] Resource tries to modify item with dirty payload, aborting STORE." );
}*/
// check and update revisions
if ( pimItems.at( i ).rev() != (int)mPreviousRevision )
throw HandlerException( "[LLCONFLICT] Item was modified elsewhere, aborting STORE." );
}
pimItems[ i ].setRev( pimItems[ i ].rev() + 1 );
}
QSet<QByteArray> changes;
qint64 partSizes = 0;
bool invalidateCache = false;
// apply modifications
m_streamParser->beginList();
while ( !m_streamParser->atListEnd() ) {
// parse the command
QByteArray command = m_streamParser->readString();
if ( command.isEmpty() )
throw HandlerException( "Syntax error" );
Operation op = Replace;
bool silent = false;
if ( command.startsWith( '+' ) ) {
op = Add;
command = command.mid( 1 );
} else if ( command.startsWith( '-' ) ) {
op = Delete;
command = command.mid( 1 );
}
if ( command.endsWith( ".SILENT" ) ) {
command.chop( 7 );
silent = true;
}
// qDebug() << "STORE: handling command: " << command;
// handle commands that can be applied to more than one item
if ( command == AKONADI_PARAM_FLAGS ) {
bool flagsChanged = true;
const QList<QByteArray> flags = m_streamParser->readParenthesizedList();
// TODO move this iteration to an SQL query.
for ( int i = 0; i < pimItems.count(); ++i ) {
if ( op == Replace ) {
flagsChanged = replaceFlags( pimItems[ i ], flags );
} else if ( op == Add ) {
if ( !addFlags( pimItems[ i ], flags, flagsChanged ) )
return failureResponse( "Unable to add item flags." );
} else if ( op == Delete ) {
if ( !deleteFlags( pimItems[ i ], flags ) )
return failureResponse( "Unable to remove item flags." );
}
// TODO what is this about?
if ( !silent ) {
sendPimItemResponse( pimItems[i] );
}
}
if ( flagsChanged )
changes << AKONADI_PARAM_FLAGS;
continue;
}
// handle commands that can only be applied to one item
if ( pimItems.size() > 1 )
throw HandlerException( "This Modification can only be applied to a single item" );
PimItem &item = pimItems.first();
if ( !item.isValid() )
throw HandlerException( "Invalid item in query result!?" );
if ( command == AKONADI_PARAM_REMOTEID ) {
const QString rid = m_streamParser->readUtf8String();
if ( item.remoteId() != rid ) {
if ( !connection()->isOwnerResource( item ) )
throw HandlerException( "Only resources can modify remote identifiers" );
item.setRemoteId( rid );
changes << AKONADI_PARAM_REMOTEID;
}
}
else if ( command == AKONADI_PARAM_REMOTEREVISION ) {
const QString remoteRevision = m_streamParser->readUtf8String();
if ( item.remoteRevision() != remoteRevision ) {
if ( !connection()->isOwnerResource( item ) )
throw HandlerException( "Only resources can modify remote revisions" );
item.setRemoteRevision( remoteRevision );
changes << AKONADI_PARAM_REMOTEREVISION;
}
}
else if ( command == AKONADI_PARAM_UNDIRTY ) {
m_streamParser->readString(); // read the 'false' string
item.setDirty( false );
}
else if ( command == AKONADI_PARAM_INVALIDATECACHE ) {
invalidateCache = true;
}
else if ( command == AKONADI_PARAM_SIZE ) {
mSize = m_streamParser->readNumber();
changes << AKONADI_PARAM_SIZE;
}
else if ( command == "PARTS" ) {
const QList<QByteArray> parts = m_streamParser->readParenthesizedList();
if ( op == Delete ) {
if ( !store->removeItemParts( item, parts ) )
return failureResponse( "Unable to remove item parts." );
changes += QSet<QByteArray>::fromList( parts );
}
}
else if ( command == "COLLECTION" ) {
throw HandlerException( "Item moving via STORE is deprecated, update your Akonadi client" );
}
// parts/attributes
else {
// obtain and configure the part object
int partVersion = 0;
QByteArray partName;
ImapParser::splitVersionedKey( command, partName, partVersion );
SelectQueryBuilder<Part> qb;
qb.addValueCondition( Part::pimItemIdColumn(), Query::Equals, item.id() );
qb.addValueCondition( Part::nameColumn(), Query::Equals, QString::fromUtf8( partName ) );
if ( !qb.exec() )
return failureResponse( "Unable to check item part existence" );
Part::List result = qb.result();
Part part;
if ( !result.isEmpty() )
part = result.first();
part.setName( QString::fromUtf8( partName ) );
part.setVersion( partVersion );
part.setPimItemId( item.id() );
QByteArray value;
if ( m_streamParser->hasLiteral() ) {
const qint64 dataSize = m_streamParser->remainingLiteralSize();
partSizes += dataSize;
const bool storeInFile = ( DbConfig::configuredDatabase()->useExternalPayloadFile() && dataSize > DbConfig::configuredDatabase()->sizeThreshold() );
//actual case when streaming storage is used: external payload is enabled, data is big enough in a literal
if ( storeInFile ) {
// use first part as value for the initial insert into / update to the database.
// this will give us a proper filename to stream the rest of the parts contents into
// NOTE: we have to set the correct size (== dataSize) directly
value = m_streamParser->readLiteralPart();
// qDebug() << Q_FUNC_INFO << "VALUE in STORE: " << value << value.size() << dataSize;
if ( part.isValid() ) {
PartHelper::update( &part, value, dataSize );
} else {
// qDebug() << "insert from Store::handleLine";
part.setData( value );
part.setDatasize( dataSize );
if ( !PartHelper::insert( &part ) )
return failureResponse( "Unable to add item part" );
}
//the actual streaming code for the remaining parts:
// reads from the parser, writes immediately to the file
// ### move this entire block to part helper? should be useful for append as well
const QString fileName = QString::fromUtf8( part.data() );
QFile file( fileName );
if ( file.open( QIODevice::WriteOnly | QIODevice::Append ) ) {
while ( !m_streamParser->atLiteralEnd() ) {
value = m_streamParser->readLiteralPart();
file.write( value ); // ### error handling?
}
file.close();
} else {
return failureResponse( "Unable to update item part" );
}
changes << partName;
continue;
} else { // not store in file
//don't write in streaming way as the data goes to the database
while (!m_streamParser->atLiteralEnd()) {
value += m_streamParser->readLiteralPart();
}
}
} else { //not a literal
value = m_streamParser->readString();
partSizes += value.size();
}
// only relevant for non-literals or non-external literals
const QByteArray origData = PartHelper::translateData( part );
if ( origData != value ) {
if ( part.isValid() ) {
PartHelper::update( &part, value, value.size() );
} else {
// qDebug() << "insert from Store::handleLine: " << value.left(100);
part.setData( value );
part.setDatasize( value.size() );
if ( !PartHelper::insert( &part ) )
return failureResponse( "Unable to add item part" );
}
changes << partName;
}
} // parts/attribute modification
}
QString datetime;
if ( !changes.isEmpty() ) {
// update item size
if ( pimItems.size() == 1 && (mSize > 0 || partSizes > 0) )
pimItems.first().setSize( qMax( mSize, partSizes ) );
// run update query and prepare change notifications
for ( int i = 0; i < pimItems.count(); ++i ) {
PimItem &item = pimItems[ i ];
item.setDatetime( modificationtime );
item.setAtime( modificationtime );
if ( !connection()->isOwnerResource( item ) )
item.setDirty( true );
if ( !item.update() )
throw HandlerException( "Unable to write item changes into the database" );
if ( invalidateCache ) {
if ( !store->invalidateItemCache( item ) ) {
throw HandlerException( "Unable to invalidate item cache in the database" );
}
}
store->notificationCollector()->itemChanged( item, changes );
}
if ( !transaction.commit() )
return failureResponse( "Cannot commit transaction." );
datetime = QLocale::c().toString( modificationtime, QLatin1String( "dd-MMM-yyyy hh:mm:ss +0000" ) );
} else {
datetime = QLocale::c().toString( pimItems.first().datetime(), QLatin1String( "dd-MMM-yyyy hh:mm:ss +0000" ) );
}
// TODO: When implementing support for modifying multiple items at once, the revisions of the items should be in the responses.
// or only modified items should appear in the repsponse.
Response response;
response.setTag( tag() );
response.setSuccess();
response.setString( "DATETIME " + ImapParser::quote( datetime.toUtf8() ) + " STORE completed" );
emit responseAvailable( response );
return true;
}
void Store::parseCommand()
{
mScope.parseScope( m_streamParser );
// parse the stuff before the modification list
while ( !m_streamParser->hasList() ) {
const QByteArray command = m_streamParser->readString();
if ( command.isEmpty() ) { // ie. we are at command end
throw HandlerException( "No modification list provided in STORE command" );
} else if ( command == AKONADI_PARAM_REVISION ) {
mPreviousRevision = m_streamParser->readNumber();
mCheckRevision = true;
} else if ( command == AKONADI_PARAM_SIZE ) {
mSize = m_streamParser->readNumber();
}
}
}
void Store::sendPimItemResponse( const PimItem &pimItem )
{
const QVector<Flag> flags = pimItem.flags();
QStringList flagList;
for ( int j = 0; j < flags.count(); ++j )
flagList.append( flags[ j ].name() );
Response response;
response.setUntagged();
// IMAP protocol violation: should actually be the sequence number
response.setString( QByteArray::number( pimItem.id() ) + " FETCH (FLAGS (" + flagList.join( QLatin1String(" ") ).toUtf8() + "))" );
emit responseAvailable( response );
}
#include "store.moc"
<commit_msg>Enable the conflict detection for resources again.<commit_after>/***************************************************************************
* Copyright (C) 2006 by Tobias Koenig <[email protected]> *
* *
* 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 "store.h"
#include "akonadi.h"
#include "akonadiconnection.h"
#include "handlerhelper.h"
#include "response.h"
#include "storage/datastore.h"
#include "storage/transaction.h"
#include "storage/itemqueryhelper.h"
#include "storage/selectquerybuilder.h"
#include "storage/parthelper.h"
#include "storage/dbconfig.h"
#include "storage/itemretriever.h"
#include "libs/imapparser_p.h"
#include "libs/protocol_p.h"
#include "imapstreamparser.h"
#include <QtCore/QStringList>
#include <QLocale>
#include <QDebug>
#include <QFile>
#include <algorithm>
#include <functional>
using namespace Akonadi;
Store::Store( Scope::SelectionScope scope )
: Handler()
, mScope( scope )
, mPos( 0 )
, mPreviousRevision( -1 )
, mSize( 0 )
, mCheckRevision( false )
{
}
bool Store::replaceFlags( const PimItem &item, const QList<QByteArray> &flags )
{
Flag::List flagList = HandlerHelper::resolveFlags( flags );
DataStore *store = connection()->storageBackend();
Flag::List currentFlags = item.flags();
std::sort( flagList.begin(), flagList.end(), _detail::ById<std::less>() );
std::sort( currentFlags.begin(), currentFlags.end(), _detail::ById<std::less>() );
if ( flagList == currentFlags )
return false;
if ( !store->setItemFlags( item, flagList ) )
throw HandlerException( "Store::replaceFlags: Unable to set new item flags" );
return true;
}
bool Store::addFlags( const PimItem &item, const QList<QByteArray> &flags, bool& flagsChanged )
{
const Flag::List flagList = HandlerHelper::resolveFlags( flags );
DataStore *store = connection()->storageBackend();
if ( !store->appendItemFlags( item, flagList, flagsChanged ) ) {
qDebug( "Store::addFlags: Unable to add new item flags" );
return false;
}
return true;
}
bool Store::deleteFlags( const PimItem &item, const QList<QByteArray> &flags )
{
DataStore *store = connection()->storageBackend();
QVector<Flag> flagList;
flagList.reserve( flags.size() );
for ( int i = 0; i < flags.count(); ++i ) {
Flag flag = Flag::retrieveByName( QString::fromUtf8( flags[ i ] ) );
if ( !flag.isValid() )
continue;
flagList.append( flag );
}
if ( !store->removeItemFlags( item, flagList ) ) {
qDebug( "Store::deleteFlags: Unable to remove item flags" );
return false;
}
return true;
}
bool Store::parseStream()
{
parseCommand();
DataStore *store = connection()->storageBackend();
Transaction transaction( store );
// Set the same modification time for each item.
const QDateTime modificationtime = QDateTime::currentDateTime().toUTC();
// retrieve selected items
SelectQueryBuilder<PimItem> qb;
ItemQueryHelper::scopeToQuery( mScope, connection(), qb );
if ( !qb.exec() )
return failureResponse( "Unable to retrieve items" );
PimItem::List pimItems = qb.result();
if ( pimItems.isEmpty() )
return failureResponse( "No items found" );
for ( int i = 0; i < pimItems.size(); ++i ) {
if ( mCheckRevision ) {
// check for conflicts if a resources tries to overwrite an item with dirty payload
if ( connection()->isOwnerResource( pimItems.at( i ) ) ) {
if ( pimItems.at( i ).dirty() )
throw HandlerException( "[LRCONFLICT] Resource tries to modify item with dirty payload, aborting STORE." );
}
// check and update revisions
if ( pimItems.at( i ).rev() != (int)mPreviousRevision )
throw HandlerException( "[LLCONFLICT] Item was modified elsewhere, aborting STORE." );
}
pimItems[ i ].setRev( pimItems[ i ].rev() + 1 );
}
QSet<QByteArray> changes;
qint64 partSizes = 0;
bool invalidateCache = false;
// apply modifications
m_streamParser->beginList();
while ( !m_streamParser->atListEnd() ) {
// parse the command
QByteArray command = m_streamParser->readString();
if ( command.isEmpty() )
throw HandlerException( "Syntax error" );
Operation op = Replace;
bool silent = false;
if ( command.startsWith( '+' ) ) {
op = Add;
command = command.mid( 1 );
} else if ( command.startsWith( '-' ) ) {
op = Delete;
command = command.mid( 1 );
}
if ( command.endsWith( ".SILENT" ) ) {
command.chop( 7 );
silent = true;
}
// qDebug() << "STORE: handling command: " << command;
// handle commands that can be applied to more than one item
if ( command == AKONADI_PARAM_FLAGS ) {
bool flagsChanged = true;
const QList<QByteArray> flags = m_streamParser->readParenthesizedList();
// TODO move this iteration to an SQL query.
for ( int i = 0; i < pimItems.count(); ++i ) {
if ( op == Replace ) {
flagsChanged = replaceFlags( pimItems[ i ], flags );
} else if ( op == Add ) {
if ( !addFlags( pimItems[ i ], flags, flagsChanged ) )
return failureResponse( "Unable to add item flags." );
} else if ( op == Delete ) {
if ( !deleteFlags( pimItems[ i ], flags ) )
return failureResponse( "Unable to remove item flags." );
}
// TODO what is this about?
if ( !silent ) {
sendPimItemResponse( pimItems[i] );
}
}
if ( flagsChanged )
changes << AKONADI_PARAM_FLAGS;
continue;
}
// handle commands that can only be applied to one item
if ( pimItems.size() > 1 )
throw HandlerException( "This Modification can only be applied to a single item" );
PimItem &item = pimItems.first();
if ( !item.isValid() )
throw HandlerException( "Invalid item in query result!?" );
if ( command == AKONADI_PARAM_REMOTEID ) {
const QString rid = m_streamParser->readUtf8String();
if ( item.remoteId() != rid ) {
if ( !connection()->isOwnerResource( item ) )
throw HandlerException( "Only resources can modify remote identifiers" );
item.setRemoteId( rid );
changes << AKONADI_PARAM_REMOTEID;
}
}
else if ( command == AKONADI_PARAM_REMOTEREVISION ) {
const QString remoteRevision = m_streamParser->readUtf8String();
if ( item.remoteRevision() != remoteRevision ) {
if ( !connection()->isOwnerResource( item ) )
throw HandlerException( "Only resources can modify remote revisions" );
item.setRemoteRevision( remoteRevision );
changes << AKONADI_PARAM_REMOTEREVISION;
}
}
else if ( command == AKONADI_PARAM_UNDIRTY ) {
m_streamParser->readString(); // read the 'false' string
item.setDirty( false );
}
else if ( command == AKONADI_PARAM_INVALIDATECACHE ) {
invalidateCache = true;
}
else if ( command == AKONADI_PARAM_SIZE ) {
mSize = m_streamParser->readNumber();
changes << AKONADI_PARAM_SIZE;
}
else if ( command == "PARTS" ) {
const QList<QByteArray> parts = m_streamParser->readParenthesizedList();
if ( op == Delete ) {
if ( !store->removeItemParts( item, parts ) )
return failureResponse( "Unable to remove item parts." );
changes += QSet<QByteArray>::fromList( parts );
}
}
else if ( command == "COLLECTION" ) {
throw HandlerException( "Item moving via STORE is deprecated, update your Akonadi client" );
}
// parts/attributes
else {
// obtain and configure the part object
int partVersion = 0;
QByteArray partName;
ImapParser::splitVersionedKey( command, partName, partVersion );
SelectQueryBuilder<Part> qb;
qb.addValueCondition( Part::pimItemIdColumn(), Query::Equals, item.id() );
qb.addValueCondition( Part::nameColumn(), Query::Equals, QString::fromUtf8( partName ) );
if ( !qb.exec() )
return failureResponse( "Unable to check item part existence" );
Part::List result = qb.result();
Part part;
if ( !result.isEmpty() )
part = result.first();
part.setName( QString::fromUtf8( partName ) );
part.setVersion( partVersion );
part.setPimItemId( item.id() );
QByteArray value;
if ( m_streamParser->hasLiteral() ) {
const qint64 dataSize = m_streamParser->remainingLiteralSize();
partSizes += dataSize;
const bool storeInFile = ( DbConfig::configuredDatabase()->useExternalPayloadFile() && dataSize > DbConfig::configuredDatabase()->sizeThreshold() );
//actual case when streaming storage is used: external payload is enabled, data is big enough in a literal
if ( storeInFile ) {
// use first part as value for the initial insert into / update to the database.
// this will give us a proper filename to stream the rest of the parts contents into
// NOTE: we have to set the correct size (== dataSize) directly
value = m_streamParser->readLiteralPart();
// qDebug() << Q_FUNC_INFO << "VALUE in STORE: " << value << value.size() << dataSize;
if ( part.isValid() ) {
PartHelper::update( &part, value, dataSize );
} else {
// qDebug() << "insert from Store::handleLine";
part.setData( value );
part.setDatasize( dataSize );
if ( !PartHelper::insert( &part ) )
return failureResponse( "Unable to add item part" );
}
//the actual streaming code for the remaining parts:
// reads from the parser, writes immediately to the file
// ### move this entire block to part helper? should be useful for append as well
const QString fileName = QString::fromUtf8( part.data() );
QFile file( fileName );
if ( file.open( QIODevice::WriteOnly | QIODevice::Append ) ) {
while ( !m_streamParser->atLiteralEnd() ) {
value = m_streamParser->readLiteralPart();
file.write( value ); // ### error handling?
}
file.close();
} else {
return failureResponse( "Unable to update item part" );
}
changes << partName;
continue;
} else { // not store in file
//don't write in streaming way as the data goes to the database
while (!m_streamParser->atLiteralEnd()) {
value += m_streamParser->readLiteralPart();
}
}
} else { //not a literal
value = m_streamParser->readString();
partSizes += value.size();
}
// only relevant for non-literals or non-external literals
const QByteArray origData = PartHelper::translateData( part );
if ( origData != value ) {
if ( part.isValid() ) {
PartHelper::update( &part, value, value.size() );
} else {
// qDebug() << "insert from Store::handleLine: " << value.left(100);
part.setData( value );
part.setDatasize( value.size() );
if ( !PartHelper::insert( &part ) )
return failureResponse( "Unable to add item part" );
}
changes << partName;
}
} // parts/attribute modification
}
QString datetime;
if ( !changes.isEmpty() ) {
// update item size
if ( pimItems.size() == 1 && (mSize > 0 || partSizes > 0) )
pimItems.first().setSize( qMax( mSize, partSizes ) );
// run update query and prepare change notifications
for ( int i = 0; i < pimItems.count(); ++i ) {
PimItem &item = pimItems[ i ];
item.setDatetime( modificationtime );
item.setAtime( modificationtime );
if ( !connection()->isOwnerResource( item ) )
item.setDirty( true );
if ( !item.update() )
throw HandlerException( "Unable to write item changes into the database" );
if ( invalidateCache ) {
if ( !store->invalidateItemCache( item ) ) {
throw HandlerException( "Unable to invalidate item cache in the database" );
}
}
store->notificationCollector()->itemChanged( item, changes );
}
if ( !transaction.commit() )
return failureResponse( "Cannot commit transaction." );
datetime = QLocale::c().toString( modificationtime, QLatin1String( "dd-MMM-yyyy hh:mm:ss +0000" ) );
} else {
datetime = QLocale::c().toString( pimItems.first().datetime(), QLatin1String( "dd-MMM-yyyy hh:mm:ss +0000" ) );
}
// TODO: When implementing support for modifying multiple items at once, the revisions of the items should be in the responses.
// or only modified items should appear in the repsponse.
Response response;
response.setTag( tag() );
response.setSuccess();
response.setString( "DATETIME " + ImapParser::quote( datetime.toUtf8() ) + " STORE completed" );
emit responseAvailable( response );
return true;
}
void Store::parseCommand()
{
mScope.parseScope( m_streamParser );
// parse the stuff before the modification list
while ( !m_streamParser->hasList() ) {
const QByteArray command = m_streamParser->readString();
if ( command.isEmpty() ) { // ie. we are at command end
throw HandlerException( "No modification list provided in STORE command" );
} else if ( command == AKONADI_PARAM_REVISION ) {
mPreviousRevision = m_streamParser->readNumber();
mCheckRevision = true;
} else if ( command == AKONADI_PARAM_SIZE ) {
mSize = m_streamParser->readNumber();
}
}
}
void Store::sendPimItemResponse( const PimItem &pimItem )
{
const QVector<Flag> flags = pimItem.flags();
QStringList flagList;
for ( int j = 0; j < flags.count(); ++j )
flagList.append( flags[ j ].name() );
Response response;
response.setUntagged();
// IMAP protocol violation: should actually be the sequence number
response.setString( QByteArray::number( pimItem.id() ) + " FETCH (FLAGS (" + flagList.join( QLatin1String(" ") ).toUtf8() + "))" );
emit responseAvailable( response );
}
#include "store.moc"
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: options.hxx,v $
*
* $Revision: 1.20 $
*
* last change: $Author: hr $ $Date: 2006-06-19 23:24:15 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef CONFIGMGR_MISC_OPTIONS_HXX_
#define CONFIGMGR_MISC_OPTIONS_HXX_
#ifndef CONFIGMGR_MISC_REQUESTOPTIONS_HXX_
#include "requestoptions.hxx"
#endif
#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hxx>
#endif
#ifndef _SALHELPER_SIMPLEREFERENCEOBJECT_HXX_
#include <salhelper/simplereferenceobject.hxx>
#endif
#ifndef _VOS_REF_HXX_
#include <vos/ref.hxx>
#endif
namespace configmgr
{
namespace css = ::com::sun::star;
/**
class OOptions is created one time per Configuration[update]Access
all important options should stored in this class.
The object will be forwarded to all other objects so we only
need to extend this classobject and all other class can work with
the new options or important options etc.
*/
class OOptions : public salhelper::SimpleReferenceObject
{
RequestOptions m_aRequestOptions; // current options to use
public:
typedef RequestOptions::Locale Locale;
typedef RequestOptions::LocaleString LocaleString;
typedef RequestOptions::Entity Entity;
OOptions()
: m_aRequestOptions()
{}
explicit
OOptions(const RequestOptions& _aDefaultOptions)
: m_aRequestOptions(_aDefaultOptions)
{
}
OOptions(const OOptions& _aOtherOptions)
: salhelper::SimpleReferenceObject()
, m_aRequestOptions(_aOtherOptions.m_aRequestOptions)
{
}
bool isForSessionUser() const { return ! m_aRequestOptions.hasEntity(); }
LocaleString getLocale() const { return m_aRequestOptions.getLocale(); }
Entity getUser() const { return m_aRequestOptions.getEntity(); }
RequestOptions const & getRequestOptions() const
{ return m_aRequestOptions; }
void setUser(const Entity & _rUser)
{ m_aRequestOptions.setEntity(_rUser); }
void setLocale(const Locale & _rLocale)
{ m_aRequestOptions.setLocale(_rLocale); }
void setMultiLocaleMode()
{ m_aRequestOptions.setAllLocales(); }
void enableAsync(bool _bEnable)
{ m_aRequestOptions.enableAsync(_bEnable); }
};
typedef vos::ORef<OOptions> OptionsRef;
struct ltOptions
{
lessRequestOptions ltData;
bool operator()(OptionsRef const &o1, OptionsRef const &o2) const
{
return ltData(o1->getRequestOptions(),o2->getRequestOptions());
}
};
} // namespace
#endif
<commit_msg>INTEGRATION: CWS configrefactor01 (1.20.42); FILE MERGED 2007/01/11 20:16:01 mmeeks 1.20.42.1: Submitted by: mmeeks More re-factoring, lots of locking rationalized, drastically reduced the mutex count, also removed ~300k interlocked increments with a non-interlocking SimpleReferencedObject base<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: options.hxx,v $
*
* $Revision: 1.21 $
*
* last change: $Author: ihi $ $Date: 2007-11-23 14:22:26 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef CONFIGMGR_MISC_OPTIONS_HXX_
#define CONFIGMGR_MISC_OPTIONS_HXX_
#ifndef CONFIGMGR_MISC_REQUESTOPTIONS_HXX_
#include "requestoptions.hxx"
#endif
#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hxx>
#endif
#ifndef CONFIGMGR_UTILITY_HXX_
#include "utility.hxx"
#endif
#ifndef _VOS_REF_HXX_
#include <vos/ref.hxx>
#endif
namespace configmgr
{
namespace css = ::com::sun::star;
/**
class OOptions is created one time per Configuration[update]Access
all important options should stored in this class.
The object will be forwarded to all other objects so we only
need to extend this classobject and all other class can work with
the new options or important options etc.
*/
class OOptions : public configmgr::SimpleReferenceObject
{
RequestOptions m_aRequestOptions; // current options to use
public:
typedef RequestOptions::Locale Locale;
typedef RequestOptions::LocaleString LocaleString;
typedef RequestOptions::Entity Entity;
OOptions()
: m_aRequestOptions()
{}
explicit
OOptions(const RequestOptions& _aDefaultOptions)
: m_aRequestOptions(_aDefaultOptions)
{
}
OOptions(const OOptions& _aOtherOptions)
: configmgr::SimpleReferenceObject()
, m_aRequestOptions(_aOtherOptions.m_aRequestOptions)
{
}
bool isForSessionUser() const { return ! m_aRequestOptions.hasEntity(); }
LocaleString getLocale() const { return m_aRequestOptions.getLocale(); }
Entity getUser() const { return m_aRequestOptions.getEntity(); }
RequestOptions const & getRequestOptions() const
{ return m_aRequestOptions; }
void setUser(const Entity & _rUser)
{ m_aRequestOptions.setEntity(_rUser); }
void setLocale(const Locale & _rLocale)
{ m_aRequestOptions.setLocale(_rLocale); }
void setMultiLocaleMode()
{ m_aRequestOptions.setAllLocales(); }
void enableAsync(bool _bEnable)
{ m_aRequestOptions.enableAsync(_bEnable); }
};
typedef vos::ORef<OOptions> OptionsRef;
struct ltOptions
{
lessRequestOptions ltData;
bool operator()(OptionsRef const &o1, OptionsRef const &o2) const
{
return ltData(o1->getRequestOptions(),o2->getRequestOptions());
}
};
} // namespace
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: tracer.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: hr $ $Date: 2000-11-07 12:14:37 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
// SUNPRO5 does not like the following to be done after including stdio.h, that's why it's here at the very
// beginning of the file
#undef _TIME_T_DEFINED
#include <time.h>
#include <rtl/string.hxx>
#include <map>
namespace configmgr
{
typedef ::std::map< ::rtl::OString, void*, ::std::less< ::rtl::OString > > VirtualDevices;
}
#ifndef _CONFIGMGR_TRACER_HXX_
#include "tracer.hxx"
#endif
#ifdef CFG_ENABLE_TRACING
#include <cstdarg>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#define INFO 1
#define WARNING 2
#define ERROR 4
namespace configmgr
{
struct OTracerSetup
{
sal_Int32 s_nTraceMask;
sal_Int32 s_nIndentDepth;
FILE* s_pOutputMedium;
sal_Bool s_bInitialized;
VirtualDevices s_aDevices;
OTracerSetup()
:s_nTraceMask(INFO | WARNING | ERROR)
,s_nIndentDepth(0)
,s_pOutputMedium(NULL)
,s_bInitialized(sal_False)
{
}
};
//==========================================================================
//= OConfigTracer
//==========================================================================
::osl::Mutex OConfigTracer::s_aMutex;
OTracerSetup* OConfigTracer::s_pImpl = NULL;
//--------------------------------------------------------------------------
void OConfigTracer::ensureData()
{
if (s_pImpl)
return;
s_pImpl = new OTracerSetup;
}
//--------------------------------------------------------------------------
void OConfigTracer::inc()
{
::osl::MutexGuard aGuard(s_aMutex);
ensureData();
++s_pImpl->s_nIndentDepth;
}
//--------------------------------------------------------------------------
void OConfigTracer::dec()
{
::osl::MutexGuard aGuard(s_aMutex);
ensureData();
--s_pImpl->s_nIndentDepth;
}
//--------------------------------------------------------------------------
void OConfigTracer::traceInfo(const sal_Char* _pFormat, ...)
{
::osl::MutexGuard aGuard(s_aMutex);
ensureData();
if (s_pImpl->s_nTraceMask & INFO)
{
va_list args;
va_start(args, _pFormat);
implTrace("info : ", _pFormat, args);
va_end(args);
}
}
//--------------------------------------------------------------------------
void OConfigTracer::traceWarning(const sal_Char* _pFormat, ...)
{
::osl::MutexGuard aGuard(s_aMutex);
ensureData();
if (s_pImpl->s_nTraceMask & WARNING)
{
va_list args;
va_start(args, _pFormat);
implTrace("warning : ", _pFormat, args);
va_end(args);
}
}
//--------------------------------------------------------------------------
void OConfigTracer::traceError(const sal_Char* _pFormat, ...)
{
::osl::MutexGuard aGuard(s_aMutex);
ensureData();
if (s_pImpl->s_nTraceMask & ERROR)
{
va_list args;
va_start(args, _pFormat);
implTrace("error : ", _pFormat, args);
va_end(args);
}
}
//--------------------------------------------------------------------------
void OConfigTracer::indent()
{
for (sal_Int32 i=0; i<s_pImpl->s_nIndentDepth; ++i)
fprintf(s_pImpl->s_pOutputMedium, " ");
}
//--------------------------------------------------------------------------
FILE* disambiguate(const ::rtl::OString& _rFileName)
{
FILE* pExistenceCheck = NULL;
sal_Int32 i = 1;
::rtl::OString sLoop;
while (i <= 256)
{
sLoop = _rFileName;
sLoop += ".";
sLoop += ::rtl::OString::valueOf(i);
pExistenceCheck = fopen(sLoop.getStr(), "r");
if (!pExistenceCheck)
// does not exist
return fopen(sLoop.getStr(), "w+");
// already exists, try the next name
fclose(pExistenceCheck);
++i;
}
// could not open such a file
return NULL;
}
//--------------------------------------------------------------------------
void OConfigTracer::ensureInitalized()
{
if (s_pImpl->s_bInitialized)
return;
s_pImpl->s_bInitialized = sal_True;
char* pSettings = getenv("ENVCFGFLAGS");
if (!pSettings)
return;
/* currently recognized structure :
+ switches have to be separated by whitespaces
+ valid switches are:
-m[e|o|f<file>] - output to stderr (e), stdout (o) or a file (f). In the latter case the whole rest
of the param ('til the next one, means 'til the next whitespace) is the filename
-t{i,w,e}* - type of output : i includes infos, w includes warnings, e includes errors
*/
s_pImpl->s_pOutputMedium = stderr;
s_pImpl->s_nTraceMask = 0;
char* pParamLoop = pSettings;
while (*pParamLoop)
{
while (!isspace(*pParamLoop) && *pParamLoop)
++pParamLoop;
sal_Int32 nLen = pParamLoop - pSettings;
if ((nLen > 1) && (*pSettings == '-'))
{
++pSettings;
switch (*pSettings)
{
case 'm':
case 'w':
if (nLen > 2)
{
++pSettings;
switch (*pSettings)
{
case 'e':
s_pImpl->s_pOutputMedium = stderr;
break;
case 'o':
s_pImpl->s_pOutputMedium = stdout;
break;
case 'f':
{
++pSettings;
// copy the filename into an own buffer
::rtl::OString sFileName(pSettings, pParamLoop - pSettings);
// open the file
s_pImpl->s_pOutputMedium = disambiguate(sFileName);
break;
}
}
}
break;
case 'd':
{ // assign a virtual device
// copy the device assingment description
::rtl::OString sDescription(pSettings + 1, pParamLoop - pSettings - 1);
sal_Int32 nSep = sDescription.indexOf(':');
if (-1 == nSep)
break; // invalid format
::rtl::OString sVirtualDeviceName, sFileName;
sVirtualDeviceName = sDescription.copy(0, nSep);
sFileName = sDescription.copy(nSep + 1);
FILE* pVirtualDevice = disambiguate(sFileName);
if (pVirtualDevice)
s_pImpl->s_aDevices[sVirtualDeviceName] = pVirtualDevice;
}
case 't':
{
++pSettings;
while (pSettings != pParamLoop)
{
switch (*pSettings)
{
case 'i': s_pImpl->s_nTraceMask |= INFO; break;
case 'w': s_pImpl->s_nTraceMask |= WARNING; break;
case 'e': s_pImpl->s_nTraceMask |= ERROR; break;
}
++pSettings;
}
}
}
}
if (!*pParamLoop)
break;
++pParamLoop;
pSettings = pParamLoop;
}
}
//--------------------------------------------------------------------------
void OConfigTracer::traceToVirtualDevice(const sal_Char* _pDeviceName, const sal_Char* _pFormat, ...)
{
::osl::MutexGuard aGuard(s_aMutex);
ensureData();
ensureInitalized();
VirtualDevices::const_iterator aDeviceMediumPos = s_pImpl->s_aDevices.find(::rtl::OString(_pDeviceName));
if (aDeviceMediumPos != s_pImpl->s_aDevices.end())
{
FILE* pDeviceMedium = (FILE*)aDeviceMediumPos->second;
va_list args;
va_start(args, _pFormat);
vfprintf(pDeviceMedium, _pFormat, args);
fflush(pDeviceMedium);
va_end(args);
}
}
//--------------------------------------------------------------------------
::rtl::OString OConfigTracer::getTimeStamp()
{
time_t aTime = time(NULL);
tm* pStructuredTime = gmtime(&aTime);
::rtl::OString sTimeStamp(asctime(pStructuredTime));
// cut the trainling linefeed (asctime is defined to contain such a line feed)
sal_Int32 nStampLen = sTimeStamp.getLength();
if ((0 != nStampLen) && ('\n' == sTimeStamp.getStr()[nStampLen - 1]))
sTimeStamp = sTimeStamp.copy(0, nStampLen - 1);
return sTimeStamp;
}
//--------------------------------------------------------------------------
void OConfigTracer::implTrace(const sal_Char* _pType, const sal_Char* _pFormat, va_list args)
{
ensureInitalized();
if (!s_pImpl->s_pOutputMedium)
// no tracing enabled
return;
fprintf(s_pImpl->s_pOutputMedium, "%s", _pType);
indent();
vfprintf(s_pImpl->s_pOutputMedium, _pFormat, args);
fprintf(s_pImpl->s_pOutputMedium,"\n");
fflush(s_pImpl->s_pOutputMedium);
}
} // namespace configmgr
#endif // defined(DEBUG) || defined(_DEBUG)
//**************************************************************************
// history:
// $Log: not supported by cvs2svn $
// Revision 1.1.1.1 2000/09/18 16:13:41 hr
// initial import
//
// Revision 1.7 2000/09/15 09:51:51 willem.vandorp
// OpenOffice header added
//
// Revision 1.6 2000/08/31 10:00:21 fs
// time_t unknown
//
// Revision 1.5 2000/08/30 14:34:09 fs
// getTimeStamp
//
// Revision 1.4 2000/08/20 12:55:42 fs
// #77860# introduced an impl class; introduces virtual trace devices
//
// Revision 1.3 2000/08/17 07:18:02 lla
// im/export
//
// Revision 1.2 2000/08/10 06:53:45 fs
// read settings from the ENVCFGFLAGS environment variable
//
// Revision 1.1 2000/08/09 18:52:46 fs
// helper classes for tracing
//
//
// Revision 1.0 09.08.00 13:10:05 fs
//**************************************************************************
<commit_msg>#80122# additional traces upon initialization (process id / executable name)<commit_after>/*************************************************************************
*
* $RCSfile: tracer.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: fs $ $Date: 2000-11-29 12:45:31 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
// SUNPRO5 does not like the following to be done after including stdio.h, that's why it's here at the very
// beginning of the file
#undef _TIME_T_DEFINED
#include <time.h>
#include <rtl/string.hxx>
#include <map>
namespace configmgr
{
typedef ::std::map< ::rtl::OString, void*, ::std::less< ::rtl::OString > > VirtualDevices;
}
#ifndef _CONFIGMGR_TRACER_HXX_
#include "tracer.hxx"
#endif
#ifdef CFG_ENABLE_TRACING
#include <cstdarg>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <osl/process.h>
#include <rtl/ustring.hxx>
#define INFO 1
#define WARNING 2
#define ERROR 4
namespace configmgr
{
struct OTracerSetup
{
sal_Int32 s_nTraceMask;
sal_Int32 s_nIndentDepth;
FILE* s_pOutputMedium;
sal_Bool s_bInitialized;
VirtualDevices s_aDevices;
OTracerSetup()
:s_nTraceMask(INFO | WARNING | ERROR)
,s_nIndentDepth(0)
,s_pOutputMedium(NULL)
,s_bInitialized(sal_False)
{
}
};
//==========================================================================
//= OConfigTracer
//==========================================================================
::osl::Mutex OConfigTracer::s_aMutex;
OTracerSetup* OConfigTracer::s_pImpl = NULL;
//--------------------------------------------------------------------------
void OConfigTracer::ensureData()
{
if (s_pImpl)
return;
s_pImpl = new OTracerSetup;
}
//--------------------------------------------------------------------------
void OConfigTracer::inc()
{
::osl::MutexGuard aGuard(s_aMutex);
ensureData();
++s_pImpl->s_nIndentDepth;
}
//--------------------------------------------------------------------------
void OConfigTracer::dec()
{
::osl::MutexGuard aGuard(s_aMutex);
ensureData();
--s_pImpl->s_nIndentDepth;
}
//--------------------------------------------------------------------------
void OConfigTracer::traceInfo(const sal_Char* _pFormat, ...)
{
::osl::MutexGuard aGuard(s_aMutex);
ensureData();
if (s_pImpl->s_nTraceMask & INFO)
{
va_list args;
va_start(args, _pFormat);
implTrace("info : ", _pFormat, args);
va_end(args);
}
}
//--------------------------------------------------------------------------
void OConfigTracer::traceWarning(const sal_Char* _pFormat, ...)
{
::osl::MutexGuard aGuard(s_aMutex);
ensureData();
if (s_pImpl->s_nTraceMask & WARNING)
{
va_list args;
va_start(args, _pFormat);
implTrace("warning : ", _pFormat, args);
va_end(args);
}
}
//--------------------------------------------------------------------------
void OConfigTracer::traceError(const sal_Char* _pFormat, ...)
{
::osl::MutexGuard aGuard(s_aMutex);
ensureData();
if (s_pImpl->s_nTraceMask & ERROR)
{
va_list args;
va_start(args, _pFormat);
implTrace("error : ", _pFormat, args);
va_end(args);
}
}
//--------------------------------------------------------------------------
void OConfigTracer::indent()
{
for (sal_Int32 i=0; i<s_pImpl->s_nIndentDepth; ++i)
fprintf(s_pImpl->s_pOutputMedium, " ");
}
//--------------------------------------------------------------------------
FILE* disambiguate(const ::rtl::OString& _rFileName)
{
FILE* pExistenceCheck = NULL;
sal_Int32 i = 1;
::rtl::OString sLoop;
while (i <= 256)
{
sLoop = _rFileName;
sLoop += ".";
sLoop += ::rtl::OString::valueOf(i);
pExistenceCheck = fopen(sLoop.getStr(), "r");
if (!pExistenceCheck)
// does not exist
return fopen(sLoop.getStr(), "w+");
// already exists, try the next name
fclose(pExistenceCheck);
++i;
}
// could not open such a file
return NULL;
}
//--------------------------------------------------------------------------
void OConfigTracer::ensureInitalized()
{
if (s_pImpl->s_bInitialized)
return;
s_pImpl->s_bInitialized = sal_True;
char* pSettings = getenv("ENVCFGFLAGS");
if (!pSettings)
return;
/* currently recognized structure :
+ switches have to be separated by whitespaces
+ valid switches are:
-m[e|o|f<file>] - output to stderr (e), stdout (o) or a file (f). In the latter case the whole rest
of the param ('til the next one, means 'til the next whitespace) is the filename
-t{i,w,e}* - type of output : i includes infos, w includes warnings, e includes errors
*/
s_pImpl->s_pOutputMedium = stderr;
s_pImpl->s_nTraceMask = 0;
char* pParamLoop = pSettings;
while (*pParamLoop)
{
while (!isspace(*pParamLoop) && *pParamLoop)
++pParamLoop;
sal_Int32 nLen = pParamLoop - pSettings;
if ((nLen > 1) && (*pSettings == '-'))
{
++pSettings;
switch (*pSettings)
{
case 'm':
case 'w':
if (nLen > 2)
{
++pSettings;
switch (*pSettings)
{
case 'e':
s_pImpl->s_pOutputMedium = stderr;
break;
case 'o':
s_pImpl->s_pOutputMedium = stdout;
break;
case 'f':
{
++pSettings;
// copy the filename into an own buffer
::rtl::OString sFileName(pSettings, pParamLoop - pSettings);
// open the file
s_pImpl->s_pOutputMedium = disambiguate(sFileName);
break;
}
}
}
break;
case 'd':
{ // assign a virtual device
// copy the device assingment description
::rtl::OString sDescription(pSettings + 1, pParamLoop - pSettings - 1);
sal_Int32 nSep = sDescription.indexOf(':');
if (-1 == nSep)
break; // invalid format
::rtl::OString sVirtualDeviceName, sFileName;
sVirtualDeviceName = sDescription.copy(0, nSep);
sFileName = sDescription.copy(nSep + 1);
FILE* pVirtualDevice = disambiguate(sFileName);
if (pVirtualDevice)
s_pImpl->s_aDevices[sVirtualDeviceName] = pVirtualDevice;
}
case 't':
{
++pSettings;
while (pSettings != pParamLoop)
{
switch (*pSettings)
{
case 'i': s_pImpl->s_nTraceMask |= INFO; break;
case 'w': s_pImpl->s_nTraceMask |= WARNING; break;
case 'e': s_pImpl->s_nTraceMask |= ERROR; break;
}
++pSettings;
}
}
}
}
if (!*pParamLoop)
break;
++pParamLoop;
pSettings = pParamLoop;
}
// trace some initial information
CFG_TRACE_INFO_NI("initialization: process id: 0x%08X", osl_getProcess(0));
::rtl::OUString sExecutable;
osl_getExecutableFile(&sExecutable.pData);
CFG_TRACE_INFO_NI("initialization: executable file name: %s", OUSTRING2ASCII(sExecutable));
}
//--------------------------------------------------------------------------
void OConfigTracer::traceToVirtualDevice(const sal_Char* _pDeviceName, const sal_Char* _pFormat, ...)
{
::osl::MutexGuard aGuard(s_aMutex);
ensureData();
ensureInitalized();
VirtualDevices::const_iterator aDeviceMediumPos = s_pImpl->s_aDevices.find(::rtl::OString(_pDeviceName));
if (aDeviceMediumPos != s_pImpl->s_aDevices.end())
{
FILE* pDeviceMedium = (FILE*)aDeviceMediumPos->second;
va_list args;
va_start(args, _pFormat);
vfprintf(pDeviceMedium, _pFormat, args);
fflush(pDeviceMedium);
va_end(args);
}
}
//--------------------------------------------------------------------------
::rtl::OString OConfigTracer::getTimeStamp()
{
time_t aTime = time(NULL);
tm* pStructuredTime = gmtime(&aTime);
::rtl::OString sTimeStamp(asctime(pStructuredTime));
// cut the trainling linefeed (asctime is defined to contain such a line feed)
sal_Int32 nStampLen = sTimeStamp.getLength();
if ((0 != nStampLen) && ('\n' == sTimeStamp.getStr()[nStampLen - 1]))
sTimeStamp = sTimeStamp.copy(0, nStampLen - 1);
return sTimeStamp;
}
//--------------------------------------------------------------------------
void OConfigTracer::implTrace(const sal_Char* _pType, const sal_Char* _pFormat, va_list args)
{
ensureInitalized();
if (!s_pImpl->s_pOutputMedium)
// no tracing enabled
return;
fprintf(s_pImpl->s_pOutputMedium, "%s", _pType);
indent();
vfprintf(s_pImpl->s_pOutputMedium, _pFormat, args);
fprintf(s_pImpl->s_pOutputMedium,"\n");
fflush(s_pImpl->s_pOutputMedium);
}
} // namespace configmgr
#endif // defined(DEBUG) || defined(_DEBUG)
//**************************************************************************
// history:
// $Log: not supported by cvs2svn $
// Revision 1.2 2000/11/07 12:14:37 hr
// #65293#: includes
//
// Revision 1.1.1.1 2000/09/18 16:13:41 hr
// initial import
//
// Revision 1.7 2000/09/15 09:51:51 willem.vandorp
// OpenOffice header added
//
// Revision 1.6 2000/08/31 10:00:21 fs
// time_t unknown
//
// Revision 1.5 2000/08/30 14:34:09 fs
// getTimeStamp
//
// Revision 1.4 2000/08/20 12:55:42 fs
// #77860# introduced an impl class; introduces virtual trace devices
//
// Revision 1.3 2000/08/17 07:18:02 lla
// im/export
//
// Revision 1.2 2000/08/10 06:53:45 fs
// read settings from the ENVCFGFLAGS environment variable
//
// Revision 1.1 2000/08/09 18:52:46 fs
// helper classes for tracing
//
//
// Revision 1.0 09.08.00 13:10:05 fs
//**************************************************************************
<|endoftext|> |
<commit_before>/*
Copyright (c) 2009 Tobias Koenig <[email protected]>
This library 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 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 Library General Public
License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
*/
#include <QtCore/QDebug>
#include <QtCore/QStringList>
#include <QtCore/QUrl>
#include "nepomuksearch.h"
#include "search/result.h"
using namespace Akonadi;
static qint64 uriToItemId( const QUrl &url )
{
bool ok = false;
const qint64 id = url.queryItemValue( QLatin1String( "item" ) ).toLongLong( &ok );
if ( !ok )
return -1;
else
return id;
}
NepomukSearch::NepomukSearch( QObject* parent )
: QObject( parent ), mSearchService( 0 )
{
if ( !Nepomuk::Search::QueryServiceClient::serviceAvailable() ) {
qWarning() << "Nepomuk QueryServer interface not available!";
} else {
mSearchService = new Nepomuk::Search::QueryServiceClient( this );
connect( mSearchService, SIGNAL( newEntries( const QList<Nepomuk::Search::Result>& ) ),
this, SLOT( hitsAdded( const QList<Nepomuk::Search::Result>& ) ) );
}
}
NepomukSearch::~NepomukSearch()
{
if ( mSearchService ) {
mSearchService->close();
delete mSearchService;
}
}
QStringList NepomukSearch::search( const QString &query )
{
if ( !mSearchService ) {
qWarning() << "Nepomuk search service not available!";
return QStringList();
}
mSearchService->blockingQuery( query );
return mMatchingUIDs.toList();
}
void NepomukSearch::hitsAdded( const QList<Nepomuk::Search::Result>& entries )
{
if ( !mSearchService ) {
qWarning() << "Nepomuk search service not available!";
return;
}
Q_FOREACH( const Nepomuk::Search::Result &result, entries ) {
const qint64 itemId = uriToItemId( result.resourceUri() );
if ( itemId == -1 ) {
qWarning() << "Nepomuk QueryServer: Retrieved invalid item id from server!";
continue;
}
mMatchingUIDs.insert( QString::number( itemId ) );
}
}
#include "nepomuksearch.moc"
<commit_msg>Finding objects not handled by Akonadi is perfectly normal here, so no need to warn about that.<commit_after>/*
Copyright (c) 2009 Tobias Koenig <[email protected]>
This library 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 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 Library General Public
License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
*/
#include <QtCore/QDebug>
#include <QtCore/QStringList>
#include <QtCore/QUrl>
#include "nepomuksearch.h"
#include "search/result.h"
using namespace Akonadi;
static qint64 uriToItemId( const QUrl &url )
{
bool ok = false;
const qint64 id = url.queryItemValue( QLatin1String( "item" ) ).toLongLong( &ok );
if ( !ok )
return -1;
else
return id;
}
NepomukSearch::NepomukSearch( QObject* parent )
: QObject( parent ), mSearchService( 0 )
{
if ( !Nepomuk::Search::QueryServiceClient::serviceAvailable() ) {
qWarning() << "Nepomuk QueryServer interface not available!";
} else {
mSearchService = new Nepomuk::Search::QueryServiceClient( this );
connect( mSearchService, SIGNAL( newEntries( const QList<Nepomuk::Search::Result>& ) ),
this, SLOT( hitsAdded( const QList<Nepomuk::Search::Result>& ) ) );
}
}
NepomukSearch::~NepomukSearch()
{
if ( mSearchService ) {
mSearchService->close();
delete mSearchService;
}
}
QStringList NepomukSearch::search( const QString &query )
{
if ( !mSearchService ) {
qWarning() << "Nepomuk search service not available!";
return QStringList();
}
mSearchService->blockingQuery( query );
return mMatchingUIDs.toList();
}
void NepomukSearch::hitsAdded( const QList<Nepomuk::Search::Result>& entries )
{
if ( !mSearchService ) {
qWarning() << "Nepomuk search service not available!";
return;
}
Q_FOREACH( const Nepomuk::Search::Result &result, entries ) {
const qint64 itemId = uriToItemId( result.resourceUri() );
if ( itemId == -1 )
continue;
mMatchingUIDs.insert( QString::number( itemId ) );
}
}
#include "nepomuksearch.moc"
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: cmtree.cxx,v $
*
* $Revision: 1.36 $
*
* last change: $Author: ihi $ $Date: 2006-08-24 10:42: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
*
************************************************************************/
#include <stdio.h>
#include "subtree.hxx"
#ifndef CONFIGMGR_CHANGE_HXX
#include "change.hxx"
#endif
#ifndef CONFIGMGR_TREECHANGELIST_HXX
#include "treechangelist.hxx"
#endif
#ifndef CONFIGMGR_TREEPROVIDER_HXX
#include "treeprovider.hxx"
#endif
//#include "treeactions.hxx"
#ifndef _RTL_STRING_HXX_
#include <rtl/string.hxx>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef INCLUDED_DEQUE
#include <deque>
#define INCLUDED_DEQUE
#endif
#ifndef INCLUDED_VECTOR
#include <vector>
#define INCLUDED_VECTOR
#endif
#ifndef INCLUDED_IOSTREAM
#include <iostream>
#define INCLUDED_IOSTREAM
#endif
#ifndef INCLUDED_EXCEPTION
#include <exception>
#define INCLUDED_EXCEPTION
#endif
#ifndef INCLUDED_SET
#include <set>
#define INCLUDED_SET
#endif
using namespace std;
using namespace rtl;
using namespace com::sun::star::uno;
namespace configmgr
{
// ------------------------ ChildListSet implementations ------------------------
ChildListSet::ChildListSet(ChildListSet const& aSet, treeop::DeepChildCopy)
{
for(ChildList::iterator it = aSet.GetSet().begin();
it != aSet.GetSet().end();
++it)
{
INode* pOrg = *it;
std::auto_ptr<INode> aCopy = pOrg->clone();
m_aChildList.insert(m_aChildList.end(), aCopy.release());
}
}
ChildListSet::~ChildListSet()
{
for(ChildList::iterator it = m_aChildList.begin();
it != m_aChildList.end();
++it)
delete *it;
}
// ---------------------------- Node implementation ----------------------------
INode::INode(node::Attributes _aAttr):m_aAttributes(_aAttr){}
INode::INode(OUString const& aName, node::Attributes _aAttr)
:m_aName(aName)
,m_aAttributes(_aAttr){}
// CopyCTor will be create automatically
INode::~INode() {}
ISubtree* INode::asISubtree(){return NULL;}
ISubtree const* INode::asISubtree() const {return NULL;}
ValueNode* INode::asValueNode() {return NULL;}
ValueNode const* INode::asValueNode() const {return NULL;}
void INode::modifyState(node::State _eNewState)
{
m_aAttributes.setState(_eNewState);
}
void INode::modifyAccess(node::Access _aAccessLevel)
{
OSL_ENSURE( node::accessWritable <= _aAccessLevel && _aAccessLevel <= node::accessReadonly,"Invalid access level for Node");
m_aAttributes.setAccess(_aAccessLevel);
}
void INode::markMandatory()
{
m_aAttributes.markMandatory();
}
void INode::markRemovable()
{
m_aAttributes.markRemovable();
}
void INode::promoteAccessToDefault()
{
if (m_aAttributes.isFinalized())
m_aAttributes.setAccess(node::accessReadonly);
if ( m_aAttributes.isMandatory())
m_aAttributes.setRemovability(false,false);
}
void INode::forceReadonlyToFinalized()
{
if (m_aAttributes.isReadonly())
{
m_aAttributes.setAccess(node::accessFinal);
}
}
// ------------------------- SearchNode implementation -------------------------
SearchNode::SearchNode():INode(node::Attributes()){}
SearchNode::SearchNode(OUString const& aName)
:INode(aName, node::Attributes()){}
std::auto_ptr<INode> SearchNode::clone() const {return std::auto_ptr<INode>(new SearchNode(*this));}
SearchNode::~SearchNode(){}
//==========================================================================
//= OPropagateLevels
//==========================================================================
/** fills a subtree with the correct level informations
*/
struct OPropagateLevels : public NodeModification
{
public:
typedef sal_Int16 Level;
OPropagateLevels(Level _nParentLevel, Level _nParentDefaultLevel)
: m_nLevel ( childLevel(_nParentLevel) )
, m_nDefaultLevel ( childLevel(_nParentDefaultLevel) )
{
}
virtual void handle(ValueNode&) { /* not interested in value nodes */ }
virtual void handle(ISubtree& _rSubtree)
{
_rSubtree.setLevels(m_nLevel, m_nDefaultLevel);
}
static Level childLevel(Level _nLevel)
{
OSL_ASSERT(0 > treeop::ALL_LEVELS);
return (_nLevel > 0) ? _nLevel-1 : _nLevel;
}
protected:
Level m_nLevel;
Level m_nDefaultLevel;
};
// -------------------------- ISubtree implementation --------------------------
ISubtree* ISubtree::asISubtree() {return this;}
ISubtree const* ISubtree::asISubtree() const {return this;}
//--------------------------------------------------------------------------
static inline bool adjustLevel(sal_Int16& _rLevel, sal_Int16 _nNewLevel)
{
if (_rLevel == treeop::ALL_LEVELS) return false;
if (_nNewLevel <= _rLevel &&
_nNewLevel != treeop::ALL_LEVELS) return false;
_rLevel = _nNewLevel;
return true;
}
//--------------------------------------------------------------------------
void ISubtree::setLevels(sal_Int16 _nLevel, sal_Int16 _nDefaultLevels)
{
bool bActive = false;
if (_nLevel && adjustLevel(m_nLevel, _nLevel))
bActive = true;
if (_nDefaultLevels && adjustLevel(m_nDefaultLevels, _nDefaultLevels))
bActive = true;
// forward the level numbers to any child subtrees we have
if (bActive)
{
OPropagateLevels aPropagate(_nLevel,_nDefaultLevels);
aPropagate.applyToChildren(*this);
}
}
// --------------------------- Subtree implementation ---------------------------
std::auto_ptr<INode> Subtree::clone() const
{
return std::auto_ptr<INode>(new Subtree(*this, treeop::DeepChildCopy()));
}
INode* Subtree::doGetChild(OUString const& aName) const
{
SearchNode searchObj(aName);
#if OSL_DEBUG_LEVEL > 1
for (ChildList::iterator it2 = m_aChildren.GetSet().begin();
it2 != m_aChildren.GetSet().end();
++it2)
{
INode* pINode = *it2;
OUString aName2 = pINode->getName();
volatile int dummy;
dummy = 0;
}
#endif
ChildList::iterator it = m_aChildren.GetSet().find(&searchObj);
if (it == m_aChildren.GetSet().end())
return NULL;
else
return *it;
}
INode* Subtree::addChild(std::auto_ptr<INode> aNode) // takes ownership
{
OUString aName = aNode->getName();
std::pair<ChildList::iterator, bool> aInserted =
m_aChildren.GetSet().insert(aNode.get());
if (aInserted.second)
aNode.release();
return *aInserted.first;
}
::std::auto_ptr<INode> Subtree::removeChild(OUString const& aName)
{
SearchNode searchObj(aName);
ChildList::const_iterator it = m_aChildren.GetSet().find(&searchObj);
::std::auto_ptr<INode> aReturn;
if (m_aChildren.GetSet().end() != it)
{
aReturn = ::std::auto_ptr<INode>(*it);
m_aChildren.GetSet().erase(it);
}
return aReturn;
}
// // -------------------------- ValueNode implementation --------------------------
void Subtree::forEachChild(NodeAction& anAction) const
{
for(ChildList::const_iterator it = m_aChildren.GetSet().begin();
it != m_aChildren.GetSet().end();
++it)
(**it).dispatch(anAction);
}
void Subtree::forEachChild(NodeModification& anAction)
{
ChildList::iterator it = m_aChildren.GetSet().begin();
while( it != m_aChildren.GetSet().end() )
{
// modification-safe iteration
(**it++).dispatch(anAction);
}
}
// // -------------------------- ValueNode implementation --------------------------
bool ValueNode::setValueType(uno::Type const& _aType)
{
if (_aType == this->getValueType()) return true;
if (!this->isNull()) return false;
uno::TypeClass eTC = this->getValueType().getTypeClass();
if (eTC != uno::TypeClass_VOID && eTC != uno::TypeClass_ANY)
return false;
m_aValuePair = AnyPair(_aType);
OSL_ASSERT(_aType == this->getValueType());
return true;
}
bool ValueNode::setValue(Any const& _aValue)
{
sal_Bool bRet = m_aValuePair.setFirst(_aValue);
if (bRet) this->markAsDefault(false);
return !! bRet;
}
bool ValueNode::changeDefault(Any const& _aValue)
{
return !! m_aValuePair.setSecond(_aValue);
}
void ValueNode::setDefault()
{
OSL_PRECOND( hasUsableDefault(), "No default value to set for value node");
m_aValuePair.clear( selectValue() );
this->markAsDefault();
OSL_POSTCOND( isDefault(), "Could not set value node to default");
}
void ValueNode::promoteToDefault()
{
if (!isDefault())
{
if (m_aValuePair.hasFirst())
{
OSL_VERIFY( m_aValuePair.setSecond(m_aValuePair.getFirst()) );
m_aValuePair.clear( selectValue() );
}
else
{
m_aValuePair.clear( selectDeflt() );
OSL_ASSERT( m_aValuePair.isNull() );
}
this->markAsDefault();
OSL_ENSURE( !m_aValuePair.hasFirst(), "Leaving orphaned value in after promoting to default");
}
else
OSL_ENSURE( !m_aValuePair.hasFirst(), "Orphaned value in default node won't be promoted");
OSL_POSTCOND( isDefault(), "Could not promote value node to default");
}
std::auto_ptr<INode> ValueNode::clone() const
{
return std::auto_ptr<INode>(new ValueNode(*this));
}
ValueNode* ValueNode::asValueNode() {return this;}
ValueNode const* ValueNode::asValueNode() const {return this;}
} // namespace configmgr
<commit_msg>INTEGRATION: CWS pchfix02 (1.35.60); FILE MERGED 2006/09/01 17:20:42 kaib 1.35.60.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: cmtree.cxx,v $
*
* $Revision: 1.37 $
*
* last change: $Author: obo $ $Date: 2006-09-16 15:20:21 $
*
* 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_configmgr.hxx"
#include <stdio.h>
#include "subtree.hxx"
#ifndef CONFIGMGR_CHANGE_HXX
#include "change.hxx"
#endif
#ifndef CONFIGMGR_TREECHANGELIST_HXX
#include "treechangelist.hxx"
#endif
#ifndef CONFIGMGR_TREEPROVIDER_HXX
#include "treeprovider.hxx"
#endif
//#include "treeactions.hxx"
#ifndef _RTL_STRING_HXX_
#include <rtl/string.hxx>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef INCLUDED_DEQUE
#include <deque>
#define INCLUDED_DEQUE
#endif
#ifndef INCLUDED_VECTOR
#include <vector>
#define INCLUDED_VECTOR
#endif
#ifndef INCLUDED_IOSTREAM
#include <iostream>
#define INCLUDED_IOSTREAM
#endif
#ifndef INCLUDED_EXCEPTION
#include <exception>
#define INCLUDED_EXCEPTION
#endif
#ifndef INCLUDED_SET
#include <set>
#define INCLUDED_SET
#endif
using namespace std;
using namespace rtl;
using namespace com::sun::star::uno;
namespace configmgr
{
// ------------------------ ChildListSet implementations ------------------------
ChildListSet::ChildListSet(ChildListSet const& aSet, treeop::DeepChildCopy)
{
for(ChildList::iterator it = aSet.GetSet().begin();
it != aSet.GetSet().end();
++it)
{
INode* pOrg = *it;
std::auto_ptr<INode> aCopy = pOrg->clone();
m_aChildList.insert(m_aChildList.end(), aCopy.release());
}
}
ChildListSet::~ChildListSet()
{
for(ChildList::iterator it = m_aChildList.begin();
it != m_aChildList.end();
++it)
delete *it;
}
// ---------------------------- Node implementation ----------------------------
INode::INode(node::Attributes _aAttr):m_aAttributes(_aAttr){}
INode::INode(OUString const& aName, node::Attributes _aAttr)
:m_aName(aName)
,m_aAttributes(_aAttr){}
// CopyCTor will be create automatically
INode::~INode() {}
ISubtree* INode::asISubtree(){return NULL;}
ISubtree const* INode::asISubtree() const {return NULL;}
ValueNode* INode::asValueNode() {return NULL;}
ValueNode const* INode::asValueNode() const {return NULL;}
void INode::modifyState(node::State _eNewState)
{
m_aAttributes.setState(_eNewState);
}
void INode::modifyAccess(node::Access _aAccessLevel)
{
OSL_ENSURE( node::accessWritable <= _aAccessLevel && _aAccessLevel <= node::accessReadonly,"Invalid access level for Node");
m_aAttributes.setAccess(_aAccessLevel);
}
void INode::markMandatory()
{
m_aAttributes.markMandatory();
}
void INode::markRemovable()
{
m_aAttributes.markRemovable();
}
void INode::promoteAccessToDefault()
{
if (m_aAttributes.isFinalized())
m_aAttributes.setAccess(node::accessReadonly);
if ( m_aAttributes.isMandatory())
m_aAttributes.setRemovability(false,false);
}
void INode::forceReadonlyToFinalized()
{
if (m_aAttributes.isReadonly())
{
m_aAttributes.setAccess(node::accessFinal);
}
}
// ------------------------- SearchNode implementation -------------------------
SearchNode::SearchNode():INode(node::Attributes()){}
SearchNode::SearchNode(OUString const& aName)
:INode(aName, node::Attributes()){}
std::auto_ptr<INode> SearchNode::clone() const {return std::auto_ptr<INode>(new SearchNode(*this));}
SearchNode::~SearchNode(){}
//==========================================================================
//= OPropagateLevels
//==========================================================================
/** fills a subtree with the correct level informations
*/
struct OPropagateLevels : public NodeModification
{
public:
typedef sal_Int16 Level;
OPropagateLevels(Level _nParentLevel, Level _nParentDefaultLevel)
: m_nLevel ( childLevel(_nParentLevel) )
, m_nDefaultLevel ( childLevel(_nParentDefaultLevel) )
{
}
virtual void handle(ValueNode&) { /* not interested in value nodes */ }
virtual void handle(ISubtree& _rSubtree)
{
_rSubtree.setLevels(m_nLevel, m_nDefaultLevel);
}
static Level childLevel(Level _nLevel)
{
OSL_ASSERT(0 > treeop::ALL_LEVELS);
return (_nLevel > 0) ? _nLevel-1 : _nLevel;
}
protected:
Level m_nLevel;
Level m_nDefaultLevel;
};
// -------------------------- ISubtree implementation --------------------------
ISubtree* ISubtree::asISubtree() {return this;}
ISubtree const* ISubtree::asISubtree() const {return this;}
//--------------------------------------------------------------------------
static inline bool adjustLevel(sal_Int16& _rLevel, sal_Int16 _nNewLevel)
{
if (_rLevel == treeop::ALL_LEVELS) return false;
if (_nNewLevel <= _rLevel &&
_nNewLevel != treeop::ALL_LEVELS) return false;
_rLevel = _nNewLevel;
return true;
}
//--------------------------------------------------------------------------
void ISubtree::setLevels(sal_Int16 _nLevel, sal_Int16 _nDefaultLevels)
{
bool bActive = false;
if (_nLevel && adjustLevel(m_nLevel, _nLevel))
bActive = true;
if (_nDefaultLevels && adjustLevel(m_nDefaultLevels, _nDefaultLevels))
bActive = true;
// forward the level numbers to any child subtrees we have
if (bActive)
{
OPropagateLevels aPropagate(_nLevel,_nDefaultLevels);
aPropagate.applyToChildren(*this);
}
}
// --------------------------- Subtree implementation ---------------------------
std::auto_ptr<INode> Subtree::clone() const
{
return std::auto_ptr<INode>(new Subtree(*this, treeop::DeepChildCopy()));
}
INode* Subtree::doGetChild(OUString const& aName) const
{
SearchNode searchObj(aName);
#if OSL_DEBUG_LEVEL > 1
for (ChildList::iterator it2 = m_aChildren.GetSet().begin();
it2 != m_aChildren.GetSet().end();
++it2)
{
INode* pINode = *it2;
OUString aName2 = pINode->getName();
volatile int dummy;
dummy = 0;
}
#endif
ChildList::iterator it = m_aChildren.GetSet().find(&searchObj);
if (it == m_aChildren.GetSet().end())
return NULL;
else
return *it;
}
INode* Subtree::addChild(std::auto_ptr<INode> aNode) // takes ownership
{
OUString aName = aNode->getName();
std::pair<ChildList::iterator, bool> aInserted =
m_aChildren.GetSet().insert(aNode.get());
if (aInserted.second)
aNode.release();
return *aInserted.first;
}
::std::auto_ptr<INode> Subtree::removeChild(OUString const& aName)
{
SearchNode searchObj(aName);
ChildList::const_iterator it = m_aChildren.GetSet().find(&searchObj);
::std::auto_ptr<INode> aReturn;
if (m_aChildren.GetSet().end() != it)
{
aReturn = ::std::auto_ptr<INode>(*it);
m_aChildren.GetSet().erase(it);
}
return aReturn;
}
// // -------------------------- ValueNode implementation --------------------------
void Subtree::forEachChild(NodeAction& anAction) const
{
for(ChildList::const_iterator it = m_aChildren.GetSet().begin();
it != m_aChildren.GetSet().end();
++it)
(**it).dispatch(anAction);
}
void Subtree::forEachChild(NodeModification& anAction)
{
ChildList::iterator it = m_aChildren.GetSet().begin();
while( it != m_aChildren.GetSet().end() )
{
// modification-safe iteration
(**it++).dispatch(anAction);
}
}
// // -------------------------- ValueNode implementation --------------------------
bool ValueNode::setValueType(uno::Type const& _aType)
{
if (_aType == this->getValueType()) return true;
if (!this->isNull()) return false;
uno::TypeClass eTC = this->getValueType().getTypeClass();
if (eTC != uno::TypeClass_VOID && eTC != uno::TypeClass_ANY)
return false;
m_aValuePair = AnyPair(_aType);
OSL_ASSERT(_aType == this->getValueType());
return true;
}
bool ValueNode::setValue(Any const& _aValue)
{
sal_Bool bRet = m_aValuePair.setFirst(_aValue);
if (bRet) this->markAsDefault(false);
return !! bRet;
}
bool ValueNode::changeDefault(Any const& _aValue)
{
return !! m_aValuePair.setSecond(_aValue);
}
void ValueNode::setDefault()
{
OSL_PRECOND( hasUsableDefault(), "No default value to set for value node");
m_aValuePair.clear( selectValue() );
this->markAsDefault();
OSL_POSTCOND( isDefault(), "Could not set value node to default");
}
void ValueNode::promoteToDefault()
{
if (!isDefault())
{
if (m_aValuePair.hasFirst())
{
OSL_VERIFY( m_aValuePair.setSecond(m_aValuePair.getFirst()) );
m_aValuePair.clear( selectValue() );
}
else
{
m_aValuePair.clear( selectDeflt() );
OSL_ASSERT( m_aValuePair.isNull() );
}
this->markAsDefault();
OSL_ENSURE( !m_aValuePair.hasFirst(), "Leaving orphaned value in after promoting to default");
}
else
OSL_ENSURE( !m_aValuePair.hasFirst(), "Orphaned value in default node won't be promoted");
OSL_POSTCOND( isDefault(), "Could not promote value node to default");
}
std::auto_ptr<INode> ValueNode::clone() const
{
return std::auto_ptr<INode>(new ValueNode(*this));
}
ValueNode* ValueNode::asValueNode() {return this;}
ValueNode const* ValueNode::asValueNode() const {return this;}
} // namespace configmgr
<|endoftext|> |
<commit_before>// Copyright (c) 2009 hp-FEM group at the University of Nevada, Reno (UNR).
// Distributed under the terms of the BSD license (see the LICENSE
// file for the exact terms).
// Email: [email protected], home page: http://hpfem.org/
#include "transforms.h"
#define N_chebyshev_max (3+2*(MAX_P-1))
typedef double ChebyshevMatrix[N_chebyshev_max][N_chebyshev_max];
typedef double TransformationMatrix[N_chebyshev_max][MAX_P+1];
// for one particular p:
TransformationMatrix transformation_matrix;
// for all p:
TransformationMatrix transformation_matrix_list[MAX_P+1];
int transformation_matrix_initialized=0;
TransformationMatrix *get_transformation_matrix(int p)
{
return & (transformation_matrix_list[p]);
}
void fill_chebyshev_points(int n, double *chebyshev_points)
{
for (int i=0; i < n; i++)
chebyshev_points[i] = -cos(i*M_PI/(n-1));
/*
for (int i=0; i < N_chebyshev_max; i++)
printf("%f ", chebyshev_points[i]);
printf("\n");
printf("done.\n");
*/
}
// transform values from (-1, 0) to (-1, 1)
#define map_left(x) (2*x+1)
// transform values from (0, 1) to (-1, 1)
#define map_right(x) (2*x-1)
double phi(int i, double x)
{
if (x < 0) {
if (i == 0)
return lobatto_fn_tab_1d[0](map_left(x));
else if (i % 2 == 0)
return 0;
else
return lobatto_fn_tab_1d[(i+1)/2](map_left(x));
} else {
if (i == 0)
return 0;
else if (i == 1)
return lobatto_fn_tab_1d[0](map_left(x));
else if (i % 2 == 1)
return 0;
else {
return lobatto_fn_tab_1d[i/2](map_left(x));
}
}
}
void fill_chebyshev_matrix(int n, ChebyshevMatrix *chebyshev_matrix)
{
double chebyshev_points[N_chebyshev_max];
fill_chebyshev_points(n, chebyshev_points);
for (int i=0; i < n; i++) {
for (int j=0; j < n; j++) {
//printf("XXX %d %d %f \n", i, j, phi(j, chebyshev_points[i]));
//printf("XXX %d %d %f \n", i, j, (*chebyshev_matrix)[i][j]);
(*chebyshev_matrix)[i][j] = phi(j, chebyshev_points[i]);
//printf("%f ", (*chebyshev_matrix)[i][j]);
}
//printf("\n");
}
//error("stop.");
}
void fill_transformation_matrix(int p, int p_ref, TransformationMatrix
transformation_matrix)
{
double chebyshev_points[N_chebyshev_max];
ChebyshevMatrix chebyshev_matrix;
int n = 3+2*(p_ref-1);
fill_chebyshev_points(n, chebyshev_points);
fill_chebyshev_matrix(n, &chebyshev_matrix);
for (int j=0; j < p+1; j++) {
// FIXME: don't compute the matrix all the time, e.g. move this out of
// the cycle and make sure the gaussian elimination doesn't overwrite
// the _mat.
Matrix *_mat = new DenseMatrix(n);
_mat->zero();
for (int _i=0; _i < n; _i++)
for (int _j=0; _j < n; _j++)
_mat->add(_i, _j, (chebyshev_matrix)[_i][_j]);
double f[n];
for (int i=0; i < n; i++)
f[i] = lobatto_fn_tab_1d[j](chebyshev_points[i]);
solve_linear_system(_mat, f);
for (int i=0; i < n; i++)
transformation_matrix[i][j] = f[i];
}
for (int i=0; i < n; i++) {
for (int j=0; j < p+1; j++) {
printf("%f ", transformation_matrix[i][j]);
}
printf("\n");
}
error("stop.");
}
void transform_element_refined(int comp, double *y_prev, double *y_prev_ref, Element
*e, Element *e_ref_left, Element *e_ref_right, Mesh *mesh, Mesh
*mesh_ref)
{
printf("ELEMENT: %d %f %f\n", e->id, e->x1, e->x2);
double y_prev_loc[MAX_P+1];
double y_prev_loc_trans[N_chebyshev_max+1];
if (e->dof[comp][0] == -1)
y_prev_loc[0] = mesh->bc_left_dir_values[comp];
else
y_prev_loc[0] = y_prev[e->dof[comp][0]];
if (e->dof[comp][1] == -1)
y_prev_loc[1] = mesh->bc_right_dir_values[comp];
else
y_prev_loc[1] = y_prev[e->dof[comp][1]];
for (int i=2; i < e->p + 1; i++)
y_prev_loc[i] = y_prev[e->dof[comp][i]];
for (int i=0; i < e->p + 1; i++)
printf("y_prev_loc[%d] = %f\n", i, y_prev_loc[i]);
TransformationMatrix transformation_matrix;
fill_transformation_matrix(e->p, e_ref_left->p, transformation_matrix);
//fill_transformation_matrix();
//double TransformationMatrix *transformation_matrix =
// get_transformation_matrix(e_ref_left->p + 1);
for (int i=0; i < 3 + 2*(e_ref_left->p - 1); i++) {
y_prev_loc_trans[i] = 0.;
for (int j=0; j < e->p + 1; j++)
y_prev_loc_trans[i] += transformation_matrix[i][j] * y_prev_loc[j];
}
for (int i=0; i < 3 + 2*(e_ref_left->p - 1); i++)
printf("y_prev_loc_trans[%d] = %f\n", i, y_prev_loc_trans[i]);
printf("----------------------\n");
// copying computed coefficients into the elements e_ref_left and
// e_ref_right
if (e->dof[comp][0] != -1)
y_prev_ref[e_ref_left->dof[comp][0]] = y_prev_loc_trans[0];
y_prev_ref[e_ref_left->dof[comp][1]] = y_prev_loc_trans[1];
y_prev_ref[e_ref_right->dof[comp][0]] = y_prev_loc_trans[1];
if (e->dof[comp][1] != -1)
y_prev_ref[e_ref_right->dof[comp][1]] = y_prev_loc_trans[2];
if (e_ref_left->p != e_ref_right->p)
error("internal error in transform_element: the left and right elements must have the same order.");
int counter = 0;
for (int p=2; p < e_ref_left->p + 1; p++) {
y_prev_ref[e_ref_left->dof[comp][p]] = y_prev_loc_trans[3+counter];
counter++;
y_prev_ref[e_ref_right->dof[comp][p]] = y_prev_loc_trans[3+counter];
counter++;
}
}
void transform_element_unrefined(int comp, double *y_prev, double *y_prev_ref, Element
*e, Element *e_ref, Mesh *mesh, Mesh *mesh_ref)
{
for (int p=0; p < e->p + 1; p++) {
if (e->dof[comp][p] != -1)
y_prev_ref[e_ref->dof[comp][p]] = y_prev[e->dof[comp][p]];
}
for (int p=e->p+1; p < e_ref->p + 1; p++) {
y_prev_ref[e_ref->dof[comp][p]] = 0.;
}
}
/* This only works after the dofs are assigned in the reference (and coarse)
* solution. */
void transfer_solution(Mesh *mesh, Mesh *mesh_ref, double *y_prev, double *y_prev_ref)
{
Iterator *I = new Iterator(mesh);
Iterator *I_ref = new Iterator(mesh_ref);
Element *e, *e_ref, *e_ref_left, *e_ref_right;
for (int comp=0; comp < mesh->get_n_eq(); comp++) {
I->reset();
I_ref->reset();
while ((e = I->next_active_element()) != NULL) {
e_ref = I_ref->next_active_element();
if (e->level == e_ref->level)
transform_element_unrefined(comp, y_prev, y_prev_ref, e,
e_ref, mesh, mesh_ref);
else if (e->level + 1 == e_ref->level) {
e_ref_left = e_ref;
e_ref_right = I_ref->next_active_element();
transform_element_refined(comp, y_prev, y_prev_ref, e,
e_ref_left, e_ref_right, mesh, mesh_ref);
}
else
error("internal error in transfer_solution: element orders mismatch.");
}
}
}
<commit_msg>works<commit_after>// Copyright (c) 2009 hp-FEM group at the University of Nevada, Reno (UNR).
// Distributed under the terms of the BSD license (see the LICENSE
// file for the exact terms).
// Email: [email protected], home page: http://hpfem.org/
#include "transforms.h"
#define N_chebyshev_max (3+2*(MAX_P-1))
typedef double ChebyshevMatrix[N_chebyshev_max][N_chebyshev_max];
typedef double TransformationMatrix[N_chebyshev_max][MAX_P+1];
// for one particular p:
TransformationMatrix transformation_matrix;
// for all p:
TransformationMatrix transformation_matrix_list[MAX_P+1];
int transformation_matrix_initialized=0;
TransformationMatrix *get_transformation_matrix(int p)
{
return & (transformation_matrix_list[p]);
}
void fill_chebyshev_points(int n, double *chebyshev_points)
{
for (int i=0; i < n; i++)
chebyshev_points[i] = -cos(i*M_PI/(n-1));
/*
for (int i=0; i < N_chebyshev_max; i++)
printf("%f ", chebyshev_points[i]);
printf("\n");
printf("done.\n");
*/
}
// transform values from (-1, 0) to (-1, 1)
#define map_left(x) (2*x+1)
// transform values from (0, 1) to (-1, 1)
#define map_right(x) (2*x-1)
double phi(int i, double x)
{
if (x < 0) {
if (i == 0)
return lobatto_fn_tab_1d[0](map_left(x));
else if (i % 2 == 0)
return 0;
else
return lobatto_fn_tab_1d[(i+1)/2](map_left(x));
} else {
if (i == 0)
return 0;
else if (i == 1)
return lobatto_fn_tab_1d[0](map_right(x));
else if (i % 2 == 1)
return 0;
else {
return lobatto_fn_tab_1d[i/2](map_right(x));
}
}
}
void fill_chebyshev_matrix(int n, ChebyshevMatrix *chebyshev_matrix)
{
double chebyshev_points[N_chebyshev_max];
fill_chebyshev_points(n, chebyshev_points);
for (int i=0; i < n; i++) {
for (int j=0; j < n; j++) {
//printf("XXX %d %d %f \n", i, j, phi(j, chebyshev_points[i]));
//printf("XXX %d %d %f \n", i, j, (*chebyshev_matrix)[i][j]);
(*chebyshev_matrix)[i][j] = phi(j, chebyshev_points[i]);
//printf("%f ", (*chebyshev_matrix)[i][j]);
}
//printf("\n");
}
//error("stop.");
}
void fill_transformation_matrix(int p, int p_ref, TransformationMatrix
transformation_matrix)
{
double chebyshev_points[N_chebyshev_max];
ChebyshevMatrix chebyshev_matrix;
int n = 3+2*(p_ref-1);
fill_chebyshev_points(n, chebyshev_points);
fill_chebyshev_matrix(n, &chebyshev_matrix);
for (int j=0; j < p+1; j++) {
// FIXME: don't compute the matrix all the time, e.g. move this out of
// the cycle and make sure the gaussian elimination doesn't overwrite
// the _mat.
Matrix *_mat = new DenseMatrix(n);
_mat->zero();
for (int _i=0; _i < n; _i++)
for (int _j=0; _j < n; _j++)
_mat->add(_i, _j, chebyshev_matrix[_i][_j]);
printf("chebyshev stuff:\n");
for (int _i=0; _i < n; _i++) {
for (int _j=0; _j < n; _j++) {
printf("%f ", chebyshev_matrix[_i][_j]);
}
printf("\n");
}
printf("----- END ---- \n");
double f[n];
for (int i=0; i < n; i++)
f[i] = lobatto_fn_tab_1d[j](chebyshev_points[i]);
printf("chebyshev_points\n");
for (int i=0; i < 5; i++)
printf("%f ", chebyshev_points[i]);
printf("\n");
printf("XXXXXX\n");
for (int i=0; i < n; i++)
printf("%f ", f[i]);
printf("\n");
solve_linear_system(_mat, f);
for (int i=0; i < n; i++)
transformation_matrix[i][j] = f[i];
}
for (int i=0; i < n; i++) {
for (int j=0; j < p+1; j++) {
printf("%f ", transformation_matrix[i][j]);
}
printf("\n");
}
error("stop.");
}
void transform_element_refined(int comp, double *y_prev, double *y_prev_ref, Element
*e, Element *e_ref_left, Element *e_ref_right, Mesh *mesh, Mesh
*mesh_ref)
{
printf("ELEMENT: %d %f %f\n", e->id, e->x1, e->x2);
double y_prev_loc[MAX_P+1];
double y_prev_loc_trans[N_chebyshev_max+1];
if (e->dof[comp][0] == -1)
y_prev_loc[0] = mesh->bc_left_dir_values[comp];
else
y_prev_loc[0] = y_prev[e->dof[comp][0]];
if (e->dof[comp][1] == -1)
y_prev_loc[1] = mesh->bc_right_dir_values[comp];
else
y_prev_loc[1] = y_prev[e->dof[comp][1]];
for (int i=2; i < e->p + 1; i++)
y_prev_loc[i] = y_prev[e->dof[comp][i]];
for (int i=0; i < e->p + 1; i++)
printf("y_prev_loc[%d] = %f\n", i, y_prev_loc[i]);
TransformationMatrix transformation_matrix;
fill_transformation_matrix(e->p, e_ref_left->p, transformation_matrix);
//fill_transformation_matrix();
//double TransformationMatrix *transformation_matrix =
// get_transformation_matrix(e_ref_left->p + 1);
for (int i=0; i < 3 + 2*(e_ref_left->p - 1); i++) {
y_prev_loc_trans[i] = 0.;
for (int j=0; j < e->p + 1; j++)
y_prev_loc_trans[i] += transformation_matrix[i][j] * y_prev_loc[j];
}
for (int i=0; i < 3 + 2*(e_ref_left->p - 1); i++)
printf("y_prev_loc_trans[%d] = %f\n", i, y_prev_loc_trans[i]);
printf("----------------------\n");
// copying computed coefficients into the elements e_ref_left and
// e_ref_right
if (e->dof[comp][0] != -1)
y_prev_ref[e_ref_left->dof[comp][0]] = y_prev_loc_trans[0];
y_prev_ref[e_ref_left->dof[comp][1]] = y_prev_loc_trans[1];
y_prev_ref[e_ref_right->dof[comp][0]] = y_prev_loc_trans[1];
if (e->dof[comp][1] != -1)
y_prev_ref[e_ref_right->dof[comp][1]] = y_prev_loc_trans[2];
if (e_ref_left->p != e_ref_right->p)
error("internal error in transform_element: the left and right elements must have the same order.");
int counter = 0;
for (int p=2; p < e_ref_left->p + 1; p++) {
y_prev_ref[e_ref_left->dof[comp][p]] = y_prev_loc_trans[3+counter];
counter++;
y_prev_ref[e_ref_right->dof[comp][p]] = y_prev_loc_trans[3+counter];
counter++;
}
}
void transform_element_unrefined(int comp, double *y_prev, double *y_prev_ref, Element
*e, Element *e_ref, Mesh *mesh, Mesh *mesh_ref)
{
for (int p=0; p < e->p + 1; p++) {
if (e->dof[comp][p] != -1)
y_prev_ref[e_ref->dof[comp][p]] = y_prev[e->dof[comp][p]];
}
for (int p=e->p+1; p < e_ref->p + 1; p++) {
y_prev_ref[e_ref->dof[comp][p]] = 0.;
}
}
/* This only works after the dofs are assigned in the reference (and coarse)
* solution. */
void transfer_solution(Mesh *mesh, Mesh *mesh_ref, double *y_prev, double *y_prev_ref)
{
Iterator *I = new Iterator(mesh);
Iterator *I_ref = new Iterator(mesh_ref);
Element *e, *e_ref, *e_ref_left, *e_ref_right;
for (int comp=0; comp < mesh->get_n_eq(); comp++) {
I->reset();
I_ref->reset();
while ((e = I->next_active_element()) != NULL) {
e_ref = I_ref->next_active_element();
if (e->level == e_ref->level)
transform_element_unrefined(comp, y_prev, y_prev_ref, e,
e_ref, mesh, mesh_ref);
else if (e->level + 1 == e_ref->level) {
e_ref_left = e_ref;
e_ref_right = I_ref->next_active_element();
transform_element_refined(comp, y_prev, y_prev_ref, e,
e_ref_left, e_ref_right, mesh, mesh_ref);
}
else
error("internal error in transfer_solution: element orders mismatch.");
}
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2017 Tmplt <[email protected]>
*
* 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 <system_error>
#include <cerrno>
#include <experimental/filesystem>
#include <pybind11/pybind11.h>
#include <pybind11/embed.h>
#include <pybind11/stl.h>
#include <array>
#include "components/searcher.hpp"
#include "components/menu.hpp"
#include "utils.hpp"
namespace fs = std::experimental::filesystem;
namespace py = pybind11;
namespace bookwyrm {
searcher::searcher(const item &wanted)
: wanted_(wanted)
{
#ifdef DEBUG
/* Bookwyrm must be run from build/. */
const auto source_path = fs::canonical(fs::path("../src/sources"));
#else
const std::array<fs::path, 2> paths = {"/etc/bookwyrm/sources",
"~/.config/bookwyrm/sources"};
#endif
/* Append source_path to Python's sys.path. */
auto sys_path = py::reinterpret_borrow<py::list>(py::module::import("sys").attr("path"));
sys_path.append(source_path.c_str());
/*
* Find all Python modules and populate the
* list of sources by loading them.
*
* The first occurance of a module will be imported,
* the latter ones will be ignored by Python. So we
* either need to prepend the paths to sys.path, or
* make sure that we don't clash with the many module
* names in Python.
*/
string module_file;
for (const fs::path &p : fs::directory_iterator(source_path)) {
module_file = p.filename();
auto file_ext_pos = module_file.rfind(".py");
if (file_ext_pos == string::npos) {
/*
* It's not a Python module.
* (or at least doesn't contain ".py"
*/
continue;
}
if (!utils::valid_file(p)) {
_logger->warn("can't load module '{}': not a regular file or unreadable"
"; ignoring...",
module_file);
continue;
}
module_file.resize(file_ext_pos);
try {
_logger->debug("loading module '{}'...", module_file);
sources_.emplace_back(py::module::import(module_file.c_str()));
} catch (const py::error_already_set &err) {
// This is printed on on termbox, we might want to save these
// until the program closes down.
_logger->warn("{}; ignoring...", err.what());
}
}
if (sources_.empty())
throw program_error("couldn't find any sources, terminating...");
}
searcher::~searcher()
{
/*
* Current behaviour is that the program cannot terminate unless
* all source threads has joined. We'll of course want do to this.
*
* It's not possible to end a std::thread in a smooth matter. We could
* instead have a control variable that the source scripts check every
* once in a while. When this is set upon quitting the curses UI, we'll
* have to let each script handle its own termination.
*/
py::gil_scoped_release nogil;
for (auto &t : threads_)
t.join();
}
searcher& searcher::async_search()
{
for (const auto &m : sources_) {
try {
threads_.emplace_back([m, this]() {
py::gil_scoped_acquire gil;
m.attr("find")(this->wanted_, this);
});
} catch (const py::error_already_set &err) {
_logger->error("module '{}' did something wrong ({}); ignoring...",
m.attr("__name__").cast<string>(), err.what());
continue;
}
}
/* Convenience; only to chain member functions. */
return *this;
}
void searcher::display_menu()
{
menu_.display();
}
void searcher::append_item(std::tuple<nonexacts_t, exacts_t> item_comps)
{
item item(item_comps);
/* if (!item.matches(wanted_)) */
/* return; */
std::lock_guard<std::mutex> guard(items_mutex_);
items_.push_back(item);
menu_.update();
}
/* ns bookwyrm */
}
<commit_msg>searcher: remove note about printing on tb window<commit_after>/*
* Copyright (C) 2017 Tmplt <[email protected]>
*
* 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 <system_error>
#include <cerrno>
#include <experimental/filesystem>
#include <pybind11/pybind11.h>
#include <pybind11/embed.h>
#include <pybind11/stl.h>
#include <array>
#include "components/searcher.hpp"
#include "components/menu.hpp"
#include "utils.hpp"
namespace fs = std::experimental::filesystem;
namespace py = pybind11;
namespace bookwyrm {
searcher::searcher(const item &wanted)
: wanted_(wanted)
{
#ifdef DEBUG
/* Bookwyrm must be run from build/. */
const auto source_path = fs::canonical(fs::path("../src/sources"));
#else
const std::array<fs::path, 2> paths = {"/etc/bookwyrm/sources",
"~/.config/bookwyrm/sources"};
#endif
/* Append source_path to Python's sys.path. */
auto sys_path = py::reinterpret_borrow<py::list>(py::module::import("sys").attr("path"));
sys_path.append(source_path.c_str());
/*
* Find all Python modules and populate the
* list of sources by loading them.
*
* The first occurance of a module will be imported,
* the latter ones will be ignored by Python. So we
* either need to prepend the paths to sys.path, or
* make sure that we don't clash with the many module
* names in Python.
*/
string module_file;
for (const fs::path &p : fs::directory_iterator(source_path)) {
module_file = p.filename();
auto file_ext_pos = module_file.rfind(".py");
if (file_ext_pos == string::npos) {
/*
* It's not a Python module.
* (or at least doesn't contain ".py"
*/
continue;
}
if (!utils::valid_file(p)) {
_logger->warn("can't load module '{}': not a regular file or unreadable"
"; ignoring...",
module_file);
continue;
}
module_file.resize(file_ext_pos);
try {
_logger->debug("loading module '{}'...", module_file);
sources_.emplace_back(py::module::import(module_file.c_str()));
} catch (const py::error_already_set &err) {
_logger->warn("{}; ignoring...", err.what());
}
}
if (sources_.empty())
throw program_error("couldn't find any sources, terminating...");
}
searcher::~searcher()
{
/*
* Current behaviour is that the program cannot terminate unless
* all source threads has joined. We'll of course want do to this.
*
* It's not possible to end a std::thread in a smooth matter. We could
* instead have a control variable that the source scripts check every
* once in a while. When this is set upon quitting the curses UI, we'll
* have to let each script handle its own termination.
*/
py::gil_scoped_release nogil;
for (auto &t : threads_)
t.join();
}
searcher& searcher::async_search()
{
for (const auto &m : sources_) {
try {
threads_.emplace_back([m, this]() {
py::gil_scoped_acquire gil;
m.attr("find")(this->wanted_, this);
});
} catch (const py::error_already_set &err) {
_logger->error("module '{}' did something wrong ({}); ignoring...",
m.attr("__name__").cast<string>(), err.what());
continue;
}
}
/* Convenience; only to chain member functions. */
return *this;
}
void searcher::display_menu()
{
menu_.display();
}
void searcher::append_item(std::tuple<nonexacts_t, exacts_t> item_comps)
{
item item(item_comps);
/* if (!item.matches(wanted_)) */
/* return; */
std::lock_guard<std::mutex> guard(items_mutex_);
items_.push_back(item);
menu_.update();
}
/* ns bookwyrm */
}
<|endoftext|> |
<commit_before>#include "libtorrent/udp_socket.hpp"
#include "libtorrent/connection_queue.hpp"
#include <stdlib.h>
#include <boost/bind.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/array.hpp>
#include <asio/read.hpp>
using namespace libtorrent;
udp_socket::udp_socket(asio::io_service& ios, udp_socket::callback_t const& c
, connection_queue& cc)
: m_callback(c)
, m_ipv4_sock(ios)
, m_ipv6_sock(ios)
, m_bind_port(0)
, m_socks5_sock(ios)
, m_connection_ticket(-1)
, m_cc(cc)
, m_resolver(ios)
, m_tunnel_packets(false)
{
}
void udp_socket::send(udp::endpoint const& ep, char const* p, int len)
{
if (m_tunnel_packets)
{
// send udp packets through SOCKS5 server
wrap(ep, p, len);
return;
}
asio::error_code ec;
if (ep.address().is_v4() && m_ipv4_sock.is_open())
m_ipv4_sock.send_to(asio::buffer(p, len), ep, 0, ec);
else
m_ipv6_sock.send_to(asio::buffer(p, len), ep, 0, ec);
}
void udp_socket::on_read(udp::socket* s, asio::error_code const& e, std::size_t bytes_transferred)
{
if (e) return;
if (!m_callback) return;
if (s == &m_ipv4_sock)
{
#ifndef BOOST_NO_EXCEPTIONS
try {
#endif
if (m_tunnel_packets && m_v4_ep == m_proxy_addr)
unwrap(m_v4_buf, bytes_transferred);
else
m_callback(m_v4_ep, m_v4_buf, bytes_transferred);
#ifndef BOOST_NO_EXCEPTIONS
} catch(std::exception&) {}
#endif
s->async_receive_from(asio::buffer(m_v4_buf, sizeof(m_v4_buf))
, m_v4_ep, boost::bind(&udp_socket::on_read, this, s, _1, _2));
}
else
{
#ifndef BOOST_NO_EXCEPTIONS
try {
#endif
if (m_tunnel_packets && m_v6_ep == m_proxy_addr)
unwrap(m_v6_buf, bytes_transferred);
else
m_callback(m_v6_ep, m_v6_buf, bytes_transferred);
#ifndef BOOST_NO_EXCEPTIONS
} catch(std::exception&) {}
#endif
s->async_receive_from(asio::buffer(m_v6_buf, sizeof(m_v6_buf))
, m_v6_ep, boost::bind(&udp_socket::on_read, this, s, _1, _2));
}
}
void udp_socket::wrap(udp::endpoint const& ep, char const* p, int len)
{
using namespace libtorrent::detail;
char header[20];
char* h = header;
write_uint16(0, h); // reserved
write_uint8(0, h); // fragment
write_uint8(ep.address().is_v4()?1:4, h); // atyp
write_address(ep.address(), h);
write_uint16(ep.port(), h);
boost::array<asio::const_buffer, 2> iovec;
iovec[0] = asio::const_buffer(header, h - header);
iovec[1] = asio::const_buffer(p, len);
asio::error_code ec;
if (m_proxy_addr.address().is_v4() && m_ipv4_sock.is_open())
m_ipv4_sock.send_to(iovec, m_proxy_addr, 0, ec);
else
m_ipv6_sock.send_to(iovec, m_proxy_addr, 0, ec);
}
// unwrap the UDP packet from the SOCKS5 header
void udp_socket::unwrap(char const* buf, int size)
{
using namespace libtorrent::detail;
// the minimum socks5 header size
if (size <= 10) return;
char const* p = buf;
p += 2; // reserved
int frag = read_uint8(p);
// fragmentation is not supported
if (frag != 0) return;
udp::endpoint sender;
int atyp = read_uint8(p);
if (atyp == 1)
{
// IPv4
sender.address(address_v4(read_uint32(p)));
sender.port(read_uint16(p));
}
else if (atyp == 4)
{
// IPv6
TORRENT_ASSERT(false && "not supported yet");
}
else
{
// domain name not supported
return;
}
m_callback(sender, p, size - (p - buf));
}
void udp_socket::close()
{
m_ipv4_sock.close();
m_ipv6_sock.close();
m_socks5_sock.close();
m_callback.clear();
if (m_connection_ticket >= 0)
{
m_cc.done(m_connection_ticket);
m_connection_ticket = -1;
}
}
void udp_socket::bind(int port)
{
asio::error_code ec;
if (m_ipv4_sock.is_open()) m_ipv4_sock.close();
if (m_ipv6_sock.is_open()) m_ipv6_sock.close();
m_ipv4_sock.open(udp::v4(), ec);
if (!ec)
{
m_ipv4_sock.bind(udp::endpoint(address_v4::any(), port), ec);
m_ipv4_sock.async_receive_from(asio::buffer(m_v4_buf, sizeof(m_v4_buf))
, m_v4_ep, boost::bind(&udp_socket::on_read, this, &m_ipv4_sock, _1, _2));
}
m_ipv6_sock.open(udp::v6(), ec);
if (!ec)
{
m_ipv6_sock.set_option(v6only(true), ec);
m_ipv6_sock.bind(udp::endpoint(address_v6::any(), port), ec);
m_ipv6_sock.async_receive_from(asio::buffer(m_v6_buf, sizeof(m_v6_buf))
, m_v6_ep, boost::bind(&udp_socket::on_read, this, &m_ipv6_sock, _1, _2));
}
m_bind_port = port;
}
void udp_socket::set_proxy_settings(proxy_settings const& ps)
{
m_socks5_sock.close();
m_tunnel_packets = false;
m_proxy_settings = ps;
if (ps.type == proxy_settings::socks5
|| ps.type == proxy_settings::socks5_pw)
{
// connect to socks5 server and open up the UDP tunnel
tcp::resolver::query q(ps.hostname
, boost::lexical_cast<std::string>(ps.port));
m_resolver.async_resolve(q, boost::bind(
&udp_socket::on_name_lookup, this, _1, _2));
}
}
void udp_socket::on_name_lookup(asio::error_code const& e, tcp::resolver::iterator i)
{
if (e) return;
m_proxy_addr.address(i->endpoint().address());
m_proxy_addr.port(i->endpoint().port());
m_cc.enqueue(boost::bind(&udp_socket::on_connect, this, _1)
, boost::bind(&udp_socket::on_timeout, this), seconds(10));
}
void udp_socket::on_timeout()
{
m_socks5_sock.close();
m_connection_ticket = -1;
}
void udp_socket::on_connect(int ticket)
{
m_connection_ticket = ticket;
asio::error_code ec;
m_socks5_sock.open(m_proxy_addr.address().is_v4()?tcp::v4():tcp::v6(), ec);
m_socks5_sock.async_connect(tcp::endpoint(m_proxy_addr.address(), m_proxy_addr.port())
, boost::bind(&udp_socket::on_connected, this, _1));
}
void udp_socket::on_connected(asio::error_code const& e)
{
m_cc.done(m_connection_ticket);
m_connection_ticket = -1;
if (e) return;
using namespace libtorrent::detail;
// send SOCKS5 authentication methods
char* p = &m_tmp_buf[0];
write_uint8(5, p); // SOCKS VERSION 5
if (m_proxy_settings.username.empty()
|| m_proxy_settings.type == proxy_settings::socks5)
{
write_uint8(1, p); // 1 authentication method (no auth)
write_uint8(0, p); // no authentication
}
else
{
write_uint8(2, p); // 2 authentication methods
write_uint8(0, p); // no authentication
write_uint8(2, p); // username/password
}
asio::async_write(m_socks5_sock, asio::buffer(m_tmp_buf, p - m_tmp_buf)
, boost::bind(&udp_socket::handshake1, this, _1));
}
void udp_socket::handshake1(asio::error_code const& e)
{
if (e) return;
asio::async_read(m_socks5_sock, asio::buffer(m_tmp_buf, 2)
, boost::bind(&udp_socket::handshake2, this, _1));
}
void udp_socket::handshake2(asio::error_code const& e)
{
if (e) return;
using namespace libtorrent::detail;
char* p = &m_tmp_buf[0];
int version = read_uint8(p);
int method = read_uint8(p);
if (version < 5) return;
if (method == 0)
{
socks_forward_udp();
}
else if (method == 2)
{
if (m_proxy_settings.username.empty())
{
m_socks5_sock.close();
return;
}
// start sub-negotiation
char* p = &m_tmp_buf[0];
write_uint8(1, p);
write_uint8(m_proxy_settings.username.size(), p);
write_string(m_proxy_settings.username, p);
write_uint8(m_proxy_settings.password.size(), p);
write_string(m_proxy_settings.password, p);
asio::async_write(m_socks5_sock, asio::buffer(m_tmp_buf, p - m_tmp_buf)
, boost::bind(&udp_socket::handshake3, this, _1));
}
else
{
m_socks5_sock.close();
return;
}
}
void udp_socket::handshake3(asio::error_code const& e)
{
if (e) return;
asio::async_read(m_socks5_sock, asio::buffer(m_tmp_buf, 2)
, boost::bind(&udp_socket::handshake4, this, _1));
}
void udp_socket::handshake4(asio::error_code const& e)
{
if (e) return;
using namespace libtorrent::detail;
char* p = &m_tmp_buf[0];
int version = read_uint8(p);
int status = read_uint8(p);
if (version != 1) return;
if (status != 0) return;
socks_forward_udp();
}
void udp_socket::socks_forward_udp()
{
using namespace libtorrent::detail;
// send SOCKS5 UDP command
char* p = &m_tmp_buf[0];
write_uint8(5, p); // SOCKS VERSION 5
write_uint8(3, p); // UDP ASSOCIATE command
write_uint8(0, p); // reserved
write_uint8(0, p); // ATYP IPv4
write_uint32(0, p); // IP any
write_uint16(m_bind_port, p);
asio::async_write(m_socks5_sock, asio::buffer(m_tmp_buf, p - m_tmp_buf)
, boost::bind(&udp_socket::connect1, this, _1));
}
void udp_socket::connect1(asio::error_code const& e)
{
if (e) return;
asio::async_read(m_socks5_sock, asio::buffer(m_tmp_buf, 10)
, boost::bind(&udp_socket::connect2, this, _1));
}
void udp_socket::connect2(asio::error_code const& e)
{
if (e) return;
using namespace libtorrent::detail;
char* p = &m_tmp_buf[0];
int version = read_uint8(p); // VERSION
int status = read_uint8(p); // STATUS
read_uint8(p); // RESERVED
int atyp = read_uint8(p); // address type
if (version != 5) return;
if (status != 0) return;
if (atyp == 1)
{
m_proxy_addr.address(address_v4(read_uint32(p)));
m_proxy_addr.port(read_uint16(p));
}
else
{
// in this case we need to read more data from the socket
TORRENT_ASSERT(false && "not implemented yet!");
}
m_tunnel_packets = true;
}
<commit_msg>made udp_socket not use exception<commit_after>#include "libtorrent/udp_socket.hpp"
#include "libtorrent/connection_queue.hpp"
#include <stdlib.h>
#include <boost/bind.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/array.hpp>
#include <asio/read.hpp>
using namespace libtorrent;
udp_socket::udp_socket(asio::io_service& ios, udp_socket::callback_t const& c
, connection_queue& cc)
: m_callback(c)
, m_ipv4_sock(ios)
, m_ipv6_sock(ios)
, m_bind_port(0)
, m_socks5_sock(ios)
, m_connection_ticket(-1)
, m_cc(cc)
, m_resolver(ios)
, m_tunnel_packets(false)
{
}
void udp_socket::send(udp::endpoint const& ep, char const* p, int len)
{
if (m_tunnel_packets)
{
// send udp packets through SOCKS5 server
wrap(ep, p, len);
return;
}
asio::error_code ec;
if (ep.address().is_v4() && m_ipv4_sock.is_open())
m_ipv4_sock.send_to(asio::buffer(p, len), ep, 0, ec);
else
m_ipv6_sock.send_to(asio::buffer(p, len), ep, 0, ec);
}
void udp_socket::on_read(udp::socket* s, asio::error_code const& e, std::size_t bytes_transferred)
{
if (e) return;
if (!m_callback) return;
if (s == &m_ipv4_sock)
{
#ifndef BOOST_NO_EXCEPTIONS
try {
#endif
if (m_tunnel_packets && m_v4_ep == m_proxy_addr)
unwrap(m_v4_buf, bytes_transferred);
else
m_callback(m_v4_ep, m_v4_buf, bytes_transferred);
#ifndef BOOST_NO_EXCEPTIONS
} catch(std::exception&) {}
#endif
s->async_receive_from(asio::buffer(m_v4_buf, sizeof(m_v4_buf))
, m_v4_ep, boost::bind(&udp_socket::on_read, this, s, _1, _2));
}
else
{
#ifndef BOOST_NO_EXCEPTIONS
try {
#endif
if (m_tunnel_packets && m_v6_ep == m_proxy_addr)
unwrap(m_v6_buf, bytes_transferred);
else
m_callback(m_v6_ep, m_v6_buf, bytes_transferred);
#ifndef BOOST_NO_EXCEPTIONS
} catch(std::exception&) {}
#endif
s->async_receive_from(asio::buffer(m_v6_buf, sizeof(m_v6_buf))
, m_v6_ep, boost::bind(&udp_socket::on_read, this, s, _1, _2));
}
}
void udp_socket::wrap(udp::endpoint const& ep, char const* p, int len)
{
using namespace libtorrent::detail;
char header[20];
char* h = header;
write_uint16(0, h); // reserved
write_uint8(0, h); // fragment
write_uint8(ep.address().is_v4()?1:4, h); // atyp
write_address(ep.address(), h);
write_uint16(ep.port(), h);
boost::array<asio::const_buffer, 2> iovec;
iovec[0] = asio::const_buffer(header, h - header);
iovec[1] = asio::const_buffer(p, len);
asio::error_code ec;
if (m_proxy_addr.address().is_v4() && m_ipv4_sock.is_open())
m_ipv4_sock.send_to(iovec, m_proxy_addr, 0, ec);
else
m_ipv6_sock.send_to(iovec, m_proxy_addr, 0, ec);
}
// unwrap the UDP packet from the SOCKS5 header
void udp_socket::unwrap(char const* buf, int size)
{
using namespace libtorrent::detail;
// the minimum socks5 header size
if (size <= 10) return;
char const* p = buf;
p += 2; // reserved
int frag = read_uint8(p);
// fragmentation is not supported
if (frag != 0) return;
udp::endpoint sender;
int atyp = read_uint8(p);
if (atyp == 1)
{
// IPv4
sender.address(address_v4(read_uint32(p)));
sender.port(read_uint16(p));
}
else if (atyp == 4)
{
// IPv6
TORRENT_ASSERT(false && "not supported yet");
}
else
{
// domain name not supported
return;
}
m_callback(sender, p, size - (p - buf));
}
void udp_socket::close()
{
asio::error_code ec;
m_ipv4_sock.close(ec);
m_ipv6_sock.close(ec);
m_socks5_sock.close(ec);
m_callback.clear();
if (m_connection_ticket >= 0)
{
m_cc.done(m_connection_ticket);
m_connection_ticket = -1;
}
}
void udp_socket::bind(int port)
{
asio::error_code ec;
if (m_ipv4_sock.is_open()) m_ipv4_sock.close(ec);
if (m_ipv6_sock.is_open()) m_ipv6_sock.close(ec);
m_ipv4_sock.open(udp::v4(), ec);
if (!ec)
{
m_ipv4_sock.bind(udp::endpoint(address_v4::any(), port), ec);
m_ipv4_sock.async_receive_from(asio::buffer(m_v4_buf, sizeof(m_v4_buf))
, m_v4_ep, boost::bind(&udp_socket::on_read, this, &m_ipv4_sock, _1, _2));
}
m_ipv6_sock.open(udp::v6(), ec);
if (!ec)
{
m_ipv6_sock.set_option(v6only(true), ec);
m_ipv6_sock.bind(udp::endpoint(address_v6::any(), port), ec);
m_ipv6_sock.async_receive_from(asio::buffer(m_v6_buf, sizeof(m_v6_buf))
, m_v6_ep, boost::bind(&udp_socket::on_read, this, &m_ipv6_sock, _1, _2));
}
m_bind_port = port;
}
void udp_socket::set_proxy_settings(proxy_settings const& ps)
{
asio::error_code ec;
m_socks5_sock.close(ec);
m_tunnel_packets = false;
m_proxy_settings = ps;
if (ps.type == proxy_settings::socks5
|| ps.type == proxy_settings::socks5_pw)
{
// connect to socks5 server and open up the UDP tunnel
tcp::resolver::query q(ps.hostname
, boost::lexical_cast<std::string>(ps.port));
m_resolver.async_resolve(q, boost::bind(
&udp_socket::on_name_lookup, this, _1, _2));
}
}
void udp_socket::on_name_lookup(asio::error_code const& e, tcp::resolver::iterator i)
{
if (e) return;
m_proxy_addr.address(i->endpoint().address());
m_proxy_addr.port(i->endpoint().port());
m_cc.enqueue(boost::bind(&udp_socket::on_connect, this, _1)
, boost::bind(&udp_socket::on_timeout, this), seconds(10));
}
void udp_socket::on_timeout()
{
asio::error_code ec;
m_socks5_sock.close(ec);
m_connection_ticket = -1;
}
void udp_socket::on_connect(int ticket)
{
m_connection_ticket = ticket;
asio::error_code ec;
m_socks5_sock.open(m_proxy_addr.address().is_v4()?tcp::v4():tcp::v6(), ec);
m_socks5_sock.async_connect(tcp::endpoint(m_proxy_addr.address(), m_proxy_addr.port())
, boost::bind(&udp_socket::on_connected, this, _1));
}
void udp_socket::on_connected(asio::error_code const& e)
{
m_cc.done(m_connection_ticket);
m_connection_ticket = -1;
if (e) return;
using namespace libtorrent::detail;
// send SOCKS5 authentication methods
char* p = &m_tmp_buf[0];
write_uint8(5, p); // SOCKS VERSION 5
if (m_proxy_settings.username.empty()
|| m_proxy_settings.type == proxy_settings::socks5)
{
write_uint8(1, p); // 1 authentication method (no auth)
write_uint8(0, p); // no authentication
}
else
{
write_uint8(2, p); // 2 authentication methods
write_uint8(0, p); // no authentication
write_uint8(2, p); // username/password
}
asio::async_write(m_socks5_sock, asio::buffer(m_tmp_buf, p - m_tmp_buf)
, boost::bind(&udp_socket::handshake1, this, _1));
}
void udp_socket::handshake1(asio::error_code const& e)
{
if (e) return;
asio::async_read(m_socks5_sock, asio::buffer(m_tmp_buf, 2)
, boost::bind(&udp_socket::handshake2, this, _1));
}
void udp_socket::handshake2(asio::error_code const& e)
{
if (e) return;
using namespace libtorrent::detail;
char* p = &m_tmp_buf[0];
int version = read_uint8(p);
int method = read_uint8(p);
if (version < 5) return;
if (method == 0)
{
socks_forward_udp();
}
else if (method == 2)
{
if (m_proxy_settings.username.empty())
{
asio::error_code ec;
m_socks5_sock.close(ec);
return;
}
// start sub-negotiation
char* p = &m_tmp_buf[0];
write_uint8(1, p);
write_uint8(m_proxy_settings.username.size(), p);
write_string(m_proxy_settings.username, p);
write_uint8(m_proxy_settings.password.size(), p);
write_string(m_proxy_settings.password, p);
asio::async_write(m_socks5_sock, asio::buffer(m_tmp_buf, p - m_tmp_buf)
, boost::bind(&udp_socket::handshake3, this, _1));
}
else
{
asio::error_code ec;
m_socks5_sock.close(ec);
return;
}
}
void udp_socket::handshake3(asio::error_code const& e)
{
if (e) return;
asio::async_read(m_socks5_sock, asio::buffer(m_tmp_buf, 2)
, boost::bind(&udp_socket::handshake4, this, _1));
}
void udp_socket::handshake4(asio::error_code const& e)
{
if (e) return;
using namespace libtorrent::detail;
char* p = &m_tmp_buf[0];
int version = read_uint8(p);
int status = read_uint8(p);
if (version != 1) return;
if (status != 0) return;
socks_forward_udp();
}
void udp_socket::socks_forward_udp()
{
using namespace libtorrent::detail;
// send SOCKS5 UDP command
char* p = &m_tmp_buf[0];
write_uint8(5, p); // SOCKS VERSION 5
write_uint8(3, p); // UDP ASSOCIATE command
write_uint8(0, p); // reserved
write_uint8(0, p); // ATYP IPv4
write_uint32(0, p); // IP any
write_uint16(m_bind_port, p);
asio::async_write(m_socks5_sock, asio::buffer(m_tmp_buf, p - m_tmp_buf)
, boost::bind(&udp_socket::connect1, this, _1));
}
void udp_socket::connect1(asio::error_code const& e)
{
if (e) return;
asio::async_read(m_socks5_sock, asio::buffer(m_tmp_buf, 10)
, boost::bind(&udp_socket::connect2, this, _1));
}
void udp_socket::connect2(asio::error_code const& e)
{
if (e) return;
using namespace libtorrent::detail;
char* p = &m_tmp_buf[0];
int version = read_uint8(p); // VERSION
int status = read_uint8(p); // STATUS
read_uint8(p); // RESERVED
int atyp = read_uint8(p); // address type
if (version != 5) return;
if (status != 0) return;
if (atyp == 1)
{
m_proxy_addr.address(address_v4(read_uint32(p)));
m_proxy_addr.port(read_uint16(p));
}
else
{
// in this case we need to read more data from the socket
TORRENT_ASSERT(false && "not implemented yet!");
}
m_tunnel_packets = true;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: XMLFootnoteSeparatorExport.cxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: hr $ $Date: 2007-06-27 15:32:49 $
*
* 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_xmloff.hxx"
#ifndef _XMLOFF_XMLFOOTNOTESEPARATOREXPORT_HXX
#include "XMLFootnoteSeparatorExport.hxx"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _XMLOFF_XMLEXP_HXX
#include <xmloff/xmlexp.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_XMLUCONV_HXX
#include <xmloff/xmluconv.hxx>
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#ifndef _XMLOFF_PROPERTYSETMAPPER_HXX
#include <xmloff/xmlprmap.hxx>
#endif
#ifndef _XMLOFF_PAGEMASTERSTYLEMAP_HXX
#include <xmloff/PageMasterStyleMap.hxx>
#endif
#ifndef _COM_SUN_STAR_TEXT_HORIZONTALADJUST_HPP_
#include <com/sun/star/text/HorizontalAdjust.hpp>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
using namespace ::com::sun::star;
using namespace ::xmloff::token;
using ::rtl::OUStringBuffer;
using ::std::vector;
XMLFootnoteSeparatorExport::XMLFootnoteSeparatorExport(SvXMLExport& rExp) :
rExport(rExp)
{
}
XMLFootnoteSeparatorExport::~XMLFootnoteSeparatorExport()
{
}
static const SvXMLEnumMapEntry aXML_HorizontalAdjust_Enum[] =
{
{ XML_LEFT, text::HorizontalAdjust_LEFT },
{ XML_CENTER, text::HorizontalAdjust_CENTER },
{ XML_RIGHT, text::HorizontalAdjust_RIGHT },
{ XML_TOKEN_INVALID, 0 }
};
void XMLFootnoteSeparatorExport::exportXML(
const vector<XMLPropertyState> * pProperties,
sal_uInt32
#ifdef DBG_UTIL
nIdx
#endif
,
const UniReference<XMLPropertySetMapper> & rMapper)
{
DBG_ASSERT(NULL != pProperties, "Need property states");
// intialize values
sal_Int16 eLineAdjust = text::HorizontalAdjust_LEFT;
sal_Int32 nLineColor = 0;
sal_Int32 nLineDistance = 0;
sal_Int8 nLineRelWidth = 0;
sal_Int32 nLineTextDistance = 0;
sal_Int16 nLineWeight = 0;
// find indices into property map and get values
sal_uInt32 nCount = pProperties->size();
for(sal_uInt32 i = 0; i < nCount; i++)
{
const XMLPropertyState& rState = (*pProperties)[i];
if( rState.mnIndex == -1 )
continue;
switch (rMapper->GetEntryContextId(rState.mnIndex))
{
case CTF_PM_FTN_LINE_ADJUST:
rState.maValue >>= eLineAdjust;
break;
case CTF_PM_FTN_LINE_COLOR:
rState.maValue >>= nLineColor;
break;
case CTF_PM_FTN_DISTANCE:
rState.maValue >>= nLineDistance;
break;
case CTF_PM_FTN_LINE_WIDTH:
rState.maValue >>= nLineRelWidth;
break;
case CTF_PM_FTN_LINE_DISTANCE:
rState.maValue >>= nLineTextDistance;
break;
case CTF_PM_FTN_LINE_WEIGTH:
DBG_ASSERT( i == nIdx,
"received wrong property state index" );
rState.maValue >>= nLineWeight;
break;
}
}
OUStringBuffer sBuf;
// weight/width
if (nLineWeight > 0)
{
rExport.GetMM100UnitConverter().convertMeasure(sBuf, nLineWeight);
rExport.AddAttribute(XML_NAMESPACE_STYLE, XML_WIDTH,
sBuf.makeStringAndClear());
}
// line text distance
if (nLineTextDistance > 0)
{
rExport.GetMM100UnitConverter().convertMeasure(sBuf,nLineTextDistance);
rExport.AddAttribute(XML_NAMESPACE_STYLE, XML_DISTANCE_BEFORE_SEP,
sBuf.makeStringAndClear());
}
// line distance
if (nLineDistance > 0)
{
rExport.GetMM100UnitConverter().convertMeasure(sBuf, nLineDistance);
rExport.AddAttribute(XML_NAMESPACE_STYLE, XML_DISTANCE_AFTER_SEP,
sBuf.makeStringAndClear());
}
// adjustment
if (rExport.GetMM100UnitConverter().convertEnum(
sBuf, eLineAdjust, aXML_HorizontalAdjust_Enum))
{
rExport.AddAttribute(XML_NAMESPACE_STYLE, XML_ADJUSTMENT,
sBuf.makeStringAndClear());
}
// relative line width
SvXMLUnitConverter::convertPercent(sBuf, nLineRelWidth);
rExport.AddAttribute(XML_NAMESPACE_STYLE, XML_REL_WIDTH,
sBuf.makeStringAndClear());
// color
rExport.GetMM100UnitConverter().convertColor(sBuf, nLineColor);
rExport.AddAttribute(XML_NAMESPACE_STYLE, XML_COLOR,
sBuf.makeStringAndClear());
SvXMLElementExport aElem(rExport, XML_NAMESPACE_STYLE,
XML_FOOTNOTE_SEP, sal_True, sal_True);
}
<commit_msg>INTEGRATION: CWS changefileheader (1.11.162); FILE MERGED 2008/04/01 16:09:54 thb 1.11.162.3: #i85898# Stripping all external header guards 2008/04/01 13:05:00 thb 1.11.162.2: #i85898# Stripping all external header guards 2008/03/31 16:28:21 rt 1.11.162.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: XMLFootnoteSeparatorExport.cxx,v $
* $Revision: 1.12 $
*
* 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_xmloff.hxx"
#include "XMLFootnoteSeparatorExport.hxx"
#include <tools/debug.hxx>
#include <xmloff/xmlexp.hxx>
#include "xmlnmspe.hxx"
#include <xmloff/xmluconv.hxx>
#include <xmloff/xmltoken.hxx>
#include <xmloff/xmlprmap.hxx>
#ifndef _XMLOFF_PAGEMASTERSTYLEMAP_HXX
#include <xmloff/PageMasterStyleMap.hxx>
#endif
#include <com/sun/star/text/HorizontalAdjust.hpp>
#include <rtl/ustrbuf.hxx>
using namespace ::com::sun::star;
using namespace ::xmloff::token;
using ::rtl::OUStringBuffer;
using ::std::vector;
XMLFootnoteSeparatorExport::XMLFootnoteSeparatorExport(SvXMLExport& rExp) :
rExport(rExp)
{
}
XMLFootnoteSeparatorExport::~XMLFootnoteSeparatorExport()
{
}
static const SvXMLEnumMapEntry aXML_HorizontalAdjust_Enum[] =
{
{ XML_LEFT, text::HorizontalAdjust_LEFT },
{ XML_CENTER, text::HorizontalAdjust_CENTER },
{ XML_RIGHT, text::HorizontalAdjust_RIGHT },
{ XML_TOKEN_INVALID, 0 }
};
void XMLFootnoteSeparatorExport::exportXML(
const vector<XMLPropertyState> * pProperties,
sal_uInt32
#ifdef DBG_UTIL
nIdx
#endif
,
const UniReference<XMLPropertySetMapper> & rMapper)
{
DBG_ASSERT(NULL != pProperties, "Need property states");
// intialize values
sal_Int16 eLineAdjust = text::HorizontalAdjust_LEFT;
sal_Int32 nLineColor = 0;
sal_Int32 nLineDistance = 0;
sal_Int8 nLineRelWidth = 0;
sal_Int32 nLineTextDistance = 0;
sal_Int16 nLineWeight = 0;
// find indices into property map and get values
sal_uInt32 nCount = pProperties->size();
for(sal_uInt32 i = 0; i < nCount; i++)
{
const XMLPropertyState& rState = (*pProperties)[i];
if( rState.mnIndex == -1 )
continue;
switch (rMapper->GetEntryContextId(rState.mnIndex))
{
case CTF_PM_FTN_LINE_ADJUST:
rState.maValue >>= eLineAdjust;
break;
case CTF_PM_FTN_LINE_COLOR:
rState.maValue >>= nLineColor;
break;
case CTF_PM_FTN_DISTANCE:
rState.maValue >>= nLineDistance;
break;
case CTF_PM_FTN_LINE_WIDTH:
rState.maValue >>= nLineRelWidth;
break;
case CTF_PM_FTN_LINE_DISTANCE:
rState.maValue >>= nLineTextDistance;
break;
case CTF_PM_FTN_LINE_WEIGTH:
DBG_ASSERT( i == nIdx,
"received wrong property state index" );
rState.maValue >>= nLineWeight;
break;
}
}
OUStringBuffer sBuf;
// weight/width
if (nLineWeight > 0)
{
rExport.GetMM100UnitConverter().convertMeasure(sBuf, nLineWeight);
rExport.AddAttribute(XML_NAMESPACE_STYLE, XML_WIDTH,
sBuf.makeStringAndClear());
}
// line text distance
if (nLineTextDistance > 0)
{
rExport.GetMM100UnitConverter().convertMeasure(sBuf,nLineTextDistance);
rExport.AddAttribute(XML_NAMESPACE_STYLE, XML_DISTANCE_BEFORE_SEP,
sBuf.makeStringAndClear());
}
// line distance
if (nLineDistance > 0)
{
rExport.GetMM100UnitConverter().convertMeasure(sBuf, nLineDistance);
rExport.AddAttribute(XML_NAMESPACE_STYLE, XML_DISTANCE_AFTER_SEP,
sBuf.makeStringAndClear());
}
// adjustment
if (rExport.GetMM100UnitConverter().convertEnum(
sBuf, eLineAdjust, aXML_HorizontalAdjust_Enum))
{
rExport.AddAttribute(XML_NAMESPACE_STYLE, XML_ADJUSTMENT,
sBuf.makeStringAndClear());
}
// relative line width
SvXMLUnitConverter::convertPercent(sBuf, nLineRelWidth);
rExport.AddAttribute(XML_NAMESPACE_STYLE, XML_REL_WIDTH,
sBuf.makeStringAndClear());
// color
rExport.GetMM100UnitConverter().convertColor(sBuf, nLineColor);
rExport.AddAttribute(XML_NAMESPACE_STYLE, XML_COLOR,
sBuf.makeStringAndClear());
SvXMLElementExport aElem(rExport, XML_NAMESPACE_STYLE,
XML_FOOTNOTE_SEP, sal_True, sal_True);
}
<|endoftext|> |
<commit_before>/*
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
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, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
/*
* TODO:
*
* handle timeouts
* notice if the socket was closed on us unexpectedly!
*
*/
#include "debugkit.h"
#include <QtGui>
#include <assert.h>
#include <fstream>
using namespace std;
// Constructor which creates the main window.
DebugKit::DebugKit() {
setWindowTitle(tr("openc2e's Debug Kit"));
tabwidget = new QTabWidget(this);
setCentralWidget(tabwidget);
infopage = new QWidget();
infolayout = new QGridLayout(infopage);
connectedstatus = new QLabel(infopage);
connectedstatus->setText(tr("Not connected"));
infolayout->addWidget(connectedstatus, 0, 0, 1, 3);
hostname_edit = new QLineEdit(infopage);
hostname_edit->setText("localhost");
infolayout->addWidget(hostname_edit, 1, 0);
port_edit = new QSpinBox(infopage);
port_edit->setMinimum(1); port_edit->setMaximum(65535);
port_edit->setValue(20001); // TODO: read from dotfile
infolayout->addWidget(port_edit, 1, 1);
connect_button = new QPushButton(tr("Connect"), infopage);
connect_button->connect(connect_button, SIGNAL(clicked()), this, SLOT(connectButton()));
infolayout->addWidget(connect_button, 1, 2);
QLabel *gamedatalabel = new QLabel(tr("Game data directories:"), this);
infolayout->addWidget(gamedatalabel, 2, 0, 1, 3);
gamedatadirs = new QListWidget(infopage);
infolayout->addWidget(gamedatadirs, 3, 0, 1, 3);
tabwidget->addTab(infopage, tr("Info"));
injectorpage = new QWidget();
injectorlayout = new QGridLayout(injectorpage);
agentlist = new QListWidget(injectorpage);
agentlist->setSortingEnabled(true);
agentlist->connect(agentlist, SIGNAL(currentRowChanged(int)), this, SLOT(selectedAgentChanged(int)));
injectorlayout->addWidget(agentlist, 0, 0);
inject_button = new QPushButton(tr("Inject"), injectorpage);
inject_button->setDisabled(true);
inject_button->connect(inject_button, SIGNAL(clicked()), this, SLOT(injectButton()));
injectorlayout->addWidget(inject_button, 1, 0);
tabwidget->addTab(injectorpage, tr("Agent Injector"));
debugpage = new QWidget();
tabwidget->addTab(debugpage, tr("Debug"));
resize(600, 400);
socket = new QTcpSocket();
socket->connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError()));
setConnectedStatus(false);
tryConnect();
}
DebugKit::~DebugKit() {
delete socket;
}
void DebugKit::connectButton() {
if (connect_button->text() == tr("Disconnect")) {
setConnectedStatus(false);
connectedstatus->setText(tr("Not connected"));
} else {
tryConnect();
}
}
void DebugKit::setConnectedStatus(bool s) {
tabwidget->setTabEnabled(1, s);
tabwidget->setTabEnabled(2, s);
hostname_edit->setDisabled(s);
port_edit->setDisabled(s);
gamedatadirs->setDisabled(!s);
if (s) {
connect_button->setText(tr("Disconnect"));
} else {
gamedatadirs->clear();
connect_button->setText(tr("Connect"));
}
}
void DebugKit::setBusyStatus(bool s) {
connect_button->setDisabled(s);
if (agentlist->currentRow() != -1)
inject_button->setDisabled(s);
}
void DebugKit::tryConnect() {
assert(socket->state() == QAbstractSocket::UnconnectedState);
setBusyStatus(true);
socket->connect(socket, SIGNAL(connected()), this, SLOT(connectAttempt()));
socket->connectToHost(hostname_edit->text(), port_edit->value());
}
void DebugKit::socketError() {
socket->disconnect(socket, SIGNAL(connected()), 0, 0);
//if (socket->error() == QAbstractSocket::RemoteHostClosedError)
// return;
setBusyStatus(false);
setConnectedStatus(false);
QString err = tr("Not connected") + " (" + socket->errorString() + ")";
if (socket->error() == QAbstractSocket::ConnectionRefusedError)
err = err + " - " + tr("Is openc2e running?");
connectedstatus->setText(err);
}
void DebugKit::connectAttempt() {
socket->disconnect(socket, SIGNAL(connected()), this, SLOT(connectAttempt()));
setBusyStatus(false);
// obtain the data we need: outs "hi\n", outs gnam, outs "\n", outs oc2e ddir
socket->write("outs \"hi\\n\"\nouts gnam\nouts \"\\n\"\nouts oc2e ddir\nrscr\n");
socket->waitForReadyRead(200); // wait for 200ms at most
QString result = socket->readLine().data();
if (result == "hi\n") {
setConnectedStatus(true);
QString gnam = QString(socket->readLine().data()).trimmed();
connectedstatus->setText(tr("Connected to game") + " \"" + gnam + "\"");
QString l = socket->readLine().data();
while (l.size() > 0) {
gamedatadirs->addItem(l.trimmed());
l = socket->readLine().data();
}
readAgents();
} else {
setConnectedStatus(false);
connectedstatus->setText(tr("Not connected") + " (" + tr("bad handshake \"") + result + "\"" + tr("; are you sure openc2e is running?") + ")");
}
socket->close();
}
void DebugKit::selectedAgentChanged(int i) {
if (i != -1)
inject_button->setDisabled(false);
}
#include <iostream>
#include <string>
#include "../../endianlove.h"
#include "../../streamutils.h"
std::string readpascalstring(std::istream &s) {
uint16 size;
uint8 a; s.read((char *)&a, 1);
if (a == 255)
size = read16(s);
else
size = a;
char x[size];
s.read((char *)&x, size);
return std::string(x, size);
}
struct c1cobfile {
uint16 no_objects;
uint32 expire_month;
uint32 expire_day;
uint32 expire_year;
std::vector<std::string> scripts;
std::vector<std::string> imports;
uint16 no_objects_used;
std::string name;
c1cobfile(std::ifstream &s) {
s >> std::noskipws;
uint16 version = read16(s);
// TODO: mph
if (version != 1) {
//QMessageBox::warning(this, tr("Failed to open"), tr("Version %1 is not supported").arg((int)version));
return;
}
no_objects = read16(s);
expire_month = read32(s);
expire_day = read32(s);
expire_year = read32(s);
uint16 noscripts = read16(s);
uint16 noimports = read16(s);
no_objects_used = read16(s);
uint16 reserved_zero = read16(s);
assert(reserved_zero == 0);
for (unsigned int i = 0; i < noscripts; i++)
scripts.push_back(readpascalstring(s));
for (unsigned int i = 0; i < noimports; i++)
imports.push_back(readpascalstring(s));
uint32 imagewidth = read32(s);
uint32 imageheight = read32(s);
uint16 secondimagewidth = read16(s);
assert(imagewidth == secondimagewidth);
char imagedata[imagewidth * imageheight];
s.read((char *)&imagedata, imagewidth * imageheight);
name = readpascalstring(s);
}
};
void DebugKit::readAgents() {
inject_button->setDisabled(true);
agentlist->clear();
for (unsigned int i = 0; i < gamedatadirs->count(); i++) {
QString dirname = gamedatadirs->item(i)->text();
QDir dir(dirname);
if (!dir.exists()) {
QMessageBox msgBox(QMessageBox::Warning, tr("Directory missing"), dirname, 0, this);
continue;
}
QStringList filters;
filters << "*.cob";
dir.setNameFilters(filters);
QStringList cobfiles = dir.entryList();
for (unsigned int j = 0; j < cobfiles.size(); j++) {
QString file = dirname + '/' + cobfiles[j];
std::ifstream cobstream(file.toAscii(), std::ios::binary);
if (!cobstream.fail()) {
c1cobfile cobfile(cobstream);
QListWidgetItem *newItem = new QListWidgetItem(cobfile.name.c_str(), agentlist);
newItem->setToolTip(file);
}
}
}
}
void DebugKit::injectButton() {
QString filename = agentlist->currentItem()->toolTip();
std::ifstream cobstream(filename.toAscii(), std::ios::binary);
if (cobstream.fail()) {
QMessageBox::warning(this, tr("Failed to open"), filename);
return;
}
c1cobfile cobfile(cobstream);
std::string idata;
// this works around a stupid qt issue where it drops the socket if there's no lines returned
// TODO: surely this is just fuzzie being dumb
idata += "outs \"\\n\"\n";
for (unsigned int i = 0; i < cobfile.scripts.size(); i++) {
idata += cobfile.scripts[i] + "\n";
}
for (unsigned int i = 0; i < cobfile.imports.size(); i++) {
idata += "iscr," + cobfile.imports[i] + "\n";
}
idata += "rscr\n";
injectdata = idata.c_str();
setBusyStatus(true);
socket->connect(socket, SIGNAL(connected()), this, SLOT(injectAttempt()));
socket->connectToHost(hostname_edit->text(), port_edit->value());
}
void DebugKit::injectAttempt() {
socket->disconnect(socket, SIGNAL(connected()), this, SLOT(injectAttempt()));
setBusyStatus(false);
socket->write(injectdata.toAscii());
socket->waitForReadyRead(200); // wait for 200ms at most
QString result = QString(socket->readAll().data()).trimmed();
std::cout << (char *)result.toAscii().data() << std::endl;
socket->close();
if (result.size())
QMessageBox::warning(this, tr("Injection returned data (error?)"), result);
}
<commit_msg>Replace variable-size arrays with boost vectors in debugkit to fix compilation on windows (sigh)<commit_after>/*
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
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, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
/*
* TODO:
*
* handle timeouts
* notice if the socket was closed on us unexpectedly!
*
*/
#include "debugkit.h"
#include <QtGui>
#include <assert.h>
#include <fstream>
#include <boost/scoped_array.hpp>
using namespace std;
// Constructor which creates the main window.
DebugKit::DebugKit() {
setWindowTitle(tr("openc2e's Debug Kit"));
tabwidget = new QTabWidget(this);
setCentralWidget(tabwidget);
infopage = new QWidget();
infolayout = new QGridLayout(infopage);
connectedstatus = new QLabel(infopage);
connectedstatus->setText(tr("Not connected"));
infolayout->addWidget(connectedstatus, 0, 0, 1, 3);
hostname_edit = new QLineEdit(infopage);
hostname_edit->setText("localhost");
infolayout->addWidget(hostname_edit, 1, 0);
port_edit = new QSpinBox(infopage);
port_edit->setMinimum(1); port_edit->setMaximum(65535);
port_edit->setValue(20001); // TODO: read from dotfile
infolayout->addWidget(port_edit, 1, 1);
connect_button = new QPushButton(tr("Connect"), infopage);
connect_button->connect(connect_button, SIGNAL(clicked()), this, SLOT(connectButton()));
infolayout->addWidget(connect_button, 1, 2);
QLabel *gamedatalabel = new QLabel(tr("Game data directories:"), this);
infolayout->addWidget(gamedatalabel, 2, 0, 1, 3);
gamedatadirs = new QListWidget(infopage);
infolayout->addWidget(gamedatadirs, 3, 0, 1, 3);
tabwidget->addTab(infopage, tr("Info"));
injectorpage = new QWidget();
injectorlayout = new QGridLayout(injectorpage);
agentlist = new QListWidget(injectorpage);
agentlist->setSortingEnabled(true);
agentlist->connect(agentlist, SIGNAL(currentRowChanged(int)), this, SLOT(selectedAgentChanged(int)));
injectorlayout->addWidget(agentlist, 0, 0);
inject_button = new QPushButton(tr("Inject"), injectorpage);
inject_button->setDisabled(true);
inject_button->connect(inject_button, SIGNAL(clicked()), this, SLOT(injectButton()));
injectorlayout->addWidget(inject_button, 1, 0);
tabwidget->addTab(injectorpage, tr("Agent Injector"));
debugpage = new QWidget();
tabwidget->addTab(debugpage, tr("Debug"));
resize(600, 400);
socket = new QTcpSocket();
socket->connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError()));
setConnectedStatus(false);
tryConnect();
}
DebugKit::~DebugKit() {
delete socket;
}
void DebugKit::connectButton() {
if (connect_button->text() == tr("Disconnect")) {
setConnectedStatus(false);
connectedstatus->setText(tr("Not connected"));
} else {
tryConnect();
}
}
void DebugKit::setConnectedStatus(bool s) {
tabwidget->setTabEnabled(1, s);
tabwidget->setTabEnabled(2, s);
hostname_edit->setDisabled(s);
port_edit->setDisabled(s);
gamedatadirs->setDisabled(!s);
if (s) {
connect_button->setText(tr("Disconnect"));
} else {
gamedatadirs->clear();
connect_button->setText(tr("Connect"));
}
}
void DebugKit::setBusyStatus(bool s) {
connect_button->setDisabled(s);
if (agentlist->currentRow() != -1)
inject_button->setDisabled(s);
}
void DebugKit::tryConnect() {
assert(socket->state() == QAbstractSocket::UnconnectedState);
setBusyStatus(true);
socket->connect(socket, SIGNAL(connected()), this, SLOT(connectAttempt()));
socket->connectToHost(hostname_edit->text(), port_edit->value());
}
void DebugKit::socketError() {
socket->disconnect(socket, SIGNAL(connected()), 0, 0);
//if (socket->error() == QAbstractSocket::RemoteHostClosedError)
// return;
setBusyStatus(false);
setConnectedStatus(false);
QString err = tr("Not connected") + " (" + socket->errorString() + ")";
if (socket->error() == QAbstractSocket::ConnectionRefusedError)
err = err + " - " + tr("Is openc2e running?");
connectedstatus->setText(err);
}
void DebugKit::connectAttempt() {
socket->disconnect(socket, SIGNAL(connected()), this, SLOT(connectAttempt()));
setBusyStatus(false);
// obtain the data we need: outs "hi\n", outs gnam, outs "\n", outs oc2e ddir
socket->write("outs \"hi\\n\"\nouts gnam\nouts \"\\n\"\nouts oc2e ddir\nrscr\n");
socket->waitForReadyRead(200); // wait for 200ms at most
QString result = socket->readLine().data();
if (result == "hi\n") {
setConnectedStatus(true);
QString gnam = QString(socket->readLine().data()).trimmed();
connectedstatus->setText(tr("Connected to game") + " \"" + gnam + "\"");
QString l = socket->readLine().data();
while (l.size() > 0) {
gamedatadirs->addItem(l.trimmed());
l = socket->readLine().data();
}
readAgents();
} else {
setConnectedStatus(false);
connectedstatus->setText(tr("Not connected") + " (" + tr("bad handshake \"") + result + "\"" + tr("; are you sure openc2e is running?") + ")");
}
socket->close();
}
void DebugKit::selectedAgentChanged(int i) {
if (i != -1)
inject_button->setDisabled(false);
}
#include <iostream>
#include <string>
#include "../../endianlove.h"
#include "../../streamutils.h"
std::string readpascalstring(std::istream &s) {
uint16 size;
uint8 a; s.read((char *)&a, 1);
if (a == 255)
size = read16(s);
else
size = a;
boost::scoped_array<char> x(new char[size]);
//char x[size];
s.read(x.get(), size);
return std::string(x.get(), size);
}
struct c1cobfile {
uint16 no_objects;
uint32 expire_month;
uint32 expire_day;
uint32 expire_year;
std::vector<std::string> scripts;
std::vector<std::string> imports;
uint16 no_objects_used;
std::string name;
c1cobfile(std::ifstream &s) {
s >> std::noskipws;
uint16 version = read16(s);
// TODO: mph
if (version != 1) {
//QMessageBox::warning(this, tr("Failed to open"), tr("Version %1 is not supported").arg((int)version));
return;
}
no_objects = read16(s);
expire_month = read32(s);
expire_day = read32(s);
expire_year = read32(s);
uint16 noscripts = read16(s);
uint16 noimports = read16(s);
no_objects_used = read16(s);
uint16 reserved_zero = read16(s);
assert(reserved_zero == 0);
for (unsigned int i = 0; i < noscripts; i++)
scripts.push_back(readpascalstring(s));
for (unsigned int i = 0; i < noimports; i++)
imports.push_back(readpascalstring(s));
uint32 imagewidth = read32(s);
uint32 imageheight = read32(s);
uint16 secondimagewidth = read16(s);
assert(imagewidth == secondimagewidth);
boost::scoped_array<char> imagedata(new char[imagewidth * imageheight]);
s.read(imagedata.get(), imagewidth * imageheight);
name = readpascalstring(s);
}
};
void DebugKit::readAgents() {
inject_button->setDisabled(true);
agentlist->clear();
for (unsigned int i = 0; i < gamedatadirs->count(); i++) {
QString dirname = gamedatadirs->item(i)->text();
QDir dir(dirname);
if (!dir.exists()) {
QMessageBox msgBox(QMessageBox::Warning, tr("Directory missing"), dirname, 0, this);
continue;
}
QStringList filters;
filters << "*.cob";
dir.setNameFilters(filters);
QStringList cobfiles = dir.entryList();
for (unsigned int j = 0; j < cobfiles.size(); j++) {
QString file = dirname + '/' + cobfiles[j];
std::ifstream cobstream(file.toAscii(), std::ios::binary);
if (!cobstream.fail()) {
c1cobfile cobfile(cobstream);
QListWidgetItem *newItem = new QListWidgetItem(cobfile.name.c_str(), agentlist);
newItem->setToolTip(file);
}
}
}
}
void DebugKit::injectButton() {
QString filename = agentlist->currentItem()->toolTip();
std::ifstream cobstream(filename.toAscii(), std::ios::binary);
if (cobstream.fail()) {
QMessageBox::warning(this, tr("Failed to open"), filename);
return;
}
c1cobfile cobfile(cobstream);
std::string idata;
// this works around a stupid qt issue where it drops the socket if there's no lines returned
// TODO: surely this is just fuzzie being dumb
idata += "outs \"\\n\"\n";
for (unsigned int i = 0; i < cobfile.scripts.size(); i++) {
idata += cobfile.scripts[i] + "\n";
}
for (unsigned int i = 0; i < cobfile.imports.size(); i++) {
idata += "iscr," + cobfile.imports[i] + "\n";
}
idata += "rscr\n";
injectdata = idata.c_str();
setBusyStatus(true);
socket->connect(socket, SIGNAL(connected()), this, SLOT(injectAttempt()));
socket->connectToHost(hostname_edit->text(), port_edit->value());
}
void DebugKit::injectAttempt() {
socket->disconnect(socket, SIGNAL(connected()), this, SLOT(injectAttempt()));
setBusyStatus(false);
socket->write(injectdata.toAscii());
socket->waitForReadyRead(200); // wait for 200ms at most
QString result = QString(socket->readAll().data()).trimmed();
std::cout << (char *)result.toAscii().data() << std::endl;
socket->close();
if (result.size())
QMessageBox::warning(this, tr("Injection returned data (error?)"), result);
}
<|endoftext|> |
<commit_before>#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/time.h>
#include "runner.hh"
#include <iostream>
using namespace v8;
using namespace std;
SpawnRunner::SpawnRunner(JsString& file, JsArray& args, JsObject& options)
: file_(file),
args_(args),
options_(options),
timeout_(0),
status_(0),
child_pid_(-1),
has_timedout_(false) {
JsValue timeout_opt = options->Get(Symbol("timeout"));
if(timeout_opt->IsNumber()) {
timeout_ = static_cast<int64_t>(timeout_opt->IntegerValue());
}
}
JsObject SpawnRunner::Run() {
pid_t pid = fork();
if(pid == 0) {
RunChild();
_exit(127);
} else {
int stat = RunParent(pid);
return BuildResultObject(stat);
}
return BuildResultObject(0);
}
int SpawnRunner::RunChild() {
if(PipeStdio()) { return 1; }
if(SetEnvironment()) { return 1; }
if(ChangeDirectory()) { return 1; }
String::Utf8Value file(file_);
char** args = BuildArgs();
execvp(*file, args);
fprintf(stderr, "errno: %d\n", errno);
perror(*file);
return 1;
}
int SpawnRunner::RunParent(pid_t pid) {
child_pid_ = pid;
int stat;
if(0 < timeout_) {
struct timeval tv;
gettimeofday(&tv, NULL);
suseconds_t timeout = timeout_ * 1000;
suseconds_t start = tv.tv_usec;
while(waitpid(pid, &stat, WNOHANG) == 0) {
usleep(TIMEOUT_INTERVAL);
gettimeofday(&tv, NULL);
if(timeout < tv.tv_usec - start) {
kill(pid, SIGTERM);
has_timedout_ = true;
}
}
} else {
waitpid(pid, &stat, 0);
}
return stat;
}
JsObject SpawnRunner::BuildResultObject(int stat) {
Local<Object> result = Object::New();
if(WIFEXITED(stat)) {
status_ = WEXITSTATUS(stat);
result->Set(Symbol("signal"), Null());
} else if(WIFSIGNALED(stat)) {
int sig = WTERMSIG(stat);
JsString signame = String::New(node::signo_string(sig));
result->Set(Symbol("signal"), signame);
status_ = 128 + sig;
}
result->Set(Symbol("status"), Number::New(status_));
result->Set(Symbol("pid"), Number::New(child_pid_));
result->Set(Symbol("file"), file_);
result->Set(Symbol("args"), args_);
if(has_timedout_) {
result->Set(Symbol("_hasTimedOut"), Boolean::New(has_timedout_));
}
return result;
}
char** SpawnRunner::BuildArgs() {
int len = args_->Length();
char** args = new char*[len + 1];
for(int i = 0; i < len; i++) {
String::Utf8Value value(args_->Get(i));
char* str = new char[value.length() + 1];
strcpy(str, *value);
args[i] = str;
}
// add sentinel
args[len] = NULL;
return args;
}
int SpawnRunner::PipeStdio() {
JsArray stdio = options_->Get(Symbol("stdio")).As<Array>();
const char* files[3] = {"/dev/stdin", "/dev/stdout", "/dev/stderr"};
const char* names[3] = {"stdin pipe", "stdout pipe", "stderr pipe"};
int modes[3] = {O_RDONLY, O_WRONLY, O_WRONLY};
for(int i = 0; i < 3; i++) {
JsValue pipe = stdio->Get(Number::New(i));
int fd;
if(pipe->IsNumber()) {
fd = pipe->IntegerValue();
} else {
fd = open(files[i], modes[i]);
if(fd == -1) {
fprintf(stderr, "errno: %d\n", errno);
perror(files[i]);
return 1;
}
}
if(dup2(fd, i) == -1) {
fprintf(stderr, "errno: %d\n", errno);
perror(names[i]);
return 1;
}
}
return 0;
}
int SpawnRunner::SetEnvironment() {
JsArray envPairs = options_->Get(Symbol("envPairs")).As<Array>();
int len = envPairs->Length();
for(int i = 0; i < len; i++) {
String::Utf8Value value(envPairs->Get(i));
putenv(*value);
}
return 0;
}
int SpawnRunner::ChangeDirectory() {
JsValue cwd = options_->Get(Symbol("cwd"));
if(cwd->IsString()) {
String::Utf8Value cwd_value(cwd);
int err = chdir(*cwd_value);
if(err) {
fprintf(stderr, "errno: %d\n", errno);
perror(*cwd_value);
return err;
}
}
return 0;
}
<commit_msg>Fix spawn timeout<commit_after>#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/time.h>
#include "runner.hh"
#include <iostream>
using namespace v8;
using namespace std;
const double usec = 1.0 / 1000 / 1000;
double tv_to_seconds(struct timeval* tv) {
return tv->tv_sec + tv->tv_usec * usec;
}
SpawnRunner::SpawnRunner(JsString& file, JsArray& args, JsObject& options)
: file_(file),
args_(args),
options_(options),
timeout_(0),
status_(0),
child_pid_(-1),
has_timedout_(false) {
JsValue timeout_opt = options->Get(Symbol("timeout"));
if(timeout_opt->IsNumber()) {
timeout_ = static_cast<int64_t>(timeout_opt->IntegerValue());
}
}
JsObject SpawnRunner::Run() {
pid_t pid = fork();
if(pid == 0) {
RunChild();
_exit(127);
} else {
int stat = RunParent(pid);
return BuildResultObject(stat);
}
return BuildResultObject(0);
}
int SpawnRunner::RunChild() {
if(PipeStdio()) { return 1; }
if(SetEnvironment()) { return 1; }
if(ChangeDirectory()) { return 1; }
String::Utf8Value file(file_);
char** args = BuildArgs();
execvp(*file, args);
fprintf(stderr, "errno: %d\n", errno);
perror(*file);
return 1;
}
int SpawnRunner::RunParent(pid_t pid) {
child_pid_ = pid;
int stat;
if(0 < timeout_) {
struct timeval tv;
gettimeofday(&tv, NULL);
double timeout = timeout_ / 1000.0;
double start = tv_to_seconds(&tv);
while(waitpid(pid, &stat, WNOHANG) == 0) {
usleep(TIMEOUT_INTERVAL);
gettimeofday(&tv, NULL);
if(timeout < tv_to_seconds(&tv) - start) {
kill(pid, SIGTERM);
has_timedout_ = true;
}
}
} else {
waitpid(pid, &stat, 0);
}
return stat;
}
JsObject SpawnRunner::BuildResultObject(int stat) {
Local<Object> result = Object::New();
if(WIFEXITED(stat)) {
status_ = WEXITSTATUS(stat);
result->Set(Symbol("signal"), Null());
} else if(WIFSIGNALED(stat)) {
int sig = WTERMSIG(stat);
JsString signame = String::New(node::signo_string(sig));
result->Set(Symbol("signal"), signame);
status_ = 128 + sig;
}
result->Set(Symbol("status"), Number::New(status_));
result->Set(Symbol("pid"), Number::New(child_pid_));
result->Set(Symbol("file"), file_);
result->Set(Symbol("args"), args_);
if(has_timedout_) {
result->Set(Symbol("_hasTimedOut"), Boolean::New(has_timedout_));
}
return result;
}
char** SpawnRunner::BuildArgs() {
int len = args_->Length();
char** args = new char*[len + 1];
for(int i = 0; i < len; i++) {
String::Utf8Value value(args_->Get(i));
char* str = new char[value.length() + 1];
strcpy(str, *value);
args[i] = str;
}
// add sentinel
args[len] = NULL;
return args;
}
int SpawnRunner::PipeStdio() {
JsArray stdio = options_->Get(Symbol("stdio")).As<Array>();
const char* files[3] = {"/dev/stdin", "/dev/stdout", "/dev/stderr"};
const char* names[3] = {"stdin pipe", "stdout pipe", "stderr pipe"};
int modes[3] = {O_RDONLY, O_WRONLY, O_WRONLY};
for(int i = 0; i < 3; i++) {
JsValue pipe = stdio->Get(Number::New(i));
int fd;
if(pipe->IsNumber()) {
fd = pipe->IntegerValue();
} else {
fd = open(files[i], modes[i]);
if(fd == -1) {
fprintf(stderr, "errno: %d\n", errno);
perror(files[i]);
return 1;
}
}
if(dup2(fd, i) == -1) {
fprintf(stderr, "errno: %d\n", errno);
perror(names[i]);
return 1;
}
}
return 0;
}
int SpawnRunner::SetEnvironment() {
JsArray envPairs = options_->Get(Symbol("envPairs")).As<Array>();
int len = envPairs->Length();
for(int i = 0; i < len; i++) {
String::Utf8Value value(envPairs->Get(i));
putenv(*value);
}
return 0;
}
int SpawnRunner::ChangeDirectory() {
JsValue cwd = options_->Get(Symbol("cwd"));
if(cwd->IsString()) {
String::Utf8Value cwd_value(cwd);
int err = chdir(*cwd_value);
if(err) {
fprintf(stderr, "errno: %d\n", errno);
perror(*cwd_value);
return err;
}
}
return 0;
}
<|endoftext|> |
<commit_before>/////////////////////////////////////////////////////////////////
/*
* Amira Reader for the nrrd (Nearly Raw Raster Data) format:
* http://teem.sourceforge.net/nrrd/format.html
* Currently only supports 3d single channel data
* Copyright 2009 Gregory Jefferis. All rights reserved.
* License GPL >=3
* Certain portions of this code were copied/amended from the CMTK
* library: http://www.nitrc.org/projects/cmtk/
*/
/////////////////////////////////////////////////////////////////
#include <NrrdIO/NrrdIOAPI.h>
#include <hxfield/HxUniformScalarField3.h>
#include <Amira/HxMessage.h>
#include <teem/nrrd.h>
NRRDIO_API
int NrrdReader(const char* filename)
{
Nrrd *nrrd = nrrdNew();
if ( nrrdLoad( nrrd, filename, NULL ) )
throw biffGetDone(NRRD);
if ( nrrd->dim > 4 )
{
theMsg->printf("ERROR: for now, nrrd input can only handle data with dimension 4 or less.");
return 0;
} else if ( nrrd->spaceDim > 3 ){
theMsg->printf("ERROR: for now, nrrd input can only handle data with space dimension 3 or less.");
return 0;
}
const int dims[4] =
{
(nrrd->dim > 0) ? nrrd->axis[0].size : 1,
(nrrd->dim > 1) ? nrrd->axis[1].size : 1,
(nrrd->dim > 2) ? nrrd->axis[2].size : 1,
(nrrd->dim > 3) ? nrrd->axis[3].size : 1
};
McPrimType pType = NULL;
switch ( nrrd->type )
{
case nrrdTypeUChar: pType = MC_UINT8; break;
case nrrdTypeChar: pType = MC_INT8; break;
case nrrdTypeUShort: pType = MC_UINT16;break;
case nrrdTypeShort: pType = MC_INT16; break;
case nrrdTypeInt: pType = MC_INT32; break;
case nrrdTypeFloat: pType = MC_FLOAT; break;
case nrrdTypeDouble: pType = MC_DOUBLE;break;
default: break;
}
if(pType == NULL)
{
theMsg->printf("ERROR: unknown nrrd input type.");
return 0;
}
HxUniformScalarField3* field = new HxUniformScalarField3(dims,pType,nrrd->data);
// First fetch axis spacing
double spacing[3] = { 1.0, 1.0, 1.0 };
int firstSpaceAxis = -1;
int numSpaceAxesSoFar = 0;
int nonSpatialDimension = -1;
for ( size_t ax = 0; ax < nrrd->dim; ++ax )
{
switch ( nrrd->axis[ax].kind )
{
case nrrdKindUnknown:
case nrrdKindDomain:
case nrrdKindSpace:
case nrrdKindTime: firstSpaceAxis=firstSpaceAxis<0?ax:firstSpaceAxis;
numSpaceAxesSoFar++; break;
default: nonSpatialDimension = ax; continue;
}
switch ( nrrdSpacingCalculate( nrrd, ax, spacing+ax, nrrd->axis[ax].spaceDirection ) )
{
case nrrdSpacingStatusScalarNoSpace:
break;
case nrrdSpacingStatusDirection:
break;
case nrrdSpacingStatusScalarWithSpace:
theMsg->printf("WARNING: nrrdSpacingCalculate returned nrrdSpacingStatusScalarWithSpace\n");
spacing[ax] = nrrd->axis[ax].spacing;
break;
case nrrdSpacingStatusNone:
default:
theMsg->printf("WARNING: no pixel spacings in Nrrd for axis %d ; setting to 1.0\n",ax);
spacing[ax] = 1.0;
break;
}
}
if ( firstSpaceAxis < 0 || firstSpaceAxis >1 )
{
theMsg->printf("ERROR: Unable to identify first spatial axis in nrrd. Got %d\n", firstSpaceAxis);
return 0;
}
// Figure out size of non-spatial dimension (ie vector, colour etc)
int nDataVar = 1;
if ( nonSpatialDimension == 0) nDataVar = dims[nonSpatialDimension];
else if ( nonSpatialDimension > 0) {
// At the moment we can't handle having the vector dimension come later because
// that would require shuffling the nrrd data block to prepare it for Amira
theMsg->printf("ERROR: Only nrrds with vector values in the 0th dimension (not %d) are currently supported\n", nonSpatialDimension);
return 0;
}
// Now initialise lattice
// HxLattice3* lattice = new HxLattice3(&dims[firstSpaceAxis], nDataVar, primType, otherLattice->coords()->duplicate());
// Now let's set the physical dimensions
// This is done by defining the bounding box, the range of the voxel centres
// given in the order: xmin,xmax,ymin ...
float *bbox = field->bbox();
bbox[0] = isnan(nrrd->spaceOrigin[0])?0.0f:(float) nrrd->spaceOrigin[0];
bbox[2] = isnan(nrrd->spaceOrigin[1])?0.0f:(float) nrrd->spaceOrigin[1];
bbox[4] = isnan(nrrd->spaceOrigin[2])?0.0f:(float) nrrd->spaceOrigin[2];
// When a dimension is 1, Amira still seems to have a defined spacing
bbox[1] = bbox[0] + (float) spacing[0] * ( dims[0+firstSpaceAxis] == 1 ? 1 : (dims[0+firstSpaceAxis] - 1) );
bbox[3] = bbox[2] + (float) spacing[1] * ( dims[1+firstSpaceAxis] == 1 ? 1 : (dims[1+firstSpaceAxis] - 1) );
bbox[5] = bbox[4] + (float) spacing[2] * ( dims[2+firstSpaceAxis] == 1 ? 1 : (dims[2+firstSpaceAxis] - 1) );
// Shouldn't need to check for data loading
HxData::registerData(field, filename);
return 1;
}
<commit_msg>Correctly read in 4D data<commit_after>/////////////////////////////////////////////////////////////////
/*
* Amira Reader for the nrrd (Nearly Raw Raster Data) format:
* http://teem.sourceforge.net/nrrd/format.html
* Currently only supports 3d single channel data
* Copyright 2009 Gregory Jefferis. All rights reserved.
* License GPL >=3
* Certain portions of this code were copied/amended from the CMTK
* library: http://www.nitrc.org/projects/cmtk/
*/
/////////////////////////////////////////////////////////////////
#include <NrrdIO/NrrdIOAPI.h>
#include <hxfield/HxUniformScalarField3.h>
#include <Amira/HxMessage.h>
#include <teem/nrrd.h>
NRRDIO_API
int NrrdReader(const char* filename)
{
Nrrd *nrrd = nrrdNew();
if ( nrrdLoad( nrrd, filename, NULL ) )
throw biffGetDone(NRRD);
if ( nrrd->dim > 4 )
{
theMsg->printf("ERROR: for now, nrrd input can only handle data with dimension 4 or less.");
return 0;
} else if ( nrrd->spaceDim > 3 ){
theMsg->printf("ERROR: for now, nrrd input can only handle data with space dimension 3 or less.");
return 0;
}
const int dims[4] =
{
(nrrd->dim > 0) ? nrrd->axis[0].size : 1,
(nrrd->dim > 1) ? nrrd->axis[1].size : 1,
(nrrd->dim > 2) ? nrrd->axis[2].size : 1,
(nrrd->dim > 3) ? nrrd->axis[3].size : 1
};
McPrimType pType = NULL;
switch ( nrrd->type )
{
case nrrdTypeUChar: pType = MC_UINT8; break;
case nrrdTypeChar: pType = MC_INT8; break;
case nrrdTypeUShort: pType = MC_UINT16;break;
case nrrdTypeShort: pType = MC_INT16; break;
case nrrdTypeInt: pType = MC_INT32; break;
case nrrdTypeFloat: pType = MC_FLOAT; break;
case nrrdTypeDouble: pType = MC_DOUBLE;break;
default: break;
}
if(pType == NULL)
{
theMsg->printf("ERROR: unknown nrrd input type.");
return 0;
}
// First fetch axis spacing
double spacing[3] = { 1.0, 1.0, 1.0 };
int firstSpaceAxis = -1;
int numSpaceAxesSoFar = 0;
int nonSpatialDimension = -1;
for ( unsigned int ax = 0; ax < nrrd->dim; ++ax )
{
switch ( nrrd->axis[ax].kind )
{
case nrrdKindUnknown:
case nrrdKindDomain:
case nrrdKindSpace:
case nrrdKindTime: firstSpaceAxis=firstSpaceAxis<0?ax:firstSpaceAxis; break;
default: nonSpatialDimension = ax; continue;
}
switch ( nrrdSpacingCalculate( nrrd, ax, spacing+numSpaceAxesSoFar, nrrd->axis[ax].spaceDirection ) )
{
case nrrdSpacingStatusScalarNoSpace:
break;
case nrrdSpacingStatusDirection:
break;
case nrrdSpacingStatusScalarWithSpace:
theMsg->printf("WARNING: nrrdSpacingCalculate returned nrrdSpacingStatusScalarWithSpace\n");
spacing[numSpaceAxesSoFar] = nrrd->axis[ax].spacing;
break;
case nrrdSpacingStatusNone:
default:
theMsg->printf("WARNING: no pixel spacings in Nrrd for axis %d ; setting to 1.0\n",ax);
spacing[numSpaceAxesSoFar] = 1.0;
break;
}
numSpaceAxesSoFar++;
}
if ( firstSpaceAxis < 0 || firstSpaceAxis >1 )
{
theMsg->printf("ERROR: Unable to identify first spatial axis in nrrd. Got %d\n", firstSpaceAxis);
return 0;
}
// Figure out size of non-spatial dimension (ie vector, colour etc)
int nDataVar = 1;
if ( nonSpatialDimension == 0) nDataVar = dims[nonSpatialDimension];
else if ( nonSpatialDimension > 0) {
// At the moment we can't handle having the vector dimension come later because
// that would require shuffling the nrrd data block to prepare it for Amira
theMsg->printf("ERROR: Only nrrds with vector values in the 0th dimension (not %d) are currently supported\n", nonSpatialDimension);
return 0;
}
// Initialise coordinates (these will be uniform) starting at first space axis
HxUniformCoord3* coord = new HxUniformCoord3(&dims[firstSpaceAxis]);
// Now let's set the physical dimensions
// This is done by defining the bounding box, the range of the voxel centres
// given in the order: xmin,xmax,ymin ...
float *bbox = coord->bbox();
bbox[0] = isnan(nrrd->spaceOrigin[0])?0.0f:(float) nrrd->spaceOrigin[0];
bbox[2] = isnan(nrrd->spaceOrigin[1])?0.0f:(float) nrrd->spaceOrigin[1];
bbox[4] = isnan(nrrd->spaceOrigin[2])?0.0f:(float) nrrd->spaceOrigin[2];
// When a dimension is 1, Amira still seems to have a defined spacing
bbox[1] = bbox[0] + (float) spacing[0] * ( dims[0+firstSpaceAxis] == 1 ? 1 : (dims[0+firstSpaceAxis] - 1) );
bbox[3] = bbox[2] + (float) spacing[1] * ( dims[1+firstSpaceAxis] == 1 ? 1 : (dims[1+firstSpaceAxis] - 1) );
bbox[5] = bbox[4] + (float) spacing[2] * ( dims[2+firstSpaceAxis] == 1 ? 1 : (dims[2+firstSpaceAxis] - 1) );
// Finally initialise lattice
HxLattice3* lattice = new HxLattice3(nDataVar, pType, coord, nrrd->data);
HxField3* field = HxLattice3::create(lattice);
// Shouldn't need to check for data loading
HxData::registerData(field, filename);
return 1;
}
<|endoftext|> |
<commit_before>/*
* extract.cpp
* Modified by: Rohit Gupta CDAC, Mumbai, India
* on July 15, 2012 to implement parallel processing
* Modified by: Nadi Tomeh - LIMSI/CNRS
* Machine Translation Marathon 2010, Dublin
*/
#include <cstdio>
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <stdlib.h>
#include <assert.h>
#include <cstring>
#include <sstream>
#include <map>
#include <set>
#include <vector>
#include <limits>
#include "SentenceAlignment.h"
#include "tables-core.h"
#include "InputFileStream.h"
#include "OutputFileStream.h"
#include "PhraseExtractionOptions.h"
using namespace std;
using namespace MosesTraining;
namespace MosesTraining
{
// HPhraseVertex represents a point in the alignment matrix
typedef pair <int, int> HPhraseVertex;
// Phrase represents a bi-phrase; each bi-phrase is defined by two points in the alignment matrix:
// bottom-left and top-right
typedef pair<HPhraseVertex, HPhraseVertex> HPhrase;
// HPhraseVector is a vector of HPhrases
typedef vector < HPhrase > HPhraseVector;
// SentenceVertices represents, from all extracted phrases, all vertices that have the same positioning
// The key of the map is the English index and the value is a set of the source ones
typedef map <int, set<int> > HSentenceVertices;
REO_POS getOrientWordModel(SentenceAlignment &, REO_MODEL_TYPE, bool, bool,
int, int, int, int, int, int, int,
bool (*)(int, int), bool (*)(int, int));
REO_POS getOrientPhraseModel(SentenceAlignment &, REO_MODEL_TYPE, bool, bool,
int, int, int, int, int, int, int,
bool (*)(int, int), bool (*)(int, int),
const HSentenceVertices &, const HSentenceVertices &);
REO_POS getOrientHierModel(SentenceAlignment &, REO_MODEL_TYPE, bool, bool,
int, int, int, int, int, int, int,
bool (*)(int, int), bool (*)(int, int),
const HSentenceVertices &, const HSentenceVertices &,
const HSentenceVertices &, const HSentenceVertices &,
REO_POS);
void insertVertex(HSentenceVertices &, int, int);
void insertPhraseVertices(HSentenceVertices &, HSentenceVertices &, HSentenceVertices &, HSentenceVertices &,
int, int, int, int);
string getOrientString(REO_POS, REO_MODEL_TYPE);
bool ge(int, int);
bool le(int, int);
bool lt(int, int);
bool isAligned (SentenceAlignment &, int, int);
int sentenceOffset = 0;
std::vector<std::string> Tokenize(const std::string& str,
const std::string& delimiters = " \t");
bool flexScoreFlag = false;
}
namespace MosesTraining
{
class ExtractTask
{
public:
ExtractTask(size_t id, SentenceAlignment &sentence,PhraseExtractionOptions &initoptions, Moses::OutputFileStream &extractFileOrientation)
:m_sentence(sentence),
m_options(initoptions),
m_extractFileOrientation(extractFileOrientation)
{}
void Run();
private:
void extract(SentenceAlignment &);
void addPhrase(SentenceAlignment &, int, int, int, int, string &);
void writePhrasesToFile();
SentenceAlignment &m_sentence;
const PhraseExtractionOptions &m_options;
Moses::OutputFileStream &m_extractFileOrientation;
};
}
int main(int argc, char* argv[])
{
cerr << "PhraseExtract v1.4, written by Philipp Koehn\n"
<< "phrase extraction from an aligned parallel corpus\n";
if (argc < 6) {
cerr << "syntax: extract en de align extract max-length [orientation [ --model [wbe|phrase|hier]-[msd|mslr|mono] ] ";
cerr<<"| --OnlyOutputSpanInfo | --NoTTable | --GZOutput | --IncludeSentenceId | --SentenceOffset n | --InstanceWeights filename ]\n";
exit(1);
}
Moses::OutputFileStream extractFileOrientation;
const char* const &fileNameE = argv[1];
const char* const &fileNameF = argv[2];
const char* const &fileNameA = argv[3];
const string fileNameExtract = string(argv[4]);
PhraseExtractionOptions options(atoi(argv[5]));
for(int i=6; i<argc; i++) {
if (strcmp(argv[i],"--OnlyOutputSpanInfo") == 0) {
options.initOnlyOutputSpanInfo(true);
} else if (strcmp(argv[i],"orientation") == 0 || strcmp(argv[i],"--Orientation") == 0) {
options.initOrientationFlag(true);
} else if (strcmp(argv[i],"--FlexibilityScore") == 0) {
options.initFlexScoreFlag(true);
} else if (strcmp(argv[i],"--NoTTable") == 0) {
options.initTranslationFlag(false);
} else if (strcmp(argv[i], "--IncludeSentenceId") == 0) {
options.initIncludeSentenceIdFlag(true);
} else if (strcmp(argv[i], "--SentenceOffset") == 0) {
if (i+1 >= argc || argv[i+1][0] < '0' || argv[i+1][0] > '9') {
cerr << "extract: syntax error, used switch --SentenceOffset without a number" << endl;
exit(1);
}
sentenceOffset = atoi(argv[++i]);
} else if (strcmp(argv[i], "--GZOutput") == 0) {
options.initGzOutput(true);
} else if (strcmp(argv[i], "--InstanceWeights") == 0) {
if (i+1 >= argc) {
cerr << "extract: syntax error, used switch --InstanceWeights without file name" << endl;
exit(1);
}
options.initInstanceWeightsFile(argv[++i]);
} else if (strcmp(argv[i], "--Debug") == 0) {
options.debug = true;
} else if (strcmp(argv[i], "--MinPhraseLength") == 0) {
options.minPhraseLength = atoi(argv[++i]);
} else if (strcmp(argv[i], "--Separator") == 0) {
options.separator = argv[++i];
} else if(strcmp(argv[i],"--model") == 0) {
if (i+1 >= argc) {
cerr << "extract: syntax error, no model's information provided to the option --model " << endl;
exit(1);
}
char* modelParams = argv[++i];
char* modelName = strtok(modelParams, "-");
char* modelType = strtok(NULL, "-");
// REO_MODEL_TYPE intModelType;
if(strcmp(modelName, "wbe") == 0) {
options.initWordModel(true);
if(strcmp(modelType, "msd") == 0)
options.initWordType(REO_MSD);
else if(strcmp(modelType, "mslr") == 0)
options.initWordType(REO_MSLR);
else if(strcmp(modelType, "mono") == 0 || strcmp(modelType, "monotonicity") == 0)
options.initWordType(REO_MONO);
else {
cerr << "extract: syntax error, unknown reordering model type: " << modelType << endl;
exit(1);
}
} else if(strcmp(modelName, "phrase") == 0) {
options.initPhraseModel(true);
if(strcmp(modelType, "msd") == 0)
options.initPhraseType(REO_MSD);
else if(strcmp(modelType, "mslr") == 0)
options.initPhraseType(REO_MSLR);
else if(strcmp(modelType, "mono") == 0 || strcmp(modelType, "monotonicity") == 0)
options.initPhraseType(REO_MONO);
else {
cerr << "extract: syntax error, unknown reordering model type: " << modelType << endl;
exit(1);
}
} else if(strcmp(modelName, "hier") == 0) {
options.initHierModel(true);
if(strcmp(modelType, "msd") == 0)
options.initHierType(REO_MSD);
else if(strcmp(modelType, "mslr") == 0)
options.initHierType(REO_MSLR);
else if(strcmp(modelType, "mono") == 0 || strcmp(modelType, "monotonicity") == 0)
options.initHierType(REO_MONO);
else {
cerr << "extract: syntax error, unknown reordering model type: " << modelType << endl;
exit(1);
}
} else {
cerr << "extract: syntax error, unknown reordering model: " << modelName << endl;
exit(1);
}
options.initAllModelsOutputFlag(true);
} else {
cerr << "extract: syntax error, unknown option '" << string(argv[i]) << "'\n";
exit(1);
}
}
// default reordering model if no model selected
// allows for the old syntax to be used
if(options.isOrientationFlag() && !options.isAllModelsOutputFlag()) {
options.initWordModel(true);
options.initWordType(REO_MSD);
}
// open input files
Moses::InputFileStream eFile(fileNameE);
Moses::InputFileStream fFile(fileNameF);
Moses::InputFileStream aFile(fileNameA);
istream *eFileP = &eFile;
istream *fFileP = &fFile;
istream *aFileP = &aFile;
istream *iwFileP = NULL;
auto_ptr<Moses::InputFileStream> instanceWeightsFile;
if (options.getInstanceWeightsFile().length()) {
instanceWeightsFile.reset(new Moses::InputFileStream(options.getInstanceWeightsFile()));
iwFileP = instanceWeightsFile.get();
}
// open output files
if (options.isOrientationFlag()) {
string fileNameExtractOrientation = fileNameExtract + ".o" + (options.isGzOutput()?".gz":"");
extractFileOrientation.Open(fileNameExtractOrientation.c_str());
}
int i = sentenceOffset;
string englishString, foreignString, alignmentString, weightString;
while(getline(*eFileP, englishString)) {
i++;
getline(*eFileP, englishString);
getline(*fFileP, foreignString);
getline(*aFileP, alignmentString);
if (iwFileP) {
getline(*iwFileP, weightString);
}
if (i%10000 == 0) cerr << "." << flush;
SentenceAlignment sentence;
// cout << "read in: " << englishString << " & " << foreignString << " & " << alignmentString << endl;
//az: output src, tgt, and alingment line
if (options.isOnlyOutputSpanInfo()) {
cout << "LOG: SRC: " << foreignString << endl;
cout << "LOG: TGT: " << englishString << endl;
cout << "LOG: ALT: " << alignmentString << endl;
cout << "LOG: PHRASES_BEGIN:" << endl;
}
if (sentence.create( englishString.c_str(), foreignString.c_str(), alignmentString.c_str(), weightString.c_str(), i, false)) {
ExtractTask *task = new ExtractTask(i-1, sentence, options, extractFileOrientation);
task->Run();
delete task;
}
if (options.isOnlyOutputSpanInfo()) cout << "LOG: PHRASES_END:" << endl; //az: mark end of phrases
}
eFile.Close();
fFile.Close();
aFile.Close();
//az: only close if we actually opened it
if (!options.isOnlyOutputSpanInfo()) {
if (options.isOrientationFlag()) {
extractFileOrientation.Close();
}
}
}
namespace MosesTraining
{
void ExtractTask::Run()
{
extract(m_sentence);
}
void ExtractTask::extract(SentenceAlignment &sentence)
{
int countE = sentence.target.size();
int countF = sentence.source.size();
HPhraseVector inboundPhrases;
HSentenceVertices inTopLeft;
HSentenceVertices inTopRight;
HSentenceVertices inBottomLeft;
HSentenceVertices inBottomRight;
HSentenceVertices outTopLeft;
HSentenceVertices outTopRight;
HSentenceVertices outBottomLeft;
HSentenceVertices outBottomRight;
HSentenceVertices::const_iterator it;
bool relaxLimit = m_options.isHierModel();
bool buildExtraStructure = m_options.isPhraseModel() || m_options.isHierModel();
// check alignments for target phrase startE...endE
// loop over extracted phrases which are compatible with the word-alignments
for(int startE=0; startE<countE; startE++) {
for(int endE=startE;
(endE<countE && (relaxLimit || endE<startE+m_options.maxPhraseLength));
endE++) {
int minF = std::numeric_limits<int>::max();
int maxF = -1;
vector< int > usedF = sentence.alignedCountS;
for(int ei=startE; ei<=endE; ei++) {
for(size_t i=0; i<sentence.alignedToT[ei].size(); i++) {
int fi = sentence.alignedToT[ei][i];
if (fi<minF) {
minF = fi;
}
if (fi>maxF) {
maxF = fi;
}
usedF[ fi ]--;
}
}
if (maxF >= 0 && // aligned to any source words at all
(relaxLimit || maxF-minF < m_options.maxPhraseLength)) { // source phrase within limits
// check if source words are aligned to out of bound target words
bool out_of_bounds = false;
for(int fi=minF; fi<=maxF && !out_of_bounds; fi++)
if (usedF[fi]>0) {
// cout << "ouf of bounds: " << fi << "\n";
out_of_bounds = true;
}
// cout << "doing if for ( " << minF << "-" << maxF << ", " << startE << "," << endE << ")\n";
if (!out_of_bounds) {
// start point of source phrase may retreat over unaligned
for(int startF=minF;
(startF>=0 &&
(relaxLimit || startF>maxF-m_options.maxPhraseLength) && // within length limit
(startF==minF || sentence.alignedCountS[startF]==0)); // unaligned
startF--)
// end point of source phrase may advance over unaligned
for(int endF=maxF;
(endF<countF &&
(relaxLimit || endF<startF+m_options.maxPhraseLength) && // within length limit
(endF - startF + 1 > m_options.minPhraseLength) && // within length limit
(endF==maxF || sentence.alignedCountS[endF]==0)); // unaligned
endF++) { // at this point we have extracted a phrase
if(buildExtraStructure) { // phrase || hier
if(endE-startE < m_options.maxPhraseLength && endF-startF < m_options.maxPhraseLength) { // within limit
inboundPhrases.push_back(HPhrase(HPhraseVertex(startF,startE),
HPhraseVertex(endF,endE)));
insertPhraseVertices(inTopLeft, inTopRight, inBottomLeft, inBottomRight,
startF, startE, endF, endE);
} else
insertPhraseVertices(outTopLeft, outTopRight, outBottomLeft, outBottomRight,
startF, startE, endF, endE);
} else {
string orientationInfo = "";
if(m_options.isWordModel()) {
REO_POS wordPrevOrient, wordNextOrient;
bool connectedLeftTopP = isAligned( sentence, startF-1, startE-1 );
bool connectedRightTopP = isAligned( sentence, endF+1, startE-1 );
bool connectedLeftTopN = isAligned( sentence, endF+1, endE+1 );
bool connectedRightTopN = isAligned( sentence, startF-1, endE+1 );
wordPrevOrient = getOrientWordModel(sentence, m_options.isWordType(), connectedLeftTopP, connectedRightTopP, startF, endF, startE, endE, countF, 0, 1, &ge, <);
wordNextOrient = getOrientWordModel(sentence, m_options.isWordType(), connectedLeftTopN, connectedRightTopN, endF, startF, endE, startE, 0, countF, -1, <, &ge);
orientationInfo += getOrientString(wordPrevOrient, m_options.isWordType()) + " " + getOrientString(wordNextOrient, m_options.isWordType());
if(m_options.isAllModelsOutputFlag())
" | | ";
}
addPhrase(sentence, startE, endE, startF, endF, orientationInfo);
}
}
}
}
}
}
}
REO_POS getOrientWordModel(SentenceAlignment & sentence, REO_MODEL_TYPE modelType,
bool connectedLeftTop, bool connectedRightTop,
int startF, int endF, int startE, int endE, int countF, int zero, int unit,
bool (*ge)(int, int), bool (*lt)(int, int) )
{
if( connectedLeftTop && !connectedRightTop)
return LEFT;
if(modelType == REO_MONO)
return UNKNOWN;
if (!connectedLeftTop && connectedRightTop)
return RIGHT;
if(modelType == REO_MSD)
return UNKNOWN;
for(int indexF=startF-2*unit; (*ge)(indexF, zero) && !connectedLeftTop; indexF=indexF-unit)
connectedLeftTop = isAligned(sentence, indexF, startE-unit);
for(int indexF=endF+2*unit; (*lt)(indexF,countF) && !connectedRightTop; indexF=indexF+unit)
connectedRightTop = isAligned(sentence, indexF, startE-unit);
if(connectedLeftTop && !connectedRightTop)
return DRIGHT;
else if(!connectedLeftTop && connectedRightTop)
return DLEFT;
return UNKNOWN;
}
// to be called with countF-1 instead of countF
REO_POS getOrientPhraseModel (SentenceAlignment & sentence, REO_MODEL_TYPE modelType,
bool connectedLeftTop, bool connectedRightTop,
int startF, int endF, int startE, int endE, int countF, int zero, int unit,
bool (*ge)(int, int), bool (*lt)(int, int),
const HSentenceVertices & inBottomRight, const HSentenceVertices & inBottomLeft)
{
HSentenceVertices::const_iterator it;
if((connectedLeftTop && !connectedRightTop) ||
//(startE == 0 && startF == 0) ||
//(startE == sentence.target.size()-1 && startF == sentence.source.size()-1) ||
((it = inBottomRight.find(startE - unit)) != inBottomRight.end() &&
it->second.find(startF-unit) != it->second.end()))
return LEFT;
if(modelType == REO_MONO)
return UNKNOWN;
if((!connectedLeftTop && connectedRightTop) ||
((it = inBottomLeft.find(startE - unit)) != inBottomLeft.end() && it->second.find(endF + unit) != it->second.end()))
return RIGHT;
if(modelType == REO_MSD)
return UNKNOWN;
connectedLeftTop = false;
for(int indexF=startF-2*unit; (*ge)(indexF, zero) && !connectedLeftTop; indexF=indexF-unit)
if(connectedLeftTop = (it = inBottomRight.find(startE - unit)) != inBottomRight.end() &&
it->second.find(indexF) != it->second.end())
return DRIGHT;
connectedRightTop = false;
for(int indexF=endF+2*unit; (*lt)(indexF, countF) && !connectedRightTop; indexF=indexF+unit)
if(connectedRightTop = (it = inBottomLeft.find(startE - unit)) != inBottomLeft.end() &&
it->second.find(indexF) != it->second.end())
return DLEFT;
return UNKNOWN;
}
// to be called with countF-1 instead of countF
REO_POS getOrientHierModel (SentenceAlignment & sentence, REO_MODEL_TYPE modelType,
bool connectedLeftTop, bool connectedRightTop,
int startF, int endF, int startE, int endE, int countF, int zero, int unit,
bool (*ge)(int, int), bool (*lt)(int, int),
const HSentenceVertices & inBottomRight, const HSentenceVertices & inBottomLeft,
const HSentenceVertices & outBottomRight, const HSentenceVertices & outBottomLeft,
REO_POS phraseOrient)
{
HSentenceVertices::const_iterator it;
if(phraseOrient == LEFT ||
(connectedLeftTop && !connectedRightTop) ||
// (startE == 0 && startF == 0) ||
//(startE == sentence.target.size()-1 && startF == sentence.source.size()-1) ||
((it = inBottomRight.find(startE - unit)) != inBottomRight.end() &&
it->second.find(startF-unit) != it->second.end()) ||
((it = outBottomRight.find(startE - unit)) != outBottomRight.end() &&
it->second.find(startF-unit) != it->second.end()))
return LEFT;
if(modelType == REO_MONO)
return UNKNOWN;
if(phraseOrient == RIGHT ||
(!connectedLeftTop && connectedRightTop) ||
((it = inBottomLeft.find(startE - unit)) != inBottomLeft.end() &&
it->second.find(endF + unit) != it->second.end()) ||
((it = outBottomLeft.find(startE - unit)) != outBottomLeft.end() &&
it->second.find(endF + unit) != it->second.end()))
return RIGHT;
if(modelType == REO_MSD)
return UNKNOWN;
if(phraseOrient != UNKNOWN)
return phraseOrient;
connectedLeftTop = false;
for(int indexF=startF-2*unit; (*ge)(indexF, zero) && !connectedLeftTop; indexF=indexF-unit) {
if((connectedLeftTop = (it = inBottomRight.find(startE - unit)) != inBottomRight.end() &&
it->second.find(indexF) != it->second.end()) ||
(connectedLeftTop = (it = outBottomRight.find(startE - unit)) != outBottomRight.end() &&
it->second.find(indexF) != it->second.end()))
return DRIGHT;
}
connectedRightTop = false;
for(int indexF=endF+2*unit; (*lt)(indexF, countF) && !connectedRightTop; indexF=indexF+unit) {
if((connectedRightTop = (it = inBottomLeft.find(startE - unit)) != inBottomLeft.end() &&
it->second.find(indexF) != it->second.end()) ||
(connectedRightTop = (it = outBottomLeft.find(startE - unit)) != outBottomLeft.end() &&
it->second.find(indexF) != it->second.end()))
return DLEFT;
}
return UNKNOWN;
}
bool isAligned ( SentenceAlignment &sentence, int fi, int ei )
{
if (ei == -1 && fi == -1)
return true;
if (ei <= -1 || fi <= -1)
return false;
if ((size_t)ei == sentence.target.size() && (size_t)fi == sentence.source.size())
return true;
if ((size_t)ei >= sentence.target.size() || (size_t)fi >= sentence.source.size())
return false;
for(size_t i=0; i<sentence.alignedToT[ei].size(); i++)
if (sentence.alignedToT[ei][i] == fi)
return true;
return false;
}
bool ge(int first, int second)
{
return first >= second;
}
bool le(int first, int second)
{
return first <= second;
}
bool lt(int first, int second)
{
return first < second;
}
void insertVertex( HSentenceVertices & corners, int x, int y )
{
set<int> tmp;
tmp.insert(x);
pair< HSentenceVertices::iterator, bool > ret = corners.insert( pair<int, set<int> > (y, tmp) );
if(ret.second == false) {
ret.first->second.insert(x);
}
}
void insertPhraseVertices(
HSentenceVertices & topLeft,
HSentenceVertices & topRight,
HSentenceVertices & bottomLeft,
HSentenceVertices & bottomRight,
int startF, int startE, int endF, int endE)
{
insertVertex(topLeft, startF, startE);
insertVertex(topRight, endF, startE);
insertVertex(bottomLeft, startF, endE);
insertVertex(bottomRight, endF, endE);
}
string getOrientString(REO_POS orient, REO_MODEL_TYPE modelType)
{
switch(orient) {
case LEFT:
return "mono";
break;
case RIGHT:
return "swap";
break;
case DRIGHT:
return "dright";
break;
case DLEFT:
return "dleft";
break;
case UNKNOWN:
switch(modelType) {
case REO_MONO:
return "nomono";
break;
case REO_MSD:
return "other";
break;
case REO_MSLR:
return "dright";
break;
}
break;
}
return "";
}
int getClass(const std::string &str)
{
size_t pos = str.find("swap");
if (pos == str.npos) {
return 0;
}
else if (pos == 0) {
return 1;
}
else {
return 2;
}
}
void ExtractTask::addPhrase( SentenceAlignment &sentence, int startE, int endE, int startF, int endF , string &orientationInfo)
{
if (m_options.isOnlyOutputSpanInfo()) {
cout << startF << " " << endF << " " << startE << " " << endE << endl;
return;
}
const string &sep = m_options.separator;
m_extractFileOrientation << sentence.sentenceID << " " << sep << " ";
m_extractFileOrientation << getClass(orientationInfo) << " " << sep << " ";
// position
m_extractFileOrientation << startF << " " << endF << " " << sep << " ";
// start
m_extractFileOrientation << "<s> ";
for(int fi=0; fi<startF; fi++) {
m_extractFileOrientation << sentence.source[fi] << " ";
}
m_extractFileOrientation << sep << " ";
// middle
for(int fi=startF; fi<=endF; fi++) {
m_extractFileOrientation << sentence.source[fi] << " ";
}
m_extractFileOrientation << sep << " ";
// end
for(int fi=endF+1; fi<sentence.source.size(); fi++) {
m_extractFileOrientation << sentence.source[fi] << " ";
}
m_extractFileOrientation << "</s> ";
// target
/*
for(int ei=startE; ei<=endE; ei++) {
m_extractFileOrientation << sentence.target[ei] << " ";
}
*/
m_extractFileOrientation << endl;
}
/** tokenise input string to vector of string. each element has been separated by a character in the delimiters argument.
The separator can only be 1 character long. The default delimiters are space or tab
*/
std::vector<std::string> Tokenize(const std::string& str,
const std::string& delimiters)
{
std::vector<std::string> tokens;
// Skip delimiters at beginning.
std::string::size_type lastPos = str.find_first_not_of(delimiters, 0);
// Find first "non-delimiter".
std::string::size_type pos = str.find_first_of(delimiters, lastPos);
while (std::string::npos != pos || std::string::npos != lastPos) {
// Found a token, add it to the vector.
tokens.push_back(str.substr(lastPos, pos - lastPos));
// Skip delimiters. Note the "not_of"
lastPos = str.find_first_not_of(delimiters, pos);
// Find next "non-delimiter"
pos = str.find_first_of(delimiters, lastPos);
}
return tokens;
}
}
<commit_msg>delete extract-ordering. Not part of the core functionality<commit_after><|endoftext|> |
<commit_before>/*
* Copyright 2017 Devin Matthews and Intel Corp.
*
* 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.
*
* 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.
*/
#include <cstdint>
#include <string>
#include <cpuid.h>
static std::string get_cpu_name()
{
char cpu_name[48] = {};
uint32_t eax, ebx, ecx, edx;
__cpuid(0x80000002u, eax, ebx, ecx, edx);
//printf("%x %x %x %x\n", eax, ebx, ecx, edx);
*(uint32_t *)&cpu_name[0] = eax;
*(uint32_t *)&cpu_name[4] = ebx;
*(uint32_t *)&cpu_name[8] = ecx;
*(uint32_t *)&cpu_name[12] = edx;
__cpuid(0x80000003u, eax, ebx, ecx, edx);
//printf("%x %x %x %x\n", eax, ebx, ecx, edx);
*(uint32_t *)&cpu_name[16+0] = eax;
*(uint32_t *)&cpu_name[16+4] = ebx;
*(uint32_t *)&cpu_name[16+8] = ecx;
*(uint32_t *)&cpu_name[16+12] = edx;
__cpuid(0x80000004u, eax, ebx, ecx, edx);
//printf("%x %x %x %x\n", eax, ebx, ecx, edx);
*(uint32_t *)&cpu_name[32+0] = eax;
*(uint32_t *)&cpu_name[32+4] = ebx;
*(uint32_t *)&cpu_name[32+8] = ecx;
*(uint32_t *)&cpu_name[32+12] = edx;
return std::string(cpu_name);
}
int vpu_count()
{
std::string name = get_cpu_name();
return 2;
if (name.find("Intel(R) Xeon(R)") != std::string::npos)
{
auto loc = name.find("Platinum");
if (loc == std::string::npos) loc = name.find("Gold");
if (loc == std::string::npos) loc = name.find("Silver");
if (loc == std::string::npos) loc = name.find("Bronze");
if (loc == std::string::npos) loc = name.find("W");
if (loc == std::string::npos) return -1;
auto sku = atoi(name.substr(loc+1, 4).c_str());
if (8199 >= sku && sku >= 8100) return 2;
else if (6199 >= sku && sku >= 6100) return 2;
else if (sku == 5122) return 2;
else if (5199 >= sku && sku >= 5100) return 1;
else if (4199 >= sku && sku >= 4100) return 1;
else if (3199 >= sku && sku >= 3100) return 1;
else if (2199 >= sku && sku >= 2120) return 2;
else if (2119 >= sku && sku >= 2100) return 1;
else return -1;
}
else if (name.find("Intel(R) Core(TM) i9") != std::string::npos)
{
return 1;
}
else if (name.find("Intel(R) Core(TM) i7") != std::string::npos)
{
if (name.find("7800X") != std::string::npos ||
name.find("7820X") != std::string::npos) return 1;
else return -1;
}
else
{
return -1;
}
}
<commit_msg>Fix vpu_count.<commit_after>/*
* Copyright 2017 Devin Matthews and Intel Corp.
*
* 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.
*
* 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.
*/
#include <cstdint>
#include <string>
#include <cpuid.h>
static std::string get_cpu_name()
{
char cpu_name[48] = {};
uint32_t eax, ebx, ecx, edx;
__cpuid(0x80000002u, eax, ebx, ecx, edx);
*(uint32_t *)&cpu_name[0] = eax;
*(uint32_t *)&cpu_name[4] = ebx;
*(uint32_t *)&cpu_name[8] = ecx;
*(uint32_t *)&cpu_name[12] = edx;
__cpuid(0x80000003u, eax, ebx, ecx, edx);
*(uint32_t *)&cpu_name[16+0] = eax;
*(uint32_t *)&cpu_name[16+4] = ebx;
*(uint32_t *)&cpu_name[16+8] = ecx;
*(uint32_t *)&cpu_name[16+12] = edx;
__cpuid(0x80000004u, eax, ebx, ecx, edx);
*(uint32_t *)&cpu_name[32+0] = eax;
*(uint32_t *)&cpu_name[32+4] = ebx;
*(uint32_t *)&cpu_name[32+8] = ecx;
*(uint32_t *)&cpu_name[32+12] = edx;
return std::string(cpu_name);
}
int vpu_count()
{
std::string name = get_cpu_name();
if (name.find("Intel(R) Xeon(R)") != std::string::npos)
{
auto loc = name.find("Platinum");
if (loc == std::string::npos) loc = name.find("Gold");
if (loc == std::string::npos) loc = name.find("Silver");
if (loc == std::string::npos) loc = name.find("Bronze");
if (loc == std::string::npos) loc = name.find("W");
if (loc == std::string::npos) return -1;
loc = name.find_first_of("- ", loc+1)+1;
auto sku = atoi(name.substr(loc, 4).c_str());
if (8199 >= sku && sku >= 8100) return 2;
else if (6199 >= sku && sku >= 6100) return 2;
else if (sku == 5122) return 2;
else if (5199 >= sku && sku >= 5100) return 1;
else if (4199 >= sku && sku >= 4100) return 1;
else if (3199 >= sku && sku >= 3100) return 1;
else if (2199 >= sku && sku >= 2120) return 2;
else if (2119 >= sku && sku >= 2100) return 1;
else return -1;
}
else if (name.find("Intel(R) Core(TM) i9") != std::string::npos)
{
return 2;
}
else if (name.find("Intel(R) Core(TM) i7") != std::string::npos)
{
if (name.find("7800X") != std::string::npos ||
name.find("7820X") != std::string::npos) return 2;
else return -1;
}
else
{
return -1;
}
}
<|endoftext|> |
<commit_before>/*
* WrapperIO.cpp
* This file is part of FRESteamWorks.
*
* Created by Ventero <http://github.com/Ventero>
* Copyright (c) 2012-2014 Level Up Labs, LLC. All rights reserved.
*/
#include "WrapperIO.h"
#include <algorithm>
#include <fstream>
#include <iostream>
#include <ios>
#include <iostream>
#include <iterator>
#include <sstream>
using namespace amf;
void sendData(Serializer& serializer) {
std::vector<u8> data = serializer.data();
if(data.size() > 1024) {
// due to output buffering, large outputs need to be sent via a tempfile
sendDataTempFile(serializer);
return;
}
serializer.clear();
// first, send a length prefix
std::vector<u8> length = AmfInteger(data.size()).serialize();
std::copy(length.begin(), length.end(), std::ostream_iterator<u8>(std::cout));
// send actual data
std::copy(data.begin(), data.end(), std::ostream_iterator<u8>(std::cout));
}
void sendDataTempFile(Serializer& serializer) {
std::vector<u8> data = serializer.data();
serializer.clear();
// send length via stdout
std::vector<u8> length = AmfInteger(data.size()).serialize();
std::copy(length.begin(), length.end(), std::ostream_iterator<u8>(std::cout));
std::string filename = std::tmpnam(nullptr);
std::fstream tmpfile(filename, std::ios::out | std::ios::binary);
std::copy(data.begin(), data.end(), std::ostream_iterator<u8>(tmpfile));
tmpfile.close();
send(filename);
}
void sendItem(const AmfItem& item) {
Serializer serializer;
serializer << item;
sendData(serializer);
}
void send(bool value) {
sendItem(AmfBool(value));
}
void send(int32 value) {
sendItem(AmfInteger(value));
}
void send(uint32 value) {
sendItem(AmfInteger(value));
}
void send(uint64 value) {
sendItem(AmfString(std::to_string(value)));
}
void send(float value) {
sendItem(AmfDouble(value));
}
void send(double value) {
sendItem(AmfDouble(value));
}
void send(std::string value) {
sendItem(AmfString(value));
}
void send(const AmfItem& value) {
sendItem(value);
}
// sentinel for pseudo-void functions
void send(std::nullptr_t) { }
// TODO: replace this mess with AMF
bool get_bool() {
std::string item;
std::getline(std::cin, item);
return item == "true";
}
int32 get_int() {
std::string item;
std::getline(std::cin, item);
return std::stoi(item);
}
float get_float() {
std::string item;
std::getline(std::cin, item);
return std::stof(item);
}
std::string get_string() {
std::string item;
std::getline(std::cin, item);
size_t length = std::stoi(item);
if (length < 1) return "";
if (length > 1024)
return readTempFileBuf(length);
char* buf = new char[length];
std::cin.read(buf, length);
// remove trailing newline
std::string result(buf, length - 1);
delete[] buf;
return result;
}
std::string get_bytearray() {
std::string item;
std::getline(std::cin, item);
size_t length = std::stoi(item);
if (length < 1) return "";
return readTempFileBuf(length);
}
uint64 get_uint64() {
std::string str = get_string();
std::istringstream ss(str);
uint64 val;
if(!(ss >> val)) return 0;
return val;
}
std::vector<std::string> get_string_array() {
return get_array<std::string>(get_string);
}
std::string readTempFileBuf(size_t length) {
std::string filename;
std::getline(std::cin, filename);
std::ifstream tempfile(filename, std::ios::in | std::ios::binary);
char* buf = new char[length];
tempfile.read(buf, length);
std::string result(buf, length - 1);
delete[] buf;
tempfile.close();
std::remove(filename.c_str());
return result;
}
<commit_msg>Flush stdout after sending data.<commit_after>/*
* WrapperIO.cpp
* This file is part of FRESteamWorks.
*
* Created by Ventero <http://github.com/Ventero>
* Copyright (c) 2012-2014 Level Up Labs, LLC. All rights reserved.
*/
#include "WrapperIO.h"
#include <algorithm>
#include <fstream>
#include <iostream>
#include <ios>
#include <iostream>
#include <iterator>
#include <sstream>
using namespace amf;
void sendData(Serializer& serializer) {
std::vector<u8> data = serializer.data();
if(data.size() > 1024) {
// due to output buffering, large outputs need to be sent via a tempfile
sendDataTempFile(serializer);
return;
}
serializer.clear();
// first, send a length prefix
std::vector<u8> length = AmfInteger(data.size()).serialize();
std::copy(length.begin(), length.end(), std::ostream_iterator<u8>(std::cout));
// send actual data
std::copy(data.begin(), data.end(), std::ostream_iterator<u8>(std::cout));
std::cout << std::flush;
}
void sendDataTempFile(Serializer& serializer) {
std::vector<u8> data = serializer.data();
serializer.clear();
// send length via stdout
std::vector<u8> length = AmfInteger(data.size()).serialize();
std::copy(length.begin(), length.end(), std::ostream_iterator<u8>(std::cout));
std::string filename = std::tmpnam(nullptr);
std::fstream tmpfile(filename, std::ios::out | std::ios::binary);
std::copy(data.begin(), data.end(), std::ostream_iterator<u8>(tmpfile));
tmpfile.close();
send(filename);
}
void sendItem(const AmfItem& item) {
Serializer serializer;
serializer << item;
sendData(serializer);
}
void send(bool value) {
sendItem(AmfBool(value));
}
void send(int32 value) {
sendItem(AmfInteger(value));
}
void send(uint32 value) {
sendItem(AmfInteger(value));
}
void send(uint64 value) {
sendItem(AmfString(std::to_string(value)));
}
void send(float value) {
sendItem(AmfDouble(value));
}
void send(double value) {
sendItem(AmfDouble(value));
}
void send(std::string value) {
sendItem(AmfString(value));
}
void send(const AmfItem& value) {
sendItem(value);
}
// sentinel for pseudo-void functions
void send(std::nullptr_t) { }
// TODO: replace this mess with AMF
bool get_bool() {
std::string item;
std::getline(std::cin, item);
return item == "true";
}
int32 get_int() {
std::string item;
std::getline(std::cin, item);
return std::stoi(item);
}
float get_float() {
std::string item;
std::getline(std::cin, item);
return std::stof(item);
}
std::string get_string() {
std::string item;
std::getline(std::cin, item);
size_t length = std::stoi(item);
if (length < 1) return "";
if (length > 1024)
return readTempFileBuf(length);
char* buf = new char[length];
std::cin.read(buf, length);
// remove trailing newline
std::string result(buf, length - 1);
delete[] buf;
return result;
}
std::string get_bytearray() {
std::string item;
std::getline(std::cin, item);
size_t length = std::stoi(item);
if (length < 1) return "";
return readTempFileBuf(length);
}
uint64 get_uint64() {
std::string str = get_string();
std::istringstream ss(str);
uint64 val;
if(!(ss >> val)) return 0;
return val;
}
std::vector<std::string> get_string_array() {
return get_array<std::string>(get_string);
}
std::string readTempFileBuf(size_t length) {
std::string filename;
std::getline(std::cin, filename);
std::ifstream tempfile(filename, std::ios::in | std::ios::binary);
char* buf = new char[length];
tempfile.read(buf, length);
std::string result(buf, length - 1);
delete[] buf;
tempfile.close();
std::remove(filename.c_str());
return result;
}
<|endoftext|> |
<commit_before>/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* 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 Library General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* E133Receiver.cpp
* Copyright (C) 2011 Simon Newton
*/
#include <ola/Callback.h>
#include <ola/Logging.h>
#include <ola/network/IPV4Address.h>
#include <ola/rdm/RDMCommand.h>
#include <ola/rdm/RDMHelper.h>
#include <string>
#include <vector>
#include "plugins/e131/e131/E133Header.h"
#include "plugins/e131/e131/DMPAddress.h"
#include "plugins/e131/e131/E133Layer.h"
#include "E133Receiver.h"
using ola::plugin::e131::DMPAddressData;
using ola::plugin::e131::E133Header;
using ola::plugin::e131::TwoByteRangeDMPAddress;
using ola::rdm::RDMRequest;
E133Receiver::E133Receiver(unsigned int universe,
ola::rdm::RDMControllerInterface *local_controller)
: m_e133_layer(NULL),
m_local_controller(local_controller),
m_universe(universe) {
if (!universe)
OLA_FATAL <<
"E133Receiver created with universe 0, this isn't valid";
}
/**
* Check for requests that have timed out
*/
void E133Receiver::CheckForStaleRequests(const ola::TimeStamp *now) {
(void) now;
}
/**
* Handle a RDM response addressed to this universe
*/
void E133Receiver::HandlePacket(
const ola::plugin::e131::TransportHeader &transport_header,
const ola::plugin::e131::E133Header &e133_header,
const std::string &raw_request) {
OLA_INFO << "Got data from " << transport_header.SourceIP() <<
" for universe " << e133_header.Universe();
// attempt to unpack as a request
const ola::rdm::RDMRequest *request = ola::rdm::RDMRequest::InflateFromData(
reinterpret_cast<const uint8_t*>(raw_request.data()),
raw_request.size());
if (!request) {
OLA_WARN << "Failed to unpack E1.33 RDM message, ignoring request.";
return;
}
m_local_controller->SendRDMRequest(
request,
ola::NewSingleCallback(this,
&E133Receiver::RequestComplete,
transport_header.SourceIP(),
transport_header.SourcePort(),
e133_header.Sequence()));
}
/**
* Handle a completed RDM request
*/
void E133Receiver::RequestComplete(ola::network::IPV4Address src_ip,
uint16_t src_port,
uint8_t sequence_number,
ola::rdm::rdm_response_code response_code,
const ola::rdm::RDMResponse *response,
const std::vector<std::string> &packets) {
if (response_code != ola::rdm::RDM_COMPLETED_OK) {
OLA_WARN << "E1.33 request failed with code " <<
ola::rdm::ResponseCodeToString(response_code) <<
", dropping request";
}
OLA_INFO << "rdm size is " << response->Size();
// TODO(simon): handle the ack overflow case here
// For now we just send back one packet.
unsigned int actual_size = response->Size();
uint8_t *rdm_data = new uint8_t[actual_size + 1];
rdm_data[0] = ola::rdm::RDMCommand::START_CODE;
if (!response->Pack(rdm_data + 1, &actual_size)) {
OLA_WARN << "Failed to pack RDM response, aborting send";
delete[] rdm_data;
return;
}
unsigned int rdm_data_size = actual_size + 1;
ola::plugin::e131::TwoByteRangeDMPAddress range_addr(0,
1,
rdm_data_size);
ola::plugin::e131::DMPAddressData<
ola::plugin::e131::TwoByteRangeDMPAddress> range_chunk(
&range_addr,
rdm_data,
rdm_data_size);
std::vector<DMPAddressData<TwoByteRangeDMPAddress> > ranged_chunks;
ranged_chunks.push_back(range_chunk);
const ola::plugin::e131::DMPPDU *pdu =
ola::plugin::e131::NewRangeDMPSetProperty<uint16_t>(
true,
false,
ranged_chunks);
E133Header header("foo bar",
100,
sequence_number,
m_universe,
false, // management
false); // squawk
bool result = m_e133_layer->SendDMP(header, pdu, src_ip, src_port);
if (!result)
OLA_WARN << "Failed to send E1.33 response";
// send response back to src ip:port with correct seq #
delete[] rdm_data;
delete pdu;
if (response)
delete response;
(void) src_port;
(void) packets;
}
<commit_msg> * e133: handle the broad/vendorcast case in the receiver<commit_after>/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* 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 Library General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* E133Receiver.cpp
* Copyright (C) 2011 Simon Newton
*/
#include <ola/Callback.h>
#include <ola/Logging.h>
#include <ola/network/IPV4Address.h>
#include <ola/rdm/RDMCommand.h>
#include <ola/rdm/RDMHelper.h>
#include <string>
#include <vector>
#include "plugins/e131/e131/E133Header.h"
#include "plugins/e131/e131/DMPAddress.h"
#include "plugins/e131/e131/E133Layer.h"
#include "E133Receiver.h"
using ola::plugin::e131::DMPAddressData;
using ola::plugin::e131::E133Header;
using ola::plugin::e131::TwoByteRangeDMPAddress;
using ola::rdm::RDMRequest;
E133Receiver::E133Receiver(unsigned int universe,
ola::rdm::RDMControllerInterface *local_controller)
: m_e133_layer(NULL),
m_local_controller(local_controller),
m_universe(universe) {
if (!universe)
OLA_FATAL <<
"E133Receiver created with universe 0, this isn't valid";
}
/**
* Check for requests that have timed out
*/
void E133Receiver::CheckForStaleRequests(const ola::TimeStamp *now) {
(void) now;
}
/**
* Handle a RDM response addressed to this universe
*/
void E133Receiver::HandlePacket(
const ola::plugin::e131::TransportHeader &transport_header,
const ola::plugin::e131::E133Header &e133_header,
const std::string &raw_request) {
OLA_INFO << "Got data from " << transport_header.SourceIP() <<
" for universe " << e133_header.Universe();
// attempt to unpack as a request
const ola::rdm::RDMRequest *request = ola::rdm::RDMRequest::InflateFromData(
reinterpret_cast<const uint8_t*>(raw_request.data()),
raw_request.size());
if (!request) {
OLA_WARN << "Failed to unpack E1.33 RDM message, ignoring request.";
return;
}
m_local_controller->SendRDMRequest(
request,
ola::NewSingleCallback(this,
&E133Receiver::RequestComplete,
transport_header.SourceIP(),
transport_header.SourcePort(),
e133_header.Sequence()));
}
/**
* Handle a completed RDM request
*/
void E133Receiver::RequestComplete(ola::network::IPV4Address src_ip,
uint16_t src_port,
uint8_t sequence_number,
ola::rdm::rdm_response_code response_code,
const ola::rdm::RDMResponse *response,
const std::vector<std::string> &packets) {
if (response_code != ola::rdm::RDM_COMPLETED_OK) {
OLA_WARN << "E1.33 request failed with code " <<
ola::rdm::ResponseCodeToString(response_code) <<
", dropping request";
delete response;
return;
}
OLA_INFO << "rdm size is " << response->Size();
// TODO(simon): handle the ack overflow case here
// For now we just send back one packet.
unsigned int actual_size = response->Size();
uint8_t *rdm_data = new uint8_t[actual_size + 1];
rdm_data[0] = ola::rdm::RDMCommand::START_CODE;
if (!response->Pack(rdm_data + 1, &actual_size)) {
OLA_WARN << "Failed to pack RDM response, aborting send";
delete[] rdm_data;
return;
}
unsigned int rdm_data_size = actual_size + 1;
ola::plugin::e131::TwoByteRangeDMPAddress range_addr(0,
1,
rdm_data_size);
ola::plugin::e131::DMPAddressData<
ola::plugin::e131::TwoByteRangeDMPAddress> range_chunk(
&range_addr,
rdm_data,
rdm_data_size);
std::vector<DMPAddressData<TwoByteRangeDMPAddress> > ranged_chunks;
ranged_chunks.push_back(range_chunk);
const ola::plugin::e131::DMPPDU *pdu =
ola::plugin::e131::NewRangeDMPSetProperty<uint16_t>(
true,
false,
ranged_chunks);
E133Header header("foo bar",
100,
sequence_number,
m_universe,
false, // management
false); // squawk
bool result = m_e133_layer->SendDMP(header, pdu, src_ip, src_port);
if (!result)
OLA_WARN << "Failed to send E1.33 response";
// send response back to src ip:port with correct seq #
delete[] rdm_data;
delete pdu;
if (response)
delete response;
(void) src_port;
(void) packets;
}
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2012 Artem Pavlenko
*
* 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
*
*****************************************************************************/
#ifndef MAPNIK_JSON_FEATURE_GENERATOR_GRAMMAR_HPP
#define MAPNIK_JSON_FEATURE_GENERATOR_GRAMMAR_HPP
// mapnik
#include <mapnik/global.hpp>
#include <mapnik/feature.hpp>
#include <mapnik/json/geometry_generator_grammar.hpp>
#include <mapnik/feature_kv_iterator.hpp>
// boost
#include <boost/spirit/include/karma.hpp>
#include <boost/spirit/include/phoenix.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/phoenix_fusion.hpp>
#include <boost/spirit/include/phoenix_function.hpp>
#include <boost/fusion/include/boost_tuple.hpp>
#include <boost/fusion/include/at.hpp>
#include <boost/fusion/include/cons.hpp>
namespace boost { namespace spirit { namespace traits {
template <>
struct is_container<mapnik::Feature const> : mpl::false_ {} ;
template <>
struct container_iterator<mapnik::Feature const>
{
typedef mapnik::feature_kv_iterator2 type;
};
template <>
struct begin_container<mapnik::Feature const>
{
static mapnik::feature_kv_iterator2
call (mapnik::Feature const& f)
{
return mapnik::feature_kv_iterator2(mapnik::value_not_null(),f.begin(),f.end());
}
};
template <>
struct end_container<mapnik::Feature const>
{
static mapnik::feature_kv_iterator2
call (mapnik::Feature const& f)
{
return mapnik::feature_kv_iterator2(mapnik::value_not_null(),f.end(),f.end());
}
};
template <>
struct transform_attribute<const boost::fusion::cons<mapnik::feature_impl const&, boost::fusion::nil>,
mapnik::geometry_container const& ,karma::domain>
{
typedef mapnik::geometry_container const& type;
static type pre(const boost::fusion::cons<mapnik::feature_impl const&, boost::fusion::nil>& f)
{
return boost::fusion::at<mpl::int_<0> >(f).paths();
}
};
}}}
namespace mapnik { namespace json {
namespace karma = boost::spirit::karma;
namespace phoenix = boost::phoenix;
struct get_id
{
template <typename T>
struct result { typedef int type; };
int operator() (mapnik::Feature const& f) const
{
return f.id();
}
};
struct make_properties_range
{
typedef boost::iterator_range<mapnik::feature_kv_iterator> properties_range_type;
template <typename T>
struct result { typedef properties_range_type type; };
properties_range_type operator() (mapnik::Feature const& f) const
{
return boost::make_iterator_range(f.begin(),f.end());
}
};
struct utf8
{
template <typename T>
struct result { typedef std::string type; };
std::string operator() (UnicodeString const& ustr) const
{
std::string result;
to_utf8(ustr,result);
return result;
}
};
struct value_base
{
template <typename T>
struct result { typedef mapnik::value_base const& type; };
mapnik::value_base const& operator() (mapnik::value const& val) const
{
return val.base();
}
};
template <typename OutputIterator>
struct escaped_string
: karma::grammar<OutputIterator, std::string(char const*)>
{
escaped_string()
: escaped_string::base_type(esc_str)
{
using boost::spirit::karma::maxwidth;
using boost::spirit::karma::right_align;
esc_char.add('\a', "\\a")('\b', "\\b")('\f', "\\f")('\n', "\\n")
('\r', "\\r")('\t', "\\t")('\v', "\\v")('\\', "\\\\")
('\'', "\\\'")('\"', "\\\"")
;
esc_str = karma::lit(karma::_r1)
<< *(esc_char
| karma::print
| "\\u" << right_align(4,karma::lit('0'))[karma::hex])
<< karma::lit(karma::_r1)
;
}
karma::rule<OutputIterator, std::string(char const*)> esc_str;
karma::symbols<char, char const*> esc_char;
};
template <typename OutputIterator>
struct feature_generator_grammar:
karma::grammar<OutputIterator, mapnik::Feature const&()>
{
typedef boost::tuple<std::string, mapnik::value> pair_type;
typedef make_properties_range::properties_range_type range_type;
feature_generator_grammar()
: feature_generator_grammar::base_type(feature)
, quote_("\"")
{
using boost::spirit::karma::lit;
using boost::spirit::karma::uint_;
using boost::spirit::karma::bool_;
using boost::spirit::karma::int_;
using boost::spirit::karma::double_;
using boost::spirit::karma::_val;
using boost::spirit::karma::_1;
using boost::spirit::karma::_r1;
using boost::spirit::karma::string;
using boost::spirit::karma::eps;
feature = lit("{\"type\":\"Feature\",\"id\":")
<< uint_[_1 = id_(_val)]
<< lit(",\"geometry\":") << geometry
<< lit(",\"properties\":") << properties
<< lit('}')
;
properties = lit('{')
<< pair % lit(',')
<< lit('}')
;
pair = lit('"')
<< string[_1 = phoenix::at_c<0>(_val)] << lit('"')
<< lit(':')
<< value(phoenix::at_c<1>(_val))
;
value = (value_null_| bool_ | int_| double_ | ustring)[_1 = value_base_(_r1)]
;
value_null_ = string[_1 = "null"]
;
ustring = escaped_string_(quote_.c_str())[_1 = utf8_(_val)]
;
}
// rules
karma::rule<OutputIterator, mapnik::Feature const&()> feature;
multi_geometry_generator_grammar<OutputIterator> geometry;
escaped_string<OutputIterator> escaped_string_;
karma::rule<OutputIterator, mapnik::Feature const&()> properties;
karma::rule<OutputIterator, pair_type()> pair;
karma::rule<OutputIterator, void(mapnik::value const&)> value;
karma::rule<OutputIterator, mapnik::value_null()> value_null_;
karma::rule<OutputIterator, UnicodeString()> ustring;
// phoenix functions
phoenix::function<get_id> id_;
phoenix::function<value_base> value_base_;
phoenix::function<utf8> utf8_;
std::string quote_;
};
}}
#endif // MAPNIK_JSON_FEATURE_GENERATOR_GRAMMAR_HPP
<commit_msg>+ geojson generator : allow empty properties<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2012 Artem Pavlenko
*
* 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
*
*****************************************************************************/
#ifndef MAPNIK_JSON_FEATURE_GENERATOR_GRAMMAR_HPP
#define MAPNIK_JSON_FEATURE_GENERATOR_GRAMMAR_HPP
// mapnik
#include <mapnik/global.hpp>
#include <mapnik/feature.hpp>
#include <mapnik/json/geometry_generator_grammar.hpp>
#include <mapnik/feature_kv_iterator.hpp>
// boost
#include <boost/spirit/include/karma.hpp>
#include <boost/spirit/include/phoenix.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/phoenix_fusion.hpp>
#include <boost/spirit/include/phoenix_function.hpp>
#include <boost/fusion/include/boost_tuple.hpp>
#include <boost/fusion/include/at.hpp>
#include <boost/fusion/include/cons.hpp>
namespace boost { namespace spirit { namespace traits {
template <>
struct is_container<mapnik::Feature const> : mpl::false_ {} ;
template <>
struct container_iterator<mapnik::Feature const>
{
typedef mapnik::feature_kv_iterator2 type;
};
template <>
struct begin_container<mapnik::Feature const>
{
static mapnik::feature_kv_iterator2
call (mapnik::Feature const& f)
{
return mapnik::feature_kv_iterator2(mapnik::value_not_null(),f.begin(),f.end());
}
};
template <>
struct end_container<mapnik::Feature const>
{
static mapnik::feature_kv_iterator2
call (mapnik::Feature const& f)
{
return mapnik::feature_kv_iterator2(mapnik::value_not_null(),f.end(),f.end());
}
};
template <>
struct transform_attribute<const boost::fusion::cons<mapnik::feature_impl const&, boost::fusion::nil>,
mapnik::geometry_container const& ,karma::domain>
{
typedef mapnik::geometry_container const& type;
static type pre(const boost::fusion::cons<mapnik::feature_impl const&, boost::fusion::nil>& f)
{
return boost::fusion::at<mpl::int_<0> >(f).paths();
}
};
}}}
namespace mapnik { namespace json {
namespace karma = boost::spirit::karma;
namespace phoenix = boost::phoenix;
struct get_id
{
template <typename T>
struct result { typedef int type; };
int operator() (mapnik::Feature const& f) const
{
return f.id();
}
};
struct make_properties_range
{
typedef boost::iterator_range<mapnik::feature_kv_iterator> properties_range_type;
template <typename T>
struct result { typedef properties_range_type type; };
properties_range_type operator() (mapnik::Feature const& f) const
{
return boost::make_iterator_range(f.begin(),f.end());
}
};
struct utf8
{
template <typename T>
struct result { typedef std::string type; };
std::string operator() (UnicodeString const& ustr) const
{
std::string result;
to_utf8(ustr,result);
return result;
}
};
struct value_base
{
template <typename T>
struct result { typedef mapnik::value_base const& type; };
mapnik::value_base const& operator() (mapnik::value const& val) const
{
return val.base();
}
};
template <typename OutputIterator>
struct escaped_string
: karma::grammar<OutputIterator, std::string(char const*)>
{
escaped_string()
: escaped_string::base_type(esc_str)
{
using boost::spirit::karma::maxwidth;
using boost::spirit::karma::right_align;
esc_char.add('\a', "\\a")('\b', "\\b")('\f', "\\f")('\n', "\\n")
('\r', "\\r")('\t', "\\t")('\v', "\\v")('\\', "\\\\")
('\'', "\\\'")('\"', "\\\"")
;
esc_str = karma::lit(karma::_r1)
<< *(esc_char
| karma::print
| "\\u" << right_align(4,karma::lit('0'))[karma::hex])
<< karma::lit(karma::_r1)
;
}
karma::rule<OutputIterator, std::string(char const*)> esc_str;
karma::symbols<char, char const*> esc_char;
};
template <typename OutputIterator>
struct feature_generator_grammar:
karma::grammar<OutputIterator, mapnik::Feature const&()>
{
typedef boost::tuple<std::string, mapnik::value> pair_type;
typedef make_properties_range::properties_range_type range_type;
feature_generator_grammar()
: feature_generator_grammar::base_type(feature)
, quote_("\"")
{
using boost::spirit::karma::lit;
using boost::spirit::karma::uint_;
using boost::spirit::karma::bool_;
using boost::spirit::karma::int_;
using boost::spirit::karma::double_;
using boost::spirit::karma::_val;
using boost::spirit::karma::_1;
using boost::spirit::karma::_r1;
using boost::spirit::karma::string;
using boost::spirit::karma::eps;
feature = lit("{\"type\":\"Feature\",\"id\":")
<< uint_[_1 = id_(_val)]
<< lit(",\"geometry\":") << geometry
<< lit(",\"properties\":") << properties
<< lit('}')
;
properties = lit('{')
<< -(pair % lit(','))
<< lit('}')
;
pair = lit('"')
<< string[_1 = phoenix::at_c<0>(_val)] << lit('"')
<< lit(':')
<< value(phoenix::at_c<1>(_val))
;
value = (value_null_| bool_ | int_| double_ | ustring)[_1 = value_base_(_r1)]
;
value_null_ = string[_1 = "null"]
;
ustring = escaped_string_(quote_.c_str())[_1 = utf8_(_val)]
;
}
// rules
karma::rule<OutputIterator, mapnik::Feature const&()> feature;
multi_geometry_generator_grammar<OutputIterator> geometry;
escaped_string<OutputIterator> escaped_string_;
karma::rule<OutputIterator, mapnik::Feature const&()> properties;
karma::rule<OutputIterator, pair_type()> pair;
karma::rule<OutputIterator, void(mapnik::value const&)> value;
karma::rule<OutputIterator, mapnik::value_null()> value_null_;
karma::rule<OutputIterator, UnicodeString()> ustring;
// phoenix functions
phoenix::function<get_id> id_;
phoenix::function<value_base> value_base_;
phoenix::function<utf8> utf8_;
std::string quote_;
};
}}
#endif // MAPNIK_JSON_FEATURE_GENERATOR_GRAMMAR_HPP
<|endoftext|> |
<commit_before>// Important do not use this FilterTask for final Filtered AOD productions!
// Due to the variability of the used config file, it is to easy to loose track of the used settings!
AliAnalysisTask *AddTask_pdill_JPsiFilter_PbPb(
TString cfg="ConfigJpsi_nano_PbPb2015.C",
Bool_t gridconf=kFALSE,
TString period="",
Bool_t storeLS = kFALSE,
Bool_t hasMC_aod = kFALSE,
ULong64_t triggers=AliVEvent::kMB+AliVEvent::kCentral+AliVEvent::kSemiCentral+AliVEvent::kEMCEGA+AliVEvent::kEMCEJE
){
//get the current analysis manager
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
Error("AddTaskJPSIFilter", "No analysis manager found.");
return 0;
}
//check for output aod handler
if (!mgr->GetOutputEventHandler()||mgr->GetOutputEventHandler()->IsA()!=AliAODHandler::Class()) {
Warning("AddTaskJPSIFilter","No AOD output handler available. Not adding the task!");
return 0;
}
//Do we have an MC handler?
Bool_t hasMC=(AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler()!=0x0)||hasMC_aod;
//Do we run on AOD?
Bool_t isAOD=mgr->GetInputEventHandler()->IsA()==AliAODInputHandler::Class();
//Allow merging of the filtered aods on grid trains
if(mgr->GetGridHandler()) {
printf(" SET MERGE FILTERED AODs \n");
//mgr->GetGridHandler()->SetMergeAOD(kTRUE);
}
TString configFile("");
printf("pwd: %s \n",gSystem->pwd());
if(cfg.IsNull()) cfg="ConfigJpsi_nano_PbPb2015.C";
TString alienPath("alien:///alice/cern.ch/user/p/pdillens/PWGDQ/dielectron/macrosJPSI/");
TString alirootPath("$ALICE_PHYSICS/PWGDQ/dielectron/macrosJPSI/");
////////// >>>>>>>>>> alien config
if(gridconf) {
if(!gSystem->Exec(Form("alien_cp %s/%s .",alienPath.Data(),cfg.Data()))) {
gSystem->Exec(Form("ls -l %s",gSystem->pwd()));
configFile=gSystem->pwd();
}
else {
printf("ERROR: couldn't copy file %s/%s from grid \n", alienPath.Data(),cfg.Data() );
return;
}
}
///////// >>>>>>>>> aliroot config
else if(!gridconf) configFile=alirootPath.Data();
///////// add config to path
configFile+="/";
configFile+=cfg.Data();
//load dielectron configuration file (only once)
TString checkconfig="ConfigJpsi_nano_PbPb2015";
if (!gROOT->GetListOfGlobalFunctions()->FindObject(checkconfig.Data()))
gROOT->LoadMacro(configFile.Data());
AliDielectron *jpsi=ConfigJpsi_nano_PbPb2015(0,hasMC,period);
if(isAOD) {
//add options to AliAODHandler to duplicate input event
AliAODHandler *aodHandler = (AliAODHandler*)mgr->GetOutputEventHandler();
aodHandler->SetCreateNonStandardAOD();
aodHandler->SetNeedsHeaderReplication();
if(!period.Contains("LHC10h")) aodHandler->SetNeedsTOFHeaderReplication();
aodHandler->SetNeedsVZEROReplication();
/*aodHandler->SetNeedsTracksBranchReplication();
aodHandler->SetNeedsCaloClustersBranchReplication();
aodHandler->SetNeedsVerticesBranchReplication();
aodHandler->SetNeedsCascadesBranchReplication();
aodHandler->SetNeedsTrackletsBranchReplication();
aodHandler->SetNeedsPMDClustersBranchReplication();
aodHandler->SetNeedsJetsBranchReplication();
aodHandler->SetNeedsFMDClustersBranchReplication();
//aodHandler->SetNeedsMCParticlesBranchReplication();
aodHandler->SetNeedsDimuonsBranchReplication();*/
// if(hasMC) aodHandler->SetNeedsV0sBranchReplication();
if(hasMC) aodHandler->SetNeedsMCParticlesBranchReplication();
jpsi->SetHasMC(hasMC);
}
//Create task and add it to the analysis manager
AliAnalysisTaskDielectronFilter *task=new AliAnalysisTaskDielectronFilter("jpsi_DielectronFilter");
task->SetTriggerMask(triggers);
// task->SetTriggerMask(AliVEvent::kMB+AliVEvent::kCentral+AliVEvent::kSemiCentral);
if (!hasMC) task->UsePhysicsSelection();
// //Add event filter
// AliDielectronEventCuts *eventCuts=new AliDielectronEventCuts("eventCuts","Vertex Track && |vtxZ|<10 && ncontrib>0");
// if(!hasMC) eventCuts->SetRequireVertex();
// if (isAOD) eventCuts->SetVertexType(AliDielectronEventCuts::kVtxAny);
// eventCuts->SetMinVtxContributors(1);
// eventCuts->SetVertexZ(-10.,10.);
// eventCuts->SetCentralityRange(0.0,90.0);
// task->SetEventFilter(eventCuts);
task->SetDielectron(jpsi);
if(storeLS) task->SetStoreLikeSignCandidates(storeLS);
task->SetCreateNanoAODs(kTRUE);
task->SetStoreEventsWithSingleTracks(kTRUE);
//task->SetStoreHeader(kTRUE);
mgr->AddTask(task);
//----------------------
//create data containers
//----------------------
TString containerName = mgr->GetCommonFileName();
containerName += ":PWGDQ_dielectronFilter";
//create output container
AliAnalysisDataContainer *cOutputHist1 =
mgr->CreateContainer("jpsi_FilterQA",
THashList::Class(),
AliAnalysisManager::kOutputContainer,
containerName.Data());
AliAnalysisDataContainer *cOutputHist2 =
mgr->CreateContainer("jpsi_FilterEventStat",
TH1D::Class(),
AliAnalysisManager::kOutputContainer,
containerName.Data());
mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
mgr->ConnectOutput(task, 0, mgr->GetCommonOutputContainer());
mgr->ConnectOutput(task, 1, cOutputHist1);
mgr->ConnectOutput(task, 2, cOutputHist2);
return task;
}
<commit_msg>DQ update PbPb filter AddTask<commit_after>// Important do not use this FilterTask for final Filtered AOD productions!
// Due to the variability of the used config file, it is to easy to loose track of the used settings!
AliAnalysisTask *AddTask_pdill_JPsiFilter_PbPb(
TString cfg="ConfigJpsi_nano_PbPb2015.C",
Bool_t gridconf=kFALSE,
TString period="",
Bool_t storeLS = kFALSE,
Bool_t hasMC_aod = kFALSE,
ULong64_t triggers = AliVEvent::kMB+AliVEvent::kCentral+AliVEvent::kSemiCentral+AliVEvent::kEMCEGA+AliVEvent::kEMCEJE
){
//get the current analysis manager
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
Error("AddTaskJPSIFilter", "No analysis manager found.");
return 0;
}
//check for output aod handler
if (!mgr->GetOutputEventHandler()||mgr->GetOutputEventHandler()->IsA()!=AliAODHandler::Class()) {
Warning("AddTaskJPSIFilter","No AOD output handler available. Not adding the task!");
return 0;
}
//Do we have an MC handler?
Bool_t hasMC=(AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler()!=0x0)||hasMC_aod;
//Do we run on AOD?
Bool_t isAOD=mgr->GetInputEventHandler()->IsA()==AliAODInputHandler::Class();
//Allow merging of the filtered aods on grid trains
if(mgr->GetGridHandler()) {
printf(" SET MERGE FILTERED AODs \n");
//mgr->GetGridHandler()->SetMergeAOD(kTRUE);
}
TString configFile("");
printf("pwd: %s \n",gSystem->pwd());
if(cfg.IsNull()) cfg="ConfigJpsi_nano_PbPb2015.C";
TString alienPath("alien:///alice/cern.ch/user/p/pdillens/PWGDQ/dielectron/macrosJPSI/");
TString alirootPath("$ALICE_PHYSICS/PWGDQ/dielectron/macrosJPSI/");
////////// >>>>>>>>>> alien config
if(gridconf) {
if(!gSystem->Exec(Form("alien_cp %s/%s .",alienPath.Data(),cfg.Data()))) {
gSystem->Exec(Form("ls -l %s",gSystem->pwd()));
configFile=gSystem->pwd();
}
else {
printf("ERROR: couldn't copy file %s/%s from grid \n", alienPath.Data(),cfg.Data() );
return;
}
}
///////// >>>>>>>>> aliroot config
else if(!gridconf) configFile=alirootPath.Data();
///////// add config to path
//configFile+="/";
configFile+=cfg.Data();
//load dielectron configuration file (only once)
TString checkconfig="ConfigJpsi_nano_PbPb2015";
if (!gROOT->GetListOfGlobalFunctions()->FindObject(checkconfig.Data()))
gROOT->LoadMacro(configFile.Data());
printf("%s \n",configFile.Data());
AliDielectron *jpsi=ConfigJpsi_nano_PbPb2015(0,hasMC,period);
if(isAOD) {
//add options to AliAODHandler to duplicate input event
AliAODHandler *aodHandler = (AliAODHandler*)mgr->GetOutputEventHandler();
aodHandler->SetCreateNonStandardAOD();
aodHandler->SetNeedsHeaderReplication();
if(!period.Contains("LHC10h")) aodHandler->SetNeedsTOFHeaderReplication();
aodHandler->SetNeedsVZEROReplication();
// aodHandler->SetNeedsTracksBranchReplication();
// aodHandler->SetNeedsCaloClustersBranchReplication();
// aodHandler->SetNeedsVerticesBranchReplication();
// aodHandler->SetNeedsCascadesBranchReplication();
// aodHandler->SetNeedsTrackletsBranchReplication();
// aodHandler->SetNeedsPMDClustersBranchReplication();
// aodHandler->SetNeedsJetsBranchReplication();
// aodHandler->SetNeedsFMDClustersBranchReplication();
// aodHandler->SetNeedsMCParticlesBranchReplication();
// aodHandler->SetNeedsDimuonsBranchReplication();
if(hasMC) aodHandler->SetNeedsV0sBranchReplication();
if(hasMC) aodHandler->SetNeedsMCParticlesBranchReplication();
jpsi->SetHasMC(hasMC);
}
//Create task and add it to the analysis manager
AliAnalysisTaskDielectronFilter *task=new AliAnalysisTaskDielectronFilter("jpsi_DielectronFilter");
task->SetTriggerMask(triggers);
// task->SetTriggerMask(AliVEvent::kMB+AliVEvent::kCentral+AliVEvent::kSemiCentral);
if (!hasMC) task->UsePhysicsSelection();
// //Add event filter
// AliDielectronEventCuts *eventCuts=new AliDielectronEventCuts("eventCuts","Vertex Track && |vtxZ|<10 && ncontrib>0");
// if(!hasMC) eventCuts->SetRequireVertex();
// if (isAOD) eventCuts->SetVertexType(AliDielectronEventCuts::kVtxAny);
// eventCuts->SetMinVtxContributors(1);
// eventCuts->SetVertexZ(-10.,10.);
// eventCuts->SetCentralityRange(0.0,90.0);
// task->SetEventFilter(eventCuts);
task->SetDielectron(jpsi);
if(storeLS) task->SetStoreLikeSignCandidates(storeLS);
task->SetCreateNanoAODs(kTRUE);
task->SetStoreEventsWithSingleTracks(kTRUE);
task->SetStoreHeader(kTRUE);
task->SetStoreEventplanes(kTRUE);
mgr->AddTask(task);
//----------------------
//create data containers
//----------------------
TString containerName = mgr->GetCommonFileName();
containerName += ":PWGDQ_dielectronFilter";
//create output container
AliAnalysisDataContainer *cOutputHist1 =
mgr->CreateContainer("jpsi_FilterQA",
THashList::Class(),
AliAnalysisManager::kOutputContainer,
containerName.Data());
AliAnalysisDataContainer *cOutputHist2 =
mgr->CreateContainer("jpsi_FilterEventStat",
TH1D::Class(),
AliAnalysisManager::kOutputContainer,
containerName.Data());
mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
mgr->ConnectOutput(task, 0, mgr->GetCommonOutputContainer());
mgr->ConnectOutput(task, 1, cOutputHist1);
mgr->ConnectOutput(task, 2, cOutputHist2);
return task;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: objshimp.hxx,v $
*
* $Revision: 1.39 $
*
* last change: $Author: ihi $ $Date: 2007-11-21 16:50:10 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _SFX_OBJSHIMP_HXX
#define _SFX_OBJSHIMP_HXX
//#include <hash_map>
#ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_
#include <com/sun/star/frame/XModel.hpp>
#endif
#ifndef _DATETIME_HXX
#include <tools/datetime.hxx>
#endif
#include <svtools/securityoptions.hxx>
#include <sfx2/objsh.hxx>
#include "sfx2/docmacromode.hxx"
#include "bitset.hxx"
namespace svtools { class AsynchronLink; }
//====================================================================
DBG_NAMEEX(SfxObjectShell)
class SfxViewFrame;
struct MarkData_Impl
{
String aMark;
String aUserData;
SfxViewFrame* pFrame;
};
class SfxFrame;
class SfxToolBoxConfig;
class SfxAcceleratorManager;
class SfxBasicManagerHolder;
struct SfxObjectShell_Impl : public ::sfx2::IMacroDocumentAccess
{
::comphelper::EmbeddedObjectContainer* mpObjectContainer;
SfxAcceleratorManager* pAccMgr;
SfxDocumentInfo* pDocInfo;
SfxConfigManager* pCfgMgr;
SfxBasicManagerHolder*
pBasicManager;
SfxObjectShell& rDocShell;
::com::sun::star::uno::Reference< ::com::sun::star::script::XLibraryContainer >
xBasicLibraries;
::com::sun::star::uno::Reference< ::com::sun::star::script::XLibraryContainer >
xDialogLibraries;
::sfx2::DocumentMacroMode
aMacroMode;
SfxProgress* pProgress;
String aTitle;
String aTempName;
DateTime nTime;
sal_uInt16 nVisualDocumentNumber;
sal_Int16 nDocumentSignatureState;
sal_Int16 nScriptingSignatureState;
sal_Bool bTemplateConfig:1,
bInList:1, // ob per First/Next erreichbar
bClosing:1, // sal_True w"aehrend Close(), um Benachrichtigungs-Rekursionen zu verhindern
bSetInPlaceObj:1, // sal_True, falls bereits versucht wurde pInPlaceObject zu casten
bIsSaving:1,
bPasswd:1,
bIsTmp:1,
bIsNamedVisible:1,
bIsTemplate:1,
bIsAbortingImport:1, // Importvorgang soll abgebrochen werden.
bImportDone : 1, //Import schon fertig? Fuer AutoReload von Docs.
bInPrepareClose : 1,
bPreparedForClose : 1,
bWaitingForPicklist : 1,// Muss noch in die Pickliste
bModuleSearched : 1,
bIsBasicDefault : 1,
bIsHelpObjSh : 1,
bForbidCaching : 1,
bForbidReload : 1,
bSupportsEventMacros: 1,
bLoadingWindows: 1,
bBasicInitialized :1,
//bHidden :1, // indicates a hidden view shell
bIsPrintJobCancelable :1, // Stampit disable/enable cancel button for print jobs ... default = true = enable!
bOwnsStorage:1,
bNoBaseURL:1,
bInitialized:1,
bSignatureErrorIsShown:1,
bModelInitialized:1, // whether the related model is initialized
bPreserveVersions:1,
m_bMacroSignBroken:1, // whether the macro signature was explicitly broken
m_bNoBasicCapabilities:1,
bQueryLoadTemplate:1,
bLoadReadonly:1,
bUseUserData:1,
bSaveVersionOnClose:1;
String aNewName; // Der Name, unter dem das Doc gespeichert
// werden soll
IndexBitSet aBitSet;
sal_uInt32 lErr;
sal_uInt16 nEventId; // falls vor Activate noch ein
// Open/Create gesendet werden mu/s
sal_Bool bDoNotTouchDocInfo;
AutoReloadTimer_Impl *pReloadTimer;
MarkData_Impl* pMarkData;
sal_uInt16 nLoadedFlags;
sal_uInt16 nFlagsInProgress;
String aMark;
Size aViewSize; // wird leider vom Writer beim
sal_Bool bInFrame; // HTML-Import gebraucht
sal_Bool bModalMode;
sal_Bool bRunningMacro;
sal_Bool bReloadAvailable;
sal_uInt16 nAutoLoadLocks;
SfxModule* pModule;
SfxFrame* pFrame;
SfxToolBoxConfig* pTbxConfig;
SfxEventConfigItem_Impl* pEventConfig;
SfxObjectShellFlags eFlags;
svtools::AsynchronLink* pCloser;
String aBaseURL;
sal_Bool bReadOnlyUI;
SvRefBaseRef xHeaderAttributes;
sal_Bool bHiddenLockedByAPI;
sal_Bool bInCloseEvent;
::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel > xModel;
sal_uInt16 nStyleFilter;
sal_Bool bDisposing;
sal_Bool m_bEnableSetModified;
sal_Bool m_bIsModified;
Rectangle m_aVisArea;
MapUnit m_nMapUnit;
sal_Bool m_bCreateTempStor;
::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage > m_xDocStorage;
sal_Bool m_bIsInit;
SfxObjectShell_Impl( SfxObjectShell& _rDocShell );
virtual ~SfxObjectShell_Impl();
// IMacroDocumentAccess overridables
virtual sal_Int16 getImposedMacroExecMode() const;
virtual ::rtl::OUString getDocumentLocation() const;
virtual ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage > getLastCommitDocumentStorage();
virtual bool documentStorageHasMacros() const;
virtual ::com::sun::star::uno::Reference< ::com::sun::star::document::XEmbeddedScripts > getEmbeddedDocumentScripts() const;
virtual sal_Int16 getScriptingSignatureState() const;
virtual void showBrokenSignatureWarning( const ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionHandler >& _rxInteraction ) const;
};
#endif
<commit_msg>INTEGRATION: CWS fwk80_SRC680 (1.39.16); FILE MERGED 2008/01/02 12:28:23 mav 1.39.16.1: #i84941# to handle the macro execution mode use MediaDescriptor only<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: objshimp.hxx,v $
*
* $Revision: 1.40 $
*
* last change: $Author: rt $ $Date: 2008-01-29 15:29:37 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _SFX_OBJSHIMP_HXX
#define _SFX_OBJSHIMP_HXX
//#include <hash_map>
#ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_
#include <com/sun/star/frame/XModel.hpp>
#endif
#ifndef _DATETIME_HXX
#include <tools/datetime.hxx>
#endif
#include <svtools/securityoptions.hxx>
#include <sfx2/objsh.hxx>
#include "sfx2/docmacromode.hxx"
#include "bitset.hxx"
namespace svtools { class AsynchronLink; }
//====================================================================
DBG_NAMEEX(SfxObjectShell)
class SfxViewFrame;
struct MarkData_Impl
{
String aMark;
String aUserData;
SfxViewFrame* pFrame;
};
class SfxFrame;
class SfxToolBoxConfig;
class SfxAcceleratorManager;
class SfxBasicManagerHolder;
struct SfxObjectShell_Impl : public ::sfx2::IMacroDocumentAccess
{
::comphelper::EmbeddedObjectContainer* mpObjectContainer;
SfxAcceleratorManager* pAccMgr;
SfxDocumentInfo* pDocInfo;
SfxConfigManager* pCfgMgr;
SfxBasicManagerHolder*
pBasicManager;
SfxObjectShell& rDocShell;
::com::sun::star::uno::Reference< ::com::sun::star::script::XLibraryContainer >
xBasicLibraries;
::com::sun::star::uno::Reference< ::com::sun::star::script::XLibraryContainer >
xDialogLibraries;
::sfx2::DocumentMacroMode
aMacroMode;
SfxProgress* pProgress;
String aTitle;
String aTempName;
DateTime nTime;
sal_uInt16 nVisualDocumentNumber;
sal_Int16 nDocumentSignatureState;
sal_Int16 nScriptingSignatureState;
sal_Bool bTemplateConfig:1,
bInList:1, // ob per First/Next erreichbar
bClosing:1, // sal_True w"aehrend Close(), um Benachrichtigungs-Rekursionen zu verhindern
bSetInPlaceObj:1, // sal_True, falls bereits versucht wurde pInPlaceObject zu casten
bIsSaving:1,
bPasswd:1,
bIsTmp:1,
bIsNamedVisible:1,
bIsTemplate:1,
bIsAbortingImport:1, // Importvorgang soll abgebrochen werden.
bImportDone : 1, //Import schon fertig? Fuer AutoReload von Docs.
bInPrepareClose : 1,
bPreparedForClose : 1,
bWaitingForPicklist : 1,// Muss noch in die Pickliste
bModuleSearched : 1,
bIsBasicDefault : 1,
bIsHelpObjSh : 1,
bForbidCaching : 1,
bForbidReload : 1,
bSupportsEventMacros: 1,
bLoadingWindows: 1,
bBasicInitialized :1,
//bHidden :1, // indicates a hidden view shell
bIsPrintJobCancelable :1, // Stampit disable/enable cancel button for print jobs ... default = true = enable!
bOwnsStorage:1,
bNoBaseURL:1,
bInitialized:1,
bSignatureErrorIsShown:1,
bModelInitialized:1, // whether the related model is initialized
bPreserveVersions:1,
m_bMacroSignBroken:1, // whether the macro signature was explicitly broken
m_bNoBasicCapabilities:1,
bQueryLoadTemplate:1,
bLoadReadonly:1,
bUseUserData:1,
bSaveVersionOnClose:1;
String aNewName; // Der Name, unter dem das Doc gespeichert
// werden soll
IndexBitSet aBitSet;
sal_uInt32 lErr;
sal_uInt16 nEventId; // falls vor Activate noch ein
// Open/Create gesendet werden mu/s
sal_Bool bDoNotTouchDocInfo;
AutoReloadTimer_Impl *pReloadTimer;
MarkData_Impl* pMarkData;
sal_uInt16 nLoadedFlags;
sal_uInt16 nFlagsInProgress;
String aMark;
Size aViewSize; // wird leider vom Writer beim
sal_Bool bInFrame; // HTML-Import gebraucht
sal_Bool bModalMode;
sal_Bool bRunningMacro;
sal_Bool bReloadAvailable;
sal_uInt16 nAutoLoadLocks;
SfxModule* pModule;
SfxFrame* pFrame;
SfxToolBoxConfig* pTbxConfig;
SfxEventConfigItem_Impl* pEventConfig;
SfxObjectShellFlags eFlags;
svtools::AsynchronLink* pCloser;
String aBaseURL;
sal_Bool bReadOnlyUI;
SvRefBaseRef xHeaderAttributes;
sal_Bool bHiddenLockedByAPI;
sal_Bool bInCloseEvent;
::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel > xModel;
sal_uInt16 nStyleFilter;
sal_Bool bDisposing;
sal_Bool m_bEnableSetModified;
sal_Bool m_bIsModified;
Rectangle m_aVisArea;
MapUnit m_nMapUnit;
sal_Bool m_bCreateTempStor;
::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage > m_xDocStorage;
sal_Bool m_bIsInit;
SfxObjectShell_Impl( SfxObjectShell& _rDocShell );
virtual ~SfxObjectShell_Impl();
// IMacroDocumentAccess overridables
virtual sal_Int16 getImposedMacroExecMode() const;
virtual sal_Bool setImposedMacroExecMode( sal_uInt16 nMacroMode );
virtual ::rtl::OUString getDocumentLocation() const;
virtual ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage > getLastCommitDocumentStorage();
virtual sal_Bool documentStorageHasMacros() const;
virtual ::com::sun::star::uno::Reference< ::com::sun::star::document::XEmbeddedScripts > getEmbeddedDocumentScripts() const;
virtual sal_Int16 getScriptingSignatureState() const;
virtual void showBrokenSignatureWarning( const ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionHandler >& _rxInteraction ) const;
};
#endif
<|endoftext|> |
<commit_before>/////////////////////////////////////////////////////////////////
/*
* Template of a read routine
*/
/////////////////////////////////////////////////////////////////
#include <NrrdIO/NrrdIOAPI.h>
#include <hxfield/HxUniformScalarField3.h>
#include <Amira/HxMessage.h>
#include <teem/nrrd.h>
NRRDIO_API
int NrrdReader(const char* filename)
{
Nrrd *nrrd = nrrdNew();
if ( nrrdLoad( nrrd, filename, NULL ) )
throw biffGetDone(NRRD);
if ( nrrd->dim > 3 )
{
theMsg->printf("ERROR: for now, nrrd input can only handle data with dimension 3 or less.");
return 0;
}
const int dims[3] =
{
(nrrd->dim > 0) ? nrrd->axis[0].size : 1,
(nrrd->dim > 1) ? nrrd->axis[1].size : 1,
(nrrd->dim > 2) ? nrrd->axis[2].size : 1
};
HxUniformScalarField3* field = NULL;
switch ( nrrd->type )
{
case nrrdTypeUChar: field = new HxUniformScalarField3(dims,MC_UINT8,nrrd->data); break;
case nrrdTypeChar: field = new HxUniformScalarField3(dims,MC_INT8,nrrd->data); break;
case nrrdTypeUShort: field = new HxUniformScalarField3(dims,MC_UINT16,nrrd->data); break;
case nrrdTypeShort: field = new HxUniformScalarField3(dims,MC_INT16,nrrd->data); break;
case nrrdTypeInt: field = new HxUniformScalarField3(dims,MC_INT32,nrrd->data); break;
case nrrdTypeFloat: field = new HxUniformScalarField3(dims,MC_FLOAT,nrrd->data); break;
case nrrdTypeDouble: field = new HxUniformScalarField3(dims,MC_DOUBLE,nrrd->data); break;
default: break;
}
if(field == NULL)
{
theMsg->printf("ERROR: unknown nrrd input type.");
return 0;
}
// Shouldn't need to check for data loading
HxData::registerData(field, filename);
return 1;
}
<commit_msg>Correctly loads voxel dimensions from nrrd data<commit_after>/////////////////////////////////////////////////////////////////
/*
* Template of a read routine
*/
/////////////////////////////////////////////////////////////////
#include <NrrdIO/NrrdIOAPI.h>
#include <hxfield/HxUniformScalarField3.h>
#include <Amira/HxMessage.h>
#include <teem/nrrd.h>
NRRDIO_API
int NrrdReader(const char* filename)
{
Nrrd *nrrd = nrrdNew();
if ( nrrdLoad( nrrd, filename, NULL ) )
throw biffGetDone(NRRD);
if ( nrrd->dim > 3 )
{
theMsg->printf("ERROR: for now, nrrd input can only handle data with dimension 3 or less.");
return 0;
}
const int dims[3] =
{
(nrrd->dim > 0) ? nrrd->axis[0].size : 1,
(nrrd->dim > 1) ? nrrd->axis[1].size : 1,
(nrrd->dim > 2) ? nrrd->axis[2].size : 1
};
HxUniformScalarField3* field = NULL;
switch ( nrrd->type )
{
case nrrdTypeUChar: field = new HxUniformScalarField3(dims,MC_UINT8,nrrd->data); break;
case nrrdTypeChar: field = new HxUniformScalarField3(dims,MC_INT8,nrrd->data); break;
case nrrdTypeUShort: field = new HxUniformScalarField3(dims,MC_UINT16,nrrd->data); break;
case nrrdTypeShort: field = new HxUniformScalarField3(dims,MC_INT16,nrrd->data); break;
case nrrdTypeInt: field = new HxUniformScalarField3(dims,MC_INT32,nrrd->data); break;
case nrrdTypeFloat: field = new HxUniformScalarField3(dims,MC_FLOAT,nrrd->data); break;
case nrrdTypeDouble: field = new HxUniformScalarField3(dims,MC_DOUBLE,nrrd->data); break;
default: break;
}
if(field == NULL)
{
theMsg->printf("ERROR: unknown nrrd input type.");
return 0;
}
// First fetch axis spacing
double spacing[3] = { 1.0, 1.0, 1.0 };
for ( size_t ax = 0; ax < nrrd->dim; ++ax )
{
switch ( nrrdSpacingCalculate( nrrd, ax, spacing+ax, nrrd->axis[ax].spaceDirection ) )
{
case nrrdSpacingStatusScalarNoSpace:
break;
case nrrdSpacingStatusDirection:
break;
case nrrdSpacingStatusScalarWithSpace:
theMsg->printf("WARNING: nrrdSpacingCalculate returned nrrdSpacingStatusScalarWithSpace\n");
spacing[ax] = nrrd->axis[ax].spacing;
break;
case nrrdSpacingStatusNone:
default:
theMsg->printf("WARNING: no pixel spacings in Nrrd for axis %d ; setting to 1.0\n",ax);
spacing[ax] = 1.0;
break;
}
}
// Now let's set the physical dimensions
// This is done by defining the bounding box, the range of the voxel centres
// given in the order: xmin,xmax,ymin ...
float *bbox = field->bbox();
bbox[0] = isnan(nrrd->spaceOrigin[0])?0.0f:(float) nrrd->spaceOrigin[0];
bbox[2] = isnan(nrrd->spaceOrigin[1])?0.0f:(float) nrrd->spaceOrigin[1];
bbox[4] = isnan(nrrd->spaceOrigin[2])?0.0f:(float) nrrd->spaceOrigin[2];
// When a dimension is 1, Amira still seems to have a defined spacing
bbox[1] = bbox[0] + (float) spacing[0] * ( dims[0] == 1 ? 1 : (dims[0] - 1) );
bbox[3] = bbox[2] + (float) spacing[1] * ( dims[1] == 1 ? 1 : (dims[1] - 1) );
bbox[5] = bbox[4] + (float) spacing[2] * ( dims[2] == 1 ? 1 : (dims[2] - 1) );
// Shouldn't need to check for data loading
HxData::registerData(field, filename);
return 1;
}
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "buildsettingspropertiespage.h"
#include "buildstep.h"
#include "buildstepspage.h"
#include "project.h"
#include "target.h"
#include "buildconfiguration.h"
#include <coreplugin/coreconstants.h>
#include <extensionsystem/pluginmanager.h>
#include <utils/qtcassert.h>
#include <QtCore/QMargins>
#include <QtCore/QTimer>
#include <QtCore/QCoreApplication>
#include <QtGui/QComboBox>
#include <QtGui/QInputDialog>
#include <QtGui/QLabel>
#include <QtGui/QMenu>
#include <QtGui/QPushButton>
#include <QtGui/QVBoxLayout>
using namespace ProjectExplorer;
using namespace ProjectExplorer::Internal;
///
// BuildSettingsPanelFactory
///
QString BuildSettingsPanelFactory::id() const
{
return QLatin1String(BUILDSETTINGS_PANEL_ID);
}
QString BuildSettingsPanelFactory::displayName() const
{
return QCoreApplication::translate("BuildSettingsPanelFactory", "Build Settings");
}
bool BuildSettingsPanelFactory::supports(Target *target)
{
return target->buildConfigurationFactory();
}
IPropertiesPanel *BuildSettingsPanelFactory::createPanel(Target *target)
{
return new BuildSettingsPanel(target);
}
///
// BuildSettingsPanel
///
BuildSettingsPanel::BuildSettingsPanel(Target *target) :
m_widget(new BuildSettingsWidget(target)),
m_icon(":/projectexplorer/images/BuildSettings.png")
{
}
BuildSettingsPanel::~BuildSettingsPanel()
{
delete m_widget;
}
QString BuildSettingsPanel::displayName() const
{
return QCoreApplication::translate("BuildSettingsPanel", "Build Settings");
}
QWidget *BuildSettingsPanel::widget() const
{
return m_widget;
}
QIcon BuildSettingsPanel::icon() const
{
return m_icon;
}
///
// BuildSettingsWidget
///
BuildSettingsWidget::~BuildSettingsWidget()
{
clear();
}
BuildSettingsWidget::BuildSettingsWidget(Target *target) :
m_target(target),
m_buildConfiguration(0),
m_leftMargin(0)
{
Q_ASSERT(m_target);
setupUi();
}
void BuildSettingsWidget::setupUi()
{
m_leftMargin = Constants::PANEL_LEFT_MARGIN;
QVBoxLayout *vbox = new QVBoxLayout(this);
vbox->setContentsMargins(0, 0, 0, 0);
if (!m_target->buildConfigurationFactory()) {
QLabel * noSettingsLabel(new QLabel(this));
noSettingsLabel->setText(tr("No Build Settings available"));
{
QFont f(noSettingsLabel->font());
f.setPointSizeF(f.pointSizeF() * 1.2);
noSettingsLabel->setFont(f);
}
vbox->addWidget(noSettingsLabel);
return;
}
{ // Edit Build Configuration row
QHBoxLayout *hbox = new QHBoxLayout();
hbox->setContentsMargins(m_leftMargin, 0, 0, 0);
hbox->addWidget(new QLabel(tr("Edit Build Configuration:"), this));
m_buildConfigurationComboBox = new QComboBox(this);
m_buildConfigurationComboBox->setSizeAdjustPolicy(QComboBox::AdjustToContents);
hbox->addWidget(m_buildConfigurationComboBox);
m_addButton = new QPushButton(this);
m_addButton->setText(tr("Add"));
m_addButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
hbox->addWidget(m_addButton);
m_addButtonMenu = new QMenu(this);
m_addButton->setMenu(m_addButtonMenu);
m_removeButton = new QPushButton(this);
m_removeButton->setText(tr("Remove"));
m_removeButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
hbox->addWidget(m_removeButton);
hbox->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Fixed));
vbox->addLayout(hbox);
}
m_buildConfiguration = m_target->activeBuildConfiguration();
updateAddButtonMenu();
updateBuildSettings();
connect(m_buildConfigurationComboBox, SIGNAL(currentIndexChanged(int)),
this, SLOT(currentIndexChanged(int)));
connect(m_removeButton, SIGNAL(clicked()),
this, SLOT(deleteConfiguration()));
connect(m_target, SIGNAL(activeBuildConfigurationChanged(ProjectExplorer::BuildConfiguration*)),
this, SLOT(updateActiveConfiguration()));
connect(m_target, SIGNAL(addedBuildConfiguration(ProjectExplorer::BuildConfiguration*)),
this, SLOT(addedBuildConfiguration(ProjectExplorer::BuildConfiguration*)));
connect(m_target, SIGNAL(removedBuildConfiguration(ProjectExplorer::BuildConfiguration*)),
this, SLOT(removedBuildConfiguration(ProjectExplorer::BuildConfiguration*)));
foreach (BuildConfiguration *bc, m_target->buildConfigurations()) {
connect(bc, SIGNAL(displayNameChanged()),
this, SLOT(buildConfigurationDisplayNameChanged()));
}
if (m_target->buildConfigurationFactory())
connect(m_target->buildConfigurationFactory(), SIGNAL(availableCreationIdsChanged()),
SLOT(updateAddButtonMenu()));
}
void BuildSettingsWidget::addedBuildConfiguration(BuildConfiguration *bc)
{
connect(bc, SIGNAL(displayNameChanged()),
this, SLOT(buildConfigurationDisplayNameChanged()));
}
void BuildSettingsWidget::removedBuildConfiguration(BuildConfiguration *bc)
{
disconnect(bc, SIGNAL(displayNameChanged()),
this, SLOT(buildConfigurationDisplayNameChanged()));
}
void BuildSettingsWidget::buildConfigurationDisplayNameChanged()
{
for (int i = 0; i < m_buildConfigurationComboBox->count(); ++i) {
BuildConfiguration *bc = m_buildConfigurationComboBox->itemData(i).value<BuildConfiguration *>();
m_buildConfigurationComboBox->setItemText(i, bc->displayName());
}
}
void BuildSettingsWidget::addSubWidget(const QString &name, BuildConfigWidget *widget)
{
widget->setContentsMargins(m_leftMargin, 10, 0, 0);
QLabel *label = new QLabel(this);
label->setText(name);
QFont f = label->font();
f.setBold(true);
f.setPointSizeF(f.pointSizeF() * 1.2);
label->setFont(f);
label->setContentsMargins(m_leftMargin, 10, 0, 0);
layout()->addWidget(label);
layout()->addWidget(widget);
m_labels.append(label);
m_subWidgets.append(widget);
}
void BuildSettingsWidget::clear()
{
qDeleteAll(m_subWidgets);
m_subWidgets.clear();
qDeleteAll(m_labels);
m_labels.clear();
}
QList<BuildConfigWidget *> BuildSettingsWidget::subWidgets() const
{
return m_subWidgets;
}
void BuildSettingsWidget::updateAddButtonMenu()
{
m_addButtonMenu->clear();
if (m_target &&
m_target->activeBuildConfiguration()) {
m_addButtonMenu->addAction(tr("&Clone Selected"),
this, SLOT(cloneConfiguration()));
}
IBuildConfigurationFactory *factory = m_target->buildConfigurationFactory();
if (factory) {
foreach (const QString &id, factory->availableCreationIds(m_target)) {
QAction *action = m_addButtonMenu->addAction(factory->displayNameForId(id), this, SLOT(createConfiguration()));
action->setData(id);
}
}
}
void BuildSettingsWidget::updateBuildSettings()
{
// Delete old tree items
bool blocked = m_buildConfigurationComboBox->blockSignals(true);
m_buildConfigurationComboBox->clear();
clear();
// update buttons
m_removeButton->setEnabled(m_target->buildConfigurations().size() > 1);
// Add pages
BuildConfigWidget *generalConfigWidget = m_target->project()->createConfigWidget();
addSubWidget(generalConfigWidget->displayName(), generalConfigWidget);
addSubWidget(tr("Build Steps"), new BuildStepsPage(m_target, Build));
addSubWidget(tr("Clean Steps"), new BuildStepsPage(m_target, Clean));
QList<BuildConfigWidget *> subConfigWidgets = m_target->project()->subConfigWidgets();
foreach (BuildConfigWidget *subConfigWidget, subConfigWidgets)
addSubWidget(subConfigWidget->displayName(), subConfigWidget);
// Add tree items
foreach (BuildConfiguration *bc, m_target->buildConfigurations()) {
m_buildConfigurationComboBox->addItem(bc->displayName(), QVariant::fromValue<BuildConfiguration *>(bc));
if (bc == m_buildConfiguration)
m_buildConfigurationComboBox->setCurrentIndex(m_buildConfigurationComboBox->count() - 1);
}
foreach (BuildConfigWidget *widget, subWidgets())
widget->init(m_buildConfiguration);
m_buildConfigurationComboBox->blockSignals(blocked);
}
void BuildSettingsWidget::currentIndexChanged(int index)
{
BuildConfiguration *buildConfiguration = m_buildConfigurationComboBox->itemData(index).value<BuildConfiguration *>();
m_target->setActiveBuildConfiguration(buildConfiguration);
}
void BuildSettingsWidget::updateActiveConfiguration()
{
if (!m_buildConfiguration || m_buildConfiguration == m_target->activeBuildConfiguration())
return;
m_buildConfiguration = m_target->activeBuildConfiguration();
for (int i = 0; i < m_buildConfigurationComboBox->count(); ++i) {
if (m_buildConfigurationComboBox->itemData(i).value<BuildConfiguration *>() == m_buildConfiguration) {
m_buildConfigurationComboBox->setCurrentIndex(i);
break;
}
}
foreach (QWidget *widget, subWidgets()) {
if (BuildConfigWidget *buildStepWidget = qobject_cast<BuildConfigWidget*>(widget)) {
buildStepWidget->init(m_buildConfiguration);
}
}
}
void BuildSettingsWidget::createConfiguration()
{
if (!m_target->buildConfigurationFactory())
return;
QAction *action = qobject_cast<QAction *>(sender());
const QString &id = action->data().toString();
BuildConfiguration *bc = m_target->buildConfigurationFactory()->create(m_target, id);
if (bc) {
m_buildConfiguration = bc;
updateBuildSettings();
}
}
void BuildSettingsWidget::cloneConfiguration()
{
cloneConfiguration(m_buildConfiguration);
}
void BuildSettingsWidget::deleteConfiguration()
{
deleteConfiguration(m_buildConfiguration);
}
void BuildSettingsWidget::cloneConfiguration(BuildConfiguration *sourceConfiguration)
{
if (!sourceConfiguration ||
!m_target->buildConfigurationFactory())
return;
QString newDisplayName(QInputDialog::getText(this, tr("Clone configuration"), tr("New Configuration Name:")));
if (newDisplayName.isEmpty())
return;
QStringList buildConfigurationDisplayNames;
foreach(BuildConfiguration *bc, m_target->buildConfigurations())
buildConfigurationDisplayNames << bc->displayName();
newDisplayName = Project::makeUnique(newDisplayName, buildConfigurationDisplayNames);
BuildConfiguration * bc(m_target->buildConfigurationFactory()->clone(m_target, sourceConfiguration));
if (!bc)
return;
m_buildConfiguration = bc;
m_buildConfiguration->setDisplayName(newDisplayName);
m_target->addBuildConfiguration(m_buildConfiguration);
updateBuildSettings();
}
void BuildSettingsWidget::deleteConfiguration(BuildConfiguration *deleteConfiguration)
{
if (!deleteConfiguration ||
m_target->buildConfigurations().size() <= 1)
return;
if (m_target->activeBuildConfiguration() == deleteConfiguration) {
foreach (BuildConfiguration *bc, m_target->buildConfigurations()) {
if (bc != deleteConfiguration) {
m_target->setActiveBuildConfiguration(bc);
break;
}
}
}
if (m_buildConfiguration == deleteConfiguration) {
foreach (BuildConfiguration *bc, m_target->buildConfigurations()) {
if (bc != deleteConfiguration) {
m_buildConfiguration = bc;
break;
}
}
}
m_target->removeBuildConfiguration(deleteConfiguration);
updateBuildSettings();
}
<commit_msg>Fix deletion of buildconfigurations<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "buildsettingspropertiespage.h"
#include "buildstep.h"
#include "buildstepspage.h"
#include "project.h"
#include "target.h"
#include "buildconfiguration.h"
#include <coreplugin/coreconstants.h>
#include <extensionsystem/pluginmanager.h>
#include <utils/qtcassert.h>
#include <QtCore/QMargins>
#include <QtCore/QTimer>
#include <QtCore/QCoreApplication>
#include <QtGui/QComboBox>
#include <QtGui/QInputDialog>
#include <QtGui/QLabel>
#include <QtGui/QMenu>
#include <QtGui/QPushButton>
#include <QtGui/QVBoxLayout>
using namespace ProjectExplorer;
using namespace ProjectExplorer::Internal;
///
// BuildSettingsPanelFactory
///
QString BuildSettingsPanelFactory::id() const
{
return QLatin1String(BUILDSETTINGS_PANEL_ID);
}
QString BuildSettingsPanelFactory::displayName() const
{
return QCoreApplication::translate("BuildSettingsPanelFactory", "Build Settings");
}
bool BuildSettingsPanelFactory::supports(Target *target)
{
return target->buildConfigurationFactory();
}
IPropertiesPanel *BuildSettingsPanelFactory::createPanel(Target *target)
{
return new BuildSettingsPanel(target);
}
///
// BuildSettingsPanel
///
BuildSettingsPanel::BuildSettingsPanel(Target *target) :
m_widget(new BuildSettingsWidget(target)),
m_icon(":/projectexplorer/images/BuildSettings.png")
{
}
BuildSettingsPanel::~BuildSettingsPanel()
{
delete m_widget;
}
QString BuildSettingsPanel::displayName() const
{
return QCoreApplication::translate("BuildSettingsPanel", "Build Settings");
}
QWidget *BuildSettingsPanel::widget() const
{
return m_widget;
}
QIcon BuildSettingsPanel::icon() const
{
return m_icon;
}
///
// BuildSettingsWidget
///
BuildSettingsWidget::~BuildSettingsWidget()
{
clear();
}
BuildSettingsWidget::BuildSettingsWidget(Target *target) :
m_target(target),
m_buildConfiguration(0),
m_leftMargin(0)
{
Q_ASSERT(m_target);
setupUi();
}
void BuildSettingsWidget::setupUi()
{
m_leftMargin = Constants::PANEL_LEFT_MARGIN;
QVBoxLayout *vbox = new QVBoxLayout(this);
vbox->setContentsMargins(0, 0, 0, 0);
if (!m_target->buildConfigurationFactory()) {
QLabel * noSettingsLabel(new QLabel(this));
noSettingsLabel->setText(tr("No Build Settings available"));
{
QFont f(noSettingsLabel->font());
f.setPointSizeF(f.pointSizeF() * 1.2);
noSettingsLabel->setFont(f);
}
vbox->addWidget(noSettingsLabel);
return;
}
{ // Edit Build Configuration row
QHBoxLayout *hbox = new QHBoxLayout();
hbox->setContentsMargins(m_leftMargin, 0, 0, 0);
hbox->addWidget(new QLabel(tr("Edit Build Configuration:"), this));
m_buildConfigurationComboBox = new QComboBox(this);
m_buildConfigurationComboBox->setSizeAdjustPolicy(QComboBox::AdjustToContents);
hbox->addWidget(m_buildConfigurationComboBox);
m_addButton = new QPushButton(this);
m_addButton->setText(tr("Add"));
m_addButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
hbox->addWidget(m_addButton);
m_addButtonMenu = new QMenu(this);
m_addButton->setMenu(m_addButtonMenu);
m_removeButton = new QPushButton(this);
m_removeButton->setText(tr("Remove"));
m_removeButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
hbox->addWidget(m_removeButton);
hbox->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Fixed));
vbox->addLayout(hbox);
}
m_buildConfiguration = m_target->activeBuildConfiguration();
updateAddButtonMenu();
updateBuildSettings();
connect(m_buildConfigurationComboBox, SIGNAL(currentIndexChanged(int)),
this, SLOT(currentIndexChanged(int)));
connect(m_removeButton, SIGNAL(clicked()),
this, SLOT(deleteConfiguration()));
connect(m_target, SIGNAL(activeBuildConfigurationChanged(ProjectExplorer::BuildConfiguration*)),
this, SLOT(updateActiveConfiguration()));
connect(m_target, SIGNAL(addedBuildConfiguration(ProjectExplorer::BuildConfiguration*)),
this, SLOT(addedBuildConfiguration(ProjectExplorer::BuildConfiguration*)));
connect(m_target, SIGNAL(removedBuildConfiguration(ProjectExplorer::BuildConfiguration*)),
this, SLOT(removedBuildConfiguration(ProjectExplorer::BuildConfiguration*)));
foreach (BuildConfiguration *bc, m_target->buildConfigurations()) {
connect(bc, SIGNAL(displayNameChanged()),
this, SLOT(buildConfigurationDisplayNameChanged()));
}
if (m_target->buildConfigurationFactory())
connect(m_target->buildConfigurationFactory(), SIGNAL(availableCreationIdsChanged()),
SLOT(updateAddButtonMenu()));
}
void BuildSettingsWidget::addedBuildConfiguration(BuildConfiguration *bc)
{
connect(bc, SIGNAL(displayNameChanged()),
this, SLOT(buildConfigurationDisplayNameChanged()));
}
void BuildSettingsWidget::removedBuildConfiguration(BuildConfiguration *bc)
{
disconnect(bc, SIGNAL(displayNameChanged()),
this, SLOT(buildConfigurationDisplayNameChanged()));
}
void BuildSettingsWidget::buildConfigurationDisplayNameChanged()
{
for (int i = 0; i < m_buildConfigurationComboBox->count(); ++i) {
BuildConfiguration *bc = m_buildConfigurationComboBox->itemData(i).value<BuildConfiguration *>();
m_buildConfigurationComboBox->setItemText(i, bc->displayName());
}
}
void BuildSettingsWidget::addSubWidget(const QString &name, BuildConfigWidget *widget)
{
widget->setContentsMargins(m_leftMargin, 10, 0, 0);
QLabel *label = new QLabel(this);
label->setText(name);
QFont f = label->font();
f.setBold(true);
f.setPointSizeF(f.pointSizeF() * 1.2);
label->setFont(f);
label->setContentsMargins(m_leftMargin, 10, 0, 0);
layout()->addWidget(label);
layout()->addWidget(widget);
m_labels.append(label);
m_subWidgets.append(widget);
}
void BuildSettingsWidget::clear()
{
qDeleteAll(m_subWidgets);
m_subWidgets.clear();
qDeleteAll(m_labels);
m_labels.clear();
}
QList<BuildConfigWidget *> BuildSettingsWidget::subWidgets() const
{
return m_subWidgets;
}
void BuildSettingsWidget::updateAddButtonMenu()
{
m_addButtonMenu->clear();
if (m_target &&
m_target->activeBuildConfiguration()) {
m_addButtonMenu->addAction(tr("&Clone Selected"),
this, SLOT(cloneConfiguration()));
}
IBuildConfigurationFactory *factory = m_target->buildConfigurationFactory();
if (factory) {
foreach (const QString &id, factory->availableCreationIds(m_target)) {
QAction *action = m_addButtonMenu->addAction(factory->displayNameForId(id), this, SLOT(createConfiguration()));
action->setData(id);
}
}
}
void BuildSettingsWidget::updateBuildSettings()
{
// Delete old tree items
bool blocked = m_buildConfigurationComboBox->blockSignals(true);
m_buildConfigurationComboBox->clear();
clear();
// update buttons
m_removeButton->setEnabled(m_target->buildConfigurations().size() > 1);
// Add pages
BuildConfigWidget *generalConfigWidget = m_target->project()->createConfigWidget();
addSubWidget(generalConfigWidget->displayName(), generalConfigWidget);
addSubWidget(tr("Build Steps"), new BuildStepsPage(m_target, Build));
addSubWidget(tr("Clean Steps"), new BuildStepsPage(m_target, Clean));
QList<BuildConfigWidget *> subConfigWidgets = m_target->project()->subConfigWidgets();
foreach (BuildConfigWidget *subConfigWidget, subConfigWidgets)
addSubWidget(subConfigWidget->displayName(), subConfigWidget);
// Add tree items
foreach (BuildConfiguration *bc, m_target->buildConfigurations()) {
m_buildConfigurationComboBox->addItem(bc->displayName(), QVariant::fromValue<BuildConfiguration *>(bc));
if (bc == m_buildConfiguration)
m_buildConfigurationComboBox->setCurrentIndex(m_buildConfigurationComboBox->count() - 1);
}
foreach (BuildConfigWidget *widget, subWidgets())
widget->init(m_buildConfiguration);
m_buildConfigurationComboBox->blockSignals(blocked);
}
void BuildSettingsWidget::currentIndexChanged(int index)
{
BuildConfiguration *buildConfiguration = m_buildConfigurationComboBox->itemData(index).value<BuildConfiguration *>();
m_target->setActiveBuildConfiguration(buildConfiguration);
}
void BuildSettingsWidget::updateActiveConfiguration()
{
if (!m_buildConfiguration || m_buildConfiguration == m_target->activeBuildConfiguration())
return;
m_buildConfiguration = m_target->activeBuildConfiguration();
for (int i = 0; i < m_buildConfigurationComboBox->count(); ++i) {
if (m_buildConfigurationComboBox->itemData(i).value<BuildConfiguration *>() == m_buildConfiguration) {
m_buildConfigurationComboBox->setCurrentIndex(i);
break;
}
}
foreach (QWidget *widget, subWidgets()) {
if (BuildConfigWidget *buildStepWidget = qobject_cast<BuildConfigWidget*>(widget)) {
buildStepWidget->init(m_buildConfiguration);
}
}
}
void BuildSettingsWidget::createConfiguration()
{
if (!m_target->buildConfigurationFactory())
return;
QAction *action = qobject_cast<QAction *>(sender());
const QString &id = action->data().toString();
BuildConfiguration *bc = m_target->buildConfigurationFactory()->create(m_target, id);
if (bc) {
m_buildConfiguration = bc;
updateBuildSettings();
}
}
void BuildSettingsWidget::cloneConfiguration()
{
cloneConfiguration(m_buildConfiguration);
}
void BuildSettingsWidget::deleteConfiguration()
{
deleteConfiguration(m_buildConfiguration);
}
void BuildSettingsWidget::cloneConfiguration(BuildConfiguration *sourceConfiguration)
{
if (!sourceConfiguration ||
!m_target->buildConfigurationFactory())
return;
QString newDisplayName(QInputDialog::getText(this, tr("Clone configuration"), tr("New Configuration Name:")));
if (newDisplayName.isEmpty())
return;
QStringList buildConfigurationDisplayNames;
foreach(BuildConfiguration *bc, m_target->buildConfigurations())
buildConfigurationDisplayNames << bc->displayName();
newDisplayName = Project::makeUnique(newDisplayName, buildConfigurationDisplayNames);
BuildConfiguration * bc(m_target->buildConfigurationFactory()->clone(m_target, sourceConfiguration));
if (!bc)
return;
m_buildConfiguration = bc;
m_buildConfiguration->setDisplayName(newDisplayName);
m_target->addBuildConfiguration(m_buildConfiguration);
updateBuildSettings();
}
void BuildSettingsWidget::deleteConfiguration(BuildConfiguration *deleteConfiguration)
{
if (!deleteConfiguration ||
m_target->buildConfigurations().size() <= 1)
return;
m_target->removeBuildConfiguration(deleteConfiguration);
updateBuildSettings();
}
<|endoftext|> |
<commit_before>#pragma once
#ifndef OPENGM_STRUCT_PERCEPTRON_LEARNER_HXX
#define OPENGM_STRUCT_PERCEPTRON_LEARNER_HXX
#include <vector>
#include <opengm/inference/inference.hxx>
#include <opengm/graphicalmodel/weights.hxx>
#include <opengm/utilities/random.hxx>
#include <opengm/learning/gradient-accumulator.hxx>
#ifndef CI
#include <omp.h>
#endif CI
namespace opengm {
namespace learning {
template<class DATASET>
class StructuredPerceptron
{
public:
typedef DATASET DatasetType;
typedef typename DATASET::GMType GMType;
typedef typename DATASET::LossType LossType;
typedef typename GMType::ValueType ValueType;
typedef typename GMType::IndexType IndexType;
typedef typename GMType::LabelType LabelType;
typedef typename std::vector<LabelType>::const_iterator LabelIterator;
typedef FeatureAccumulator<GMType, LabelIterator> FeatureAcc;
class Parameter{
public:
enum LearningMode{
Online = 0,
Batch = 2
};
Parameter(){
eps_ = 0.00001;
maxIterations_ = 10000;
stopLoss_ = 0.0;
decayExponent_ = 0.0;
decayT0_ = 0.0;
learningMode_ = Online;
}
double eps_;
size_t maxIterations_;
double stopLoss_;
double decayExponent_;
double decayT0_;
LearningMode learningMode_;
};
StructuredPerceptron(DATASET&, const Parameter& );
template<class INF>
void learn(const typename INF::Parameter& para);
//template<class INF, class VISITOR>
//void learn(typename INF::Parameter para, VITITOR vis);
const opengm::learning::Weights<double>& getWeights(){return weights_;}
Parameter& getLerningParameters(){return para_;}
double getLearningRate( )const{
if(para_.decayExponent_<=0.000000001 && para_.decayExponent_>=-0.000000001 ){
return 1.0;
}
else{
return std::pow(para_.decayT0_ + static_cast<double>(iteration_+1),para_.decayExponent_);
}
}
private:
double updateWeights();
DATASET& dataset_;
opengm::learning::Weights<double> weights_;
Parameter para_;
size_t iteration_;
FeatureAcc featureAcc_;
};
template<class DATASET>
StructuredPerceptron<DATASET>::StructuredPerceptron(DATASET& ds, const Parameter& p )
: dataset_(ds), para_(p),iteration_(0),featureAcc_(ds.getNumberOfWeights(),false)
{
featureAcc_.resetWeights();
weights_ = opengm::learning::Weights<double>(ds.getNumberOfWeights());
}
template<class DATASET>
template<class INF>
void StructuredPerceptron<DATASET>::learn(const typename INF::Parameter& para){
const size_t nModels = dataset_.getNumberOfModels();
const size_t nWegihts = dataset_.getNumberOfWeights();
if(para_.learningMode_ == Parameter::Online){
RandomUniform<size_t> randModel(0, nModels);
std::cout<<"online mode\n";
for(iteration_=0 ; iteration_<para_.maxIterations_; ++iteration_){
if(iteration_%nModels==0){
std::cout<<"loss :"<<dataset_. template getTotalLoss<INF>(para)<<"\n";
}
// get random model
const size_t gmi = randModel();
// lock the model
dataset_.lockModel(gmi);
const GMType & gm = dataset_.getModel(gmi);
// do inference
std::vector<LabelType> arg;
opengm::infer<INF>(gm, para, arg);
featureAcc_.resetWeights();
featureAcc_.accumulateModelFeatures(gm, dataset_.getGT(gmi).begin(), arg.begin());
dataset_.unlockModel(gmi);
// update weights
const double wChange =updateWeights();
}
}
else if(para_.learningMode_ == Parameter::Batch){
std::cout<<"batch mode\n";
for(iteration_=0 ; iteration_<para_.maxIterations_; ++iteration_){
// this
if(iteration_%1==0){
std::cout<<"loss :"<<dataset_. template getTotalLoss<INF>(para)<<"\n";
}
// reset the weights
featureAcc_.resetWeights();
#ifndef CI
omp_lock_t modelLockUnlock;
omp_init_lock(&modelLockUnlock);
omp_lock_t featureAccLock;
omp_init_lock(&featureAccLock);
#endif
#pragma omp parallel for
for(size_t gmi=0; gmi<nModels; ++gmi)
{
// lock the model
omp_set_lock(&modelLockUnlock);
dataset_.lockModel(gmi);
omp_unset_lock(&modelLockUnlock);
const GMType & gm = dataset_.getModel(gmi);
//run inference
std::vector<LabelType> arg;
opengm::infer<INF>(gm, para, arg);
//
FeatureAcc featureAcc(nWegihts,false);
featureAcc.accumulateModelFeatures(gm, dataset_.getGT(gmi).begin(), arg.begin());
// acc features
#ifndef CI
omp_set_lock(&featureAccLock);
featureAcc_.accumulateFromOther(featureAcc);
omp_unset_lock(&featureAccLock);
// unlock the model
omp_set_lock(&modelLockUnlock);
dataset_.unlockModel(gmi);
omp_unset_lock(&modelLockUnlock);
#else
featureAcc_.accumulateFromOther(featureAcc);
dataset_.unlockModel(gmi);
#endif
}
// update the weights
const double wChange =updateWeights();
}
}
weights_ = dataset_.getWeights();
}
template<class DATASET>
double StructuredPerceptron<DATASET>::updateWeights(){
double wChange = 0.0;
const size_t nWegihts = dataset_.getNumberOfWeights();
for(size_t wi=0; wi<nWegihts; ++wi){
const double wOld = dataset_.getWeights().getWeight(wi);
const double wNew = wOld + getLearningRate()*featureAcc_.getWeight(wi);
wChange += std::pow(wOld-wNew,2);
dataset_.getWeights().setWeight(wi, wNew);
}
weights_ = dataset_.getWeights();
return wChange;
}
}
}
#endif
<commit_msg>update struct. perceptron<commit_after>#pragma once
#ifndef OPENGM_STRUCT_PERCEPTRON_LEARNER_HXX
#define OPENGM_STRUCT_PERCEPTRON_LEARNER_HXX
#include <vector>
#include <opengm/inference/inference.hxx>
#include <opengm/graphicalmodel/weights.hxx>
#include <opengm/utilities/random.hxx>
#include <opengm/learning/gradient-accumulator.hxx>
#ifndef CI
#include <omp.h>
#endif
namespace opengm {
namespace learning {
template<class DATASET>
class StructuredPerceptron
{
public:
typedef DATASET DatasetType;
typedef typename DATASET::GMType GMType;
typedef typename DATASET::LossType LossType;
typedef typename GMType::ValueType ValueType;
typedef typename GMType::IndexType IndexType;
typedef typename GMType::LabelType LabelType;
typedef typename std::vector<LabelType>::const_iterator LabelIterator;
typedef FeatureAccumulator<GMType, LabelIterator> FeatureAcc;
class Parameter{
public:
enum LearningMode{
Online = 0,
Batch = 2
};
Parameter(){
eps_ = 0.00001;
maxIterations_ = 10000;
stopLoss_ = 0.0;
decayExponent_ = 0.0;
decayT0_ = 0.0;
learningMode_ = Online;
}
double eps_;
size_t maxIterations_;
double stopLoss_;
double decayExponent_;
double decayT0_;
LearningMode learningMode_;
};
StructuredPerceptron(DATASET&, const Parameter& );
template<class INF>
void learn(const typename INF::Parameter& para);
//template<class INF, class VISITOR>
//void learn(typename INF::Parameter para, VITITOR vis);
const opengm::learning::Weights<double>& getWeights(){return weights_;}
Parameter& getLerningParameters(){return para_;}
double getLearningRate( )const{
if(para_.decayExponent_<=0.000000001 && para_.decayExponent_>=-0.000000001 ){
return 1.0;
}
else{
return std::pow(para_.decayT0_ + static_cast<double>(iteration_+1),para_.decayExponent_);
}
}
private:
double updateWeights();
DATASET& dataset_;
opengm::learning::Weights<double> weights_;
Parameter para_;
size_t iteration_;
FeatureAcc featureAcc_;
};
template<class DATASET>
StructuredPerceptron<DATASET>::StructuredPerceptron(DATASET& ds, const Parameter& p )
: dataset_(ds), para_(p),iteration_(0),featureAcc_(ds.getNumberOfWeights(),false)
{
featureAcc_.resetWeights();
weights_ = opengm::learning::Weights<double>(ds.getNumberOfWeights());
}
template<class DATASET>
template<class INF>
void StructuredPerceptron<DATASET>::learn(const typename INF::Parameter& para){
const size_t nModels = dataset_.getNumberOfModels();
const size_t nWegihts = dataset_.getNumberOfWeights();
if(para_.learningMode_ == Parameter::Online){
RandomUniform<size_t> randModel(0, nModels);
std::cout<<"online mode\n";
for(iteration_=0 ; iteration_<para_.maxIterations_; ++iteration_){
if(iteration_%nModels==0){
std::cout<<"loss :"<<dataset_. template getTotalLoss<INF>(para)<<"\n";
}
// get random model
const size_t gmi = randModel();
// lock the model
dataset_.lockModel(gmi);
const GMType & gm = dataset_.getModel(gmi);
// do inference
std::vector<LabelType> arg;
opengm::infer<INF>(gm, para, arg);
featureAcc_.resetWeights();
featureAcc_.accumulateModelFeatures(gm, dataset_.getGT(gmi).begin(), arg.begin());
dataset_.unlockModel(gmi);
// update weights
const double wChange =updateWeights();
}
}
else if(para_.learningMode_ == Parameter::Batch){
std::cout<<"batch mode\n";
for(iteration_=0 ; iteration_<para_.maxIterations_; ++iteration_){
// this
if(iteration_%1==0){
std::cout<<"loss :"<<dataset_. template getTotalLoss<INF>(para)<<"\n";
}
// reset the weights
featureAcc_.resetWeights();
#ifndef CI
omp_lock_t modelLockUnlock;
omp_init_lock(&modelLockUnlock);
omp_lock_t featureAccLock;
omp_init_lock(&featureAccLock);
#endif
#pragma omp parallel for
for(size_t gmi=0; gmi<nModels; ++gmi)
{
// lock the model
omp_set_lock(&modelLockUnlock);
dataset_.lockModel(gmi);
omp_unset_lock(&modelLockUnlock);
const GMType & gm = dataset_.getModel(gmi);
//run inference
std::vector<LabelType> arg;
opengm::infer<INF>(gm, para, arg);
//
FeatureAcc featureAcc(nWegihts,false);
featureAcc.accumulateModelFeatures(gm, dataset_.getGT(gmi).begin(), arg.begin());
// acc features
#ifndef CI
omp_set_lock(&featureAccLock);
featureAcc_.accumulateFromOther(featureAcc);
omp_unset_lock(&featureAccLock);
// unlock the model
omp_set_lock(&modelLockUnlock);
dataset_.unlockModel(gmi);
omp_unset_lock(&modelLockUnlock);
#else
featureAcc_.accumulateFromOther(featureAcc);
dataset_.unlockModel(gmi);
#endif
}
// update the weights
const double wChange =updateWeights();
}
}
weights_ = dataset_.getWeights();
}
template<class DATASET>
double StructuredPerceptron<DATASET>::updateWeights(){
double wChange = 0.0;
const size_t nWegihts = dataset_.getNumberOfWeights();
for(size_t wi=0; wi<nWegihts; ++wi){
const double wOld = dataset_.getWeights().getWeight(wi);
const double wNew = wOld + getLearningRate()*featureAcc_.getWeight(wi);
wChange += std::pow(wOld-wNew,2);
dataset_.getWeights().setWeight(wi, wNew);
}
weights_ = dataset_.getWeights();
return wChange;
}
}
}
#endif
<|endoftext|> |
<commit_before>#include "framework/framework.h"
#include "framework/logger.h"
#include "framework/sound_interface.h"
#include "framework/trace.h"
#include "library/sp.h"
#include "library/vec.h"
#include <SDL.h>
#include <SDL_audio.h>
#include <list>
#include <mutex>
#include <queue>
namespace
{
using namespace OpenApoc;
struct SampleData
{
sp<Sample> sample;
float gain;
int sample_position; // in bytes
SampleData(sp<Sample> sample, float gain) : sample(sample), gain(gain), sample_position(0) {}
};
struct MusicData
{
MusicData() : sample_position(0) {}
std::vector<unsigned char> samples;
int sample_position; // in bytes
};
// 'samples' must already be large enough to contain the full output size
static bool ConvertAudio(AudioFormat input_format, SDL_AudioSpec &output_spec, int input_size_bytes,
std::vector<unsigned char> &samples)
{
SDL_AudioCVT cvt;
SDL_AudioFormat sdl_input_format;
switch (input_format.format)
{
case AudioFormat::SampleFormat::PCM_SINT16:
sdl_input_format = AUDIO_S16LSB;
break;
case AudioFormat::SampleFormat::PCM_UINT8:
sdl_input_format = AUDIO_U8;
break;
default:
LogWarning("Unknown input sample format");
return false;
}
int ret =
SDL_BuildAudioCVT(&cvt, sdl_input_format, input_format.channels, input_format.frequency,
output_spec.format, output_spec.channels, output_spec.freq);
if (ret < 0)
{
LogWarning("Failed to build AudioCVT");
return false;
}
else if (ret == 0)
{
// No conversion needed
return true;
}
else
{
cvt.len = input_size_bytes;
cvt.buf = (Uint8 *)samples.data();
SDL_ConvertAudio(&cvt);
return true;
}
}
class SDLSampleData : public BackendSampleData
{
public:
SDLSampleData(sp<Sample> sample, SDL_AudioSpec &output_spec)
{
unsigned int input_size =
sample->format.getSampleSize() * sample->format.channels * sample->sampleCount;
unsigned int output_size = (SDL_AUDIO_BITSIZE(output_spec.format) / 8) *
output_spec.channels * sample->sampleCount;
this->samples.resize(std::max(input_size, output_size));
memcpy(this->samples.data(), sample->data.get(), input_size);
if (!ConvertAudio(sample->format, output_spec, input_size, this->samples))
{
LogWarning("Failed to convert sample data");
}
this->samples.resize(output_size);
}
~SDLSampleData() override = default;
std::vector<unsigned char> samples;
};
static void unwrap_callback(void *userdata, Uint8 *stream, int len);
class SDLRawBackend : public SoundBackend
{
std::recursive_mutex audio_lock;
float overall_volume;
float music_volume;
float sound_volume;
sp<MusicTrack> track;
bool music_playing;
std::function<void(void *)> music_finished_callback;
void *music_callback_data;
std::list<SampleData> live_samples;
SDL_AudioDeviceID devID;
SDL_AudioSpec output_spec;
AudioFormat preferred_format;
sp<MusicData> current_music_data;
std::queue<sp<MusicData>> music_queue;
std::future<void> get_music_future;
int music_queue_size;
void get_more_music()
{
TRACE_FN;
std::lock_guard<std::recursive_mutex> lock(this->audio_lock);
if (!this->music_playing)
{
// Music probably disabled in the time it took us to be scheduled?
return;
}
if (!this->track)
{
LogWarning("Music playing but no track?");
return;
}
while (this->music_queue.size() < this->music_queue_size)
{
auto data = mksp<MusicData>();
unsigned int input_size = this->track->format.getSampleSize() *
this->track->format.channels *
this->track->requestedSampleBufferSize;
unsigned int output_size = (SDL_AUDIO_BITSIZE(this->output_spec.format) / 8) *
this->output_spec.channels *
this->track->requestedSampleBufferSize;
data->samples.resize(std::max(input_size, output_size));
unsigned int returned_samples;
auto ret = this->track->callback(this->track, this->track->requestedSampleBufferSize,
(void *)data->samples.data(), &returned_samples);
// Reset the sizes, as we may have fewer returned_samples than asked for
input_size = this->track->format.getSampleSize() * this->track->format.channels *
returned_samples;
output_size = (SDL_AUDIO_BITSIZE(this->output_spec.format) / 8) *
this->output_spec.channels * returned_samples;
bool convert_ret =
ConvertAudio(this->track->format, this->output_spec, input_size, data->samples);
if (!convert_ret)
{
LogWarning("Failed to convert music data");
}
data->samples.resize(output_size);
if (ret == MusicTrack::MusicCallbackReturn::End)
{
this->track = nullptr;
if (this->music_finished_callback)
{
this->music_finished_callback(music_callback_data);
}
}
this->music_queue.push(data);
}
}
public:
void mixingCallback(Uint8 *stream, int len)
{
TRACE_FN;
// initialize stream buffer
memset(stream, 0, len);
std::lock_guard<std::recursive_mutex> lock(this->audio_lock);
if (this->current_music_data || !this->music_queue.empty())
{
int int_music_volume =
clamp((int)lrint(this->overall_volume * this->music_volume * 128.0f), 0, 128);
int music_bytes = 0;
while (music_bytes < len)
{
if (!this->current_music_data)
{
this->get_music_future =
fw().threadPool->enqueue(std::mem_fn(&SDLRawBackend::get_more_music), this);
if (this->music_queue.empty())
{
LogWarning("Music underrun!");
break;
}
this->current_music_data = this->music_queue.front();
this->music_queue.pop();
}
int bytes_from_this_chunk =
std::min(len - music_bytes, (int)(this->current_music_data->samples.size() -
this->current_music_data->sample_position));
SDL_MixAudioFormat(
stream + music_bytes, this->current_music_data->samples.data() +
this->current_music_data->sample_position,
this->output_spec.format, bytes_from_this_chunk, int_music_volume);
music_bytes += bytes_from_this_chunk;
this->current_music_data->sample_position += bytes_from_this_chunk;
assert(this->current_music_data->sample_position <=
this->current_music_data->samples.size());
if (this->current_music_data->sample_position ==
this->current_music_data->samples.size())
{
this->current_music_data = nullptr;
}
}
}
auto sampleIt = this->live_samples.begin();
while (sampleIt != this->live_samples.end())
{
int int_sample_volume = clamp(
(int)lrint(this->overall_volume * this->sound_volume * sampleIt->gain * 128.0f), 0,
128);
auto sampleData =
std::dynamic_pointer_cast<SDLSampleData>(sampleIt->sample->backendData);
if (!sampleData)
{
LogWarning("Sample with invalid sample data");
// Clear it in case we've changed drivers or something
sampleIt->sample->backendData = nullptr;
sampleIt = this->live_samples.erase(sampleIt);
continue;
}
if (sampleIt->sample_position == sampleData->samples.size())
{
// Reached the end of the sample
sampleIt = this->live_samples.erase(sampleIt);
continue;
}
unsigned bytes_to_mix =
std::min(len, (int)(sampleData->samples.size() - sampleIt->sample_position));
SDL_MixAudioFormat(stream, sampleData->samples.data() + sampleIt->sample_position,
this->output_spec.format, bytes_to_mix, int_sample_volume);
sampleIt->sample_position += bytes_to_mix;
assert(sampleIt->sample_position <= sampleData->samples.size());
sampleIt++;
}
}
SDLRawBackend()
: overall_volume(1.0f), music_volume(1.0f), sound_volume(1.0f),
music_callback_data(nullptr), music_playing(false), music_queue_size(2)
{
SDL_Init(SDL_INIT_AUDIO);
preferred_format.channels = 2;
preferred_format.format = AudioFormat::SampleFormat::PCM_SINT16;
preferred_format.frequency = 22050;
LogInfo("Current audio driver: %s", SDL_GetCurrentAudioDriver());
LogWarning("Changing audio drivers is not currently implemented!");
int numDevices = SDL_GetNumAudioDevices(0); // Request playback devices only
LogInfo("Number of audio devices: %d", numDevices);
for (int i = 0; i < numDevices; ++i)
{
LogInfo("Device %d: %s", i, SDL_GetAudioDeviceName(i, 0));
}
LogWarning(
"Selecting audio devices not currently implemented! Selecting first available device.");
const char *deviceName = SDL_GetAudioDeviceName(0, 0);
SDL_AudioSpec wantFormat;
wantFormat.channels = 2;
wantFormat.format = AUDIO_S16LSB;
wantFormat.freq = 22050;
wantFormat.samples = 512;
wantFormat.callback = unwrap_callback;
wantFormat.userdata = this;
devID = SDL_OpenAudioDevice(
nullptr, // "NULL" here is a 'reasonable default', which uses the platform default when
// available
0, // capturing is not supported
&wantFormat, &output_spec,
SDL_AUDIO_ALLOW_ANY_CHANGE); // hopefully we'll get a sane output format
SDL_PauseAudioDevice(devID, 0); // Run at once?
LogInfo("Audio output format: Channels %d, format %d, freq %d, samples %d",
(int)output_spec.channels, (int)output_spec.format, (int)output_spec.freq,
(int)output_spec.samples);
}
void playSample(sp<Sample> sample, float gain) override
{
// Clamp to 0..1
gain = std::min(1.0f, std::max(0.0f, gain));
if (!sample->backendData)
{
sample->backendData.reset(new SDLSampleData(sample, this->output_spec));
}
{
std::lock_guard<std::recursive_mutex> l(this->audio_lock);
this->live_samples.emplace_back(sample, gain);
}
LogInfo("Placed sound %p on queue", sample.get());
}
void playMusic(std::function<void(void *)> finishedCallback, void *callbackData) override
{
std::lock_guard<std::recursive_mutex> l(this->audio_lock);
while (!music_queue.empty())
music_queue.pop();
music_finished_callback = finishedCallback;
music_callback_data = callbackData;
music_playing = true;
this->get_music_future =
fw().threadPool->enqueue(std::mem_fn(&SDLRawBackend::get_more_music), this);
LogInfo("Playing music on SDL backend");
}
void setTrack(sp<MusicTrack> track) override
{
std::lock_guard<std::recursive_mutex> l(this->audio_lock);
LogInfo("Setting track to %p", track.get());
this->track = track;
while (!music_queue.empty())
music_queue.pop();
}
void stopMusic() override
{
std::future<void> outstanding_get_music;
{
std::lock_guard<std::recursive_mutex> l(this->audio_lock);
this->music_playing = false;
this->track = nullptr;
if (this->get_music_future.valid())
outstanding_get_music = std::move(this->get_music_future);
while (!music_queue.empty())
music_queue.pop();
}
if (outstanding_get_music.valid())
outstanding_get_music.wait();
}
virtual ~SDLRawBackend()
{
// Lock the device and stop any outstanding music threads to ensure everything is dead
// before destroying the device
SDL_LockAudioDevice(devID);
SDL_PauseAudioDevice(devID, 1);
this->stopMusic();
SDL_UnlockAudioDevice(devID);
SDL_CloseAudioDevice(devID);
SDL_QuitSubSystem(SDL_INIT_AUDIO);
}
virtual const AudioFormat &getPreferredFormat() { return preferred_format; }
float getGain(Gain g) override
{
float reqGain = 0;
switch (g)
{
case Gain::Global:
reqGain = overall_volume;
break;
case Gain::Sample:
reqGain = sound_volume;
break;
case Gain::Music:
reqGain = music_volume;
break;
}
return reqGain;
}
void setGain(Gain g, float f) override
{
// Clamp to 0..1
f = std::min(1.0f, std::max(0.0f, f));
switch (g)
{
case Gain::Global:
overall_volume = f;
break;
case Gain::Sample:
sound_volume = f;
break;
case Gain::Music:
music_volume = f;
break;
}
}
};
void unwrap_callback(void *userdata, Uint8 *stream, int len)
{
auto backend = reinterpret_cast<SDLRawBackend *>(userdata);
backend->mixingCallback(stream, len);
}
class SDLRawBackendFactory : public SoundBackendFactory
{
public:
SoundBackend *create() override
{
LogWarning("Creating SDLRaw sound backend (Might have issues!)");
int ret = SDL_InitSubSystem(SDL_INIT_AUDIO);
if (ret < 0)
{
LogWarning("Failed to init SDL_AUDIO (%d) - %s", ret, SDL_GetError());
return nullptr;
}
return new SDLRawBackend();
}
virtual ~SDLRawBackendFactory() {}
};
}; // anonymous namespace
namespace OpenApoc
{
SoundBackendFactory *getSDLSoundBackend() { return new SDLRawBackendFactory(); }
} // namespace OpenApoc
<commit_msg>SDLraw audio: print device name to info<commit_after>#include "framework/framework.h"
#include "framework/logger.h"
#include "framework/sound_interface.h"
#include "framework/trace.h"
#include "library/sp.h"
#include "library/vec.h"
#include <SDL.h>
#include <SDL_audio.h>
#include <list>
#include <mutex>
#include <queue>
namespace
{
using namespace OpenApoc;
struct SampleData
{
sp<Sample> sample;
float gain;
int sample_position; // in bytes
SampleData(sp<Sample> sample, float gain) : sample(sample), gain(gain), sample_position(0) {}
};
struct MusicData
{
MusicData() : sample_position(0) {}
std::vector<unsigned char> samples;
int sample_position; // in bytes
};
// 'samples' must already be large enough to contain the full output size
static bool ConvertAudio(AudioFormat input_format, SDL_AudioSpec &output_spec, int input_size_bytes,
std::vector<unsigned char> &samples)
{
SDL_AudioCVT cvt;
SDL_AudioFormat sdl_input_format;
switch (input_format.format)
{
case AudioFormat::SampleFormat::PCM_SINT16:
sdl_input_format = AUDIO_S16LSB;
break;
case AudioFormat::SampleFormat::PCM_UINT8:
sdl_input_format = AUDIO_U8;
break;
default:
LogWarning("Unknown input sample format");
return false;
}
int ret =
SDL_BuildAudioCVT(&cvt, sdl_input_format, input_format.channels, input_format.frequency,
output_spec.format, output_spec.channels, output_spec.freq);
if (ret < 0)
{
LogWarning("Failed to build AudioCVT");
return false;
}
else if (ret == 0)
{
// No conversion needed
return true;
}
else
{
cvt.len = input_size_bytes;
cvt.buf = (Uint8 *)samples.data();
SDL_ConvertAudio(&cvt);
return true;
}
}
class SDLSampleData : public BackendSampleData
{
public:
SDLSampleData(sp<Sample> sample, SDL_AudioSpec &output_spec)
{
unsigned int input_size =
sample->format.getSampleSize() * sample->format.channels * sample->sampleCount;
unsigned int output_size = (SDL_AUDIO_BITSIZE(output_spec.format) / 8) *
output_spec.channels * sample->sampleCount;
this->samples.resize(std::max(input_size, output_size));
memcpy(this->samples.data(), sample->data.get(), input_size);
if (!ConvertAudio(sample->format, output_spec, input_size, this->samples))
{
LogWarning("Failed to convert sample data");
}
this->samples.resize(output_size);
}
~SDLSampleData() override = default;
std::vector<unsigned char> samples;
};
static void unwrap_callback(void *userdata, Uint8 *stream, int len);
class SDLRawBackend : public SoundBackend
{
std::recursive_mutex audio_lock;
float overall_volume;
float music_volume;
float sound_volume;
sp<MusicTrack> track;
bool music_playing;
std::function<void(void *)> music_finished_callback;
void *music_callback_data;
std::list<SampleData> live_samples;
SDL_AudioDeviceID devID;
SDL_AudioSpec output_spec;
AudioFormat preferred_format;
sp<MusicData> current_music_data;
std::queue<sp<MusicData>> music_queue;
std::future<void> get_music_future;
int music_queue_size;
void get_more_music()
{
TRACE_FN;
std::lock_guard<std::recursive_mutex> lock(this->audio_lock);
if (!this->music_playing)
{
// Music probably disabled in the time it took us to be scheduled?
return;
}
if (!this->track)
{
LogWarning("Music playing but no track?");
return;
}
while (this->music_queue.size() < this->music_queue_size)
{
auto data = mksp<MusicData>();
unsigned int input_size = this->track->format.getSampleSize() *
this->track->format.channels *
this->track->requestedSampleBufferSize;
unsigned int output_size = (SDL_AUDIO_BITSIZE(this->output_spec.format) / 8) *
this->output_spec.channels *
this->track->requestedSampleBufferSize;
data->samples.resize(std::max(input_size, output_size));
unsigned int returned_samples;
auto ret = this->track->callback(this->track, this->track->requestedSampleBufferSize,
(void *)data->samples.data(), &returned_samples);
// Reset the sizes, as we may have fewer returned_samples than asked for
input_size = this->track->format.getSampleSize() * this->track->format.channels *
returned_samples;
output_size = (SDL_AUDIO_BITSIZE(this->output_spec.format) / 8) *
this->output_spec.channels * returned_samples;
bool convert_ret =
ConvertAudio(this->track->format, this->output_spec, input_size, data->samples);
if (!convert_ret)
{
LogWarning("Failed to convert music data");
}
data->samples.resize(output_size);
if (ret == MusicTrack::MusicCallbackReturn::End)
{
this->track = nullptr;
if (this->music_finished_callback)
{
this->music_finished_callback(music_callback_data);
}
}
this->music_queue.push(data);
}
}
public:
void mixingCallback(Uint8 *stream, int len)
{
TRACE_FN;
// initialize stream buffer
memset(stream, 0, len);
std::lock_guard<std::recursive_mutex> lock(this->audio_lock);
if (this->current_music_data || !this->music_queue.empty())
{
int int_music_volume =
clamp((int)lrint(this->overall_volume * this->music_volume * 128.0f), 0, 128);
int music_bytes = 0;
while (music_bytes < len)
{
if (!this->current_music_data)
{
this->get_music_future =
fw().threadPool->enqueue(std::mem_fn(&SDLRawBackend::get_more_music), this);
if (this->music_queue.empty())
{
LogWarning("Music underrun!");
break;
}
this->current_music_data = this->music_queue.front();
this->music_queue.pop();
}
int bytes_from_this_chunk =
std::min(len - music_bytes, (int)(this->current_music_data->samples.size() -
this->current_music_data->sample_position));
SDL_MixAudioFormat(
stream + music_bytes, this->current_music_data->samples.data() +
this->current_music_data->sample_position,
this->output_spec.format, bytes_from_this_chunk, int_music_volume);
music_bytes += bytes_from_this_chunk;
this->current_music_data->sample_position += bytes_from_this_chunk;
assert(this->current_music_data->sample_position <=
this->current_music_data->samples.size());
if (this->current_music_data->sample_position ==
this->current_music_data->samples.size())
{
this->current_music_data = nullptr;
}
}
}
auto sampleIt = this->live_samples.begin();
while (sampleIt != this->live_samples.end())
{
int int_sample_volume = clamp(
(int)lrint(this->overall_volume * this->sound_volume * sampleIt->gain * 128.0f), 0,
128);
auto sampleData =
std::dynamic_pointer_cast<SDLSampleData>(sampleIt->sample->backendData);
if (!sampleData)
{
LogWarning("Sample with invalid sample data");
// Clear it in case we've changed drivers or something
sampleIt->sample->backendData = nullptr;
sampleIt = this->live_samples.erase(sampleIt);
continue;
}
if (sampleIt->sample_position == sampleData->samples.size())
{
// Reached the end of the sample
sampleIt = this->live_samples.erase(sampleIt);
continue;
}
unsigned bytes_to_mix =
std::min(len, (int)(sampleData->samples.size() - sampleIt->sample_position));
SDL_MixAudioFormat(stream, sampleData->samples.data() + sampleIt->sample_position,
this->output_spec.format, bytes_to_mix, int_sample_volume);
sampleIt->sample_position += bytes_to_mix;
assert(sampleIt->sample_position <= sampleData->samples.size());
sampleIt++;
}
}
SDLRawBackend()
: overall_volume(1.0f), music_volume(1.0f), sound_volume(1.0f),
music_callback_data(nullptr), music_playing(false), music_queue_size(2)
{
SDL_Init(SDL_INIT_AUDIO);
preferred_format.channels = 2;
preferred_format.format = AudioFormat::SampleFormat::PCM_SINT16;
preferred_format.frequency = 22050;
LogInfo("Current audio driver: %s", SDL_GetCurrentAudioDriver());
LogWarning("Changing audio drivers is not currently implemented!");
int numDevices = SDL_GetNumAudioDevices(0); // Request playback devices only
LogInfo("Number of audio devices: %d", numDevices);
for (int i = 0; i < numDevices; ++i)
{
LogInfo("Device %d: %s", i, SDL_GetAudioDeviceName(i, 0));
}
LogWarning(
"Selecting audio devices not currently implemented! Selecting first available device.");
const char *deviceName = SDL_GetAudioDeviceName(0, 0);
LogInfo("Using audio device: %s", deviceName);
SDL_AudioSpec wantFormat;
wantFormat.channels = 2;
wantFormat.format = AUDIO_S16LSB;
wantFormat.freq = 22050;
wantFormat.samples = 512;
wantFormat.callback = unwrap_callback;
wantFormat.userdata = this;
devID = SDL_OpenAudioDevice(
nullptr, // "NULL" here is a 'reasonable default', which uses the platform default when
// available
0, // capturing is not supported
&wantFormat, &output_spec,
SDL_AUDIO_ALLOW_ANY_CHANGE); // hopefully we'll get a sane output format
SDL_PauseAudioDevice(devID, 0); // Run at once?
LogInfo("Audio output format: Channels %d, format %d, freq %d, samples %d",
(int)output_spec.channels, (int)output_spec.format, (int)output_spec.freq,
(int)output_spec.samples);
}
void playSample(sp<Sample> sample, float gain) override
{
// Clamp to 0..1
gain = std::min(1.0f, std::max(0.0f, gain));
if (!sample->backendData)
{
sample->backendData.reset(new SDLSampleData(sample, this->output_spec));
}
{
std::lock_guard<std::recursive_mutex> l(this->audio_lock);
this->live_samples.emplace_back(sample, gain);
}
LogInfo("Placed sound %p on queue", sample.get());
}
void playMusic(std::function<void(void *)> finishedCallback, void *callbackData) override
{
std::lock_guard<std::recursive_mutex> l(this->audio_lock);
while (!music_queue.empty())
music_queue.pop();
music_finished_callback = finishedCallback;
music_callback_data = callbackData;
music_playing = true;
this->get_music_future =
fw().threadPool->enqueue(std::mem_fn(&SDLRawBackend::get_more_music), this);
LogInfo("Playing music on SDL backend");
}
void setTrack(sp<MusicTrack> track) override
{
std::lock_guard<std::recursive_mutex> l(this->audio_lock);
LogInfo("Setting track to %p", track.get());
this->track = track;
while (!music_queue.empty())
music_queue.pop();
}
void stopMusic() override
{
std::future<void> outstanding_get_music;
{
std::lock_guard<std::recursive_mutex> l(this->audio_lock);
this->music_playing = false;
this->track = nullptr;
if (this->get_music_future.valid())
outstanding_get_music = std::move(this->get_music_future);
while (!music_queue.empty())
music_queue.pop();
}
if (outstanding_get_music.valid())
outstanding_get_music.wait();
}
virtual ~SDLRawBackend()
{
// Lock the device and stop any outstanding music threads to ensure everything is dead
// before destroying the device
SDL_LockAudioDevice(devID);
SDL_PauseAudioDevice(devID, 1);
this->stopMusic();
SDL_UnlockAudioDevice(devID);
SDL_CloseAudioDevice(devID);
SDL_QuitSubSystem(SDL_INIT_AUDIO);
}
virtual const AudioFormat &getPreferredFormat() { return preferred_format; }
float getGain(Gain g) override
{
float reqGain = 0;
switch (g)
{
case Gain::Global:
reqGain = overall_volume;
break;
case Gain::Sample:
reqGain = sound_volume;
break;
case Gain::Music:
reqGain = music_volume;
break;
}
return reqGain;
}
void setGain(Gain g, float f) override
{
// Clamp to 0..1
f = std::min(1.0f, std::max(0.0f, f));
switch (g)
{
case Gain::Global:
overall_volume = f;
break;
case Gain::Sample:
sound_volume = f;
break;
case Gain::Music:
music_volume = f;
break;
}
}
};
void unwrap_callback(void *userdata, Uint8 *stream, int len)
{
auto backend = reinterpret_cast<SDLRawBackend *>(userdata);
backend->mixingCallback(stream, len);
}
class SDLRawBackendFactory : public SoundBackendFactory
{
public:
SoundBackend *create() override
{
LogWarning("Creating SDLRaw sound backend (Might have issues!)");
int ret = SDL_InitSubSystem(SDL_INIT_AUDIO);
if (ret < 0)
{
LogWarning("Failed to init SDL_AUDIO (%d) - %s", ret, SDL_GetError());
return nullptr;
}
return new SDLRawBackend();
}
virtual ~SDLRawBackendFactory() {}
};
}; // anonymous namespace
namespace OpenApoc
{
SoundBackendFactory *getSDLSoundBackend() { return new SDLRawBackendFactory(); }
} // namespace OpenApoc
<|endoftext|> |
<commit_before>/*************************************************************************
*
* 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: objshimp.hxx,v $
* $Revision: 1.45 $
*
* 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.
*
************************************************************************/
#ifndef _SFX_OBJSHIMP_HXX
#define _SFX_OBJSHIMP_HXX
//#include <hash_map>
#include <com/sun/star/frame/XModel.hpp>
#include <tools/datetime.hxx>
#include <svtools/securityoptions.hxx>
#include <sfx2/objsh.hxx>
#include "sfx2/docmacromode.hxx"
#include "bitset.hxx"
namespace svtools { class AsynchronLink; }
//====================================================================
DBG_NAMEEX(SfxObjectShell)
class SfxViewFrame;
struct MarkData_Impl
{
String aMark;
String aUserData;
SfxViewFrame* pFrame;
};
class SfxFrame;
class SfxToolBoxConfig;
class SfxAcceleratorManager;
class SfxBasicManagerHolder;
struct SfxObjectShell_Impl : public ::sfx2::IMacroDocumentAccess
{
::comphelper::EmbeddedObjectContainer* mpObjectContainer;
SfxAcceleratorManager* pAccMgr;
SfxConfigManager* pCfgMgr;
SfxBasicManagerHolder*
pBasicManager;
SfxObjectShell& rDocShell;
::com::sun::star::uno::Reference< ::com::sun::star::script::XLibraryContainer >
xBasicLibraries;
::com::sun::star::uno::Reference< ::com::sun::star::script::XLibraryContainer >
xDialogLibraries;
::sfx2::DocumentMacroMode
aMacroMode;
SfxProgress* pProgress;
String aTitle;
String aTempName;
DateTime nTime;
sal_uInt16 nVisualDocumentNumber;
sal_Int16 nDocumentSignatureState;
sal_Int16 nScriptingSignatureState;
sal_Bool bTemplateConfig:1,
bInList:1, // ob per First/Next erreichbar
bClosing:1, // sal_True w"aehrend Close(), um Benachrichtigungs-Rekursionen zu verhindern
bSetInPlaceObj:1, // sal_True, falls bereits versucht wurde pInPlaceObject zu casten
bIsSaving:1,
bPasswd:1,
bIsTmp:1,
bIsNamedVisible:1,
bIsTemplate:1,
bIsAbortingImport:1, // Importvorgang soll abgebrochen werden.
bImportDone : 1, //Import schon fertig? Fuer AutoReload von Docs.
bInPrepareClose : 1,
bPreparedForClose : 1,
bWaitingForPicklist : 1,// Muss noch in die Pickliste
bModuleSearched : 1,
bIsHelpObjSh : 1,
bForbidCaching : 1,
bForbidReload : 1,
bSupportsEventMacros: 1,
bLoadingWindows: 1,
bBasicInitialized :1,
//bHidden :1, // indicates a hidden view shell
bIsPrintJobCancelable :1, // Stampit disable/enable cancel button for print jobs ... default = true = enable!
bOwnsStorage:1,
bNoBaseURL:1,
bInitialized:1,
bSignatureErrorIsShown:1,
bModelInitialized:1, // whether the related model is initialized
bPreserveVersions:1,
m_bMacroSignBroken:1, // whether the macro signature was explicitly broken
m_bNoBasicCapabilities:1,
bQueryLoadTemplate:1,
bLoadReadonly:1,
bUseUserData:1,
bSaveVersionOnClose:1,
m_bSharedXMLFlag:1, // whether the flag should be stored in xml file
m_bAllowShareControlFileClean:1; // whether the flag should be stored in xml file
String aNewName; // Der Name, unter dem das Doc gespeichert
// werden soll
IndexBitSet aBitSet;
sal_uInt32 lErr;
sal_uInt16 nEventId; // falls vor Activate noch ein
// Open/Create gesendet werden mu/s
sal_Bool bDoNotTouchDocInfo;
AutoReloadTimer_Impl *pReloadTimer;
MarkData_Impl* pMarkData;
sal_uInt16 nLoadedFlags;
sal_uInt16 nFlagsInProgress;
String aMark;
Size aViewSize; // wird leider vom Writer beim
sal_Bool bInFrame; // HTML-Import gebraucht
sal_Bool bModalMode;
sal_Bool bRunningMacro;
sal_Bool bReloadAvailable;
sal_uInt16 nAutoLoadLocks;
SfxModule* pModule;
SfxFrame* pFrame;
SfxToolBoxConfig* pTbxConfig;
SfxEventConfigItem_Impl* pEventConfig;
SfxObjectShellFlags eFlags;
svtools::AsynchronLink* pCloser;
String aBaseURL;
sal_Bool bReadOnlyUI;
SvRefBaseRef xHeaderAttributes;
sal_Bool bHiddenLockedByAPI;
sal_Bool bInCloseEvent;
::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel > xModel;
sal_uInt16 nStyleFilter;
sal_Bool bDisposing;
sal_Bool m_bEnableSetModified;
sal_Bool m_bIsModified;
Rectangle m_aVisArea;
MapUnit m_nMapUnit;
sal_Bool m_bCreateTempStor;
::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage > m_xDocStorage;
::com::sun::star::uno::Reference<
::com::sun::star::util::XModifyListener > m_xDocInfoListener;
sal_Bool m_bIsInit;
::rtl::OUString m_aSharedFileURL;
SfxObjectShell_Impl( SfxObjectShell& _rDocShell );
virtual ~SfxObjectShell_Impl();
// IMacroDocumentAccess overridables
virtual sal_Int16 getImposedMacroExecMode() const;
virtual sal_Bool setImposedMacroExecMode( sal_uInt16 nMacroMode );
virtual ::rtl::OUString getDocumentLocation() const;
virtual ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage > getLastCommitDocumentStorage();
virtual sal_Bool documentStorageHasMacros() const;
virtual ::com::sun::star::uno::Reference< ::com::sun::star::document::XEmbeddedScripts > getEmbeddedDocumentScripts() const;
virtual sal_Int16 getScriptingSignatureState() const;
virtual void showBrokenSignatureWarning( const ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionHandler >& _rxInteraction ) const;
};
#endif
<commit_msg>INTEGRATION: CWS dba30b (1.43.6); FILE MERGED 2008/04/15 22:18:31 fs 1.43.6.2: RESYNC: (1.43-1.44); FILE MERGED 2008/03/17 09:13:49 fs 1.43.6.1: during #152837#: IMacroDocumentAccess::(s|g)etImposedMacroExecMode renamed to (s|g)etCurrentMacroExecMode, to better fit its changed semantics<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: objshimp.hxx,v $
* $Revision: 1.46 $
*
* 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.
*
************************************************************************/
#ifndef _SFX_OBJSHIMP_HXX
#define _SFX_OBJSHIMP_HXX
//#include <hash_map>
#include <com/sun/star/frame/XModel.hpp>
#include <tools/datetime.hxx>
#include <svtools/securityoptions.hxx>
#include <sfx2/objsh.hxx>
#include "sfx2/docmacromode.hxx"
#include "bitset.hxx"
namespace svtools { class AsynchronLink; }
//====================================================================
DBG_NAMEEX(SfxObjectShell)
class SfxViewFrame;
struct MarkData_Impl
{
String aMark;
String aUserData;
SfxViewFrame* pFrame;
};
class SfxFrame;
class SfxToolBoxConfig;
class SfxAcceleratorManager;
class SfxBasicManagerHolder;
struct SfxObjectShell_Impl : public ::sfx2::IMacroDocumentAccess
{
::comphelper::EmbeddedObjectContainer* mpObjectContainer;
SfxAcceleratorManager* pAccMgr;
SfxConfigManager* pCfgMgr;
SfxBasicManagerHolder*
pBasicManager;
SfxObjectShell& rDocShell;
::com::sun::star::uno::Reference< ::com::sun::star::script::XLibraryContainer >
xBasicLibraries;
::com::sun::star::uno::Reference< ::com::sun::star::script::XLibraryContainer >
xDialogLibraries;
::sfx2::DocumentMacroMode
aMacroMode;
SfxProgress* pProgress;
String aTitle;
String aTempName;
DateTime nTime;
sal_uInt16 nVisualDocumentNumber;
sal_Int16 nDocumentSignatureState;
sal_Int16 nScriptingSignatureState;
sal_Bool bTemplateConfig:1,
bInList:1, // ob per First/Next erreichbar
bClosing:1, // sal_True w"aehrend Close(), um Benachrichtigungs-Rekursionen zu verhindern
bSetInPlaceObj:1, // sal_True, falls bereits versucht wurde pInPlaceObject zu casten
bIsSaving:1,
bPasswd:1,
bIsTmp:1,
bIsNamedVisible:1,
bIsTemplate:1,
bIsAbortingImport:1, // Importvorgang soll abgebrochen werden.
bImportDone : 1, //Import schon fertig? Fuer AutoReload von Docs.
bInPrepareClose : 1,
bPreparedForClose : 1,
bWaitingForPicklist : 1,// Muss noch in die Pickliste
bModuleSearched : 1,
bIsHelpObjSh : 1,
bForbidCaching : 1,
bForbidReload : 1,
bSupportsEventMacros: 1,
bLoadingWindows: 1,
bBasicInitialized :1,
//bHidden :1, // indicates a hidden view shell
bIsPrintJobCancelable :1, // Stampit disable/enable cancel button for print jobs ... default = true = enable!
bOwnsStorage:1,
bNoBaseURL:1,
bInitialized:1,
bSignatureErrorIsShown:1,
bModelInitialized:1, // whether the related model is initialized
bPreserveVersions:1,
m_bMacroSignBroken:1, // whether the macro signature was explicitly broken
m_bNoBasicCapabilities:1,
bQueryLoadTemplate:1,
bLoadReadonly:1,
bUseUserData:1,
bSaveVersionOnClose:1,
m_bSharedXMLFlag:1, // whether the flag should be stored in xml file
m_bAllowShareControlFileClean:1; // whether the flag should be stored in xml file
String aNewName; // Der Name, unter dem das Doc gespeichert
// werden soll
IndexBitSet aBitSet;
sal_uInt32 lErr;
sal_uInt16 nEventId; // falls vor Activate noch ein
// Open/Create gesendet werden mu/s
sal_Bool bDoNotTouchDocInfo;
AutoReloadTimer_Impl *pReloadTimer;
MarkData_Impl* pMarkData;
sal_uInt16 nLoadedFlags;
sal_uInt16 nFlagsInProgress;
String aMark;
Size aViewSize; // wird leider vom Writer beim
sal_Bool bInFrame; // HTML-Import gebraucht
sal_Bool bModalMode;
sal_Bool bRunningMacro;
sal_Bool bReloadAvailable;
sal_uInt16 nAutoLoadLocks;
SfxModule* pModule;
SfxFrame* pFrame;
SfxToolBoxConfig* pTbxConfig;
SfxEventConfigItem_Impl* pEventConfig;
SfxObjectShellFlags eFlags;
svtools::AsynchronLink* pCloser;
String aBaseURL;
sal_Bool bReadOnlyUI;
SvRefBaseRef xHeaderAttributes;
sal_Bool bHiddenLockedByAPI;
sal_Bool bInCloseEvent;
::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel > xModel;
sal_uInt16 nStyleFilter;
sal_Bool bDisposing;
sal_Bool m_bEnableSetModified;
sal_Bool m_bIsModified;
Rectangle m_aVisArea;
MapUnit m_nMapUnit;
sal_Bool m_bCreateTempStor;
::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage > m_xDocStorage;
::com::sun::star::uno::Reference<
::com::sun::star::util::XModifyListener > m_xDocInfoListener;
sal_Bool m_bIsInit;
::rtl::OUString m_aSharedFileURL;
SfxObjectShell_Impl( SfxObjectShell& _rDocShell );
virtual ~SfxObjectShell_Impl();
// IMacroDocumentAccess overridables
virtual sal_Int16 getCurrentMacroExecMode() const;
virtual sal_Bool setCurrentMacroExecMode( sal_uInt16 nMacroMode );
virtual ::rtl::OUString getDocumentLocation() const;
virtual ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage > getLastCommitDocumentStorage();
virtual sal_Bool documentStorageHasMacros() const;
virtual ::com::sun::star::uno::Reference< ::com::sun::star::document::XEmbeddedScripts > getEmbeddedDocumentScripts() const;
virtual sal_Int16 getScriptingSignatureState() const;
virtual void showBrokenSignatureWarning( const ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionHandler >& _rxInteraction ) const;
};
#endif
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "buildsettingspropertiespage.h"
#include "buildstep.h"
#include "buildstepspage.h"
#include "project.h"
#include "buildconfiguration.h"
#include <coreplugin/coreconstants.h>
#include <extensionsystem/pluginmanager.h>
#include <QtCore/QDebug>
#include <QtCore/QPair>
#include <QtGui/QInputDialog>
#include <QtGui/QLabel>
#include <QtGui/QVBoxLayout>
#include <QtGui/QMenu>
using namespace ProjectExplorer;
using namespace ProjectExplorer::Internal;
///
/// BuildSettingsPanelFactory
///
bool BuildSettingsPanelFactory::supports(Project *project)
{
return project->hasBuildSettings();
}
PropertiesPanel *BuildSettingsPanelFactory::createPanel(Project *project)
{
return new BuildSettingsPanel(project);
}
///
/// BuildSettingsPanel
///
BuildSettingsPanel::BuildSettingsPanel(Project *project)
: PropertiesPanel(),
m_widget(new BuildSettingsWidget(project))
{
}
BuildSettingsPanel::~BuildSettingsPanel()
{
delete m_widget;
}
QString BuildSettingsPanel::name() const
{
return tr("Build Settings");
}
QWidget *BuildSettingsPanel::widget()
{
return m_widget;
}
///
// BuildSettingsSubWidgets
///
BuildSettingsSubWidgets::~BuildSettingsSubWidgets()
{
clear();
}
void BuildSettingsSubWidgets::addWidget(const QString &name, QWidget *widget)
{
QSpacerItem *item = new QSpacerItem(1, 10, QSizePolicy::Fixed, QSizePolicy::Fixed);
QLabel *label = new QLabel(this);
label->setText(name);
QFont f = label->font();
f.setBold(true);
f.setPointSizeF(f.pointSizeF() *1.2);
label->setFont(f);
layout()->addItem(item);
layout()->addWidget(label);
layout()->addWidget(widget);
m_labels.append(label);
m_widgets.append(widget);
}
void BuildSettingsSubWidgets::clear()
{
foreach(QSpacerItem *item, m_spacerItems)
layout()->removeItem(item);
qDeleteAll(m_spacerItems);
qDeleteAll(m_widgets);
qDeleteAll(m_labels);
m_widgets.clear();
m_labels.clear();
}
QList<QWidget *> BuildSettingsSubWidgets::widgets() const
{
return m_widgets;
}
BuildSettingsSubWidgets::BuildSettingsSubWidgets(QWidget *parent)
: QWidget(parent)
{
new QVBoxLayout(this);
layout()->setMargin(0);
}
///
/// BuildSettingsWidget
///
BuildSettingsWidget::~BuildSettingsWidget()
{
}
BuildSettingsWidget::BuildSettingsWidget(Project *project)
: m_project(project)
{
QVBoxLayout *vbox = new QVBoxLayout(this);
vbox->setContentsMargins(0, -1, 0, -1);
QHBoxLayout *hbox = new QHBoxLayout();
hbox->addWidget(new QLabel(tr("Edit Build Configuration:"), this));
m_buildConfigurationComboBox = new QComboBox(this);
m_buildConfigurationComboBox->setSizeAdjustPolicy(QComboBox::AdjustToContents);
hbox->addWidget(m_buildConfigurationComboBox);
m_addButton = new QPushButton(this);
m_addButton->setText(tr("Add"));
m_addButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
hbox->addWidget(m_addButton);
m_removeButton = new QPushButton(this);
m_removeButton->setText(tr("Remove"));
m_removeButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
hbox->addWidget(m_removeButton);
hbox->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Fixed));
vbox->addLayout(hbox);
m_subWidgets = new BuildSettingsSubWidgets(this);
vbox->addWidget(m_subWidgets);
m_addButtonMenu = new QMenu(this);
m_addButton->setMenu(m_addButtonMenu);
updateAddButtonMenu();
m_buildConfiguration = m_project->activeBuildConfiguration()->name();
connect(m_buildConfigurationComboBox, SIGNAL(currentIndexChanged(int)),
this, SLOT(currentIndexChanged(int)));
connect(m_removeButton, SIGNAL(clicked()),
this, SLOT(deleteConfiguration()));
connect(m_project, SIGNAL(buildConfigurationDisplayNameChanged(const QString &)),
this, SLOT(buildConfigurationDisplayNameChanged(const QString &)));
if (m_project->buildConfigurationFactory())
connect(m_project->buildConfigurationFactory(), SIGNAL(availableCreationTypesChanged()), SLOT(updateAddButtonMenu()));
updateBuildSettings();
}
void BuildSettingsWidget::updateAddButtonMenu()
{
m_addButtonMenu->clear();
m_addButtonMenu->addAction(tr("&Clone Selected"),
this, SLOT(cloneConfiguration()));
IBuildConfigurationFactory *factory = m_project->buildConfigurationFactory();
if (factory) {
foreach (const QString &type, factory->availableCreationTypes()) {
QAction *action = m_addButtonMenu->addAction(factory->displayNameForType(type), this, SLOT(createConfiguration()));
action->setData(type);
}
}
}
void BuildSettingsWidget::buildConfigurationDisplayNameChanged(const QString &buildConfiguration)
{
for (int i=0; i<m_buildConfigurationComboBox->count(); ++i) {
if (m_buildConfigurationComboBox->itemData(i).toString() == buildConfiguration) {
m_buildConfigurationComboBox->setItemText(i, m_project->buildConfiguration(buildConfiguration)->displayName());
break;
}
}
}
void BuildSettingsWidget::updateBuildSettings()
{
// TODO save position, entry from combbox
// Delete old tree items
bool blocked = m_buildConfigurationComboBox->blockSignals(true);
m_buildConfigurationComboBox->clear();
m_subWidgets->clear();
// update buttons
m_removeButton->setEnabled(m_project->buildConfigurations().size() > 1);
// Add pages
BuildConfigWidget *generalConfigWidget = m_project->createConfigWidget();
m_subWidgets->addWidget(generalConfigWidget->displayName(), generalConfigWidget);
m_subWidgets->addWidget(tr("Build Steps"), new BuildStepsPage(m_project));
m_subWidgets->addWidget(tr("Clean Steps"), new BuildStepsPage(m_project, true));
QList<BuildConfigWidget *> subConfigWidgets = m_project->subConfigWidgets();
foreach (BuildConfigWidget *subConfigWidget, subConfigWidgets)
m_subWidgets->addWidget(subConfigWidget->displayName(), subConfigWidget);
// Add tree items
foreach (const BuildConfiguration *bc, m_project->buildConfigurations()) {
m_buildConfigurationComboBox->addItem(bc->displayName(), bc->name());
if (bc->name() == m_buildConfiguration)
m_buildConfigurationComboBox->setCurrentIndex(m_buildConfigurationComboBox->count() - 1);
}
m_buildConfigurationComboBox->blockSignals(blocked);
// TODO Restore position, entry from combbox
// TODO? select entry from combobox ?
activeBuildConfigurationChanged();
}
void BuildSettingsWidget::currentIndexChanged(int index)
{
m_buildConfiguration = m_buildConfigurationComboBox->itemData(index).toString();
activeBuildConfigurationChanged();
}
void BuildSettingsWidget::activeBuildConfigurationChanged()
{
for (int i = 0; i < m_buildConfigurationComboBox->count(); ++i) {
if (m_buildConfigurationComboBox->itemData(i).toString() == m_buildConfiguration) {
m_buildConfigurationComboBox->setCurrentIndex(i);
break;
}
}
foreach (QWidget *widget, m_subWidgets->widgets()) {
if (BuildConfigWidget *buildStepWidget = qobject_cast<BuildConfigWidget*>(widget)) {
buildStepWidget->init(m_buildConfiguration);
}
}
}
void BuildSettingsWidget::createConfiguration()
{
QAction *action = qobject_cast<QAction *>(sender());
const QString &type = action->data().toString();
if (m_project->buildConfigurationFactory()->create(type)) {
// TODO switching to last buildconfiguration in list might not be what we want
m_buildConfiguration = m_project->buildConfigurations().last()->name();
updateBuildSettings();
}
}
void BuildSettingsWidget::cloneConfiguration()
{
const QString configuration = m_buildConfigurationComboBox->itemData(m_buildConfigurationComboBox->currentIndex()).toString();
cloneConfiguration(configuration);
}
void BuildSettingsWidget::deleteConfiguration()
{
const QString configuration = m_buildConfigurationComboBox->itemData(m_buildConfigurationComboBox->currentIndex()).toString();
deleteConfiguration(configuration);
}
void BuildSettingsWidget::cloneConfiguration(const QString &sourceConfiguration)
{
if (sourceConfiguration.isEmpty())
return;
QString newBuildConfiguration = QInputDialog::getText(this, tr("Clone configuration"), tr("New Configuration Name:"));
if (newBuildConfiguration.isEmpty())
return;
QString newDisplayName = newBuildConfiguration;
QStringList buildConfigurationDisplayNames;
foreach(BuildConfiguration *bc, m_project->buildConfigurations())
buildConfigurationDisplayNames << bc->displayName();
newDisplayName = Project::makeUnique(newDisplayName, buildConfigurationDisplayNames);
QStringList buildConfigurationNames;
foreach(BuildConfiguration *bc, m_project->buildConfigurations())
buildConfigurationNames << bc->name();
newBuildConfiguration = Project::makeUnique(newBuildConfiguration, buildConfigurationNames);
m_project->copyBuildConfiguration(sourceConfiguration, newBuildConfiguration);
m_project->setDisplayNameFor(m_project->buildConfiguration(newBuildConfiguration), newDisplayName);
m_buildConfiguration = newBuildConfiguration;
updateBuildSettings();
}
void BuildSettingsWidget::deleteConfiguration(const QString &deleteConfiguration)
{
if (deleteConfiguration.isEmpty() || m_project->buildConfigurations().size() <= 1)
return;
if (m_project->activeBuildConfiguration()->name() == deleteConfiguration) {
foreach (BuildConfiguration *bc, m_project->buildConfigurations()) {
if (bc->name() != deleteConfiguration) {
m_project->setActiveBuildConfiguration(bc);
break;
}
}
}
if (m_buildConfiguration == deleteConfiguration) {
foreach (const BuildConfiguration *bc, m_project->buildConfigurations()) {
if (bc->name() != deleteConfiguration) {
m_buildConfiguration = bc->name();
break;
}
}
}
m_project->removeBuildConfiguration(m_project->buildConfiguration(deleteConfiguration));
updateBuildSettings();
}
<commit_msg>Fix handling of spacers on Projects pane<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "buildsettingspropertiespage.h"
#include "buildstep.h"
#include "buildstepspage.h"
#include "project.h"
#include "buildconfiguration.h"
#include <coreplugin/coreconstants.h>
#include <extensionsystem/pluginmanager.h>
#include <QtCore/QDebug>
#include <QtCore/QPair>
#include <QtGui/QInputDialog>
#include <QtGui/QLabel>
#include <QtGui/QVBoxLayout>
#include <QtGui/QMenu>
using namespace ProjectExplorer;
using namespace ProjectExplorer::Internal;
///
/// BuildSettingsPanelFactory
///
bool BuildSettingsPanelFactory::supports(Project *project)
{
return project->hasBuildSettings();
}
PropertiesPanel *BuildSettingsPanelFactory::createPanel(Project *project)
{
return new BuildSettingsPanel(project);
}
///
/// BuildSettingsPanel
///
BuildSettingsPanel::BuildSettingsPanel(Project *project)
: PropertiesPanel(),
m_widget(new BuildSettingsWidget(project))
{
}
BuildSettingsPanel::~BuildSettingsPanel()
{
delete m_widget;
}
QString BuildSettingsPanel::name() const
{
return tr("Build Settings");
}
QWidget *BuildSettingsPanel::widget()
{
return m_widget;
}
///
// BuildSettingsSubWidgets
///
BuildSettingsSubWidgets::~BuildSettingsSubWidgets()
{
clear();
}
void BuildSettingsSubWidgets::addWidget(const QString &name, QWidget *widget)
{
QSpacerItem *item = new QSpacerItem(1, 10, QSizePolicy::Fixed, QSizePolicy::Fixed);
QLabel *label = new QLabel(this);
label->setText(name);
QFont f = label->font();
f.setBold(true);
f.setPointSizeF(f.pointSizeF() *1.2);
label->setFont(f);
layout()->addItem(item);
layout()->addWidget(label);
layout()->addWidget(widget);
m_spacerItems.append(item);
m_labels.append(label);
m_widgets.append(widget);
}
void BuildSettingsSubWidgets::clear()
{
foreach(QSpacerItem *item, m_spacerItems)
layout()->removeItem(item);
qDeleteAll(m_spacerItems);
qDeleteAll(m_widgets);
qDeleteAll(m_labels);
m_widgets.clear();
m_labels.clear();
m_spacerItems.clear();
}
QList<QWidget *> BuildSettingsSubWidgets::widgets() const
{
return m_widgets;
}
BuildSettingsSubWidgets::BuildSettingsSubWidgets(QWidget *parent)
: QWidget(parent)
{
new QVBoxLayout(this);
layout()->setMargin(0);
}
///
/// BuildSettingsWidget
///
BuildSettingsWidget::~BuildSettingsWidget()
{
}
BuildSettingsWidget::BuildSettingsWidget(Project *project)
: m_project(project)
{
QVBoxLayout *vbox = new QVBoxLayout(this);
vbox->setContentsMargins(0, -1, 0, -1);
QHBoxLayout *hbox = new QHBoxLayout();
hbox->addWidget(new QLabel(tr("Edit Build Configuration:"), this));
m_buildConfigurationComboBox = new QComboBox(this);
m_buildConfigurationComboBox->setSizeAdjustPolicy(QComboBox::AdjustToContents);
hbox->addWidget(m_buildConfigurationComboBox);
m_addButton = new QPushButton(this);
m_addButton->setText(tr("Add"));
m_addButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
hbox->addWidget(m_addButton);
m_removeButton = new QPushButton(this);
m_removeButton->setText(tr("Remove"));
m_removeButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
hbox->addWidget(m_removeButton);
hbox->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Fixed));
vbox->addLayout(hbox);
m_subWidgets = new BuildSettingsSubWidgets(this);
vbox->addWidget(m_subWidgets);
m_addButtonMenu = new QMenu(this);
m_addButton->setMenu(m_addButtonMenu);
updateAddButtonMenu();
m_buildConfiguration = m_project->activeBuildConfiguration()->name();
connect(m_buildConfigurationComboBox, SIGNAL(currentIndexChanged(int)),
this, SLOT(currentIndexChanged(int)));
connect(m_removeButton, SIGNAL(clicked()),
this, SLOT(deleteConfiguration()));
connect(m_project, SIGNAL(buildConfigurationDisplayNameChanged(const QString &)),
this, SLOT(buildConfigurationDisplayNameChanged(const QString &)));
if (m_project->buildConfigurationFactory())
connect(m_project->buildConfigurationFactory(), SIGNAL(availableCreationTypesChanged()), SLOT(updateAddButtonMenu()));
updateBuildSettings();
}
void BuildSettingsWidget::updateAddButtonMenu()
{
m_addButtonMenu->clear();
m_addButtonMenu->addAction(tr("&Clone Selected"),
this, SLOT(cloneConfiguration()));
IBuildConfigurationFactory *factory = m_project->buildConfigurationFactory();
if (factory) {
foreach (const QString &type, factory->availableCreationTypes()) {
QAction *action = m_addButtonMenu->addAction(factory->displayNameForType(type), this, SLOT(createConfiguration()));
action->setData(type);
}
}
}
void BuildSettingsWidget::buildConfigurationDisplayNameChanged(const QString &buildConfiguration)
{
for (int i=0; i<m_buildConfigurationComboBox->count(); ++i) {
if (m_buildConfigurationComboBox->itemData(i).toString() == buildConfiguration) {
m_buildConfigurationComboBox->setItemText(i, m_project->buildConfiguration(buildConfiguration)->displayName());
break;
}
}
}
void BuildSettingsWidget::updateBuildSettings()
{
// TODO save position, entry from combbox
// Delete old tree items
bool blocked = m_buildConfigurationComboBox->blockSignals(true);
m_buildConfigurationComboBox->clear();
m_subWidgets->clear();
// update buttons
m_removeButton->setEnabled(m_project->buildConfigurations().size() > 1);
// Add pages
BuildConfigWidget *generalConfigWidget = m_project->createConfigWidget();
m_subWidgets->addWidget(generalConfigWidget->displayName(), generalConfigWidget);
m_subWidgets->addWidget(tr("Build Steps"), new BuildStepsPage(m_project));
m_subWidgets->addWidget(tr("Clean Steps"), new BuildStepsPage(m_project, true));
QList<BuildConfigWidget *> subConfigWidgets = m_project->subConfigWidgets();
foreach (BuildConfigWidget *subConfigWidget, subConfigWidgets)
m_subWidgets->addWidget(subConfigWidget->displayName(), subConfigWidget);
// Add tree items
foreach (const BuildConfiguration *bc, m_project->buildConfigurations()) {
m_buildConfigurationComboBox->addItem(bc->displayName(), bc->name());
if (bc->name() == m_buildConfiguration)
m_buildConfigurationComboBox->setCurrentIndex(m_buildConfigurationComboBox->count() - 1);
}
m_buildConfigurationComboBox->blockSignals(blocked);
// TODO Restore position, entry from combbox
// TODO? select entry from combobox ?
activeBuildConfigurationChanged();
}
void BuildSettingsWidget::currentIndexChanged(int index)
{
m_buildConfiguration = m_buildConfigurationComboBox->itemData(index).toString();
activeBuildConfigurationChanged();
}
void BuildSettingsWidget::activeBuildConfigurationChanged()
{
for (int i = 0; i < m_buildConfigurationComboBox->count(); ++i) {
if (m_buildConfigurationComboBox->itemData(i).toString() == m_buildConfiguration) {
m_buildConfigurationComboBox->setCurrentIndex(i);
break;
}
}
foreach (QWidget *widget, m_subWidgets->widgets()) {
if (BuildConfigWidget *buildStepWidget = qobject_cast<BuildConfigWidget*>(widget)) {
buildStepWidget->init(m_buildConfiguration);
}
}
}
void BuildSettingsWidget::createConfiguration()
{
QAction *action = qobject_cast<QAction *>(sender());
const QString &type = action->data().toString();
if (m_project->buildConfigurationFactory()->create(type)) {
// TODO switching to last buildconfiguration in list might not be what we want
m_buildConfiguration = m_project->buildConfigurations().last()->name();
updateBuildSettings();
}
}
void BuildSettingsWidget::cloneConfiguration()
{
const QString configuration = m_buildConfigurationComboBox->itemData(m_buildConfigurationComboBox->currentIndex()).toString();
cloneConfiguration(configuration);
}
void BuildSettingsWidget::deleteConfiguration()
{
const QString configuration = m_buildConfigurationComboBox->itemData(m_buildConfigurationComboBox->currentIndex()).toString();
deleteConfiguration(configuration);
}
void BuildSettingsWidget::cloneConfiguration(const QString &sourceConfiguration)
{
if (sourceConfiguration.isEmpty())
return;
QString newBuildConfiguration = QInputDialog::getText(this, tr("Clone configuration"), tr("New Configuration Name:"));
if (newBuildConfiguration.isEmpty())
return;
QString newDisplayName = newBuildConfiguration;
QStringList buildConfigurationDisplayNames;
foreach(BuildConfiguration *bc, m_project->buildConfigurations())
buildConfigurationDisplayNames << bc->displayName();
newDisplayName = Project::makeUnique(newDisplayName, buildConfigurationDisplayNames);
QStringList buildConfigurationNames;
foreach(BuildConfiguration *bc, m_project->buildConfigurations())
buildConfigurationNames << bc->name();
newBuildConfiguration = Project::makeUnique(newBuildConfiguration, buildConfigurationNames);
m_project->copyBuildConfiguration(sourceConfiguration, newBuildConfiguration);
m_project->setDisplayNameFor(m_project->buildConfiguration(newBuildConfiguration), newDisplayName);
m_buildConfiguration = newBuildConfiguration;
updateBuildSettings();
}
void BuildSettingsWidget::deleteConfiguration(const QString &deleteConfiguration)
{
if (deleteConfiguration.isEmpty() || m_project->buildConfigurations().size() <= 1)
return;
if (m_project->activeBuildConfiguration()->name() == deleteConfiguration) {
foreach (BuildConfiguration *bc, m_project->buildConfigurations()) {
if (bc->name() != deleteConfiguration) {
m_project->setActiveBuildConfiguration(bc);
break;
}
}
}
if (m_buildConfiguration == deleteConfiguration) {
foreach (const BuildConfiguration *bc, m_project->buildConfigurations()) {
if (bc->name() != deleteConfiguration) {
m_buildConfiguration = bc->name();
break;
}
}
}
m_project->removeBuildConfiguration(m_project->buildConfiguration(deleteConfiguration));
updateBuildSettings();
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: openflag.hxx,v $
*
* $Revision: 1.1.1.1 $
*
* last change: $Author: hr $ $Date: 2000-09-18 16:52:34 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _SFX_OPENFLAG_HXX
#define _SFX_OPENFLAG_HXX
// Datei zum Bearbeiten "offnen, anschliessend funktioniert nur noch
// die dritte Variante (Lesen einer Kopie)
#define SFX_STREAM_READWRITE (STREAM_READWRITE | STREAM_SHARE_DENYWRITE)
// Ich arbeite roh auf dem Original, keine Kopie
// -> Datei kann anschliessend nicht zum Bearbeiten ge"offnet werden
#define SFX_STREAM_READONLY (STREAM_READ | STREAM_SHARE_DENYWRITE) // + !bDirect
// Jemand anders bearbeitet das File, es wird eine Kopie erstellt
// -> Datei kann anschliessend zum Bearbeiten ge"offnet werden
#define SFX_STREAM_READONLY_MAKECOPY (STREAM_READ | STREAM_SHARE_DENYNONE)
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.1.1.1.1086); FILE MERGED 2005/09/06 13:05:35 rt 1.1.1.1.1086.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: openflag.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2005-09-07 19:08:20 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _SFX_OPENFLAG_HXX
#define _SFX_OPENFLAG_HXX
// Datei zum Bearbeiten "offnen, anschliessend funktioniert nur noch
// die dritte Variante (Lesen einer Kopie)
#define SFX_STREAM_READWRITE (STREAM_READWRITE | STREAM_SHARE_DENYWRITE)
// Ich arbeite roh auf dem Original, keine Kopie
// -> Datei kann anschliessend nicht zum Bearbeiten ge"offnet werden
#define SFX_STREAM_READONLY (STREAM_READ | STREAM_SHARE_DENYWRITE) // + !bDirect
// Jemand anders bearbeitet das File, es wird eine Kopie erstellt
// -> Datei kann anschliessend zum Bearbeiten ge"offnet werden
#define SFX_STREAM_READONLY_MAKECOPY (STREAM_READ | STREAM_SHARE_DENYNONE)
#endif
<|endoftext|> |
<commit_before>//
// libavg - Media Playback Engine.
// Copyright (C) 2003-2011 Ulrich von Zadow
//
// 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 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
//
// Current versions can be found at www.libavg.de
//
#include "ThreadProfiler.h"
#include "Logger.h"
#include "Exception.h"
#include "ProfilingZone.h"
#include "ScopeTimer.h"
#include <sstream>
#include <iomanip>
#include <iostream>
using namespace std;
using namespace boost;
namespace avg {
thread_specific_ptr<ThreadProfiler*> ThreadProfiler::s_pInstance;
ThreadProfiler* ThreadProfiler::get()
{
if (s_pInstance.get() == 0) {
s_pInstance.reset(new (ThreadProfiler*));
*s_pInstance = new ThreadProfiler();
}
return *s_pInstance;
}
void ThreadProfiler::kill()
{
s_pInstance.reset();
}
ThreadProfiler::ThreadProfiler()
: m_sName(""),
m_LogCategory(Logger::PROFILE)
{
m_bRunning = false;
ScopeTimer::enableTimers(Logger::get()->isFlagSet(Logger::PROFILE));
}
ThreadProfiler::~ThreadProfiler()
{
}
void ThreadProfiler::setLogCategory(long category)
{
AVG_ASSERT(!m_bRunning);
m_LogCategory = category;
}
void ThreadProfiler::start()
{
m_bRunning = true;
}
void ThreadProfiler::restart()
{
ZoneVector::iterator it;
for (it = m_Zones.begin(); it != m_Zones.end(); ++it) {
(*it)->restart();
}
}
void ThreadProfiler::startZone(const ProfilingZoneID& zoneID)
{
ZoneMap::iterator it = m_ZoneMap.find(&zoneID);
// Duplicated code to avoid instantiating a new smart pointer when it's not
// necessary.
if (it == m_ZoneMap.end()) {
ProfilingZonePtr pZone = addZone(zoneID);
pZone->start();
m_ActiveZones.push_back(pZone);
} else {
ProfilingZonePtr& pZone = it->second;
pZone->start();
m_ActiveZones.push_back(pZone);
}
}
void ThreadProfiler::stopZone(const ProfilingZoneID& zoneID)
{
ZoneMap::iterator it = m_ZoneMap.find(&zoneID);
ProfilingZonePtr& pZone = it->second;
pZone->stop();
m_ActiveZones.pop_back();
}
void ThreadProfiler::dumpStatistics()
{
if (!m_Zones.empty()) {
AVG_TRACE(m_LogCategory, "Thread " << m_sName);
AVG_TRACE(m_LogCategory, "Zone name Avg. time");
AVG_TRACE(m_LogCategory, "--------- ---------");
ZoneVector::iterator it;
for (it = m_Zones.begin(); it != m_Zones.end(); ++it) {
AVG_TRACE(m_LogCategory,
std::setw(35) << std::left
<< ((*it)->getIndentString()+(*it)->getName())
<< std::setw(9) << std::right << (*it)->getAvgUSecs());
}
AVG_TRACE(m_LogCategory, "");
}
}
void ThreadProfiler::reset()
{
ZoneVector::iterator it;
for (it = m_Zones.begin(); it != m_Zones.end(); ++it) {
(*it)->reset();
}
}
int ThreadProfiler::getNumZones()
{
return m_Zones.size();
}
const std::string& ThreadProfiler::getName() const
{
return m_sName;
}
void ThreadProfiler::setName(const std::string& sName)
{
m_sName = sName;
}
ProfilingZonePtr ThreadProfiler::addZone(const ProfilingZoneID& zoneID)
{
ProfilingZonePtr pZone(new ProfilingZone(zoneID));
m_ZoneMap[&zoneID] = pZone;
ZoneVector::iterator it;
int parentIndent = -2;
if (m_ActiveZones.empty()) {
it = m_Zones.end();
} else {
ProfilingZonePtr pActiveZone = m_ActiveZones.back();
bool bParentFound = false;
for (it = m_Zones.begin(); it != m_Zones.end(); ++it)
{
if (pActiveZone == *it) {
bParentFound = true;
break;
}
}
AVG_ASSERT(bParentFound);
parentIndent = pActiveZone->getIndentLevel();
++it;
for (; it != m_Zones.end() && (*it)->getIndentLevel() > parentIndent; ++it) {};
}
m_Zones.insert(it, pZone);
pZone->setIndentLevel(parentIndent+2);
return pZone;
}
}
<commit_msg>video branch: Merge from trunk.<commit_after>//
// libavg - Media Playback Engine.
// Copyright (C) 2003-2011 Ulrich von Zadow
//
// 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 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
//
// Current versions can be found at www.libavg.de
//
#include "ThreadProfiler.h"
#include "Logger.h"
#include "Exception.h"
#include "ProfilingZone.h"
#include "ScopeTimer.h"
#include <sstream>
#include <iomanip>
#include <iostream>
using namespace std;
using namespace boost;
namespace avg {
thread_specific_ptr<ThreadProfiler*> ThreadProfiler::s_pInstance;
ThreadProfiler* ThreadProfiler::get()
{
if (s_pInstance.get() == 0) {
s_pInstance.reset(new (ThreadProfiler*));
*s_pInstance = new ThreadProfiler();
}
return *s_pInstance;
}
void ThreadProfiler::kill()
{
delete *s_pInstance;
s_pInstance.reset();
}
ThreadProfiler::ThreadProfiler()
: m_sName(""),
m_LogCategory(Logger::PROFILE)
{
m_bRunning = false;
ScopeTimer::enableTimers(Logger::get()->isFlagSet(Logger::PROFILE));
}
ThreadProfiler::~ThreadProfiler()
{
}
void ThreadProfiler::setLogCategory(long category)
{
AVG_ASSERT(!m_bRunning);
m_LogCategory = category;
}
void ThreadProfiler::start()
{
m_bRunning = true;
}
void ThreadProfiler::restart()
{
ZoneVector::iterator it;
for (it = m_Zones.begin(); it != m_Zones.end(); ++it) {
(*it)->restart();
}
}
void ThreadProfiler::startZone(const ProfilingZoneID& zoneID)
{
ZoneMap::iterator it = m_ZoneMap.find(&zoneID);
// Duplicated code to avoid instantiating a new smart pointer when it's not
// necessary.
if (it == m_ZoneMap.end()) {
ProfilingZonePtr pZone = addZone(zoneID);
pZone->start();
m_ActiveZones.push_back(pZone);
} else {
ProfilingZonePtr& pZone = it->second;
pZone->start();
m_ActiveZones.push_back(pZone);
}
}
void ThreadProfiler::stopZone(const ProfilingZoneID& zoneID)
{
ZoneMap::iterator it = m_ZoneMap.find(&zoneID);
ProfilingZonePtr& pZone = it->second;
pZone->stop();
m_ActiveZones.pop_back();
}
void ThreadProfiler::dumpStatistics()
{
if (!m_Zones.empty()) {
AVG_TRACE(m_LogCategory, "Thread " << m_sName);
AVG_TRACE(m_LogCategory, "Zone name Avg. time");
AVG_TRACE(m_LogCategory, "--------- ---------");
ZoneVector::iterator it;
for (it = m_Zones.begin(); it != m_Zones.end(); ++it) {
AVG_TRACE(m_LogCategory,
std::setw(35) << std::left
<< ((*it)->getIndentString()+(*it)->getName())
<< std::setw(9) << std::right << (*it)->getAvgUSecs());
}
AVG_TRACE(m_LogCategory, "");
}
}
void ThreadProfiler::reset()
{
ZoneVector::iterator it;
for (it = m_Zones.begin(); it != m_Zones.end(); ++it) {
(*it)->reset();
}
}
int ThreadProfiler::getNumZones()
{
return m_Zones.size();
}
const std::string& ThreadProfiler::getName() const
{
return m_sName;
}
void ThreadProfiler::setName(const std::string& sName)
{
m_sName = sName;
}
ProfilingZonePtr ThreadProfiler::addZone(const ProfilingZoneID& zoneID)
{
ProfilingZonePtr pZone(new ProfilingZone(zoneID));
m_ZoneMap[&zoneID] = pZone;
ZoneVector::iterator it;
int parentIndent = -2;
if (m_ActiveZones.empty()) {
it = m_Zones.end();
} else {
ProfilingZonePtr pActiveZone = m_ActiveZones.back();
bool bParentFound = false;
for (it = m_Zones.begin(); it != m_Zones.end(); ++it)
{
if (pActiveZone == *it) {
bParentFound = true;
break;
}
}
AVG_ASSERT(bParentFound);
parentIndent = pActiveZone->getIndentLevel();
++it;
for (; it != m_Zones.end() && (*it)->getIndentLevel() > parentIndent; ++it) {};
}
m_Zones.insert(it, pZone);
pZone->setIndentLevel(parentIndent+2);
return pZone;
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: impldde.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: vg $ $Date: 2006-11-22 10:55:09 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _IMPLDDE_HXX
#define _IMPLDDE_HXX
#include <linksrc.hxx>
#include <tools/string.hxx>
class DdeConnection;
class DdeData;
class DdeLink;
class DdeRequest;
class DdeTransaction;
namespace sfx2
{
class SvDDEObject : public SvLinkSource
{
String sItem;
DdeConnection* pConnection;
DdeLink* pLink;
DdeRequest* pRequest;
::com::sun::star::uno::Any * pGetData;
BYTE bWaitForData : 1; // wird auf Daten gewartet?
BYTE nError : 7; // Error Code fuer den Dialog
BOOL ImplHasOtherFormat( DdeTransaction& );
DECL_LINK( ImplGetDDEData, DdeData* );
DECL_LINK( ImplDoneDDEData, void* );
protected:
virtual ~SvDDEObject();
public:
SvDDEObject();
virtual BOOL GetData( ::com::sun::star::uno::Any & rData /*out param*/,
const String & aMimeType,
BOOL bSynchron = FALSE );
virtual BOOL Connect( SvBaseLink * );
virtual void Edit( Window* pParent, sfx2::SvBaseLink* pBaseLink, const Link& rEndEditHdl );
virtual BOOL IsPending() const;
virtual BOOL IsDataComplete() const;
};
}
#endif
<commit_msg>INTEGRATION: CWS vgbugs07 (1.4.154); FILE MERGED 2007/06/04 13:34:39 vg 1.4.154.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: impldde.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: hr $ $Date: 2007-06-27 22:59:10 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _IMPLDDE_HXX
#define _IMPLDDE_HXX
#include <sfx2/linksrc.hxx>
#include <tools/string.hxx>
class DdeConnection;
class DdeData;
class DdeLink;
class DdeRequest;
class DdeTransaction;
namespace sfx2
{
class SvDDEObject : public SvLinkSource
{
String sItem;
DdeConnection* pConnection;
DdeLink* pLink;
DdeRequest* pRequest;
::com::sun::star::uno::Any * pGetData;
BYTE bWaitForData : 1; // wird auf Daten gewartet?
BYTE nError : 7; // Error Code fuer den Dialog
BOOL ImplHasOtherFormat( DdeTransaction& );
DECL_LINK( ImplGetDDEData, DdeData* );
DECL_LINK( ImplDoneDDEData, void* );
protected:
virtual ~SvDDEObject();
public:
SvDDEObject();
virtual BOOL GetData( ::com::sun::star::uno::Any & rData /*out param*/,
const String & aMimeType,
BOOL bSynchron = FALSE );
virtual BOOL Connect( SvBaseLink * );
virtual void Edit( Window* pParent, sfx2::SvBaseLink* pBaseLink, const Link& rEndEditHdl );
virtual BOOL IsPending() const;
virtual BOOL IsDataComplete() const;
};
}
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: viewfac.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: svesik $ $Date: 2004-04-21 13:21:31 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
// INCLUDE ---------------------------------------------------------------
#ifndef GCC
#pragma hdrstop
#endif
#include "app.hxx"
#include "viewfac.hxx"
// STATIC DATA -----------------------------------------------------------
DBG_NAME(SfxViewFactory);
SfxViewShell *SfxViewFactory::CreateInstance(SfxViewFrame *pFrame, SfxViewShell *pOldSh )
{
DBG_CHKTHIS(SfxViewFactory, 0);
return (*fnCreate)(pFrame, pOldSh);
}
void SfxViewFactory::InitFactory()
{
DBG_CHKTHIS(SfxViewFactory, 0);
(*fnInit)();
}
// CTOR / DTOR -----------------------------------------------------------
SfxViewFactory::SfxViewFactory( SfxViewCtor fnC, SfxViewInit fnI,
USHORT nOrdinal, const ResId& aDescrResId ):
fnCreate(fnC),
fnInit(fnI),
nOrd(nOrdinal),
aDescription(aDescrResId.GetId(), aDescrResId.GetResMgr())
{
aDescription.SetRT(aDescrResId.GetRT());
DBG_CTOR(SfxViewFactory, 0);
// SFX_APP()->RegisterViewFactory_Impl(*this);
}
SfxViewFactory::~SfxViewFactory()
{
DBG_DTOR(SfxViewFactory, 0);
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.566); FILE MERGED 2005/09/06 13:06:16 rt 1.2.566.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: viewfac.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-07 19:32:01 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// INCLUDE ---------------------------------------------------------------
#ifndef GCC
#pragma hdrstop
#endif
#include "app.hxx"
#include "viewfac.hxx"
// STATIC DATA -----------------------------------------------------------
DBG_NAME(SfxViewFactory);
SfxViewShell *SfxViewFactory::CreateInstance(SfxViewFrame *pFrame, SfxViewShell *pOldSh )
{
DBG_CHKTHIS(SfxViewFactory, 0);
return (*fnCreate)(pFrame, pOldSh);
}
void SfxViewFactory::InitFactory()
{
DBG_CHKTHIS(SfxViewFactory, 0);
(*fnInit)();
}
// CTOR / DTOR -----------------------------------------------------------
SfxViewFactory::SfxViewFactory( SfxViewCtor fnC, SfxViewInit fnI,
USHORT nOrdinal, const ResId& aDescrResId ):
fnCreate(fnC),
fnInit(fnI),
nOrd(nOrdinal),
aDescription(aDescrResId.GetId(), aDescrResId.GetResMgr())
{
aDescription.SetRT(aDescrResId.GetRT());
DBG_CTOR(SfxViewFactory, 0);
// SFX_APP()->RegisterViewFactory_Impl(*this);
}
SfxViewFactory::~SfxViewFactory()
{
DBG_DTOR(SfxViewFactory, 0);
}
<|endoftext|> |
<commit_before><commit_msg>fdo#83302 don't display read-only infobar for Base form in normal mode<commit_after><|endoftext|> |
<commit_before>#include <iostream>
using namespace std;
// devuelve true si hay elementos iguales o si hay algún cero
bool verificarElementosArray(int numero, int siguiente, int array[9])
{
if (numero > 7) return false;
int i = siguiente;
while (numero <= 7 && i <= 8)
{
if ( (array[numero] == 0 || array[i] == 0) || (array[numero] == array[i]) )
{
return true;
break;
}
i++;
}
return verificarElementosArray(numero +1, siguiente +1, array[9]);
}
bool verificarColumnas(int tablero[9][9])
{
int arr[9];
for(int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
arr[j] = tablero[j][i];
}
return verificarElementosArray(0, 1, arr[9]);
}
}
bool verificarCuadrantes (int tablero[3][3])
{
int indice;
int arrayMatriz[9];
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
indice = matriz[i][j] -1;
arrayMatriz[indice] = matriz[i][j];
}
}
return verificarElementosArray(0, 1, arrayMatriz[9]);
}
void obtenerCuadrantes (tablero[9][9]) // esta función debe devolver una matriz de 3x3
{
int columna = 0;
int limiteColumna = 3;
int cambioLimitesColumna;
int fila = 0;
int limiteFila = 3;
int cambioLimitesFila;
int subMatriz[3][3];
int i = 0
while (i < 9)
{
for (fila; fila < limiteFila; fila++)
{
for (columna; columna < limiteColumna; columna++)
{
subMatriz[fila][columna] = tablero[fila][columna];
}
}
verificarCuadrantes(subMatriz[3][3]);
}
cambioLimitesFila = limiteFila
fila = cambioLimitesFila;
limiteFila += 3;
if (limiteFila > 9)
{
limiteFila = 3;
fila = 0;
cambioLimitesColumna = limiteColumna;
columna = cambioLimitesColumna;
limiteColumna += 3;
}
i++;
}
int main ()
{
int matriz[9][9] = {
{00, 01 ,02, 03, 04, 05, 06, 07, 8},
{10, 11, 12, 13, 14, 15, 16, 17, 18},
{20, 21, 22, 23, 24, 25, 26, 27, 28},
{30, 31, 32, 33, 34, 35, 36, 37, 38},
{40, 41, 42, 43, 44, 45, 46, 47, 48},
{50, 51, 52, 53, 54, 55, 56, 57, 58},
{60, 61, 62, 63, 64, 65, 66, 67, 68},
{70, 71, 72, 73, 74, 75, 76, 77, 78},
{80, 81, 82, 83, 84, 85, 86, 87, 88}
};
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
cout << matriz[i][j] << " ";
}
cout << endl;
}
cout << "\n\n";
int arr[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
if (verificarElementosArray(0, 1, arr[])) cout << "hay elementos repeditos\n";
else cout << "no hay elementos repetidos\n";
return 0;
}
<commit_msg>Se agrega debug para encontrar errores en el codigo<commit_after>#include <iostream>
using namespace std;
// devuelve true si hay elementos iguales o si hay algún cero
bool verificarElementosArray(int numero, int siguiente, int array[9])
{
if (numero > 7) return false;
int i = siguiente;
cout <<"\n\t verificarElementosArray"<<endl;
cout <<"numero: "<<numero<<endl;
cout <<"siguiente: "<<siguiente<<endl;
while (numero <= 7 && i <= 8)
{
cout <<"i: "<<i<<endl;
cout <<"A[numero]: A["<<numero<<"]: "<<array[numero]<<endl;
cout <<"A[i]: A["<<i<<"]: "<<array[i]<<endl;
if ( /*(array[numero] == 0 || array[i] == 0) ||*/ (array[numero] == array[i]) )
{
return true;
}
i++;
}
return verificarElementosArray(numero +1, siguiente +1, array);
}
bool verificarColumnas(int tablero[9][9])
{
int arr[9];
for(int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
arr[j] = tablero[j][i];
}
return verificarElementosArray(0, 1, arr);
}
}
bool verificarCuadrantes (int tablero[3][3])
{
int indice;
int arrayMatriz[9];
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
indice = tablero[i][j] - 1;
arrayMatriz[indice] = tablero[i][j];
}
}
return verificarElementosArray(0, 1, arrayMatriz);
}
void obtenerCuadrantes (int tablero[9][9]) // esta función debe devolver una matriz de 3x3
{
int columna = 0;
int limiteColumna = 3;
int cambioLimitesColumna;
int fila = 0;
int limiteFila = 3;
int cambioLimitesFila;
int subMatriz[3][3];
int i = 0;
while (i < 9)
{
for (fila; fila < limiteFila; fila++)
{
for (columna; columna < limiteColumna; columna++)
{
subMatriz[fila][columna] = tablero[fila][columna];
}
}
verificarCuadrantes(subMatriz);
}
cambioLimitesFila = limiteFila;
fila = cambioLimitesFila;
limiteFila += 3;
if (limiteFila > 9)
{
limiteFila = 3;
fila = 0;
cambioLimitesColumna = limiteColumna;
columna = cambioLimitesColumna;
limiteColumna += 3;
}
i++;
}
void imprimirArray(int a[]){
for (int j = 0; j < 9; j++)
{
cout << a[j] << " ";
}
cout <<endl;
}
int main ()
{
int matriz[9][9] = {
{00, 01 ,02, 03, 04, 05, 06, 07, 8},
{10, 11, 12, 13, 14, 15, 16, 17, 18},
{20, 21, 22, 23, 24, 25, 26, 27, 28},
{30, 31, 32, 33, 34, 35, 36, 37, 38},
{40, 41, 42, 43, 44, 45, 46, 47, 48},
{50, 51, 52, 53, 54, 55, 56, 57, 58},
{60, 61, 62, 63, 64, 65, 66, 67, 68},
{70, 71, 72, 73, 74, 75, 76, 77, 78},
{80, 81, 82, 83, 84, 85, 86, 87, 88}
};
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
cout << matriz[i][j] << " ";
}
cout << endl;
}
cout << "\n\n";
int arr[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
imprimirArray(arr);
bool respuesta = verificarElementosArray(0, 1, arr);
cout <<" -> "<<respuesta<<endl;
if (respuesta) cout << " hay elementos repeditos\n";
else cout << "no hay elementos repetidos\n";
return 0;
}
<|endoftext|> |
<commit_before>/**
* staticunittest.cpp
*
* Copyright (C) 2004 Brad Hards <[email protected]>
*
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 "staticunittest.h"
#include "qca.h"
StaticUnitTest::StaticUnitTest()
: Tester()
{
}
void StaticUnitTest::allTests()
{
QCA::Initializer init;
QByteArray test(10);
test.fill('a');
CHECK( QCA::arrayToHex(test), QString("61616161616161616161") );
test.fill('b');
test[7] = 0x00;
CHECK( test == QCA::hexToArray(QString("62626262626262006262")), true );
QSecureArray testArray(10);
//testArray.fill( 'a' );
for (unsigned int i = 0; i < testArray.size(); i++) {
testArray[ i ] = 0x61;
}
CHECK( QCA::arrayToHex( testArray ), QString( "61616161616161616161" ) );
//testArray.fill( 'b' );
for (unsigned int i = 0; i < testArray.size(); i++) {
testArray[ i ] = 0x62;
}
testArray[6] = 0x00;
CHECK( testArray == QCA::hexToArray(QString("62626262626200626262")), true );
// capabilities are reported as a list - that is a problem for
// doing a direct comparison, since they change
// We try to work around that using contains()
QStringList supportedCapabilities = QCA::supportedFeatures();
CHECK( supportedCapabilities.contains("random"), (size_t)1 );
CHECK( supportedCapabilities.contains("sha1"), (size_t)1 );
CHECK( supportedCapabilities.contains("sha0"), (size_t)1 );
CHECK( supportedCapabilities.contains("md2"), (size_t)1 );
CHECK( supportedCapabilities.contains("md4"), (size_t)1 );
CHECK( supportedCapabilities.contains("md5"), (size_t)1 );
CHECK( supportedCapabilities.contains("ripemd160"), (size_t)1 );
QStringList defaultCapabilities = QCA::defaultFeatures();
CHECK( defaultCapabilities.contains("random"), (size_t)1 );
CHECK( QCA::isSupported("random"), true );
CHECK( QCA::isSupported("sha0"), true );
CHECK( QCA::isSupported("sha0,sha1"), true );
CHECK( QCA::isSupported("md2,md4,md5"), true );
CHECK( QCA::isSupported("md5"), true );
CHECK( QCA::isSupported("ripemd160"), true );
CHECK( QCA::isSupported("nosuchfeature"), false );
QString caps( "random,sha1,md5,ripemd160");
QStringList capList;
capList.split( caps, "," );
CHECK( QCA::isSupported(capList), true );
capList.append("noSuch");
CHECK( QCA::isSupported(capList), false );
}
<commit_msg>One more test step, covering the "just one, doesn't exist" provider<commit_after>/**
* staticunittest.cpp
*
* Copyright (C) 2004 Brad Hards <[email protected]>
*
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 "staticunittest.h"
#include "qca.h"
StaticUnitTest::StaticUnitTest()
: Tester()
{
}
void StaticUnitTest::allTests()
{
QCA::Initializer init;
QByteArray test(10);
test.fill('a');
CHECK( QCA::arrayToHex(test), QString("61616161616161616161") );
test.fill('b');
test[7] = 0x00;
CHECK( test == QCA::hexToArray(QString("62626262626262006262")), true );
QSecureArray testArray(10);
//testArray.fill( 'a' );
for (unsigned int i = 0; i < testArray.size(); i++) {
testArray[ i ] = 0x61;
}
CHECK( QCA::arrayToHex( testArray ), QString( "61616161616161616161" ) );
//testArray.fill( 'b' );
for (unsigned int i = 0; i < testArray.size(); i++) {
testArray[ i ] = 0x62;
}
testArray[6] = 0x00;
CHECK( testArray == QCA::hexToArray(QString("62626262626200626262")), true );
// capabilities are reported as a list - that is a problem for
// doing a direct comparison, since they change
// We try to work around that using contains()
QStringList supportedCapabilities = QCA::supportedFeatures();
CHECK( supportedCapabilities.contains("random"), (size_t)1 );
CHECK( supportedCapabilities.contains("sha1"), (size_t)1 );
CHECK( supportedCapabilities.contains("sha0"), (size_t)1 );
CHECK( supportedCapabilities.contains("md2"), (size_t)1 );
CHECK( supportedCapabilities.contains("md4"), (size_t)1 );
CHECK( supportedCapabilities.contains("md5"), (size_t)1 );
CHECK( supportedCapabilities.contains("ripemd160"), (size_t)1 );
QStringList defaultCapabilities = QCA::defaultFeatures();
CHECK( defaultCapabilities.contains("random"), (size_t)1 );
CHECK( QCA::isSupported("random"), true );
CHECK( QCA::isSupported("sha0"), true );
CHECK( QCA::isSupported("sha0,sha1"), true );
CHECK( QCA::isSupported("md2,md4,md5"), true );
CHECK( QCA::isSupported("md5"), true );
CHECK( QCA::isSupported("ripemd160"), true );
CHECK( QCA::isSupported("nosuchfeature"), false );
QString caps( "random,sha1,md5,ripemd160");
QStringList capList;
capList.split( caps, "," );
CHECK( QCA::isSupported(capList), true );
capList.append("noSuch");
CHECK( QCA::isSupported(capList), false );
capList.clear();
capList.append("noSuch");
CHECK( QCA::isSupported(capList), false );
}
<|endoftext|> |
<commit_before>// ==Montelight==
// Tegan Brennan, Stephen Merity, Taiyo Wilson
#include <cmath>
#include <string>
#include <iostream>
#include <fstream>
#include <vector>
#define EPSILON 0.1f
using namespace std;
struct Vector {
double x, y, z;
//
Vector(const Vector &o) : x(o.x), y(o.y), z(o.z) {}
Vector(double x_=0, double y_=0, double z_=0) : x(x_), y(y_), z(z_) {}
inline Vector operator+(const Vector &o) const {
return Vector(x + o.x, y + o.y, z + o.z);
}
inline Vector operator-(const Vector &o) const {
return Vector(x - o.x, y - o.y, z - o.z);
}
inline Vector operator*(const Vector &o) const {
return Vector(x * o.x, y * o.y, z * o.z);
}
inline Vector operator*(double o) const {
return Vector(x * o, y * o, z * o);
}
inline double dot(const Vector &o) const {
return x * o.x + y * o.y + z * o.z;
}
inline Vector &norm(){
return *this = *this * (1 / sqrt(x * x + y * y + z * z));
}
inline Vector cross(Vector &o){
return Vector(y * o.z - z * o.y, z * o.x - x * o.z, x * o.y - y * o.x);
}
inline double max() {
return fmax(x, fmax(y, z));
}
};
struct Ray {
Vector origin, direction;
Ray(const Vector &o_, const Vector &d_) : origin(o_), direction(d_) {}
};
struct Image {
unsigned int width, height;
Vector *pixels;
//
Image(unsigned int w, unsigned int h) : width(w), height(h) {
pixels = new Vector[width * height];
}
void setPixel(unsigned int x, unsigned int y, const Vector &v) {
pixels[(height - y) * width + x] = v;
}
void save(std::string filePrefix) {
std::string filename = filePrefix + ".ppm";
std::ofstream f;
f.open(filename.c_str(), std::ofstream::out);
// PPM header: P3 => RGB, width, height, and max RGB value
f << "P3 " << width << " " << height << " " << 255 << std::endl;
// For each pixel, write the space separated RGB values
for (int i=0; i < width * height; i++) {
unsigned int r = pixels[i].x * 255, g = pixels[i].y * 255, b = pixels[i].z * 255;
f << r << " " << g << " " << b << std::endl;
}
}
~Image() {
delete[] pixels;
}
};
struct Shape {
Vector color, emit;
//
Shape(const Vector color_, const Vector emit_) : color(color_), emit(emit_) {}
virtual double intersects(const Ray &r) const { return 0; }
virtual Vector randomPoint() const { return Vector(); }
};
struct Sphere : Shape {
Vector center;
double radius;
//
Sphere(const Vector center_, double radius_, const Vector color_, const Vector emit_) :
Shape(color_, emit_), center(center_), radius(radius_) {}
double intersects(const Ray &r) const {
// Find if, and at what distance, the ray intersects with this object
// Equation follows from solving quadratic equation of (r - c) ^ 2
// http://wiki.cgsociety.org/index.php/Ray_Sphere_Intersection
Vector offset = r.origin - center;
double a = r.direction.dot(r.direction);
double b = 2 * offset.dot(r.direction);
double c = offset.dot(offset) - radius * radius;
// Find discriminant for use in quadratic equation (b^2 - 4ac)
double disc = b * b - 4 * a * c;
// If the discriminant is negative, there are no real roots
// (ray misses sphere)
if (disc < 0) {
return 0;
}
// The smallest positive root is the closest intersection point
disc = sqrt(disc);
double t = - b - disc;
if (t > EPSILON) {
return t / 2;
}
t = - b + disc;
if (t > EPSILON) {
return t / 2;
}
return 0;
}
Vector randomPoint() const {
return center;
}
};
struct Tracer {
std::vector<Shape *> scene;
//
Tracer(const std::vector<Shape *> &scene_) : scene(scene_) {}
std::pair<Shape *, double> getIntersection(const Ray &r) const {
Shape *hitObj = NULL;
double closest = 1e20f;
for (Shape *obj : scene) {
double distToHit = obj->intersects(r);
if (distToHit > 0 && distToHit < closest) {
hitObj = obj;
closest = distToHit;
}
}
return std::make_pair(hitObj, closest);
}
Vector getRadiance(const Ray &r, int depth) {
// Work out what (if anything) was hit
auto result = getIntersection(r);
if (!result.first) {
return Vector();
}
Vector hit = r.origin + r.direction * result.second;
// Work out the color
Vector color;
for (Shape *light : scene) {
// Skip any objects that don't emit light
if (light->emit.max() == 0) {
continue;
}
Vector lightDirection = (light->randomPoint() - hit).norm();
Ray rayToLight = Ray(hit, lightDirection);
auto lightHit = getIntersection(rayToLight);
if (light == lightHit.first) {
color = light->emit * result.first->color;
}
}
return result.first->emit + color;
}
};
int main(int argc, const char *argv[]) {
// Initialize the image
int w = 256, h = 256;
Image img(w, h);
// Set up the scene
// Cornell box inspired: http://graphics.ucsd.edu/~henrik/images/cbox.html
std::vector<Shape *> scene = {//Scene: radius, position, emission, color, material
new Sphere(Vector(1e5+1,40.8,81.6), 1e5f, Vector(.75,.25,.25), Vector()),//Left
new Sphere(Vector(-1e5+99,40.8,81.6), 1e5f, Vector(.25,.25,.75), Vector()),//Rght
new Sphere(Vector(50,40.8, 1e5), 1e5f, Vector(.75,.75,.75), Vector()),//Back
new Sphere(Vector(50,40.8,-1e5+170), 1e5f, Vector(), Vector()),//Frnt
new Sphere(Vector(50, 1e5, 81.6), 1e5f, Vector(.75,.75,.75), Vector()),//Botm
new Sphere(Vector(50,-1e5+81.6,81.6), 1e5f, Vector(.75,.75,.75), Vector()),//Top
new Sphere(Vector(27,16.5,47), 16.5f, Vector(1,1,1) * 0.9, Vector()),//Mirr
new Sphere(Vector(73,16.5,78), 16.5f, Vector(1,1,1) * 0.9, Vector(0.4, 0.4, 0.4)),//Glas
//new Sphere(Vector(50,681.6-.27,81.6), 600, Vector(1,1,1)) //Light
new Sphere(Vector(50,65.1,81.6), 1.5, Vector(1,1,1), Vector(1,1,1)) //Light
};
Tracer tracer = Tracer(scene);
// Set up the camera
Ray camera = Ray(Vector(50, 52, 295.6), Vector(0, -0.042612, -1).norm());
// Upright camera with field of view angle set by 0.5135
Vector cx = Vector((w * 0.5135) / h, 0, 0);
// Cross product gets the vector perpendicular to cx and the "gaze" direction
Vector cy = (cx.cross(camera.direction)).norm() * 0.5135;
// Take a set number of samples per pixel
for (int samples = 0; samples < 1; ++samples) {
// For each pixel, sample a ray in that direction
for (int y = 0; y < h; ++y) {
for (int x = 0; x < w; ++x) {
// Calculate the direction of the camera ray
Vector d = (cx * ((x / float(w)) - 0.5)) + (cy * ((y / float(h)) - 0.5)) + camera.direction;
Ray ray = Ray(camera.origin + d * 140, d.norm());
Vector color = tracer.getRadiance(ray, 0);
// Add result of sample to image
img.setPixel(x, y, color);
}
}
}
// Save the resulting raytraced image
img.save("render");
return 0;
}
<commit_msg>Montelight now does global illumination<commit_after>// ==Montelight==
// Tegan Brennan, Stephen Merity, Taiyo Wilson
#include <cmath>
#include <string>
#include <iostream>
#include <fstream>
#include <vector>
#define EPSILON 0.001f
using namespace std;
struct Vector {
double x, y, z;
//
Vector(const Vector &o) : x(o.x), y(o.y), z(o.z) {}
Vector(double x_=0, double y_=0, double z_=0) : x(x_), y(y_), z(z_) {}
inline Vector operator+(const Vector &o) const {
return Vector(x + o.x, y + o.y, z + o.z);
}
inline Vector operator-(const Vector &o) const {
return Vector(x - o.x, y - o.y, z - o.z);
}
inline Vector operator*(const Vector &o) const {
return Vector(x * o.x, y * o.y, z * o.z);
}
inline Vector operator/(double o) const {
return Vector(x / o, y / o, z / o);
}
inline Vector operator*(double o) const {
return Vector(x * o, y * o, z * o);
}
inline double dot(const Vector &o) const {
return x * o.x + y * o.y + z * o.z;
}
inline Vector &norm(){
return *this = *this * (1 / sqrt(x * x + y * y + z * z));
}
inline Vector cross(Vector &o){
return Vector(y * o.z - z * o.y, z * o.x - x * o.z, x * o.y - y * o.x);
}
inline double max() {
return fmax(x, fmax(y, z));
}
};
struct Ray {
Vector origin, direction;
Ray(const Vector &o_, const Vector &d_) : origin(o_), direction(d_) {}
};
struct Image {
unsigned int width, height;
Vector *pixels;
unsigned int *samples;
//
Image(unsigned int w, unsigned int h) : width(w), height(h) {
pixels = new Vector[width * height];
samples = new unsigned int[width * height];
}
void setPixel(unsigned int x, unsigned int y, const Vector &v) {
unsigned int index = (height - y) * width + x;
pixels[index] = pixels[index] + v;
samples[index] += 1;
}
void save(std::string filePrefix) {
std::string filename = filePrefix + ".ppm";
std::ofstream f;
f.open(filename.c_str(), std::ofstream::out);
// PPM header: P3 => RGB, width, height, and max RGB value
f << "P3 " << width << " " << height << " " << 255 << std::endl;
// For each pixel, write the space separated RGB values
for (int i=0; i < width * height; i++) {
auto p = pixels[i] / samples[i];
unsigned int r = fmin(255, p.x * 255), g = fmin(255, p.y * 255), b = fmin(255, p.z * 255);
f << r << " " << g << " " << b << std::endl;
}
}
~Image() {
delete[] pixels;
delete[] samples;
}
};
struct Shape {
Vector color, emit;
//
Shape(const Vector color_, const Vector emit_) : color(color_), emit(emit_) {}
virtual double intersects(const Ray &r) const { return 0; }
virtual Vector randomPoint() const { return Vector(); }
virtual Vector getNormal(const Vector &p) const { return Vector(); }
};
struct Sphere : Shape {
Vector center;
double radius;
//
Sphere(const Vector center_, double radius_, const Vector color_, const Vector emit_) :
Shape(color_, emit_), center(center_), radius(radius_) {}
double intersects(const Ray &r) const {
// Find if, and at what distance, the ray intersects with this object
// Equation follows from solving quadratic equation of (r - c) ^ 2
// http://wiki.cgsociety.org/index.php/Ray_Sphere_Intersection
Vector offset = r.origin - center;
double a = r.direction.dot(r.direction);
double b = 2 * offset.dot(r.direction);
double c = offset.dot(offset) - radius * radius;
// Find discriminant for use in quadratic equation (b^2 - 4ac)
double disc = b * b - 4 * a * c;
// If the discriminant is negative, there are no real roots
// (ray misses sphere)
if (disc < 0) {
return 0;
}
// The smallest positive root is the closest intersection point
disc = sqrt(disc);
double t = - b - disc;
if (t > EPSILON) {
return t / 2;
}
t = - b + disc;
if (t > EPSILON) {
return t / 2;
}
return 0;
}
Vector randomPoint() const {
return center;
}
Vector getNormal(const Vector &p) const {
// Normalize the normal by using radius instead of a sqrt call
return (p - center) / radius;
}
};
struct Tracer {
std::vector<Shape *> scene;
//
Tracer(const std::vector<Shape *> &scene_) : scene(scene_) {}
std::pair<Shape *, double> getIntersection(const Ray &r) const {
Shape *hitObj = NULL;
double closest = 1e20f;
for (Shape *obj : scene) {
double distToHit = obj->intersects(r);
if (distToHit > 0 && distToHit < closest) {
hitObj = obj;
closest = distToHit;
}
}
return std::make_pair(hitObj, closest);
}
Vector getRadiance(const Ray &r, int depth) {
// Work out what (if anything) was hit
auto result = getIntersection(r);
Shape *hitObj = result.first;
if (!hitObj || depth > 4) {
return Vector();
}
Vector hitPos = r.origin + r.direction * result.second;
// Work out the contribution from directly sampling the emitters
Vector lightSampling;
/*
for (Shape *light : scene) {
// Skip any objects that don't emit light
if (light->emit.max() == 0) {
continue;
}
Vector lightDirection = (light->randomPoint() - hitPos).norm();
Ray rayToLight = Ray(hitPos, lightDirection);
auto lightHit = getIntersection(rayToLight);
if (light == lightHit.first) {
lightSampling = light->emit * hitObj->color;
}
}
*/
// Work out contribution from reflected light
Vector norm = hitObj->getNormal(hitPos);
// Orient the normal according to how the ray struck the object
if (norm.dot(r.direction) > 0) {
norm = norm * -1;
}
// TODO: Clean up this section
double r1 = 2 * M_PI * drand48();
double r2 = drand48();
double r2s = sqrt(r2);
Vector u = (fabs(norm.x)>.1 ? Vector(0, 1) : Vector(1)).cross(norm).norm();
Vector v = norm.cross(u);
Vector d = (u * cos(r1) * r2s + v * sin(r1) * r2s + norm * sqrt(1-r2)).norm();
Vector reflected = getRadiance(Ray(hitPos, d), depth + 1);
//
return hitObj->emit + lightSampling + hitObj->color * reflected;
}
};
int main(int argc, const char *argv[]) {
// Initialize the image
int w = 256, h = 256;
Image img(w, h);
// Set up the scene
// Cornell box inspired: http://graphics.ucsd.edu/~henrik/images/cbox.html
std::vector<Shape *> scene = {//Scene: radius, position, emission, color, material
new Sphere(Vector(1e5+1,40.8,81.6), 1e5f, Vector(.75,.25,.25), Vector()),//Left
new Sphere(Vector(-1e5+99,40.8,81.6), 1e5f, Vector(.25,.25,.75), Vector()),//Rght
new Sphere(Vector(50,40.8, 1e5), 1e5f, Vector(.75,.75,.75), Vector()),//Back
new Sphere(Vector(50,40.8,-1e5+170), 1e5f, Vector(), Vector()),//Frnt
new Sphere(Vector(50, 1e5, 81.6), 1e5f, Vector(.75,.75,.75), Vector()),//Botm
new Sphere(Vector(50,-1e5+81.6,81.6), 1e5f, Vector(.75,.75,.75), Vector()),//Top
new Sphere(Vector(27,16.5,47), 16.5f, Vector(1,1,1) * 0.9, Vector()),//Mirr
new Sphere(Vector(73,16.5,78), 16.5f, Vector(1,1,1) * 0.9, Vector()),//Glas
new Sphere(Vector(50,681.6-.27,81.6), 600, Vector(1,1,1) * 0.5, Vector(12,12,12)) //Light
//new Sphere(Vector(50,65.1,81.6), 1.5, Vector(1,1,1), Vector(0.7,0.7,0.7)) //Light
};
Tracer tracer = Tracer(scene);
// Set up the camera
Ray camera = Ray(Vector(50, 52, 295.6), Vector(0, -0.042612, -1).norm());
// Upright camera with field of view angle set by 0.5135
Vector cx = Vector((w * 0.5135) / h, 0, 0);
// Cross product gets the vector perpendicular to cx and the "gaze" direction
Vector cy = (cx.cross(camera.direction)).norm() * 0.5135;
// Take a set number of samples per pixel
unsigned int SAMPLES = 1000;
for (int sample = 0; sample < SAMPLES; ++sample) {
std::cout << "Taking sample " << sample << "\r" << std::flush;
// For each pixel, sample a ray in that direction
#pragma omp parallel for schedule(dynamic, 1)
for (int y = 0; y < h; ++y) {
for (int x = 0; x < w; ++x) {
// Calculate the direction of the camera ray
Vector d = (cx * ((x / float(w)) - 0.5)) + (cy * ((y / float(h)) - 0.5)) + camera.direction;
Ray ray = Ray(camera.origin + d * 140, d.norm());
Vector color = tracer.getRadiance(ray, 0);
// Add result of sample to image
img.setPixel(x, y, color);
}
}
}
// Save the resulting raytraced image
img.save("render");
return 0;
}
<|endoftext|> |
<commit_before>#include <mill/util/logger.hpp>
#include <mill/util/file_extension.hpp>
#include <mill/traj.hpp>
#include "mode_traj_convert.hpp"
#include <iostream>
namespace mill
{
const char* mode_traj_convert_usage() noexcept
{
return "usage: mill traj convert [trajfile] [format] <reference>_opt\n"
" convert format from [trajfile] to [format].\n"
" Only the first frame in a reference file is used to merge information.\n";
}
int mode_traj_convert(std::deque<std::string_view> args)
{
if(args.empty())
{
log::error("mill traj convert: too few arguments");
log::error(mode_traj_convert_usage());
return 1;
}
const auto input = args.front();
args.pop_front();
if(input == "help")
{
log::info(mode_traj_convert_usage());
return 0;
}
const auto format = args.front();
args.pop_front();
using attribute_container_type = Trajectory::attribute_container_type;
std::optional<attribute_container_type> ref_header = std::nullopt;
std::optional<Snapshot> ref_frame = std::nullopt;
if(!args.empty())
{
auto r = reader(args.front());
ref_header = r.read_header();
ref_frame = r.read_frame(); // read 1st frame
}
const std::string output = std::string(input) + "_converted." + std::string(format);
auto w = writer(output);
auto r = reader(input);
auto header = r.read_header();
if(ref_header)
{
header.merge(*ref_header);
}
w.write_header(header);
for(auto frame : r)
{
if(ref_frame)
{
// copy reference info because std::map::merge moves out the values
Snapshot ref(*ref_frame);
frame.merge_attributes(ref);
}
w.write_frame(frame);
}
return 0;
}
} // mill
<commit_msg>:sparkles: force overwrite attribute while conversion<commit_after>#include <mill/util/logger.hpp>
#include <mill/util/file_extension.hpp>
#include <mill/traj.hpp>
#include "mode_traj_convert.hpp"
#include <iostream>
namespace mill
{
const char* mode_traj_convert_usage() noexcept
{
return "usage: mill traj convert [trajfile] [format] <reference>_opt\n"
" convert format from [trajfile] to [format].\n"
" Only the first frame in a reference file is used to merge information.\n";
}
int mode_traj_convert(std::deque<std::string_view> args)
{
if(args.empty())
{
log::error("mill traj convert: too few arguments");
log::error(mode_traj_convert_usage());
return 1;
}
const auto input = args.front();
args.pop_front();
if(input == "help")
{
log::info(mode_traj_convert_usage());
return 0;
}
const auto format = args.front();
args.pop_front();
using attribute_container_type = Trajectory::attribute_container_type;
std::optional<attribute_container_type> ref_header = std::nullopt;
std::optional<Snapshot> ref_frame = std::nullopt;
if(!args.empty())
{
auto r = reader(args.front());
ref_header = r.read_header();
ref_frame = r.read_frame(); // read 1st frame
}
const std::string output = std::string(input) + "_converted." + std::string(format);
auto w = writer(output);
auto r = reader(input);
auto header = r.read_header();
if(ref_header)
{
header.merge(*ref_header);
}
w.write_header(header);
for(auto frame : r)
{
if(ref_frame)
{
if(ref_frame->size() != frame.size())
{
log::warn("number of particles in the reference file \"",
args.front(), "\" (", ref_frame->size(),
") differs from the original \"", input, "\" (",
frame.size(), "). Skipping.");
}
else
{
for(std::size_t i=0; i<frame.size(); ++i)
{
frame.at(i).attributes() = ref_frame->at(i).attributes();
}
}
}
w.write_frame(frame);
}
return 0;
}
} // mill
<|endoftext|> |
<commit_before>/*
* Copyright 2015 Aldebaran
*
* 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 "memory_list.hpp"
namespace alros {
namespace converter {
MemoryListConverter::MemoryListConverter(const std::vector<std::string>& key_list, const std::string &name, const float &frequency, const qi::SessionPtr &session):
BaseConverter(name, frequency, session),
p_memory_(session->service("ALMemory")),
_key_list(key_list)
{}
void MemoryListConverter::reset(){
}
void MemoryListConverter::callAll(const std::vector<message_actions::MessageAction> &actions){
// Get inertial data
AL::ALValue memData = p_memory_.call<AL::ALValue>("getListData", _key_list);
for(int i=0; i<memData.getSize(); i++){
if(memData[i].isFloat())
{
naoqi_msgs::MemoryPairFloat tmp_msg;
tmp_msg.memoryKey = _key_list[i];
tmp_msg.data = memData[i];
_msg.floats.push_back(tmp_msg);
}
else if(memData[i].isString())
{
naoqi_msgs::MemoryPairString tmp_msg;
tmp_msg.memoryKey = _key_list[i];
tmp_msg.data = memData[i];
_msg.strings.push_back(tmp_msg);
}
else if(memData[i].isInt())
{
naoqi_msgs::MemoryPairInt tmp_msg;
tmp_msg.memoryKey = _key_list[i];
tmp_msg.data = memData[i];
_msg.ints.push_back(tmp_msg);
}
}
for_each( message_actions::MessageAction action, actions )
{
callbacks_[action]( _msg);
}
}
void MemoryListConverter::registerCallback( const message_actions::MessageAction action, Callback_t cb )
{
callbacks_[action] = cb;
}
}
}
<commit_msg>Fix string in message creation in converter<commit_after>/*
* Copyright 2015 Aldebaran
*
* 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 "memory_list.hpp"
namespace alros {
namespace converter {
MemoryListConverter::MemoryListConverter(const std::vector<std::string>& key_list, const std::string &name, const float &frequency, const qi::SessionPtr &session):
BaseConverter(name, frequency, session),
p_memory_(session->service("ALMemory")),
_key_list(key_list)
{}
void MemoryListConverter::reset(){
}
void MemoryListConverter::callAll(const std::vector<message_actions::MessageAction> &actions){
// Get inertial data
AL::ALValue memData = p_memory_.call<AL::ALValue>("getListData", _key_list);
for(int i=0; i<memData.getSize(); i++){
if(memData[i].isFloat())
{
naoqi_msgs::MemoryPairFloat tmp_msg;
tmp_msg.memoryKey = _key_list[i];
tmp_msg.data = memData[i];
_msg.floats.push_back(tmp_msg);
}
else if(memData[i].isString())
{
naoqi_msgs::MemoryPairString tmp_msg;
tmp_msg.memoryKey = _key_list[i];
tmp_msg.data = memData[i].toString();
_msg.strings.push_back(tmp_msg);
}
else if(memData[i].isInt())
{
naoqi_msgs::MemoryPairInt tmp_msg;
tmp_msg.memoryKey = _key_list[i];
tmp_msg.data = memData[i];
_msg.ints.push_back(tmp_msg);
}
}
for_each( message_actions::MessageAction action, actions )
{
callbacks_[action]( _msg);
}
}
void MemoryListConverter::registerCallback( const message_actions::MessageAction action, Callback_t cb )
{
callbacks_[action] = cb;
}
}
}
<|endoftext|> |
<commit_before>#include <iostream>
#include "time.h"
#include <string>
#include <unistd.h>
#include "novoht.h"
#include <cstdlib>
#include <cstddef>
#include <sys/time.h>//
#include <sys/stat.h>
#define KEY_LEN 32
#define VAL_LEN 128
using namespace std;
struct timeval tp;
double diffclock(clock_t clock1, clock_t clock2){
double clock_ts=clock1-clock2;
double diffms=(clock_ts*1000)/CLOCKS_PER_SEC;
return diffms;
}
double getTime_usec() {
gettimeofday(&tp, NULL);
return static_cast<double>(tp.tv_sec) * 1E6+ static_cast<double>(tp.tv_usec);
}
string randomString(int len) {
string s(len, ' ');
srand(/*getpid()*/ clock() + getTime_usec());
static const char alphanum[] = "0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < len; ++i) {
s[i] = alphanum[rand() % (sizeof(alphanum) - 1)];
}
return s;
}
double testInsert(NoVoHT &map, string keys[], string vals[], int l){
int fails =0;
cout << "0\% Complete\r";
cout.flush();
//clock_t a=clock();
double a = getTime_usec();
int t;
for (t = 0; t<l; t++){
fails -= map.put(keys[t], vals[t]);
if ((t+1)%1000 == 0)
cout << (long)t*100/l << "\% Complete\r";
}
double b = getTime_usec();
//clock_t b=clock();
cout << "100\% Complete with " << fails << " not inserted" << endl;
//return diffclock(b,a);
return (b-a);
;
}
double testGet(NoVoHT &map, string keys[], string vals[], int l){
int fails = 0;
cout << "0\% Complete\r";
double a = getTime_usec();
for (int t=0; t<l; t++){
string* s = map.get(keys[t]);
if (!s) fails++;
else if (s->compare(vals[t]) != 0)fails++;
if ((t+1)%1000 == 0)cout << (long)t*100/l << "\% Complete\r";
}
double b = getTime_usec();
cout << "100\% Complete with " << fails << " not found" << endl;
return b-a;
}
double testRemove(NoVoHT &map, string keys[], int l){
int fails = 0;
cout << "0\% Complete\r";
double a = getTime_usec();
for (int t=0; t<l; t++){
fails -= map.remove(keys[t]);
if ((t+1)%1000 == 0)cout << (long)t*100/l << "\% Complete\r";
}
double b = getTime_usec();
cout << "100\% Complete with " << fails << " not found" << endl;
return b-a;
}
int main(int argc, char *argv[]){
cout << "\nInitializing key-value pairs for testing\n";
cout << "0\%\r";
int size = atoi(argv[1]);
string* keys = new string[size];
string* vals = new string[size];
for (int t=0; t<size; t++){
keys[t] = randomString(KEY_LEN);
vals[t] = randomString(VAL_LEN);
if(t%1000 == 0)cout << (long)t*100/size << "\%\r";
}
cout << "Done\n" << endl;
//NoVoHT map ("fbench.data", 1000000000, 10000);
char c[40];
struct stat fstate;
sprintf(c, "cat /proc/%d/status | grep VmPeak", (int)getpid());
system(c);
const char* fn = "";
if(argc > 2) fn = argv[2];
NoVoHT map (fn, size, 10000, .7);
stat(fn, &fstate);
cout << "Initial file size: " << fstate.st_size << endl << endl;
//NoVoHT map ("", 10000000, -1);
//NoVoHT map ("", 1000000, 10000, .7);
//NoVoHT map ("", 1000000, -1);
//NoVoHT map ("/dev/shm/fbench.data", 1000000, -1);
double ins, ret, rem;
cout << "Testing Insertion: Inserting " << size << " elements" << endl;
ins = testInsert(map, keys,vals,size);
stat(fn, &fstate);
cout << "File size after insertion test: " << fstate.st_size << endl << endl;
cout << "Testing Retrieval: Retrieving " << size << " elements" << endl;
ret = testGet(map,keys,vals,size);
cout << endl;
cout << "Testing Removal: Removing " << size << " elements" << endl;
rem = testRemove(map,keys,size);
stat(fn, &fstate);
cout << "File size after removal test: " << fstate.st_size << endl << endl;
cout << "\nInsertion done in " << ins << " microseconds" << endl;
cout << "Retrieval done in " << ret << " microseconds" << endl;
cout << "Removal done in " << rem << " microseconds" << endl;
system(c);
delete [] keys;
delete [] vals;
return 0;
}
<commit_msg>changed key value length<commit_after>#include <iostream>
#include "time.h"
#include <string>
#include <unistd.h>
#include "novoht.h"
#include <cstdlib>
#include <cstddef>
#include <sys/time.h>//
#include <sys/stat.h>
#define KEY_LEN 48
#define VAL_LEN 24
using namespace std;
struct timeval tp;
double diffclock(clock_t clock1, clock_t clock2){
double clock_ts=clock1-clock2;
double diffms=(clock_ts*1000)/CLOCKS_PER_SEC;
return diffms;
}
double getTime_usec() {
gettimeofday(&tp, NULL);
return static_cast<double>(tp.tv_sec) * 1E6+ static_cast<double>(tp.tv_usec);
}
string randomString(int len) {
string s(len, ' ');
srand(/*getpid()*/ clock() + getTime_usec());
static const char alphanum[] = "0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < len; ++i) {
s[i] = alphanum[rand() % (sizeof(alphanum) - 1)];
}
return s;
}
double testInsert(NoVoHT &map, string keys[], string vals[], int l){
int fails =0;
cout << "0\% Complete\r";
cout.flush();
//clock_t a=clock();
double a = getTime_usec();
int t;
for (t = 0; t<l; t++){
fails -= map.put(keys[t], vals[t]);
if ((t+1)%1000 == 0)
cout << (long)t*100/l << "\% Complete\r";
}
double b = getTime_usec();
//clock_t b=clock();
cout << "100\% Complete with " << fails << " not inserted" << endl;
//return diffclock(b,a);
return (b-a);
;
}
double testGet(NoVoHT &map, string keys[], string vals[], int l){
int fails = 0;
cout << "0\% Complete\r";
double a = getTime_usec();
for (int t=0; t<l; t++){
string* s = map.get(keys[t]);
if (!s) fails++;
else if (s->compare(vals[t]) != 0)fails++;
if ((t+1)%1000 == 0)cout << (long)t*100/l << "\% Complete\r";
}
double b = getTime_usec();
cout << "100\% Complete with " << fails << " not found" << endl;
return b-a;
}
double testRemove(NoVoHT &map, string keys[], int l){
int fails = 0;
cout << "0\% Complete\r";
double a = getTime_usec();
for (int t=0; t<l; t++){
fails -= map.remove(keys[t]);
if ((t+1)%1000 == 0)cout << (long)t*100/l << "\% Complete\r";
}
double b = getTime_usec();
cout << "100\% Complete with " << fails << " not found" << endl;
return b-a;
}
int main(int argc, char *argv[]){
cout << "\nInitializing key-value pairs for testing\n";
cout << "0\%\r";
int size = atoi(argv[1]);
string* keys = new string[size];
string* vals = new string[size];
for (int t=0; t<size; t++){
keys[t] = randomString(KEY_LEN);
vals[t] = randomString(VAL_LEN);
if(t%1000 == 0)cout << (long)t*100/size << "\%\r";
}
cout << "Done\n" << endl;
//NoVoHT map ("fbench.data", 1000000000, 10000);
char c[40];
struct stat fstate;
sprintf(c, "cat /proc/%d/status | grep VmPeak", (int)getpid());
system(c);
const char* fn = "";
if(argc > 2) fn = argv[2];
NoVoHT map (fn, size, 10000, .7);
stat(fn, &fstate);
cout << "Initial file size: " << fstate.st_size << endl << endl;
//NoVoHT map ("", 10000000, -1);
//NoVoHT map ("", 1000000, 10000, .7);
//NoVoHT map ("", 1000000, -1);
//NoVoHT map ("/dev/shm/fbench.data", 1000000, -1);
double ins, ret, rem;
cout << "Testing Insertion: Inserting " << size << " elements" << endl;
ins = testInsert(map, keys,vals,size);
stat(fn, &fstate);
cout << "File size after insertion test: " << fstate.st_size << endl << endl;
cout << "Testing Retrieval: Retrieving " << size << " elements" << endl;
ret = testGet(map,keys,vals,size);
cout << endl;
cout << "Testing Removal: Removing " << size << " elements" << endl;
rem = testRemove(map,keys,size);
stat(fn, &fstate);
cout << "File size after removal test: " << fstate.st_size << endl << endl;
cout << "\nInsertion done in " << ins << " microseconds" << endl;
cout << "Retrieval done in " << ret << " microseconds" << endl;
cout << "Removal done in " << rem << " microseconds" << endl;
system(c);
delete [] keys;
delete [] vals;
return 0;
}
<|endoftext|> |
<commit_before>//
// CompositeTileImageContribution.hpp
// G3MiOSSDK
//
// Created by Diego Gomez Deck on 4/26/14.
//
//
#ifndef __G3MiOSSDK__CompositeTileImageContribution__
#define __G3MiOSSDK__CompositeTileImageContribution__
#include "TileImageContribution.hpp"
#include <vector>
class CompositeTileImageContribution : public TileImageContribution {
public:
class ChildContribution {
public:
const int _childIndex;
const TileImageContribution* _contribution;
ChildContribution(const int childIndex,
const TileImageContribution* contribution);
~ChildContribution();
};
static const TileImageContribution* create(const std::vector<const ChildContribution*>& contributions);
private:
#ifdef C_CODE
const std::vector<const ChildContribution*> _contributions;
#endif
#ifdef JAVA_CODE
private final java.util.ArrayList<ChildContribution> _contributions;
#endif
CompositeTileImageContribution(const std::vector<const ChildContribution*>& contributions) :
TileImageContribution(false, 1),
_contributions(contributions)
{
}
public:
~CompositeTileImageContribution() {
const int size = _contributions.size();
for (int i = 0; i < size; i++) {
#ifdef C_CODE
const ChildContribution* contribution = _contributions[i];
#endif
#ifdef JAVA_CODE
final ChildContribution contribution = _contributions.get(i);
#endif
delete contribution;
}
}
const int size() const {
return _contributions.size();
}
const ChildContribution* get(int index) const {
#ifdef C_CODE
return _contributions[index];
#endif
#ifdef JAVA_CODE
return _contributions.get(index);
#endif
}
};
#endif
<commit_msg>Tile's image creation refactoring - NOT YET USABLE<commit_after>//
// CompositeTileImageContribution.hpp
// G3MiOSSDK
//
// Created by Diego Gomez Deck on 4/26/14.
//
//
#ifndef __G3MiOSSDK__CompositeTileImageContribution__
#define __G3MiOSSDK__CompositeTileImageContribution__
#include "TileImageContribution.hpp"
#include <vector>
class CompositeTileImageContribution : public TileImageContribution {
public:
class ChildContribution {
public:
const int _childIndex;
const TileImageContribution* _contribution;
ChildContribution(const int childIndex,
const TileImageContribution* contribution);
~ChildContribution();
};
static const TileImageContribution* create(const std::vector<const ChildContribution*>& contributions);
private:
#ifdef C_CODE
const std::vector<const ChildContribution*> _contributions;
#endif
#ifdef JAVA_CODE
private final java.util.ArrayList<ChildContribution> _contributions;
#endif
CompositeTileImageContribution(const std::vector<const ChildContribution*>& contributions) :
TileImageContribution(false, 1),
_contributions(contributions)
{
}
public:
~CompositeTileImageContribution() {
const int size = _contributions.size();
for (int i = 0; i < size; i++) {
#ifdef C_CODE
const ChildContribution* contribution = _contributions[i];
delete contribution;
#endif
#ifdef JAVA_CODE
final ChildContribution contribution = _contributions.get(i);
contribution.dispose();
#endif
}
}
const int size() const {
return _contributions.size();
}
const ChildContribution* get(int index) const {
#ifdef C_CODE
return _contributions[index];
#endif
#ifdef JAVA_CODE
return _contributions.get(index);
#endif
}
};
#endif
<|endoftext|> |
<commit_before>//
// Created by Derek van Vliet on 2015-03-25.
// Copyright (c) 2015 Get Set Games Inc. All rights reserved.
//
#include "FacebookParsePrivatePCH.h"
#include "CallbackDevice.h"
#if PLATFORM_IOS
NSArray* GetNSStringArray(TArray<FString> FStringArray)
{
NSMutableArray* NewArray = [NSMutableArray array];
for (auto Itr(FStringArray.CreateIterator()); Itr; Itr++)
{
FString String = (*Itr);
[NewArray addObject:String.GetNSString()];
}
return NewArray;
}
#endif
void UFacebookLoginComponent::OnRegister()
{
Super::OnRegister();
// init here
FCoreDelegates::ApplicationOpenURLDelegate.AddUObject(this, &UFacebookLoginComponent::ApplicationOpenURL_Handler);
UFacebookLoginComponent::FacebookLoginCancelledDelegate.AddUObject(this, &UFacebookLoginComponent::FacebookLoginCancelled_Handler);
UFacebookLoginComponent::FacebookLoginErrorDelegate.AddUObject(this, &UFacebookLoginComponent::FacebookLoginError_Handler);
UFacebookLoginComponent::FacebookLoginSucceededDelegate.AddUObject(this, &UFacebookLoginComponent::FacebookLoginSucceeded_Handler);
}
void UFacebookLoginComponent::OnUnregister()
{
Super::OnUnregister();
// clean up here
FCoreDelegates::ApplicationOpenURLDelegate.RemoveAll(this);
UFacebookLoginComponent::FacebookLoginCancelledDelegate.RemoveAll(this);
UFacebookLoginComponent::FacebookLoginErrorDelegate.RemoveAll(this);
UFacebookLoginComponent::FacebookLoginSucceededDelegate.RemoveAll(this);
}
void UFacebookLoginComponent::FacebookLoginWithReadPermissions(TArray<FString> Permissions)
{
#if PLATFORM_IOS
dispatch_async(dispatch_get_main_queue(), ^{
FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
[login logInWithReadPermissions:GetNSStringArray(Permissions) handler:^(FBSDKLoginManagerLoginResult *result, NSError *error)
{
if (error)
{
UFacebookLoginComponent::FacebookLoginErrorDelegate.Broadcast(FString([error description]));
}
else if (result.isCancelled)
{
UFacebookLoginComponent::FacebookLoginCancelledDelegate.Broadcast();
}
else
{
UFacebookLoginComponent::FacebookLoginSucceededDelegate.Broadcast(UFacebookFunctions::FacebookGetUserId(), UFacebookFunctions::FacebookGetAccessToken(), UFacebookFunctions::FacebookGetAccessTokenExpirationDate());
}
}];
});
#endif
}
void UFacebookLoginComponent::ApplicationOpenURL_Handler(FString URL, FString SourceApplication)
{
#if PLATFORM_IOS
IOSAppDelegate* appDelegate = (IOSAppDelegate*)[[UIApplication sharedApplication] delegate];
[[FBSDKApplicationDelegate sharedInstance] application:[UIApplication sharedApplication]
openURL:[NSURL URLWithString:URL.GetNSString()]
sourceApplication:SourceApplication.GetNSString()
annotation:appDelegate.launchAnnotation];
#endif
}
UFacebookLoginComponent::FFacebookLoginSucceededDelegate UFacebookLoginComponent::FacebookLoginSucceededDelegate;
UFacebookLoginComponent::FFacebookLoginCancelledDelegate UFacebookLoginComponent::FacebookLoginCancelledDelegate;
UFacebookLoginComponent::FFacebookLoginErrorDelegate UFacebookLoginComponent::FacebookLoginErrorDelegate;
<commit_msg>[change] call the Android/Java login method passing along specified permissions from blue print<commit_after>//
// Created by Derek van Vliet on 2015-03-25.
// Copyright (c) 2015 Get Set Games Inc. All rights reserved.
//
#include "FacebookParsePrivatePCH.h"
#include "CallbackDevice.h"
#if PLATFORM_IOS
NSArray* GetNSStringArray(TArray<FString> FStringArray)
{
NSMutableArray* NewArray = [NSMutableArray array];
for (auto Itr(FStringArray.CreateIterator()); Itr; Itr++)
{
FString String = (*Itr);
[NewArray addObject:String.GetNSString()];
}
return NewArray;
}
#endif
void UFacebookLoginComponent::OnRegister()
{
Super::OnRegister();
// init here
FCoreDelegates::ApplicationOpenURLDelegate.AddUObject(this, &UFacebookLoginComponent::ApplicationOpenURL_Handler);
UFacebookLoginComponent::FacebookLoginCancelledDelegate.AddUObject(this, &UFacebookLoginComponent::FacebookLoginCancelled_Handler);
UFacebookLoginComponent::FacebookLoginErrorDelegate.AddUObject(this, &UFacebookLoginComponent::FacebookLoginError_Handler);
UFacebookLoginComponent::FacebookLoginSucceededDelegate.AddUObject(this, &UFacebookLoginComponent::FacebookLoginSucceeded_Handler);
}
void UFacebookLoginComponent::OnUnregister()
{
Super::OnUnregister();
// clean up here
FCoreDelegates::ApplicationOpenURLDelegate.RemoveAll(this);
UFacebookLoginComponent::FacebookLoginCancelledDelegate.RemoveAll(this);
UFacebookLoginComponent::FacebookLoginErrorDelegate.RemoveAll(this);
UFacebookLoginComponent::FacebookLoginSucceededDelegate.RemoveAll(this);
}
void UFacebookLoginComponent::FacebookLoginWithReadPermissions(TArray<FString> Permissions)
{
#if PLATFORM_IOS
dispatch_async(dispatch_get_main_queue(), ^{
FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
[login logInWithReadPermissions:GetNSStringArray(Permissions) handler:^(FBSDKLoginManagerLoginResult *result, NSError *error)
{
if (error)
{
UFacebookLoginComponent::FacebookLoginErrorDelegate.Broadcast(FString([error description]));
}
else if (result.isCancelled)
{
UFacebookLoginComponent::FacebookLoginCancelledDelegate.Broadcast();
}
else
{
UFacebookLoginComponent::FacebookLoginSucceededDelegate.Broadcast(UFacebookFunctions::FacebookGetUserId(), UFacebookFunctions::FacebookGetAccessToken(), UFacebookFunctions::FacebookGetAccessTokenExpirationDate());
}
}];
});
#elif PLATFORM_ANDROID
bool bResult = false;
if (JNIEnv* Env = FAndroidApplication::GetJavaEnv())
{
jstring AchievementIdJava = Env->NewStringUTF(TCHAR_TO_UTF8(*AchievementId));
static jmethodID Method = FJavaWrapper::FindMethod(Env, FJavaWrapper::GameActivityClassID, "AndroidThunk_Java_FacebookLoginWithReadPermissions", "(Ljava/lang/String;)V", false);
bResult = FJavaWrapper::CallVoidMethod(Env, FJavaWrapper::GameActivityThis, Method, Permissions);
Env->DeleteLocalRef(AchievementIdJava);
}
return bResult;
#endif
}
void UFacebookLoginComponent::ApplicationOpenURL_Handler(FString URL, FString SourceApplication)
{
#if PLATFORM_IOS
IOSAppDelegate* appDelegate = (IOSAppDelegate*)[[UIApplication sharedApplication] delegate];
[[FBSDKApplicationDelegate sharedInstance] application:[UIApplication sharedApplication]
openURL:[NSURL URLWithString:URL.GetNSString()]
sourceApplication:SourceApplication.GetNSString()
annotation:appDelegate.launchAnnotation];
#endif
}
UFacebookLoginComponent::FFacebookLoginSucceededDelegate UFacebookLoginComponent::FacebookLoginSucceededDelegate;
UFacebookLoginComponent::FFacebookLoginCancelledDelegate UFacebookLoginComponent::FacebookLoginCancelledDelegate;
UFacebookLoginComponent::FFacebookLoginErrorDelegate UFacebookLoginComponent::FacebookLoginErrorDelegate;
<|endoftext|> |
<commit_before>#include "nano_signal_slot.hpp"
#include <iostream>
struct Foo : public Nano::Observer
{
void action() const
{
std::cout << "Hello, World!" << std::endl;
}
long action(std::size_t a) const
{
return __LINE__ ^ a;
}
};
long action(std::size_t a)
{
return __LINE__ ^ a;
}
int main()
{
Foo foo;
// Declare Nano::Signals using function signature syntax
Nano::Signal<void()> signal_one;
Nano::Signal<long(std::size_t)> signal_two;
// Connect member functions to Nano::Signals
signal_one.connect<Foo, &Foo::action>(&foo);
signal_two.connect<Foo, &Foo::action>(&foo);
// Connect a free function to a Nano::Signal
signal_two.connect<action>();
// Emit Signals
signal_one();
// Emit Signals and accumulate SRVs
signal_two.accumulate(__LINE__, [](long srv)
{
std::cout << srv << ", " << __LINE__ << std::endl;
});
// Disconnect a member function from a Nano::Signal
signal_two.disconnect<Foo, &Foo::action>(foo);
// Disconnect a free function from a Nano::Signal
signal_two.disconnect<action>();
std::cout << "\n\tAfter Disconnect\n" << std::endl;
// Emit again to test disconnects
signal_one();
signal_two(__LINE__);
// Pause the screen
std::cin.get();
}
<commit_msg>added additional var<commit_after>#include "nano_signal_slot.hpp"
#include <iostream>
#include <random>
struct Foo : public Nano::Observer
{
void action() const
{
std::cout << "Hello, World!" << std::endl;
}
long action(std::size_t a) const
{
return __LINE__ ^ a;
}
};
long action(std::size_t a)
{
return __LINE__ ^ a;
}
int main()
{
Foo foo;
std::size_t sig_arg = 9001;
// Declare Nano::Signals using function signature syntax
Nano::Signal<void()> signal_one;
Nano::Signal<long(std::size_t)> signal_two;
// Connect member functions to Nano::Signals
signal_one.connect<Foo, &Foo::action>(&foo);
signal_two.connect<Foo, &Foo::action>(&foo);
// Connect a free function to a Nano::Signal
signal_two.connect<action>();
// Emit Signals
signal_one();
signal_two(sig_arg);
// Emit Signals and accumulate SRVs (signal return values)
signal_two.accumulate(__LINE__, [](long srv)
{
std::cout << srv << ", " << __LINE__ << std::endl;
});
// Disconnect a member function from a Nano::Signal
signal_two.disconnect<Foo, &Foo::action>(foo);
// Disconnect a free function from a Nano::Signal
signal_two.disconnect<action>();
std::cout << "\n\tAfter Disconnect\n" << std::endl;
// Emit again to test disconnects
signal_one();
signal_two(__LINE__);
// Pause the screen
std::cin.get();
}
<|endoftext|> |
<commit_before>#include "GMSAssetResourceManagementSystem.hpp"
#include "../AssetResources/TextureInfoResource.hpp"
#include "../AssetResources/GMSRoomResource.hpp"
#include "../AssetResources/GMSObjectResource.hpp"
#include "../AssetResources/OtherGMSResources.hpp"
#include "../CommandLineOptions.hpp"
#include <KEngine/Events/OtherGraphicsEvents.hpp>
#include <KEngine/App.hpp>
#include <KEngine/Utility/FileSystemHelper.hpp>
#include <KEngine/Log/Log.hpp>
#include <SFML/Graphics/Image.hpp>
#include <algorithm>
#include <execution>
#include <filesystem>
#include <fstream>
#include <limits>
#include <mutex>
#include <utility>
namespace fs = std::filesystem;
namespace
{
ke::Colour gmsColourStrToColour(const ke::String & p_colourStr)
{
assert(p_colourStr.length() == 9);
assert(p_colourStr[0] == '#');
ke::Colour roomColour = {
// assume colour is in hex RGBA starting with the '#' symbol.
static_cast<uint8_t>(std::stol(p_colourStr.substr(1, 2), nullptr, 16)),
static_cast<uint8_t>(std::stol(p_colourStr.substr(3, 2), nullptr, 16)),
static_cast<uint8_t>(std::stol(p_colourStr.substr(5, 2), nullptr, 16)),
static_cast<uint8_t>(std::stol(p_colourStr.substr(7, 2), nullptr, 16)) };
return roomColour;
}
}
namespace pf
{
bool GMSAssetResourceManagementSystem::initialise()
{
ke::Log::instance()->info("Scanning assets...");
this->loadTextureAssets();
this->loadSpriteAssets();
this->loadObjectAssets();
this->loadRoomAssets();
ke::Log::instance()->info("Scanning assets... DONE");
return true;
}
void GMSAssetResourceManagementSystem::shutdown()
{
}
void GMSAssetResourceManagementSystem::update(ke::Time elapsedTime)
{
KE_UNUSED(elapsedTime);
}
void GMSAssetResourceManagementSystem::loadTextureAssets(void)
{
ke::Log::instance()->info("Scanning texture assets...");
const auto assetDirPath = ke::App::getCommandLineArgValue(pf::cli::ExecAssetsPath).as<ke::String>();
const auto texturesRootDirPath = fs::path{ assetDirPath } / "textures";
sf::Image tempImage;
std::hash<ke::String> hasher;
for (const auto & path : ke::FileSystemHelper::getChildPaths(texturesRootDirPath))
{
if (fs::is_directory(path)) // is a texture directory.
{
ke::Log::instance()->info("Discovered texture asset: {}", path.string());
auto textureFilePaths = ke::FileSystemHelper::getFilePaths(path);
if (textureFilePaths.size() == 1)
{
auto texPath = textureFilePaths[0];
auto textureResource = std::make_shared<TextureInfoResource>();
textureResource->setName(texPath.stem().string());
textureResource->setTextureId(hasher(textureResource->getName()));
textureResource->setSourcePath(texPath.string());
// retrieve size
bool ret = tempImage.loadFromFile(texPath.string());
assert(ret);
TextureInfoResource::DimensionType dimension;
dimension.width = tempImage.getSize().x;
dimension.height = tempImage.getSize().y;
textureResource->setTextureSize(dimension);
ke::App::instance()->getResourceManager()->registerResource(textureResource);
}
else
{
// ignore when there're multiple texture files in a single dir for now.
}
}
else if (fs::is_regular_file(path) && path.extension() == "png") // is a png texture.
{
ke::Log::instance()->info("Discovered texture asset: {}", path.string());
auto textureResource = std::make_shared<TextureInfoResource>();
textureResource->setName("texture_" + path.stem().string());
textureResource->setTextureId(std::stoi(textureResource->getName()));
textureResource->setSourcePath(path.string());
// retrieve size
bool ret = tempImage.loadFromFile(path.string());
assert(ret);
TextureInfoResource::DimensionType dimension;
dimension.width = tempImage.getSize().x;
dimension.height = tempImage.getSize().y;
textureResource->setTextureSize(dimension);
ke::App::instance()->getResourceManager()->registerResource(textureResource);
}
}
}
void GMSAssetResourceManagementSystem::loadSpriteAssets(void)
{
ke::Log::instance()->info("Scanning texpage assets...");
const auto assetDirPath = ke::App::getCommandLineArgValue(pf::cli::ExecAssetsPath).as<ke::String>();
const auto texpageRootDirPath = fs::path{ assetDirPath } / "texpage";
std::mutex texpagesMutex;
std::unordered_map<unsigned, std::shared_ptr<pf::GMSTexpageResource>> texpages; // <texpage_id, texpage>
const auto texpagePaths = ke::FileSystemHelper::getChildPaths(texpageRootDirPath);
std::for_each(std::execution::par_unseq, std::begin(texpagePaths), std::end(texpagePaths), [&](const auto & path)
{
if (!path.has_extension() || path.extension() != ".json") return;
ke::Log::instance()->info("Discovered GM:S texpage asset: {}", path.string());
std::ifstream texpageFileStream{ path };
ke::json texpageJson;
texpageFileStream >> texpageJson;
auto texpage = std::make_shared<pf::GMSTexpageResource>("texpage_" + path.stem().string(), path.string());
texpage->id = std::stoi(path.stem().string());
texpage->sourcePosition.x = texpageJson["src"]["x"].get<unsigned>();
texpage->sourcePosition.y = texpageJson["src"]["y"].get<unsigned>();
texpage->sourceDimension.width = texpageJson["src"]["width"].get<unsigned>();
texpage->sourceDimension.height = texpageJson["src"]["height"].get<unsigned>();
texpage->destinationPosition.x = texpageJson["dest"]["x"].get<unsigned>();
texpage->destinationPosition.y = texpageJson["dest"]["y"].get<unsigned>();
texpage->destinationDimension.width = texpageJson["dest"]["width"].get<unsigned>();
texpage->destinationDimension.height = texpageJson["dest"]["height"].get<unsigned>();
texpage->dimension.width = texpageJson["size"]["width"].get<unsigned>();
texpage->dimension.height = texpageJson["size"]["height"].get<unsigned>();
texpage->textureId = texpageJson["sheetid"].get<unsigned>();
std::scoped_lock lock(texpagesMutex);
texpages[texpage->id] = texpage;
});
ke::Log::instance()->info("Scanning sprite assets...");
const auto spriteRootDirPath = fs::path{ assetDirPath } / "sprite";
const auto spritePaths = ke::FileSystemHelper::getChildPaths(spriteRootDirPath);
std::for_each(std::execution::par_unseq, std::begin(spritePaths), std::end(spritePaths), [&](const auto & path)
{
if (!path.has_extension() || path.extension() != ".json") return;
ke::Log::instance()->info("Discovered GM:S sprite asset: {}", path.string());
std::ifstream spriteFileStream{ path };
ke::json spriteJson;
spriteFileStream >> spriteJson;
auto sprite = std::make_shared<pf::GMSSpriteResource>(path.stem().string(), path.string());
sprite->dimension.width = spriteJson["size"]["width"].get<unsigned>();
sprite->dimension.height = spriteJson["size"]["height"].get<unsigned>();
sprite->boundingBox.top = spriteJson["bounding"]["top"].get<unsigned>();
sprite->boundingBox.left = spriteJson["bounding"]["left"].get<unsigned>();
sprite->boundingBox.bottom = spriteJson["bounding"]["bottom"].get<unsigned>();
sprite->boundingBox.right = spriteJson["bounding"]["right"].get<unsigned>();
sprite->boundingBoxMode = spriteJson["bboxmode"].get<unsigned>();
sprite->separateMasks = spriteJson["sepmasks"].get<bool>();
sprite->origin.x = spriteJson["origin"]["x"].get<unsigned>();
sprite->origin.y = spriteJson["origin"]["y"].get<unsigned>();
for (const auto & textureJson : spriteJson["textures"])
{
sprite->texpageIds.push_back(textureJson.get<unsigned>());
}
});
// TODO: load and register sprite resources
}
void GMSAssetResourceManagementSystem::loadRoomAssets(void)
{
ke::Log::instance()->info("Scanning GM:S room assets...");
const auto assetDirPath = ke::App::getCommandLineArgValue(pf::cli::ExecAssetsPath).as<ke::String>();
const auto gmsRoomsRootDirPath = fs::path{ assetDirPath } / "rooms";
const auto gmsRoomPaths = ke::FileSystemHelper::getFilePaths(gmsRoomsRootDirPath);
std::hash<ke::String> hasher;
std::for_each(std::execution::par_unseq, std::begin(gmsRoomPaths), std::end(gmsRoomPaths), [&](const auto & gmsRoomPath)
{
if (!gmsRoomPath.has_extension() || gmsRoomPath.extension() != ".json") return;
ke::Log::instance()->info("Discovered GM:S room asset: {}", gmsRoomPath.string());
auto roomResource = std::make_shared<GMSRoomResource>();
roomResource->setName(gmsRoomPath.stem().string());
roomResource->setSourcePath(gmsRoomPath.string());
std::ifstream roomFileStream{ gmsRoomPath };
ke::json roomJson;
roomFileStream >> roomJson;
//
// Load general room info.
//
GMSRoomResource::SizeType roomSize;
roomSize.width = roomJson["size"]["width"].get<unsigned>();
roomSize.height = roomJson["size"]["height"].get<unsigned>();
roomResource->setSize(roomSize);
roomResource->setSpeed(roomJson["speed"].get<int>());
auto roomColourStr = roomJson["colour"].get<ke::String>();
roomResource->setColour(::gmsColourStrToColour(roomColourStr));
//
// load background info
//
const auto & roomBackgroundsJson = roomJson["bgs"];
for (const auto & backgroundJson : roomBackgroundsJson)
{
GMSRoomBackgroundInfo backgroundInfo;
backgroundInfo.enabled = backgroundJson["enabled"].get<bool>();
backgroundInfo.foreground = backgroundJson["foreground"].get<bool>();
backgroundInfo.pos = { backgroundJson["pos"]["x"].get<int>(), -backgroundJson["pos"]["y"].get<int>() };
backgroundInfo.tilex = backgroundJson["tilex"].get<bool>();
backgroundInfo.tiley = backgroundJson["tiley"].get<bool>();
backgroundInfo.speed = { backgroundJson["speed"]["x"].get<int>(), -backgroundJson["speed"]["y"].get<int>() };
backgroundInfo.stretch = backgroundJson["stretch"].get<bool>();
backgroundInfo.bg = backgroundJson.value("bg", "");
backgroundInfo.bg_hash = hasher(backgroundInfo.bg);
roomResource->addBackgroundInfo(backgroundInfo);
}
//
// load tile instances
//
const auto & roomTilesJson = roomJson["tiles"];
roomResource->tiles.reserve(roomTilesJson.size());
for (const auto & tileJson : roomTilesJson)
{
pf::GMSRoomTileInstance newTile;
newTile.instanceid = tileJson["instanceid"].get<unsigned>();
// Here we make sure to convert the GM:S room coordinates to KEngine's world coordinates.
// I.e. y-down to y-up.
// Texture coordinates are the same at the moment at y-down. I.e. (0,0) at top left.
newTile.pos = { tileJson["pos"]["x"].get<int>(), -tileJson["pos"]["y"].get<int>() };
newTile.bg = tileJson["bg"].get<ke::String>();
newTile.bg_hash = hasher(newTile.bg);
newTile.sourcepos = { tileJson["sourcepos"]["x"].get<int>(), tileJson["sourcepos"]["y"].get<int>() }; // sourcepos is y-down local image coordinates.
newTile.size = { tileJson["size"]["width"].get<int>(), tileJson["size"]["height"].get<int>() };
newTile.scale = { tileJson["scale"]["x"].get<float>(), tileJson["scale"]["y"].get<float>() };
newTile.colour = ::gmsColourStrToColour(tileJson["colour"].get<ke::String>());
// Here convert GM:S' depth system to KEngine's depth system.
// GM:S depth value: larger == further back.
// KEngine depth value: larger == further in front.
newTile.tiledepth = -tileJson["tiledepth"].get<ke::graphics::DepthType>();
roomResource->addTile(newTile);
}
//
// load object instances
//
const auto & roomObjsJson = roomJson["objs"];
roomResource->objects.reserve(roomObjsJson.size());
for (const auto & objJson : roomObjsJson)
{
pf::GMSRoomObjectInstance obj;
obj.instanceid = objJson["instanceid"].get<ke::EntityId>();
obj.obj = objJson["obj"].get<ke::String>();
obj.pos = { objJson["pos"]["x"].get<int>(), -objJson["pos"]["y"].get<int>() };
obj.scale = { objJson["scale"]["x"].get<float>(), objJson["scale"]["y"].get<float>() };
obj.rotation = objJson["rotation"].get<float>();
obj.colour = ::gmsColourStrToColour(objJson["colour"].get<ke::String>());
roomResource->addObject(obj);
}
ke::App::instance()->getResourceManager()->registerResource(roomResource);
});
}
void GMSAssetResourceManagementSystem::loadObjectAssets(void)
{
ke::Log::instance()->info("Scanning GM:S object assets...");
const auto assetDirPath = ke::App::getCommandLineArgValue(pf::cli::ExecAssetsPath).as<ke::String>();
const auto gmsObjectRootDirPath = fs::path{ assetDirPath } / "object";
const auto gmsObjectPaths = ke::FileSystemHelper::getFilePaths(gmsObjectRootDirPath);
std::for_each(std::execution::par_unseq, std::begin(gmsObjectPaths), std::end(gmsObjectPaths), [&](const auto & gmsObjectPath)
{
if (!gmsObjectPath.has_extension() || gmsObjectPath.extension() != "json") return;
ke::Log::instance()->info("Discovered GM:S object asset: {}", gmsObjectPath.string());
std::ifstream objectFileStream{ gmsObjectPath };
ke::json objectJson;
objectFileStream >> objectJson;
auto objectResource = std::make_shared<pf::GMSObjectResource>(fs::path(gmsObjectPath).stem().string(), gmsObjectPath.string());
objectResource->sprite = objectJson["sprite"].get<ke::String>();
objectResource->visible = objectJson["visible"].get<bool>();
objectResource->solid = objectJson["solid"].get<bool>();
objectResource->depth = objectJson["depth"].get<decltype(objectResource->depth)>();
objectResource->persist = objectJson["persist"].get<bool>();
objectResource->sensor = objectJson["sensor"].get<bool>();
objectResource->colshape = objectJson["colshape"].get<ke::String>();
ke::App::instance()->getResourceManager()->registerResource(objectResource);
});
}
}<commit_msg>rephrase GM:S asset loading messages<commit_after>#include "GMSAssetResourceManagementSystem.hpp"
#include "../AssetResources/TextureInfoResource.hpp"
#include "../AssetResources/GMSRoomResource.hpp"
#include "../AssetResources/GMSObjectResource.hpp"
#include "../AssetResources/OtherGMSResources.hpp"
#include "../CommandLineOptions.hpp"
#include <KEngine/Events/OtherGraphicsEvents.hpp>
#include <KEngine/App.hpp>
#include <KEngine/Utility/FileSystemHelper.hpp>
#include <KEngine/Log/Log.hpp>
#include <SFML/Graphics/Image.hpp>
#include <algorithm>
#include <execution>
#include <filesystem>
#include <fstream>
#include <limits>
#include <mutex>
#include <utility>
namespace fs = std::filesystem;
namespace
{
ke::Colour gmsColourStrToColour(const ke::String & p_colourStr)
{
assert(p_colourStr.length() == 9);
assert(p_colourStr[0] == '#');
ke::Colour roomColour = {
// assume colour is in hex RGBA starting with the '#' symbol.
static_cast<uint8_t>(std::stol(p_colourStr.substr(1, 2), nullptr, 16)),
static_cast<uint8_t>(std::stol(p_colourStr.substr(3, 2), nullptr, 16)),
static_cast<uint8_t>(std::stol(p_colourStr.substr(5, 2), nullptr, 16)),
static_cast<uint8_t>(std::stol(p_colourStr.substr(7, 2), nullptr, 16)) };
return roomColour;
}
}
namespace pf
{
bool GMSAssetResourceManagementSystem::initialise()
{
ke::Log::instance()->info("Scanning assets...");
this->loadTextureAssets();
this->loadSpriteAssets();
this->loadObjectAssets();
this->loadRoomAssets();
ke::Log::instance()->info("Scanning assets... DONE");
return true;
}
void GMSAssetResourceManagementSystem::shutdown()
{
}
void GMSAssetResourceManagementSystem::update(ke::Time elapsedTime)
{
KE_UNUSED(elapsedTime);
}
void GMSAssetResourceManagementSystem::loadTextureAssets(void)
{
ke::Log::instance()->info("Scanning texture assets...");
const auto assetDirPath = ke::App::getCommandLineArgValue(pf::cli::ExecAssetsPath).as<ke::String>();
const auto texturesRootDirPath = fs::path{ assetDirPath } / "textures";
sf::Image tempImage;
std::hash<ke::String> hasher;
for (const auto & path : ke::FileSystemHelper::getChildPaths(texturesRootDirPath))
{
if (fs::is_directory(path)) // is a texture directory.
{
auto textureFilePaths = ke::FileSystemHelper::getFilePaths(path);
if (textureFilePaths.size() == 1)
{
const auto & texPath = textureFilePaths[0];
ke::Log::instance()->info("Loading texture asset: {}", texPath.string());
auto textureResource = std::make_shared<TextureInfoResource>();
textureResource->setName(texPath.stem().string());
textureResource->setTextureId(hasher(textureResource->getName()));
textureResource->setSourcePath(texPath.string());
// retrieve size
bool ret = tempImage.loadFromFile(texPath.string());
assert(ret);
TextureInfoResource::DimensionType dimension;
dimension.width = tempImage.getSize().x;
dimension.height = tempImage.getSize().y;
textureResource->setTextureSize(dimension);
ke::App::instance()->getResourceManager()->registerResource(textureResource);
}
else
{
// ignore when there're multiple texture files in a single dir for now.
}
}
else if (fs::is_regular_file(path) && path.extension() == "png") // is a png texture.
{
ke::Log::instance()->info("Loading texture asset: {}", path.string());
auto textureResource = std::make_shared<TextureInfoResource>();
textureResource->setName("texture_" + path.stem().string());
textureResource->setTextureId(std::stoi(textureResource->getName()));
textureResource->setSourcePath(path.string());
// retrieve size
bool ret = tempImage.loadFromFile(path.string());
assert(ret);
TextureInfoResource::DimensionType dimension;
dimension.width = tempImage.getSize().x;
dimension.height = tempImage.getSize().y;
textureResource->setTextureSize(dimension);
ke::App::instance()->getResourceManager()->registerResource(textureResource);
}
}
}
void GMSAssetResourceManagementSystem::loadSpriteAssets(void)
{
ke::Log::instance()->info("Scanning texpage assets...");
const auto assetDirPath = ke::App::getCommandLineArgValue(pf::cli::ExecAssetsPath).as<ke::String>();
const auto texpageRootDirPath = fs::path{ assetDirPath } / "texpage";
std::mutex texpagesMutex;
std::unordered_map<unsigned, std::shared_ptr<pf::GMSTexpageResource>> texpages; // <texpage_id, texpage>
const auto texpagePaths = ke::FileSystemHelper::getChildPaths(texpageRootDirPath);
std::for_each(std::execution::par_unseq, std::begin(texpagePaths), std::end(texpagePaths), [&](const auto & path)
{
if (!path.has_extension() || path.extension() != ".json") return;
ke::Log::instance()->info("Loading GM:S texpage asset: {}", path.string());
std::ifstream texpageFileStream{ path };
ke::json texpageJson;
texpageFileStream >> texpageJson;
auto texpage = std::make_shared<pf::GMSTexpageResource>("texpage_" + path.stem().string(), path.string());
texpage->id = std::stoi(path.stem().string());
texpage->sourcePosition.x = texpageJson["src"]["x"].get<unsigned>();
texpage->sourcePosition.y = texpageJson["src"]["y"].get<unsigned>();
texpage->sourceDimension.width = texpageJson["src"]["width"].get<unsigned>();
texpage->sourceDimension.height = texpageJson["src"]["height"].get<unsigned>();
texpage->destinationPosition.x = texpageJson["dest"]["x"].get<unsigned>();
texpage->destinationPosition.y = texpageJson["dest"]["y"].get<unsigned>();
texpage->destinationDimension.width = texpageJson["dest"]["width"].get<unsigned>();
texpage->destinationDimension.height = texpageJson["dest"]["height"].get<unsigned>();
texpage->dimension.width = texpageJson["size"]["width"].get<unsigned>();
texpage->dimension.height = texpageJson["size"]["height"].get<unsigned>();
texpage->textureId = texpageJson["sheetid"].get<unsigned>();
std::scoped_lock lock(texpagesMutex);
texpages[texpage->id] = texpage;
});
ke::Log::instance()->info("Scanning sprite assets...");
const auto spriteRootDirPath = fs::path{ assetDirPath } / "sprite";
const auto spritePaths = ke::FileSystemHelper::getChildPaths(spriteRootDirPath);
std::for_each(std::execution::par_unseq, std::begin(spritePaths), std::end(spritePaths), [&](const auto & path)
{
if (!path.has_extension() || path.extension() != ".json") return;
ke::Log::instance()->info("Loading GM:S sprite asset: {}", path.string());
std::ifstream spriteFileStream{ path };
ke::json spriteJson;
spriteFileStream >> spriteJson;
auto sprite = std::make_shared<pf::GMSSpriteResource>(path.stem().string(), path.string());
sprite->dimension.width = spriteJson["size"]["width"].get<unsigned>();
sprite->dimension.height = spriteJson["size"]["height"].get<unsigned>();
sprite->boundingBox.top = spriteJson["bounding"]["top"].get<unsigned>();
sprite->boundingBox.left = spriteJson["bounding"]["left"].get<unsigned>();
sprite->boundingBox.bottom = spriteJson["bounding"]["bottom"].get<unsigned>();
sprite->boundingBox.right = spriteJson["bounding"]["right"].get<unsigned>();
sprite->boundingBoxMode = spriteJson["bboxmode"].get<unsigned>();
sprite->separateMasks = spriteJson["sepmasks"].get<bool>();
sprite->origin.x = spriteJson["origin"]["x"].get<unsigned>();
sprite->origin.y = spriteJson["origin"]["y"].get<unsigned>();
for (const auto & textureJson : spriteJson["textures"])
{
sprite->texpageIds.push_back(textureJson.get<unsigned>());
}
});
// TODO: load and register sprite resources
}
void GMSAssetResourceManagementSystem::loadRoomAssets(void)
{
ke::Log::instance()->info("Scanning GM:S room assets...");
const auto assetDirPath = ke::App::getCommandLineArgValue(pf::cli::ExecAssetsPath).as<ke::String>();
const auto gmsRoomsRootDirPath = fs::path{ assetDirPath } / "rooms";
const auto gmsRoomPaths = ke::FileSystemHelper::getFilePaths(gmsRoomsRootDirPath);
std::hash<ke::String> hasher;
std::for_each(std::execution::par_unseq, std::begin(gmsRoomPaths), std::end(gmsRoomPaths), [&](const auto & gmsRoomPath)
{
if (!gmsRoomPath.has_extension() || gmsRoomPath.extension() != ".json") return;
ke::Log::instance()->info("Loading GM:S room asset: {}", gmsRoomPath.string());
auto roomResource = std::make_shared<GMSRoomResource>();
roomResource->setName(gmsRoomPath.stem().string());
roomResource->setSourcePath(gmsRoomPath.string());
std::ifstream roomFileStream{ gmsRoomPath };
ke::json roomJson;
roomFileStream >> roomJson;
//
// Load general room info.
//
GMSRoomResource::SizeType roomSize;
roomSize.width = roomJson["size"]["width"].get<unsigned>();
roomSize.height = roomJson["size"]["height"].get<unsigned>();
roomResource->setSize(roomSize);
roomResource->setSpeed(roomJson["speed"].get<int>());
auto roomColourStr = roomJson["colour"].get<ke::String>();
roomResource->setColour(::gmsColourStrToColour(roomColourStr));
//
// load background info
//
const auto & roomBackgroundsJson = roomJson["bgs"];
for (const auto & backgroundJson : roomBackgroundsJson)
{
GMSRoomBackgroundInfo backgroundInfo;
backgroundInfo.enabled = backgroundJson["enabled"].get<bool>();
backgroundInfo.foreground = backgroundJson["foreground"].get<bool>();
backgroundInfo.pos = { backgroundJson["pos"]["x"].get<int>(), -backgroundJson["pos"]["y"].get<int>() };
backgroundInfo.tilex = backgroundJson["tilex"].get<bool>();
backgroundInfo.tiley = backgroundJson["tiley"].get<bool>();
backgroundInfo.speed = { backgroundJson["speed"]["x"].get<int>(), -backgroundJson["speed"]["y"].get<int>() };
backgroundInfo.stretch = backgroundJson["stretch"].get<bool>();
backgroundInfo.bg = backgroundJson.value("bg", "");
backgroundInfo.bg_hash = hasher(backgroundInfo.bg);
roomResource->addBackgroundInfo(backgroundInfo);
}
//
// load tile instances
//
const auto & roomTilesJson = roomJson["tiles"];
roomResource->tiles.reserve(roomTilesJson.size());
for (const auto & tileJson : roomTilesJson)
{
pf::GMSRoomTileInstance newTile;
newTile.instanceid = tileJson["instanceid"].get<unsigned>();
// Here we make sure to convert the GM:S room coordinates to KEngine's world coordinates.
// I.e. y-down to y-up.
// Texture coordinates are the same at the moment at y-down. I.e. (0,0) at top left.
newTile.pos = { tileJson["pos"]["x"].get<int>(), -tileJson["pos"]["y"].get<int>() };
newTile.bg = tileJson["bg"].get<ke::String>();
newTile.bg_hash = hasher(newTile.bg);
newTile.sourcepos = { tileJson["sourcepos"]["x"].get<int>(), tileJson["sourcepos"]["y"].get<int>() }; // sourcepos is y-down local image coordinates.
newTile.size = { tileJson["size"]["width"].get<int>(), tileJson["size"]["height"].get<int>() };
newTile.scale = { tileJson["scale"]["x"].get<float>(), tileJson["scale"]["y"].get<float>() };
newTile.colour = ::gmsColourStrToColour(tileJson["colour"].get<ke::String>());
// Here convert GM:S' depth system to KEngine's depth system.
// GM:S depth value: larger == further back.
// KEngine depth value: larger == further in front.
newTile.tiledepth = -tileJson["tiledepth"].get<ke::graphics::DepthType>();
roomResource->addTile(newTile);
}
//
// load object instances
//
const auto & roomObjsJson = roomJson["objs"];
roomResource->objects.reserve(roomObjsJson.size());
for (const auto & objJson : roomObjsJson)
{
pf::GMSRoomObjectInstance obj;
obj.instanceid = objJson["instanceid"].get<ke::EntityId>();
obj.obj = objJson["obj"].get<ke::String>();
obj.pos = { objJson["pos"]["x"].get<int>(), -objJson["pos"]["y"].get<int>() };
obj.scale = { objJson["scale"]["x"].get<float>(), objJson["scale"]["y"].get<float>() };
obj.rotation = objJson["rotation"].get<float>();
obj.colour = ::gmsColourStrToColour(objJson["colour"].get<ke::String>());
roomResource->addObject(obj);
}
ke::App::instance()->getResourceManager()->registerResource(roomResource);
});
}
void GMSAssetResourceManagementSystem::loadObjectAssets(void)
{
ke::Log::instance()->info("Scanning GM:S object assets...");
const auto assetDirPath = ke::App::getCommandLineArgValue(pf::cli::ExecAssetsPath).as<ke::String>();
const auto gmsObjectRootDirPath = fs::path{ assetDirPath } / "object";
const auto gmsObjectPaths = ke::FileSystemHelper::getFilePaths(gmsObjectRootDirPath);
std::for_each(std::execution::par_unseq, std::begin(gmsObjectPaths), std::end(gmsObjectPaths), [&](const auto & gmsObjectPath)
{
if (!gmsObjectPath.has_extension() || gmsObjectPath.extension() != "json") return;
ke::Log::instance()->info("Loading GM:S object asset: {}", gmsObjectPath.string());
std::ifstream objectFileStream{ gmsObjectPath };
ke::json objectJson;
objectFileStream >> objectJson;
auto objectResource = std::make_shared<pf::GMSObjectResource>(fs::path(gmsObjectPath).stem().string(), gmsObjectPath.string());
objectResource->sprite = objectJson["sprite"].get<ke::String>();
objectResource->visible = objectJson["visible"].get<bool>();
objectResource->solid = objectJson["solid"].get<bool>();
objectResource->depth = objectJson["depth"].get<decltype(objectResource->depth)>();
objectResource->persist = objectJson["persist"].get<bool>();
objectResource->sensor = objectJson["sensor"].get<bool>();
objectResource->colshape = objectJson["colshape"].get<ke::String>();
ke::App::instance()->getResourceManager()->registerResource(objectResource);
});
}
}<|endoftext|> |
<commit_before>
// Includes.
#include "UI/mainwindow.h"
#include "App/App.h"
#include "App/Factories/AdditionNodeFactoryDelegate.h"
#include "App/Factories/ConstantNodeFactoryDelegate.h"
#include "App/Factories/PrinterNodeFactoryDelegate.h"
// Qt.
#include <QApplication>
QString titleString()
{
QString name = QString::fromStdString(App::appName());
QString version = QString::fromStdString(App::appVersion());
return QString("%1 - v%2").arg(name).arg(version);
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
App app;
app.addNodeFactory(new AdditionNodeFactoryDelegate);
app.addNodeFactory(new ConstantNodeFactoryDelegate);
app.addNodeFactory(new PrinterNodeFactoryDelegate);
MainWindow w(&app);
w.setWindowTitle(titleString());
w.setMinimumSize(640, 480);
w.show();
app.setUI(&w);
app.setDelegate(&w);
return a.exec();
}
<commit_msg>Enlarge the minimum size of the main window, so that the scene view has enough space again.<commit_after>
// Includes.
#include "UI/mainwindow.h"
#include "App/App.h"
#include "App/Factories/AdditionNodeFactoryDelegate.h"
#include "App/Factories/ConstantNodeFactoryDelegate.h"
#include "App/Factories/PrinterNodeFactoryDelegate.h"
// Qt.
#include <QApplication>
QString titleString()
{
QString name = QString::fromStdString(App::appName());
QString version = QString::fromStdString(App::appVersion());
return QString("%1 - v%2").arg(name).arg(version);
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
App app;
app.addNodeFactory(new AdditionNodeFactoryDelegate);
app.addNodeFactory(new ConstantNodeFactoryDelegate);
app.addNodeFactory(new PrinterNodeFactoryDelegate);
MainWindow w(&app);
w.setWindowTitle(titleString());
w.setMinimumSize(800, 600);
w.show();
app.setUI(&w);
app.setDelegate(&w);
return a.exec();
}
<|endoftext|> |
<commit_before>5ae7ec25-2d16-11e5-af21-0401358ea401<commit_msg>5ae7ec26-2d16-11e5-af21-0401358ea401<commit_after>5ae7ec26-2d16-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>d32a362e-313a-11e5-a6cc-3c15c2e10482<commit_msg>d33041ae-313a-11e5-9122-3c15c2e10482<commit_after>d33041ae-313a-11e5-9122-3c15c2e10482<|endoftext|> |
<commit_before>4dfedf4a-2e4f-11e5-850a-28cfe91dbc4b<commit_msg>4e057b99-2e4f-11e5-aaae-28cfe91dbc4b<commit_after>4e057b99-2e4f-11e5-aaae-28cfe91dbc4b<|endoftext|> |
<commit_before>71e649f8-2e3a-11e5-8e63-c03896053bdd<commit_msg>71f4f2ac-2e3a-11e5-b56a-c03896053bdd<commit_after>71f4f2ac-2e3a-11e5-b56a-c03896053bdd<|endoftext|> |
<commit_before>52c657b0-ad5c-11e7-b75f-ac87a332f658<commit_msg>Test..<commit_after>5343ce70-ad5c-11e7-828a-ac87a332f658<|endoftext|> |
<commit_before>7f6cf5d9-2d15-11e5-af21-0401358ea401<commit_msg>7f6cf5da-2d15-11e5-af21-0401358ea401<commit_after>7f6cf5da-2d15-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>762c906a-2d53-11e5-baeb-247703a38240<commit_msg>762d10e4-2d53-11e5-baeb-247703a38240<commit_after>762d10e4-2d53-11e5-baeb-247703a38240<|endoftext|> |
<commit_before>d892e1a6-313a-11e5-9334-3c15c2e10482<commit_msg>d89e794f-313a-11e5-a86f-3c15c2e10482<commit_after>d89e794f-313a-11e5-a86f-3c15c2e10482<|endoftext|> |
<commit_before>5572c463-2e4f-11e5-a72b-28cfe91dbc4b<commit_msg>557a7f57-2e4f-11e5-b8d3-28cfe91dbc4b<commit_after>557a7f57-2e4f-11e5-b8d3-28cfe91dbc4b<|endoftext|> |
<commit_before>d89eb345-2e4e-11e5-8ce8-28cfe91dbc4b<commit_msg>d8a6937a-2e4e-11e5-85ee-28cfe91dbc4b<commit_after>d8a6937a-2e4e-11e5-85ee-28cfe91dbc4b<|endoftext|> |
<commit_before>95dd942c-35ca-11e5-931a-6c40088e03e4<commit_msg>95e7141e-35ca-11e5-8ab1-6c40088e03e4<commit_after>95e7141e-35ca-11e5-8ab1-6c40088e03e4<|endoftext|> |
<commit_before>#include "mqtt_tcp_server.hpp"
#include <stdexcept>
#include <iostream>
using namespace std;
int main(int argc, char*[]) {
cout << "C++ MQTT server" << endl;
try {
constexpr int port = 1883;
const auto useCache = argc < 2;
if(!useCache) {
cout << "Disabling the cache" << endl;
}
MqttTcpServer server(port, useCache);
server.run();
} catch(const std::exception& e) {
std::cerr << "Exception: " << e.what() << std::endl;
return 1;
}
return 0;
}
<commit_msg>Using the cache no longer default<commit_after>#include "mqtt_tcp_server.hpp"
#include <stdexcept>
#include <iostream>
using namespace std;
int main(int argc, char*[]) {
cout << "C++ MQTT server" << endl;
try {
constexpr int port = 1883;
const auto useCache = argc > 1;
if(useCache) {
cout << "Enabling the cache" << endl;
}
MqttTcpServer server(port, useCache);
server.run();
} catch(const std::exception& e) {
std::cerr << "Exception: " << e.what() << std::endl;
return 1;
}
return 0;
}
<|endoftext|> |
<commit_before>99f03347-ad5b-11e7-a3c1-ac87a332f658<commit_msg>For bobby to integrate at some point<commit_after>9a652be3-ad5b-11e7-9c20-ac87a332f658<|endoftext|> |
<commit_before>797b2ab0-2d53-11e5-baeb-247703a38240<commit_msg>797babf2-2d53-11e5-baeb-247703a38240<commit_after>797babf2-2d53-11e5-baeb-247703a38240<|endoftext|> |
<commit_before>5f894a0c-2d16-11e5-af21-0401358ea401<commit_msg>5f894a0d-2d16-11e5-af21-0401358ea401<commit_after>5f894a0d-2d16-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>787d5818-2d53-11e5-baeb-247703a38240<commit_msg>787ddb80-2d53-11e5-baeb-247703a38240<commit_after>787ddb80-2d53-11e5-baeb-247703a38240<|endoftext|> |
<commit_before>d8179d86-35ca-11e5-9579-6c40088e03e4<commit_msg>d81e1602-35ca-11e5-811f-6c40088e03e4<commit_after>d81e1602-35ca-11e5-811f-6c40088e03e4<|endoftext|> |
<commit_before>a5ed05c6-35ca-11e5-90fc-6c40088e03e4<commit_msg>a5f4074a-35ca-11e5-bea7-6c40088e03e4<commit_after>a5f4074a-35ca-11e5-bea7-6c40088e03e4<|endoftext|> |
<commit_before>5fa8a247-2e4f-11e5-947f-28cfe91dbc4b<commit_msg>5fb06738-2e4f-11e5-b6d3-28cfe91dbc4b<commit_after>5fb06738-2e4f-11e5-b6d3-28cfe91dbc4b<|endoftext|> |
<commit_before>6c782276-2fa5-11e5-81aa-00012e3d3f12<commit_msg>6c79d024-2fa5-11e5-bfc0-00012e3d3f12<commit_after>6c79d024-2fa5-11e5-bfc0-00012e3d3f12<|endoftext|> |
<commit_before>d5d3c9b0-327f-11e5-aadc-9cf387a8033e<commit_msg>d5db692e-327f-11e5-8f67-9cf387a8033e<commit_after>d5db692e-327f-11e5-8f67-9cf387a8033e<|endoftext|> |
<commit_before>586a0be3-2748-11e6-a0b9-e0f84713e7b8<commit_msg>Put the thingie in the thingie<commit_after>58769c57-2748-11e6-b9fe-e0f84713e7b8<|endoftext|> |
<commit_before>1853c826-2f67-11e5-9237-6c40088e03e4<commit_msg>185aa57e-2f67-11e5-975c-6c40088e03e4<commit_after>185aa57e-2f67-11e5-975c-6c40088e03e4<|endoftext|> |
<commit_before>e4e87087-327f-11e5-b4bf-9cf387a8033e<commit_msg>e4ee63f8-327f-11e5-ab93-9cf387a8033e<commit_after>e4ee63f8-327f-11e5-ab93-9cf387a8033e<|endoftext|> |
<commit_before>139aaf8f-2e4f-11e5-9286-28cfe91dbc4b<commit_msg>13a35cb8-2e4f-11e5-8c19-28cfe91dbc4b<commit_after>13a35cb8-2e4f-11e5-8c19-28cfe91dbc4b<|endoftext|> |
<commit_before>9e478dbd-2e4f-11e5-9f22-28cfe91dbc4b<commit_msg>9e4eceee-2e4f-11e5-92d3-28cfe91dbc4b<commit_after>9e4eceee-2e4f-11e5-92d3-28cfe91dbc4b<|endoftext|> |
<commit_before>51f4e6d1-2e4f-11e5-8514-28cfe91dbc4b<commit_msg>51fc9f11-2e4f-11e5-9803-28cfe91dbc4b<commit_after>51fc9f11-2e4f-11e5-9803-28cfe91dbc4b<|endoftext|> |
<commit_before>6d20c44c-2e4f-11e5-b999-28cfe91dbc4b<commit_msg>6d2a0573-2e4f-11e5-86b3-28cfe91dbc4b<commit_after>6d2a0573-2e4f-11e5-86b3-28cfe91dbc4b<|endoftext|> |
<commit_before>10a6c2ca-2748-11e6-9c7b-e0f84713e7b8<commit_msg>NO CHANGES<commit_after>10b3cba1-2748-11e6-b57b-e0f84713e7b8<|endoftext|> |
<commit_before>9b1d29f0-35ca-11e5-a1a7-6c40088e03e4<commit_msg>9b260da4-35ca-11e5-8bc3-6c40088e03e4<commit_after>9b260da4-35ca-11e5-8bc3-6c40088e03e4<|endoftext|> |
<commit_before>6e6facb4-2fa5-11e5-8fc0-00012e3d3f12<commit_msg>6e718176-2fa5-11e5-9b52-00012e3d3f12<commit_after>6e718176-2fa5-11e5-9b52-00012e3d3f12<|endoftext|> |
<commit_before>6613ec06-2e3a-11e5-8551-c03896053bdd<commit_msg>662a5e50-2e3a-11e5-be58-c03896053bdd<commit_after>662a5e50-2e3a-11e5-be58-c03896053bdd<|endoftext|> |
<commit_before>#include "SmartPointers.hpp"
#include "Exception.hpp"
#include "ImageImporter2D.hpp"
#include "ImageExporter2D.hpp"
#include "VTKImageExporter.hpp"
#include "VTKImageImporter.hpp"
#include "ITKImageExporter.hpp"
#include "ImageStreamer2D.hpp"
#include "DeviceManager.hpp"
#include "GaussianSmoothingFilter2D.hpp"
#include "SimpleWindow.hpp"
#include "ImageRenderer.hpp"
#include <vtkVersion.h>
#include <vtkImageData.h>
#include <vtkSmartPointer.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkInteractorStyleImage.h>
#include <vtkRenderer.h>
#include <vtkImageMapper.h>
#include <vtkActor2D.h>
#include <QApplication>
using namespace fast;
Image2D::pointer create() {
// Example of importing one 2D image
ImageImporter2D::pointer importer = ImageImporter2D::New();
importer->setFilename("lena.jpg");
return importer->getOutput();
}
int main(int argc, char ** argv) {
// Get a GPU device and set it as the default device
DeviceManager& deviceManager = DeviceManager::getInstance();
deviceManager.setDefaultDevice(deviceManager.getOneGPUDevice(true));
// Example of importing, processing and exporting a 2D image
ImageImporter2D::pointer importer = ImageImporter2D::New();
importer->setFilename("lena.jpg");
GaussianSmoothingFilter2D::pointer filter = GaussianSmoothingFilter2D::New();
filter->setInput(importer->getOutput());
filter->setMaskSize(7);
filter->setStandardDeviation(10);
Image2D::pointer filteredImage = filter->getOutput();
ImageExporter2D::pointer exporter = ImageExporter2D::New();
exporter->setFilename("test.jpg");
exporter->setInput(filteredImage);
exporter->update();
// Example of displaying an image on screen using ImageRenderer (2D) and SimpleWindow
// TODO The QApplication part should ideally be hid away
QApplication app(argc,argv);
ImageRenderer::pointer renderer = ImageRenderer::New();
renderer->setInput(filteredImage);
SimpleWindow::pointer window = SimpleWindow::New();
window->addRenderer(renderer);
window->resize(512,512);
window->runMainLoop();
// Example of creating a pipeline in another scope and updating afterwards
Image2D::pointer image2 = create();
std::cout << "after create" << std::endl;
image2->update();
// Example of streaming 2D images
ImageStreamer2D::pointer streamer = ImageStreamer2D::New();
streamer->setFilenameFormat("test_#.jpg");
GaussianSmoothingFilter2D::pointer filter2 = GaussianSmoothingFilter2D::New();
filter2->setInput(streamer->getOutput());
filter2->setMaskSize(7);
filter2->setStandardDeviation(10);
Image2Dt::pointer dynamicImage = filter2->getOutput();
// Call update 4 times
int i = 4;
while(--i) {
dynamicImage->update();
}
// ITK Export example
typedef itk::Image<float, 2> ImageType;
ITKImageExporter<ImageType>::Pointer itkExporter = ITKImageExporter<ImageType>::New();
itkExporter->SetInput(filteredImage);
ImageType::Pointer itkImage = itkExporter->GetOutput();
itkExporter->Update();
// VTK Import example
VTKImageImporter::pointer vtkImporter = VTKImageImporter::New();
vtkImporter->setInput(vtkImage);
Image2D::pointer importedImage = vtkImporter->getOutput();
vtkImporter->update();
}
<commit_msg>added missing code<commit_after>#include "SmartPointers.hpp"
#include "Exception.hpp"
#include "ImageImporter2D.hpp"
#include "ImageExporter2D.hpp"
#include "VTKImageExporter.hpp"
#include "VTKImageImporter.hpp"
#include "ITKImageExporter.hpp"
#include "ImageStreamer2D.hpp"
#include "DeviceManager.hpp"
#include "GaussianSmoothingFilter2D.hpp"
#include "SimpleWindow.hpp"
#include "ImageRenderer.hpp"
#include <vtkVersion.h>
#include <vtkImageData.h>
#include <vtkSmartPointer.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkInteractorStyleImage.h>
#include <vtkRenderer.h>
#include <vtkImageMapper.h>
#include <vtkActor2D.h>
#include <QApplication>
using namespace fast;
Image2D::pointer create() {
// Example of importing one 2D image
ImageImporter2D::pointer importer = ImageImporter2D::New();
importer->setFilename("lena.jpg");
return importer->getOutput();
}
int main(int argc, char ** argv) {
// Get a GPU device and set it as the default device
DeviceManager& deviceManager = DeviceManager::getInstance();
deviceManager.setDefaultDevice(deviceManager.getOneGPUDevice(true));
// Example of importing, processing and exporting a 2D image
ImageImporter2D::pointer importer = ImageImporter2D::New();
importer->setFilename("lena.jpg");
GaussianSmoothingFilter2D::pointer filter = GaussianSmoothingFilter2D::New();
filter->setInput(importer->getOutput());
filter->setMaskSize(7);
filter->setStandardDeviation(10);
Image2D::pointer filteredImage = filter->getOutput();
ImageExporter2D::pointer exporter = ImageExporter2D::New();
exporter->setFilename("test.jpg");
exporter->setInput(filteredImage);
exporter->update();
// Example of displaying an image on screen using ImageRenderer (2D) and SimpleWindow
// TODO The QApplication part should ideally be hid away
QApplication app(argc,argv);
ImageRenderer::pointer renderer = ImageRenderer::New();
renderer->setInput(filteredImage);
SimpleWindow::pointer window = SimpleWindow::New();
window->addRenderer(renderer);
window->resize(512,512);
window->runMainLoop();
// Example of creating a pipeline in another scope and updating afterwards
Image2D::pointer image2 = create();
std::cout << "after create" << std::endl;
image2->update();
// Example of streaming 2D images
ImageStreamer2D::pointer streamer = ImageStreamer2D::New();
streamer->setFilenameFormat("test_#.jpg");
GaussianSmoothingFilter2D::pointer filter2 = GaussianSmoothingFilter2D::New();
filter2->setInput(streamer->getOutput());
filter2->setMaskSize(7);
filter2->setStandardDeviation(10);
Image2Dt::pointer dynamicImage = filter2->getOutput();
// Call update 4 times
int i = 4;
while(--i) {
dynamicImage->update();
}
// VTK Export and render example
vtkSmartPointer<VTKImageExporter> vtkExporter = VTKImageExporter::New();
vtkExporter->SetInput(filteredImage);
vtkSmartPointer<vtkImageData> vtkImage = vtkExporter->GetOutput();
vtkExporter->Update();
// VTK mess for getting the image on screen
vtkSmartPointer<vtkImageMapper> imageMapper = vtkSmartPointer<vtkImageMapper>::New();
#if VTK_MAJOR_VERSION <= 5
imageMapper->SetInputConnection(vtkImage->GetProducerPort());
#else
imageMapper->SetInputData(vtkImage);
#endif
imageMapper->SetColorWindow(1);
imageMapper->SetColorLevel(0.5);
vtkSmartPointer<vtkActor2D> imageActor = vtkSmartPointer<vtkActor2D>::New();
imageActor->SetMapper(imageMapper);
// Setup renderers and render window
vtkSmartPointer<vtkRenderer> renderer2 = vtkSmartPointer<vtkRenderer>::New();
vtkSmartPointer<vtkRenderWindow> renderWindow = vtkSmartPointer<vtkRenderWindow>::New();
renderWindow->AddRenderer(renderer2);
renderWindow->SetSize(filteredImage->getWidth(), filteredImage->getHeight());
// Setup render window interactor
vtkSmartPointer<vtkRenderWindowInteractor> renderWindowInteractor = vtkSmartPointer<vtkRenderWindowInteractor>::New();
vtkSmartPointer<vtkInteractorStyleImage> style = vtkSmartPointer<vtkInteractorStyleImage>::New();
renderWindowInteractor->SetInteractorStyle(style);
renderWindowInteractor->SetRenderWindow(renderWindow);
renderer2->AddActor2D(imageActor);
renderWindow->Render();
renderWindowInteractor->Start();
// ITK Export example
typedef itk::Image<float, 2> ImageType;
ITKImageExporter<ImageType>::Pointer itkExporter = ITKImageExporter<ImageType>::New();
itkExporter->SetInput(filteredImage);
ImageType::Pointer itkImage = itkExporter->GetOutput();
itkExporter->Update();
// VTK Import example
VTKImageImporter::pointer vtkImporter = VTKImageImporter::New();
vtkImporter->setInput(vtkImage);
Image2D::pointer importedImage = vtkImporter->getOutput();
vtkImporter->update();
}
<|endoftext|> |
<commit_before>99c8550a-327f-11e5-9823-9cf387a8033e<commit_msg>99ce2b23-327f-11e5-a857-9cf387a8033e<commit_after>99ce2b23-327f-11e5-a857-9cf387a8033e<|endoftext|> |
<commit_before>f0408bd1-327f-11e5-a0f2-9cf387a8033e<commit_msg>f046cdb3-327f-11e5-8003-9cf387a8033e<commit_after>f046cdb3-327f-11e5-8003-9cf387a8033e<|endoftext|> |
<commit_before>ff199b8c-585a-11e5-9f4e-6c40088e03e4<commit_msg>ff2491ba-585a-11e5-9972-6c40088e03e4<commit_after>ff2491ba-585a-11e5-9972-6c40088e03e4<|endoftext|> |
<commit_before>75f05557-2e4f-11e5-a1a6-28cfe91dbc4b<commit_msg>75f7484a-2e4f-11e5-8183-28cfe91dbc4b<commit_after>75f7484a-2e4f-11e5-8183-28cfe91dbc4b<|endoftext|> |
<commit_before>2bdbb9de-2e3a-11e5-aad4-c03896053bdd<commit_msg>2be929ca-2e3a-11e5-b6e7-c03896053bdd<commit_after>2be929ca-2e3a-11e5-b6e7-c03896053bdd<|endoftext|> |
<commit_before>#include <boost/python.hpp>
#include <boost/multi_array.hpp>
#include <boost/foreach.hpp>
#include <vector>
#include <iostream>
#include <array>
#include <iostream>
#include <string>
#include "shared/path_creator.hpp"
#include "shared/tdmap.hpp"
#include "gui.cpp"
#include "shared/sizes.h"
#include "shared/sprite.hpp"
#include <stdlib.h> /* srand, rand */
#include <time.h>
#include "shared/spritesheet.hpp"
class TDGamecore
{
private:
std::vector<Player> players;
TDMap * map;
GUI * gui;
public:
TDGamecore(int number_of_players)
{
TDGamecore(number_of_players, DEFAULT_WIDTH, DEFAULT_HEIGHT);
}
TDGamecore(int number_of_players, int width, int height)
{
srand(time(NULL));
Path * path = new Path(NUM_ROWS, NUM_COLS);
std::vector<Path *> paths {path} ;
map = new TDMap(width, height, paths);
Tower * tower = new Tower(Coordinate(2,4));
tower->set_image_string("tower.png");
tower->set_attack_image_string("arrow.png");
map->add_tower(tower);
Spritesheet zombie ("zombie.png", Coordinate(128, 128));
std::vector<Coordinate> cycles;
for(int i = 5; i < 13; i++)
cycles.push_back(Coordinate(i, 5));
Sprite * sprite = new Sprite(path, &zombie, cycles);
map->add_sprite(sprite);
gui = new GUI(NUM_ROWS, NUM_COLS, paths, map);
gui->Update();
sprite->move_to_next_position();
gui->Update();
sprite->move_to_next_position();
sprite->set_attacked();
tower->set_attacking(Coordinate(1, 5));
gui->Update();
tower->remove_attack_tile(Coordinate(1, 5));
sprite->move_to_next_position();
tower->set_attacking(Coordinate(2, 5));
gui->Update();
tower->remove_attack_tile(Coordinate(2, 5));
sprite->move_to_next_position();
tower->set_attacking(Coordinate(3, 5));
gui->Update();
tower->remove_attack_tile(Coordinate(3, 5));
sprite->die();
std::vector<Coordinate> v;
for(int i = 10; i < 30; i++)
v.push_back(Coordinate(i, 5));
sprite->set_new_cycles(v);
gui->Update();
map->remove_sprite(sprite);
gui->Update();
}
void generate_new_player()
{
players.push_back(*(new Player()));
}
};
using namespace boost::python;
BOOST_PYTHON_MODULE(libtd)
{
class_<TDGamecore>("TDGamecore", init<int>());
}
<commit_msg>merging<commit_after>#include <boost/python.hpp>
#include <boost/multi_array.hpp>
#include <boost/foreach.hpp>
#include <vector>
#include <iostream>
#include <array>
#include <iostream>
#include <string>
#include "shared/path_creator.hpp"
#include "shared/tdmap.hpp"
#include "gui.cpp"
#include "shared/sizes.h"
#include "shared/sprite.hpp"
#include <stdlib.h> /* srand, rand */
#include <time.h>
#include "shared/spritesheet.hpp"
class TDGamecore
{
private:
std::vector<Player> players;
TDMap * map;
GUI * gui;
public:
TDGamecore(int number_of_players)
{
TDGamecore(number_of_players, DEFAULT_WIDTH, DEFAULT_HEIGHT);
}
TDGamecore(int number_of_players, int width, int height)
{
srand(time(NULL));
Path * path = new Path(NUM_ROWS, NUM_COLS);
std::vector<Path *> paths {path} ;
map = new TDMap(width, height, paths);
Spritesheet projectile ("projectile2.png", Coordinate(64, 64), 2);
std::vector<Coordinate> tower_cycles = {Coordinate(1, 1), Coordinate(0, 1), Coordinate(2, 0)};
Tower * tower = new Tower(Coordinate(2,4), "tower.png", &projectile, tower_cycles);
map->add_tower(tower);
Spritesheet zombie ("zombie.png", Coordinate(128, 128), 8);
std::vector<Coordinate> cycles;
for(int i = 5; i < 13; i++)
cycles.push_back(Coordinate(i, 5));
Sprite * sprite = new Sprite(path, &zombie, cycles);
map->add_sprite(sprite);
gui = new GUI(NUM_ROWS, NUM_COLS, paths, map);
gui->Update();
sprite->move_to_next_position();
gui->Update();
sprite->move_to_next_position();
sprite->set_attacked();
tower->set_attacking(Coordinate(1, 5));
gui->Update();
tower->remove_attack_tile(Coordinate(1, 5));
sprite->move_to_next_position();
tower->set_attacking(Coordinate(2, 5));
gui->Update();
tower->remove_attack_tile(Coordinate(2, 5));
sprite->move_to_next_position();
tower->set_attacking(Coordinate(3, 5));
gui->Update();
tower->remove_attack_tile(Coordinate(3, 5));
sprite->die();
std::vector<Coordinate> v;
for(int i = 10; i < 30; i++)
v.push_back(Coordinate(i, 5));
sprite->set_new_cycles(v);
gui->Update();
Sprite * sprite2 = new Sprite(path, &zombie, cycles);
map->add_sprite(sprite2);
map->remove_sprite(sprite);
gui->Update();
sprite2->move_to_next_position();
gui->Update();
sprite2->move_to_next_position();
gui->Update();
sprite2->move_to_next_position();
gui->Update();
sprite2->move_to_next_position();
gui->Update();
sprite2->move_to_next_position();
gui->Update();
sprite2->move_to_next_position();
gui->Update();
sprite2->move_to_next_position();
gui->Update();
sprite2->move_to_next_position();
gui->Update();
}
void generate_new_player()
{
players.push_back(*(new Player()));
}
};
using namespace boost::python;
BOOST_PYTHON_MODULE(libtd)
{
class_<TDGamecore>("TDGamecore", init<int>());
}
<|endoftext|> |
<commit_before>9101ae24-2d14-11e5-af21-0401358ea401<commit_msg>9101ae25-2d14-11e5-af21-0401358ea401<commit_after>9101ae25-2d14-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>d5ca3a1e-327f-11e5-a0f7-9cf387a8033e<commit_msg>d5d3c9b0-327f-11e5-aadc-9cf387a8033e<commit_after>d5d3c9b0-327f-11e5-aadc-9cf387a8033e<|endoftext|> |
<commit_before>f4730046-585a-11e5-a28f-6c40088e03e4<commit_msg>f47d469e-585a-11e5-a282-6c40088e03e4<commit_after>f47d469e-585a-11e5-a282-6c40088e03e4<|endoftext|> |
<commit_before>f267c2ab-ad59-11e7-aa9e-ac87a332f658<commit_msg>Nope, didn't work, now it does<commit_after>f2e53cf0-ad59-11e7-a38c-ac87a332f658<|endoftext|> |
<commit_before>3821acf8-5216-11e5-aec6-6c40088e03e4<commit_msg>382b8bf8-5216-11e5-a2fa-6c40088e03e4<commit_after>382b8bf8-5216-11e5-a2fa-6c40088e03e4<|endoftext|> |
<commit_before>809e9279-2d15-11e5-af21-0401358ea401<commit_msg>809e927a-2d15-11e5-af21-0401358ea401<commit_after>809e927a-2d15-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>7f6cf606-2d15-11e5-af21-0401358ea401<commit_msg>7f6cf607-2d15-11e5-af21-0401358ea401<commit_after>7f6cf607-2d15-11e5-af21-0401358ea401<|endoftext|> |
<commit_before>28beafdc-2f67-11e5-ab31-6c40088e03e4<commit_msg>28c58c8a-2f67-11e5-8b58-6c40088e03e4<commit_after>28c58c8a-2f67-11e5-8b58-6c40088e03e4<|endoftext|> |
<commit_before>#include "SIO/LCIORecords.h"
#include "SIO_functions.h"
#include "SIO_stream.h"
#include <SIO/SIORunHeaderHandler.h>
#include <SIO/SIOEventHandler.h>
#include <SIO/SIOCollectionHandler.h>
#include <SIO/SIORandomAccessHandler.h>
#include <EVENT/LCEvent.h>
#include <Exceptions.h>
namespace SIO {
sio::record_ptr LCIORecords::createEventHeaderRecord( const EVENT::LCEvent *event ) const {
auto eventHeaderRecord = std::make_shared<SIO_record>( LCSIO_HEADERRECORDNAME );
eventHeaderRecord->add_block<SIOEventHandler>( LCSIO_HEADERBLOCKNAME );
auto block = eventHeaderRecord->get_block_as<SIOEventHandler>( LCSIO_HEADERBLOCKNAME );
block->setEvent( event );
return eventHeaderRecord;
}
//----------------------------------------------------------------------------
sio::record_ptr LCIORecords::createEventHeaderRecord( IOIMPL::LCEventIOImpl **event, const std::vector<std::string> &readCol ) const {
auto eventHeaderRecord = std::make_shared<SIO_record>( LCSIO_HEADERRECORDNAME );
eventHeaderRecord->add_block<SIOEventHandler>( LCSIO_HEADERBLOCKNAME );
auto block = eventHeaderRecord->get_block_as<SIOEventHandler>( LCSIO_HEADERBLOCKNAME );
block->setEventPtr( event );
block->setReadCollectionNames( readCol );
return eventHeaderRecord;
}
//----------------------------------------------------------------------------
sio::record_ptr LCIORecords::createEventRecord( const EVENT::LCEvent *event ) const {
// create the event record
auto eventRecord = std::make_shared<SIO_record>( LCSIO_EVENTRECORDNAME );
// loop over collections and setup the blocks for writing
auto collectionNames = event->getCollectionNames();
for( auto collectionName : *collectionNames ) {
auto collection = event->getCollection( collectionName );
if( collection->isTransient() ) {
continue;
}
try {
eventRecord->add_block<SIOCollectionHandler>( collectionName, collection->getTypeName(), nullptr );
}
catch(EVENT::Exception& ex) {
continue;
}
auto block = eventRecord->get_block_as<SIOCollectionHandler>( collectionName );
auto handler = _handlerMgr.getHandler( collection->getTypeName() );
block->setHandler( handler );
}
return eventRecord;
}
//----------------------------------------------------------------------------
sio::record_ptr LCIORecords::createEventRecord(IOIMPL::LCEventIOImpl **event) const {
// create the event record
auto eventRecord = std::make_shared<SIO_record>( LCSIO_EVENTRECORDNAME );
// loop over collections and setup the blocks for reading/writing an event
auto collectionNames = (*event)->getCollectionNames();
for( auto collectionName : *collectionNames ) {
auto collection = (*event)->getCollection( collectionName );
try {
eventRecord->add_block<SIOCollectionHandler>( collectionName, collection->getTypeName(), event );
}
catch(EVENT::Exception& ex) {
continue;
}
auto block = eventRecord->get_block_as<SIOCollectionHandler>( collectionName );
auto handler = _handlerMgr.getHandler( collection->getTypeName() );
block->setHandler( handler );
block->setEvent( event );
}
return eventRecord;
}
//----------------------------------------------------------------------------
sio::record_ptr LCIORecords::createRunRecord( const EVENT::LCRunHeader *runHeader ) const {
auto runRecord = std::make_shared<SIO_record>( LCSIO_RUNRECORDNAME );
runRecord->add_block<SIORunHeaderHandler>( LCSIO_RUNBLOCKNAME );
runRecord->get_block_as<SIORunHeaderHandler>( LCSIO_RUNBLOCKNAME )->setRunHeader( runHeader );
return runRecord;
}
//----------------------------------------------------------------------------
sio::record_ptr LCIORecords::createRunRecord( IOIMPL::LCRunHeaderIOImpl **runHeader ) const {
auto runRecord = std::make_shared<SIO_record>( LCSIO_RUNRECORDNAME );
runRecord->add_block<SIORunHeaderHandler>( LCSIO_RUNBLOCKNAME );
runRecord->get_block_as<SIORunHeaderHandler>( LCSIO_RUNBLOCKNAME )->setRunHeaderPtr( runHeader );
return runRecord;
}
//----------------------------------------------------------------------------
sio::record_ptr LCIORecords::createRandomAccessRecord( LCIORandomAccessMgr *raMgr ) const {
auto raRecord = std::make_shared<SIO_record>( LCSIO_ACCESSRECORDNAME );
raRecord->add_block<SIORandomAccessHandler>( LCSIO_ACCESSBLOCKNAME, raMgr );
return raRecord;
}
//----------------------------------------------------------------------------
sio::record_ptr LCIORecords::createIndexRecord( LCIORandomAccessMgr *raMgr ) const {
auto indexRecord = std::make_shared<SIO_record>( LCSIO_INDEXRECORDNAME );
indexRecord->add_block<SIORandomAccessHandler>( LCSIO_INDEXBLOCKNAME, raMgr );
return indexRecord;
}
} // namespace
<commit_msg>Fixed wrong handler type for index record<commit_after>#include "SIO/LCIORecords.h"
#include "SIO_functions.h"
#include "SIO_stream.h"
#include <SIO/SIORunHeaderHandler.h>
#include <SIO/SIOEventHandler.h>
#include <SIO/SIOCollectionHandler.h>
#include <SIO/SIORandomAccessHandler.h>
#include <SIO/SIOIndexHandler.h>
#include <EVENT/LCEvent.h>
#include <Exceptions.h>
namespace SIO {
sio::record_ptr LCIORecords::createEventHeaderRecord( const EVENT::LCEvent *event ) const {
auto eventHeaderRecord = std::make_shared<SIO_record>( LCSIO_HEADERRECORDNAME );
eventHeaderRecord->add_block<SIOEventHandler>( LCSIO_HEADERBLOCKNAME );
auto block = eventHeaderRecord->get_block_as<SIOEventHandler>( LCSIO_HEADERBLOCKNAME );
block->setEvent( event );
return eventHeaderRecord;
}
//----------------------------------------------------------------------------
sio::record_ptr LCIORecords::createEventHeaderRecord( IOIMPL::LCEventIOImpl **event, const std::vector<std::string> &readCol ) const {
auto eventHeaderRecord = std::make_shared<SIO_record>( LCSIO_HEADERRECORDNAME );
eventHeaderRecord->add_block<SIOEventHandler>( LCSIO_HEADERBLOCKNAME );
auto block = eventHeaderRecord->get_block_as<SIOEventHandler>( LCSIO_HEADERBLOCKNAME );
block->setEventPtr( event );
block->setReadCollectionNames( readCol );
return eventHeaderRecord;
}
//----------------------------------------------------------------------------
sio::record_ptr LCIORecords::createEventRecord( const EVENT::LCEvent *event ) const {
// create the event record
auto eventRecord = std::make_shared<SIO_record>( LCSIO_EVENTRECORDNAME );
// loop over collections and setup the blocks for writing
auto collectionNames = event->getCollectionNames();
for( auto collectionName : *collectionNames ) {
auto collection = event->getCollection( collectionName );
if( collection->isTransient() ) {
continue;
}
try {
eventRecord->add_block<SIOCollectionHandler>( collectionName, collection->getTypeName(), nullptr );
}
catch(EVENT::Exception& ex) {
continue;
}
auto block = eventRecord->get_block_as<SIOCollectionHandler>( collectionName );
auto handler = _handlerMgr.getHandler( collection->getTypeName() );
block->setHandler( handler );
}
return eventRecord;
}
//----------------------------------------------------------------------------
sio::record_ptr LCIORecords::createEventRecord(IOIMPL::LCEventIOImpl **event) const {
// create the event record
auto eventRecord = std::make_shared<SIO_record>( LCSIO_EVENTRECORDNAME );
// loop over collections and setup the blocks for reading/writing an event
auto collectionNames = (*event)->getCollectionNames();
for( auto collectionName : *collectionNames ) {
auto collection = (*event)->getCollection( collectionName );
try {
eventRecord->add_block<SIOCollectionHandler>( collectionName, collection->getTypeName(), event );
}
catch(EVENT::Exception& ex) {
continue;
}
auto block = eventRecord->get_block_as<SIOCollectionHandler>( collectionName );
auto handler = _handlerMgr.getHandler( collection->getTypeName() );
block->setHandler( handler );
block->setEvent( event );
}
return eventRecord;
}
//----------------------------------------------------------------------------
sio::record_ptr LCIORecords::createRunRecord( const EVENT::LCRunHeader *runHeader ) const {
auto runRecord = std::make_shared<SIO_record>( LCSIO_RUNRECORDNAME );
runRecord->add_block<SIORunHeaderHandler>( LCSIO_RUNBLOCKNAME );
runRecord->get_block_as<SIORunHeaderHandler>( LCSIO_RUNBLOCKNAME )->setRunHeader( runHeader );
return runRecord;
}
//----------------------------------------------------------------------------
sio::record_ptr LCIORecords::createRunRecord( IOIMPL::LCRunHeaderIOImpl **runHeader ) const {
auto runRecord = std::make_shared<SIO_record>( LCSIO_RUNRECORDNAME );
runRecord->add_block<SIORunHeaderHandler>( LCSIO_RUNBLOCKNAME );
runRecord->get_block_as<SIORunHeaderHandler>( LCSIO_RUNBLOCKNAME )->setRunHeaderPtr( runHeader );
return runRecord;
}
//----------------------------------------------------------------------------
sio::record_ptr LCIORecords::createRandomAccessRecord( LCIORandomAccessMgr *raMgr ) const {
auto raRecord = std::make_shared<SIO_record>( LCSIO_ACCESSRECORDNAME );
raRecord->add_block<SIORandomAccessHandler>( LCSIO_ACCESSBLOCKNAME, raMgr );
return raRecord;
}
//----------------------------------------------------------------------------
sio::record_ptr LCIORecords::createIndexRecord( LCIORandomAccessMgr *raMgr ) const {
auto indexRecord = std::make_shared<SIO_record>( LCSIO_INDEXRECORDNAME );
indexRecord->add_block<SIOIndexHandler>( LCSIO_INDEXBLOCKNAME, raMgr );
return indexRecord;
}
} // namespace
<|endoftext|> |
<commit_before>#include <iostream>
#include <vector>
#include <map>
#include <fstream>
#include <string>
#include <iterator>
#include <functional>
#include <algorithm>
#include <deque>
#include <sstream>
std::string trim_begin(const std::string& str) {
auto alpha = std::find_if_not(str.begin(), str.end(), ::isspace);
return str.substr(std::distance(str.begin(), alpha));
}
std::string trim_end(const std::string& str) {
auto alpha = std::find_if_not(str.rbegin(), str.rend(), ::isspace).base();
return str.substr(0, std::distance(str.begin(), alpha));
}
std::string str_to_lower(const std::string& str) {
std::string lowercase;
std::transform(std::begin(str), std::end(str), std::back_inserter(lowercase), ::tolower);
return lowercase;
}
std::vector<std::string> str_split_whitespace(const std::string& str) {
std::vector<std::string> words;
std::istringstream is(str);
std::copy(
std::istream_iterator<std::string>(is),
std::istream_iterator<std::string>(),
std::back_inserter(words));
return words;
}
std::vector<std::string> str_split(const std::string& str, const char *delims) {
size_t found = std::string::npos, prev = 0;
std::vector<std::string> out;
out.reserve(log(str.size()));
found = str.find_first_of(delims);
while (found != std::string::npos) {
if (prev < found) {
out.push_back(str.substr(prev, found - prev));
}
prev = found + 1;
found = str.find_first_of(delims, prev);
}
out.push_back(str.substr(prev, std::string::npos));
return out;
}
std::vector<std::string> extract_sentences(const std::string& str) {
return str_split(str, ".?!");
}
std::vector<std::string> extract_words(const std::string& str) {
return str_split(str, " .,;\"?!");
}
class sentence_file_reader {
std::ifstream ifs;
std::deque<std::string> sentence_buffer;
static const size_t BUFFER_SIZE = 16 * 1024;
char char_buffer[BUFFER_SIZE];
public:
sentence_file_reader(const char *filename) :
ifs(filename, std::ios::in)
{}
~sentence_file_reader() {
ifs.close();
}
std::string get_next_sentence() {
std::string sn;
if (!sentence_buffer.empty()) {
sn = sentence_buffer.front();
sentence_buffer.pop_front();
}
else {
ifs.getline(char_buffer, BUFFER_SIZE);
auto sentences = extract_sentences(char_buffer);
sentence_buffer = std::deque<std::string>(std::begin(sentences), std::end(sentences));
sn = get_next_sentence();
}
return trim_begin(trim_end(sn));
}
bool has_more() {
return ifs.good() || !sentence_buffer.empty();
}
};
struct word_node {
word_node(const std::string& name) :
normalized_name(str_to_lower(name))
{}
void add_original_name(const std::string& original) {
auto found = std::find(
std::begin(original_names),
std::end(original_names),
original);
if (found == original_names.end()) {
original_names.push_back(original);
}
}
std::vector<std::string> original_names;
std::string normalized_name;
std::map<word_node*, size_t> lefts;
std::map<word_node*, size_t> rights;
};
struct word_graph {
std::map<std::string, word_node*> word_nodes;
word_node *head;
word_node *get_or_create(std::string name) {
auto word = str_to_lower(name);
auto name_exists = word_nodes.equal_range(word);
auto found_node = name_exists.first;
if (name_exists.first == name_exists.second) {
word_node *name_node = new word_node(name);
found_node = word_nodes.insert(name_exists.second, std::make_pair(word, name_node));
}
found_node->second->add_original_name(name);
return found_node->second;
}
void make_link(const std::string& a, const std::string& b) {
word_node *a_node = get_or_create(a);
word_node *b_node = get_or_create(b);
a_node->rights[b_node]++;
b_node->lefts[a_node]++;
}
};
int main(int argc, char *argv[]) {
std::ios::ios_base::sync_with_stdio(false);
const char *in_filename = "test.txt";
if (argc > 1) {
in_filename = argv[1];
}
sentence_file_reader cfr(in_filename);
word_graph graph;
std::string str;
while (cfr.has_more()) {
std::string sentence = cfr.get_next_sentence();
std::vector<std::string> words = extract_words(sentence);
if (words.size() > 1) {
graph.make_link(words[0], words[1]);
for (size_t i = 1, j = 2; j < words.size(); ++i, ++j) {
graph.make_link(words[i], words[j]);
}
}
else if (words.size() == 1 && !words[0].empty()) {
graph.get_or_create(words[0]);
}
}
for (auto &kv : graph.word_nodes) {
std::cout << kv.first << "\n- left: ";
for (auto &w_node_cnt : kv.second->lefts) {
std::cout << w_node_cnt.first->normalized_name << ":" << w_node_cnt.second << " ";
}
std::cout << "\n- right: ";
for (auto &w_node_cnt : kv.second->rights) {
std::cout << w_node_cnt.first->normalized_name << ":" << w_node_cnt.second << " ";
}
std::cout << std::endl;
}
return 0;
}
<commit_msg>Split better suited for our needs<commit_after>#include <iostream>
#include <vector>
#include <map>
#include <fstream>
#include <string>
#include <iterator>
#include <functional>
#include <algorithm>
#include <deque>
#include <sstream>
std::string trim_begin(const std::string& str) {
auto alpha = std::find_if_not(str.begin(), str.end(), ::isspace);
return str.substr(std::distance(str.begin(), alpha));
}
std::string trim_end(const std::string& str) {
auto alpha = std::find_if_not(str.rbegin(), str.rend(), ::isspace).base();
return str.substr(0, std::distance(str.begin(), alpha));
}
std::string str_to_lower(const std::string& str) {
std::string lowercase;
std::transform(std::begin(str), std::end(str), std::back_inserter(lowercase), ::tolower);
return lowercase;
}
std::vector<std::string> str_split_whitespace(const std::string& str) {
std::vector<std::string> words;
std::istringstream is(str);
std::copy(
std::istream_iterator<std::string>(is),
std::istream_iterator<std::string>(),
std::back_inserter(words));
return words;
}
std::vector<std::string> str_split(const std::string& str, const char *delims) {
size_t found = std::string::npos, prev = 0;
std::vector<std::string> out;
out.reserve(log(str.size()));
found = str.find_first_of(delims);
while (found != std::string::npos) {
if (prev < found) {
auto sub = str.substr(prev, found - prev);
if (!sub.empty())
out.push_back(sub);
}
prev = found + 1;
found = str.find_first_of(delims, prev);
}
auto sub = str.substr(prev, std::string::npos);
if (!sub.empty())
out.push_back(sub);
return out;
}
std::vector<std::string> extract_sentences(const std::string& str) {
return str_split(str, ".?!");
}
std::vector<std::string> extract_words(const std::string& str) {
return str_split(str, " .,;\"?!\n");
}
class sentence_file_reader {
std::ifstream ifs;
std::deque<std::string> sentence_buffer;
static const size_t BUFFER_SIZE = 16 * 1024;
char char_buffer[BUFFER_SIZE];
public:
sentence_file_reader(const char *filename) :
ifs(filename, std::ios::in)
{}
~sentence_file_reader() {
ifs.close();
}
std::string get_next_sentence() {
std::string sn;
if (!sentence_buffer.empty()) {
sn = sentence_buffer.front();
sentence_buffer.pop_front();
}
else {
ifs.getline(char_buffer, BUFFER_SIZE);
auto sentences = extract_sentences(char_buffer);
sentence_buffer = std::deque<std::string>(std::begin(sentences), std::end(sentences));
sn = get_next_sentence();
}
return trim_begin(trim_end(sn));
}
bool has_more() {
return ifs.good() || !sentence_buffer.empty();
}
};
struct word_node {
word_node(const std::string& name) :
normalized_name(str_to_lower(name))
{}
void add_original_name(const std::string& original) {
auto found = std::find(
std::begin(original_names),
std::end(original_names),
original);
if (found == original_names.end()) {
original_names.push_back(original);
}
}
std::vector<std::string> original_names;
std::string normalized_name;
std::map<word_node*, size_t> lefts;
std::map<word_node*, size_t> rights;
};
struct word_graph {
std::map<std::string, word_node*> word_nodes;
word_node *head;
word_node *get_or_create(std::string name) {
auto word = str_to_lower(name);
auto name_exists = word_nodes.equal_range(word);
auto found_node = name_exists.first;
if (name_exists.first == name_exists.second) {
word_node *name_node = new word_node(name);
found_node = word_nodes.insert(name_exists.second, std::make_pair(word, name_node));
}
found_node->second->add_original_name(name);
return found_node->second;
}
void make_link(const std::string& a, const std::string& b) {
word_node *a_node = get_or_create(a);
word_node *b_node = get_or_create(b);
a_node->rights[b_node]++;
b_node->lefts[a_node]++;
}
};
int main(int argc, char *argv[]) {
std::ios::ios_base::sync_with_stdio(false);
const char *in_filename = "test.txt";
if (argc > 1) {
in_filename = argv[1];
}
sentence_file_reader cfr(in_filename);
word_graph graph;
std::string str;
while (cfr.has_more()) {
std::string sentence = cfr.get_next_sentence();
std::vector<std::string> words = extract_words(sentence);
if (words.size() > 1) {
graph.make_link(words[0], words[1]);
for (size_t i = 1, j = 2; j < words.size(); ++i, ++j) {
graph.make_link(words[i], words[j]);
}
}
else if (words.size() == 1 && !words[0].empty()) {
graph.get_or_create(words[0]);
}
}
for (auto &kv : graph.word_nodes) {
std::cout << kv.first << "\n- left: ";
for (auto &w_node_cnt : kv.second->lefts) {
std::cout << "'" << w_node_cnt.first->normalized_name << "'" << ":" << w_node_cnt.second << " ";
}
std::cout << "\n- right: ";
for (auto &w_node_cnt : kv.second->rights) {
std::cout << "'" << w_node_cnt.first->normalized_name << "'" << ":" << w_node_cnt.second << " ";
}
std::cout << std::endl;
}
return 0;
}
<|endoftext|> |
<commit_before>#include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl;
}
<commit_msg>Delete main.cpp<commit_after><|endoftext|> |
<commit_before>1da786ba-585b-11e5-8b78-6c40088e03e4<commit_msg>1dae6a28-585b-11e5-ba47-6c40088e03e4<commit_after>1dae6a28-585b-11e5-ba47-6c40088e03e4<|endoftext|> |
<commit_before>c25d9b6c-35ca-11e5-96f4-6c40088e03e4<commit_msg>c2642d7e-35ca-11e5-909f-6c40088e03e4<commit_after>c2642d7e-35ca-11e5-909f-6c40088e03e4<|endoftext|> |
<commit_before>b0a31261-2e4f-11e5-8bae-28cfe91dbc4b<commit_msg>b0a9e357-2e4f-11e5-9988-28cfe91dbc4b<commit_after>b0a9e357-2e4f-11e5-9988-28cfe91dbc4b<|endoftext|> |
<commit_before>929722f5-2d3f-11e5-931f-c82a142b6f9b<commit_msg>92ec7921-2d3f-11e5-9d95-c82a142b6f9b<commit_after>92ec7921-2d3f-11e5-9d95-c82a142b6f9b<|endoftext|> |
<commit_before>d0c0103d-2d3e-11e5-b4f7-c82a142b6f9b<commit_msg>d1176c2e-2d3e-11e5-af95-c82a142b6f9b<commit_after>d1176c2e-2d3e-11e5-af95-c82a142b6f9b<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.