<commit_before>/*****************************************************************************

    (c) 2013 Hobu, Inc. hobu.inc@gmail.com

    Author: Andrew Bell andrew.bell.ia at gmail.com

    This is free software; you can redistribute and/or modify it under the
    terms of the GNU Lesser General Licence as published by the Free Software
    Foundation. See the COPYING file for more information.

    This software is distributed WITHOUT ANY WARRANTY and without even the
    implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

*****************************************************************************/

#include <hexer/Processor.hpp>
#include "las.hpp"

#include <fstream>
#include <sstream>

#include <boost/algorithm/string/compare.hpp>

using namespace std;

bool readHex(int& x, int& y, void* ctx)
{
    static int pos = 0;

    static int coords[] = {
        0, 0,
        1, 0,
        2, 1,
        3, 1,
        4, 2,
        4, 3,
        4, 4,
        3, 4,
        2, 5,
        1, 5,
        0, 5,
        -1, 4,
        -2, 4,
        -3, 3,
        -3, 2,
        -3, 1,
        -2, 1,
        -1, 0,
        -1, 2,
        0, 2,
        1, 3,
        2, 3
    };

    static int num_coords = sizeof(coords) / (sizeof(coords[0]));

    if (pos + 1 < num_coords) {
        x = coords[pos++];
        y = coords[pos++];
        return true;
    }
    return false;
}

std::string indent(int l)
{
    std::string tabs;

    tabs.append(l * 2, ' ');
    return tabs;
}

void dumpPath(hexer::Path *p)
{
    using namespace hexer;

    static int level = 0;
    Orientation o = p->orientation();
    std::string ostring = ((o == CLOCKWISE) ? "CLOCKWISE" : "ANTICLOCKWISE");
    indent(level);
    cerr << indent(level) << "Path length = " << p->pathLength() << "!\n";
    cerr << indent(level) << "Orientation = " << ostring << "!\n";
    vector<Path *> paths = p->subPaths();
    level++;
    for (int pi = 0; pi != paths.size(); ++pi)
    {
        dumpPath(paths[pi]);
    }
    level--;
}

void hextest(std::string filename)
{
    using namespace hexer;

    vector<GridInfo *> infos;
    GridInfo *gi = new GridInfo;

    gi->m_hexsize = 10;
    gi->m_density = 10;
    infos.push_back(gi);

    // LAS l(filename);
    // l.open();
    // process(infos, l.reader);

    processHexes(infos, readHex);

    // Dump hexes.
    for (HexIter iter = gi->begin(); iter != gi->end(); ++iter)
    {
        HexInfo hi = *iter;
        cerr << "Density/X/Y = " << hi.m_density << "/" <<
            hi.m_center.m_x << "/" << hi.m_center.m_y << "!\n";
    }

    delete gi;
}

void pathtest(std::string filename)
{
    using namespace hexer;

    vector<GridInfo *> infos;
    GridInfo *gi = new GridInfo;

    infos.push_back(gi);
    LAS l(filename);
    l.open();
    process(infos, l.reader);

    for (std::vector<Path*>::size_type pi = 0; pi < gi->rootPaths().size(); ++pi)
    {
        Path *p = gi->rootPaths()[pi];
        dumpPath(p);
    }

    delete gi;
}

void boundarytest(std::string filename)
{
    using namespace hexer;

    vector<GridInfo *> infos;
    GridInfo *gi = new GridInfo;

    infos.push_back(gi);

    LAS l(filename);
    l.open();
    process(infos, l.reader);

    std::ostringstream multi;
    multi.setf(std::ios::fixed);
    multi.precision(8);

    gi->toWKT(multi);

    std::cout << multi.str() << std::endl;

    delete gi;
}

int main(int argc, char* argv[])
{

    if (argc < 3)
    {
        std::cerr << "please specify a command and a filename. $ hextest PATH filename.las" << std::endl;
		return 1;
    }

    std::string command(argv[1], strlen(argv[1]));
    std::string filename(argv[2], strlen(argv[2]));

	try
	{

		if (boost::iequals(command, "BOUNDARY"))
		{
			boundarytest(filename);
			return 0;
		}

		if (boost::iequals(command, "PATH"))
		{
			pathtest(filename);
			return 0;
		}

		if (boost::iequals(command, "HEX"))
		{
			hextest(filename);
			return 0;
		}

		std::cout << "Command '" << command << "' not recognized" << std::endl;
		return 1;
	} catch (hexer::hexer_error const& e)
	{
		std::cout << "Hexer failed with error: '" << e.what() << "'" << std::endl;
		return 1;
	}

}

<commit_msg>use size_t for return<commit_after>/*****************************************************************************

    (c) 2013 Hobu, Inc. hobu.inc@gmail.com

    Author: Andrew Bell andrew.bell.ia at gmail.com

    This is free software; you can redistribute and/or modify it under the
    terms of the GNU Lesser General Licence as published by the Free Software
    Foundation. See the COPYING file for more information.

    This software is distributed WITHOUT ANY WARRANTY and without even the
    implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

*****************************************************************************/

#include <hexer/Processor.hpp>
#include "las.hpp"

#include <fstream>
#include <sstream>

#include <boost/algorithm/string/compare.hpp>

using namespace std;

bool readHex(int& x, int& y, void* ctx)
{
    static int pos = 0;

    static int coords[] = {
        0, 0,
        1, 0,
        2, 1,
        3, 1,
        4, 2,
        4, 3,
        4, 4,
        3, 4,
        2, 5,
        1, 5,
        0, 5,
        -1, 4,
        -2, 4,
        -3, 3,
        -3, 2,
        -3, 1,
        -2, 1,
        -1, 0,
        -1, 2,
        0, 2,
        1, 3,
        2, 3
    };

    static int num_coords = sizeof(coords) / (sizeof(coords[0]));

    if (pos + 1 < num_coords) {
        x = coords[pos++];
        y = coords[pos++];
        return true;
    }
    return false;
}

std::string indent(int l)
{
    std::string tabs;

    tabs.append(l * 2, ' ');
    return tabs;
}

void dumpPath(hexer::Path *p)
{
    using namespace hexer;

    static int level = 0;
    Orientation o = p->orientation();
    std::string ostring = ((o == CLOCKWISE) ? "CLOCKWISE" : "ANTICLOCKWISE");
    indent(level);
    cerr << indent(level) << "Path length = " << p->pathLength() << "!\n";
    cerr << indent(level) << "Orientation = " << ostring << "!\n";
    vector<Path *> paths = p->subPaths();
    level++;
    for (int pi = 0; pi != paths.size(); ++pi)
    {
        dumpPath(paths[pi]);
    }
    level--;
}

void hextest(std::string filename)
{
    using namespace hexer;

    vector<GridInfo *> infos;
    GridInfo *gi = new GridInfo;

    gi->m_hexsize = 10;
    gi->m_density = 10;
    infos.push_back(gi);

    // LAS l(filename);
    // l.open();
    // process(infos, l.reader);

    processHexes(infos, readHex);

    // Dump hexes.
    for (HexIter iter = gi->begin(); iter != gi->end(); ++iter)
    {
        HexInfo hi = *iter;
        cerr << "Density/X/Y = " << hi.m_density << "/" <<
            hi.m_center.m_x << "/" << hi.m_center.m_y << "!\n";
    }

    delete gi;
}

void pathtest(std::string filename)
{
    using namespace hexer;

    vector<GridInfo *> infos;
    GridInfo *gi = new GridInfo;

    infos.push_back(gi);
    LAS l(filename);
    l.open();
    process(infos, l.reader);

    for (std::vector<Path*>::size_type pi = 0; pi < gi->rootPaths().size(); ++pi)
    {
        Path *p = gi->rootPaths()[pi];
        dumpPath(p);
    }

    delete gi;
}

void boundarytest(std::string filename)
{
    using namespace hexer;

    vector<GridInfo *> infos;
    GridInfo *gi = new GridInfo;

    infos.push_back(gi);

    LAS l(filename);
    l.open();
    process(infos, l.reader);

    std::ostringstream multi;
    multi.setf(std::ios::fixed);
    multi.precision(8);

    gi->toWKT(multi);

    std::cout << multi.str() << std::endl;

    delete gi;
}

std::size_t main(int argc, char* argv[])
{

    if (argc < 3)
    {
        std::cerr << "please specify a command and a filename. $ hextest PATH filename.las" << std::endl;
		return 1;
    }

    std::string command(argv[1], strlen(argv[1]));
    std::string filename(argv[2], strlen(argv[2]));

	try
	{

		if (boost::iequals(command, "BOUNDARY"))
		{
			boundarytest(filename);
			return 0;
		}

		if (boost::iequals(command, "PATH"))
		{
			pathtest(filename);
			return 0;
		}

		if (boost::iequals(command, "HEX"))
		{
			hextest(filename);
			return 0;
		}

		std::cout << "Command '" << command << "' not recognized" << std::endl;
		return 1;
	} catch (hexer::hexer_error const& e)
	{
		std::cout << "Hexer failed with error: '" << e.what() << "'" << std::endl;
		return 1;
	}

}

<|endoftext|>


<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include "mbubbleitem.h"
#include "mbubbleitem_p.h"
#include "mbubbleitemmodel.h"

#include "mimagewidget.h"
#include "mlabel.h"
#include "mwidgetcreator.h"

M_REGISTER_WIDGET(MBubbleItem)

MBubbleItemPrivate::MBubbleItemPrivate()
    : MWidgetControllerPrivate(),
    commentsLabel(NULL),
    thumbsUpLabel(NULL),
    commentsIcon(NULL),
    thumbsUpIcon(NULL)
{
}

MBubbleItemPrivate::~MBubbleItemPrivate()
{
}

void MBubbleItemPrivate::init()
{
}

void MBubbleItemPrivate::createCommentsInfo()
{
    Q_Q(MBubbleItem);

    commentsLabel = new MLabel;
    commentsLabel->setParent(q);

    commentsIcon = new MImageWidget;
    commentsIcon->setParent(q);
    commentsIcon->setObjectName("InformationalIcon");
    commentsIcon->setImage("icon-s-common-comments", commentsIcon->minimumSize().toSize());

    q->addInformationWidget(commentsIcon);
    q->addInformationWidget(commentsLabel);

    refreshStyles();
}
void MBubbleItemPrivate::destroyCommentsInfo()
{
    Q_Q(MBubbleItem);

    q->removeInformationWidget(commentsLabel);
    q->removeInformationWidget(commentsIcon);
    if(commentsLabel->parent() == q)
        delete commentsLabel;
    if(commentsIcon->parent() == q)
        delete commentsIcon;
    commentsLabel = NULL;
    commentsIcon = NULL;
}

void MBubbleItemPrivate::createThumbsUpInfo()
{
    Q_Q(MBubbleItem);

    thumbsUpLabel = new MLabel;
    thumbsUpLabel->setParent(q);

    thumbsUpIcon = new MImageWidget;
    thumbsUpIcon->setParent(q);
    thumbsUpIcon->setObjectName("InformationalIcon");
    thumbsUpIcon->setImage("icon-s-common-like", thumbsUpIcon->minimumSize().toSize());

    q->addInformationWidget(thumbsUpIcon);
    q->addInformationWidget(thumbsUpLabel);

    refreshStyles();
}
void MBubbleItemPrivate::destroyThumbsUpInfo()
{
    Q_Q(MBubbleItem);

    q->removeInformationWidget(thumbsUpLabel);
    q->removeInformationWidget(thumbsUpIcon);
    if(thumbsUpLabel->parent() == q)
        delete thumbsUpLabel;
    if(thumbsUpIcon->parent() == q)
        delete thumbsUpIcon;

    thumbsUpLabel = NULL;
    thumbsUpIcon = NULL;
}

void MBubbleItemPrivate::refreshStyles()
{
    Q_Q(MBubbleItem);

    if (q->messageType() == MBubbleItem::Incoming) {
        if (thumbsUpLabel)
            thumbsUpLabel->setObjectName("InformationalLabelIncoming");
        if (commentsLabel)
            commentsLabel->setObjectName("InformationalLabelIncoming");
    } else {
        if (thumbsUpLabel)
            thumbsUpLabel->setObjectName("InformationalLabelOutgoing");
        if (commentsLabel)
            commentsLabel->setObjectName("InformationalLabelOutgoing");
    }
}

MBubbleItem::MBubbleItem(QGraphicsItem *parent)
    : MWidgetController(new MBubbleItemPrivate, new MBubbleItemModel, parent)
{
    Q_D(MBubbleItem);

    d->init();
}

MBubbleItem::MBubbleItem(MBubbleItemPrivate *dd, MBubbleItemModel *model, QGraphicsItem *parent)
    : MWidgetController(dd, model, parent)
{
    Q_D(MBubbleItem);

    d->init();
}

MBubbleItem::~MBubbleItem()
{
}

MImageWidget* MBubbleItem::avatar() const
{
    return model()->avatar();
}

void MBubbleItem::setAvatar(MImageWidget* avatar)
{
    MImageWidget *oldAvatar = model()->avatar();
    if(oldAvatar == avatar)
        return;

    model()->setAvatar(avatar);
    if(oldAvatar && oldAvatar->parent() == this)
        delete oldAvatar;
}

void MBubbleItem::setAvatar(const QPixmap &avatar)
{
    model()->beginTransaction();

    if (!model()->avatar()) {
        model()->setAvatar(new MImageWidget);
        model()->avatar()->setParent(this);
    }

    model()->avatar()->setPixmap(avatar);
    model()->commitTransaction();
}

QString MBubbleItem::senderName()
{
    return model()->senderName();
}

void MBubbleItem::setSenderName(const QString &senderName)
{
    model()->setSenderName(senderName);
}

QString MBubbleItem::timeStamp()
{
    return model()->timeStamp();
}

void MBubbleItem::setTimeStamp(const QString &timeStamp)
{
    model()->setTimeStamp(timeStamp);
}

QString MBubbleItem::message()
{
    return model()->message();
}

void MBubbleItem::setMessage(const QString &message)
{
    model()->setMessage(message);
}

MBubbleItem::MessageType MBubbleItem::messageType() const
{
    return static_cast<MBubbleItem::MessageType>(model()->messageType());
}

void MBubbleItem::setMessageType(MessageType messageType)
{
    Q_D(MBubbleItem);

    model()->beginTransaction();
    model()->setMessageType(messageType);

    d->refreshStyles();

    model()->commitTransaction();
}

void MBubbleItem::setCentralWidget(QGraphicsWidget* centralWidget)
{
    QGraphicsWidget *oldCentralWidget = model()->centralWidget();
    if(oldCentralWidget == centralWidget)
        return;

    model()->setCentralWidget(centralWidget);
    if(oldCentralWidget && oldCentralWidget->parent() == this)
        delete oldCentralWidget;
}

QGraphicsWidget* MBubbleItem::centralWidget()
{
    return model()->centralWidget();
}

QStack<QGraphicsWidget*> MBubbleItem::informationWidgets()
{
    return model()->informationWidgets();
}

void MBubbleItem::addInformationWidget(QGraphicsWidget *widget)
{
    QStack<QGraphicsWidget*> stack = model()->informationWidgets();
    stack.push(widget);
    model()->setInformationWidgets(stack);
}

void MBubbleItem::removeInformationWidget(QGraphicsWidget *widget)
{
    QStack<QGraphicsWidget*> stack = model()->informationWidgets();
    int index = stack.indexOf(widget);
    if (index >= 0) {
        stack.remove(index);
        model()->setInformationWidgets(stack);
    }
}

QString MBubbleItem::commentsString()
{
    Q_D(MBubbleItem);

    if (d->commentsLabel)
        return model()->commentsString();

    return QString();
}

void MBubbleItem::setCommentsString(const QString &comments)
{
    Q_D(MBubbleItem);

    if(!comments.isEmpty()) {
        if (!d->commentsLabel || !d->commentsIcon)
            d->createCommentsInfo();
        d->commentsLabel->setText(comments);
    } else if (d->commentsLabel != NULL || d->commentsIcon)
        d->destroyCommentsInfo();

    model()->setCommentsString(comments);
}

QString MBubbleItem::thumbsUpString()
{
    Q_D(MBubbleItem);

    if (d->thumbsUpLabel)
        return model()->thumbsUpString();

    return QString();
}

void MBubbleItem::setThumbsUpString(const QString &thumbsUp)
{
    Q_D(MBubbleItem);

    if(!thumbsUp.isEmpty()) {
        if (!d->thumbsUpLabel) {
            Q_ASSERT(!d->thumbsUpIcon);
            d->createThumbsUpInfo();
            Q_ASSERT(d->thumbsUpLabel);
            Q_ASSERT(d->thumbsUpIcon);
        }
        d->thumbsUpLabel->setText(thumbsUp);
    } else if (d->thumbsUpLabel != NULL) {
        Q_ASSERT(d->thumbsUpIcon);
        d->destroyThumbsUpInfo();
    }

    model()->setThumbsUpString(thumbsUp);
}

<commit_msg>Changes: MBubbleItem - make coverity even more happy<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include "mbubbleitem.h"
#include "mbubbleitem_p.h"
#include "mbubbleitemmodel.h"

#include "mimagewidget.h"
#include "mlabel.h"
#include "mwidgetcreator.h"

M_REGISTER_WIDGET(MBubbleItem)

MBubbleItemPrivate::MBubbleItemPrivate()
    : MWidgetControllerPrivate(),
    commentsLabel(NULL),
    thumbsUpLabel(NULL),
    commentsIcon(NULL),
    thumbsUpIcon(NULL)
{
}

MBubbleItemPrivate::~MBubbleItemPrivate()
{
}

void MBubbleItemPrivate::init()
{
}

void MBubbleItemPrivate::createCommentsInfo()
{
    Q_Q(MBubbleItem);

    commentsLabel = new MLabel;
    commentsLabel->setParent(q);

    commentsIcon = new MImageWidget;
    commentsIcon->setParent(q);
    commentsIcon->setObjectName("InformationalIcon");
    commentsIcon->setImage("icon-s-common-comments", commentsIcon->minimumSize().toSize());

    q->addInformationWidget(commentsIcon);
    q->addInformationWidget(commentsLabel);

    refreshStyles();
}
void MBubbleItemPrivate::destroyCommentsInfo()
{
    Q_Q(MBubbleItem);

    q->removeInformationWidget(commentsLabel);
    q->removeInformationWidget(commentsIcon);
    if(commentsLabel->parent() == q)
        delete commentsLabel;
    if(commentsIcon->parent() == q)
        delete commentsIcon;
    commentsLabel = NULL;
    commentsIcon = NULL;
}

void MBubbleItemPrivate::createThumbsUpInfo()
{
    Q_Q(MBubbleItem);

    thumbsUpLabel = new MLabel;
    thumbsUpLabel->setParent(q);

    thumbsUpIcon = new MImageWidget;
    thumbsUpIcon->setParent(q);
    thumbsUpIcon->setObjectName("InformationalIcon");
    thumbsUpIcon->setImage("icon-s-common-like", thumbsUpIcon->minimumSize().toSize());

    q->addInformationWidget(thumbsUpIcon);
    q->addInformationWidget(thumbsUpLabel);

    refreshStyles();
}
void MBubbleItemPrivate::destroyThumbsUpInfo()
{
    Q_Q(MBubbleItem);

    q->removeInformationWidget(thumbsUpLabel);
    q->removeInformationWidget(thumbsUpIcon);
    if(thumbsUpLabel->parent() == q)
        delete thumbsUpLabel;
    if(thumbsUpIcon->parent() == q)
        delete thumbsUpIcon;

    thumbsUpLabel = NULL;
    thumbsUpIcon = NULL;
}

void MBubbleItemPrivate::refreshStyles()
{
    Q_Q(MBubbleItem);

    if (q->messageType() == MBubbleItem::Incoming) {
        if (thumbsUpLabel)
            thumbsUpLabel->setObjectName("InformationalLabelIncoming");
        if (commentsLabel)
            commentsLabel->setObjectName("InformationalLabelIncoming");
    } else {
        if (thumbsUpLabel)
            thumbsUpLabel->setObjectName("InformationalLabelOutgoing");
        if (commentsLabel)
            commentsLabel->setObjectName("InformationalLabelOutgoing");
    }
}

MBubbleItem::MBubbleItem(QGraphicsItem *parent)
    : MWidgetController(new MBubbleItemPrivate, new MBubbleItemModel, parent)
{
    Q_D(MBubbleItem);

    d->init();
}

MBubbleItem::MBubbleItem(MBubbleItemPrivate *dd, MBubbleItemModel *model, QGraphicsItem *parent)
    : MWidgetController(dd, model, parent)
{
    Q_D(MBubbleItem);

    d->init();
}

MBubbleItem::~MBubbleItem()
{
}

MImageWidget* MBubbleItem::avatar() const
{
    return model()->avatar();
}

void MBubbleItem::setAvatar(MImageWidget* avatar)
{
    MImageWidget *oldAvatar = model()->avatar();
    if(oldAvatar == avatar)
        return;

    model()->setAvatar(avatar);
    if(oldAvatar && oldAvatar->parent() == this)
        delete oldAvatar;
}

void MBubbleItem::setAvatar(const QPixmap &avatar)
{
    model()->beginTransaction();

    if (!model()->avatar()) {
        model()->setAvatar(new MImageWidget);
        model()->avatar()->setParent(this);
    }

    model()->avatar()->setPixmap(avatar);
    model()->commitTransaction();
}

QString MBubbleItem::senderName()
{
    return model()->senderName();
}

void MBubbleItem::setSenderName(const QString &senderName)
{
    model()->setSenderName(senderName);
}

QString MBubbleItem::timeStamp()
{
    return model()->timeStamp();
}

void MBubbleItem::setTimeStamp(const QString &timeStamp)
{
    model()->setTimeStamp(timeStamp);
}

QString MBubbleItem::message()
{
    return model()->message();
}

void MBubbleItem::setMessage(const QString &message)
{
    model()->setMessage(message);
}

MBubbleItem::MessageType MBubbleItem::messageType() const
{
    return static_cast<MBubbleItem::MessageType>(model()->messageType());
}

void MBubbleItem::setMessageType(MessageType messageType)
{
    Q_D(MBubbleItem);

    model()->beginTransaction();
    model()->setMessageType(messageType);

    d->refreshStyles();

    model()->commitTransaction();
}

void MBubbleItem::setCentralWidget(QGraphicsWidget* centralWidget)
{
    QGraphicsWidget *oldCentralWidget = model()->centralWidget();
    if(oldCentralWidget == centralWidget)
        return;

    model()->setCentralWidget(centralWidget);
    if(oldCentralWidget && oldCentralWidget->parent() == this)
        delete oldCentralWidget;
}

QGraphicsWidget* MBubbleItem::centralWidget()
{
    return model()->centralWidget();
}

QStack<QGraphicsWidget*> MBubbleItem::informationWidgets()
{
    return model()->informationWidgets();
}

void MBubbleItem::addInformationWidget(QGraphicsWidget *widget)
{
    QStack<QGraphicsWidget*> stack = model()->informationWidgets();
    stack.push(widget);
    model()->setInformationWidgets(stack);
}

void MBubbleItem::removeInformationWidget(QGraphicsWidget *widget)
{
    QStack<QGraphicsWidget*> stack = model()->informationWidgets();
    int index = stack.indexOf(widget);
    if (index >= 0) {
        stack.remove(index);
        model()->setInformationWidgets(stack);
    }
}

QString MBubbleItem::commentsString()
{
    Q_D(MBubbleItem);

    if (d->commentsLabel)
        return model()->commentsString();

    return QString();
}

void MBubbleItem::setCommentsString(const QString &comments)
{
    Q_D(MBubbleItem);

    if(!comments.isEmpty()) {
        if (!d->commentsLabel)
            d->createCommentsInfo();
        Q_ASSERT(d->commentsLabel);
        Q_ASSERT(d->commentsIcon);
        d->commentsLabel->setText(comments);
    } else if (d->commentsLabel) {
        Q_ASSERT(d->commentsIcon);
        d->destroyCommentsInfo();
        Q_ASSERT(!d->commentsLabel);
        Q_ASSERT(!d->commentsIcon);
    }

    model()->setCommentsString(comments);
}

QString MBubbleItem::thumbsUpString()
{
    Q_D(MBubbleItem);

    if (d->thumbsUpLabel)
        return model()->thumbsUpString();

    return QString();
}

void MBubbleItem::setThumbsUpString(const QString &thumbsUp)
{
    Q_D(MBubbleItem);

    if(!thumbsUp.isEmpty()) {
        if (!d->thumbsUpLabel) {
            Q_ASSERT(!d->thumbsUpIcon);
            d->createThumbsUpInfo();
            Q_ASSERT(d->thumbsUpLabel);
            Q_ASSERT(d->thumbsUpIcon);
        }
        d->thumbsUpLabel->setText(thumbsUp);
    } else if (d->thumbsUpLabel != NULL) {
        Q_ASSERT(d->thumbsUpIcon);
        d->destroyThumbsUpInfo();
    }

    model()->setThumbsUpString(thumbsUp);
}

<|endoftext|>


<commit_before>/*
 * User.cpp
 *
 * Copyright (C) 2019-20 by RStudio, PBC
 *
 * Unless you have received this program directly from RStudio pursuant to the terms of a commercial license agreement
 * with RStudio, then this program is licensed to you under the following terms:
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
 * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 */

#include <shared_core/system/User.hpp>

#include <pwd.h>

#include <boost/algorithm/string.hpp>

#include <shared_core/Error.hpp>
#include <shared_core/FilePath.hpp>
#include <shared_core/SafeConvert.hpp>

namespace rstudio {
namespace core {
namespace system {

namespace {

inline std::string getEnvVariable(const std::string& in_name)
{
   char* value = ::getenv(in_name.c_str());
   if (value)
      return std::string(value);

   return std::string();
}

} // anonymous namespace

struct User::Impl
{
   template<class T>
   using GetPasswdFunc = std::function<int(T, struct passwd*, char*, size_t, struct passwd**)>;

   Impl() : UserId(-1), GroupId(-1)
   { };

   template<typename T>
   Error populateUser(const GetPasswdFunc<T>& in_getPasswdFunc, T in_value)
   {
      struct passwd pwd;
      struct passwd* tempPtrPwd;

      // Get the maximum size of a passwd for this system.
      long buffSize = ::sysconf(_SC_GETPW_R_SIZE_MAX);
      if (buffSize == 1)
         buffSize = 4096; // some systems return -1, be conservative!

      std::vector<char> buffer(buffSize);
      int result = in_getPasswdFunc(in_value, &pwd, &(buffer[0]), buffSize, &tempPtrPwd);
      if (tempPtrPwd == nullptr)
      {
         if (result == 0) // will happen if user is simply not found. Return EACCES (not found error).
            result = EACCES;

         Error error = systemError(result, "Failed to get user details.", ERROR_LOCATION);
         error.addProperty("user-value", safe_convert::numberToString(in_value));
         return error;
      }
      else
      {
         UserId = pwd.pw_uid;
         GroupId = pwd.pw_gid;
         Name = pwd.pw_name;
         HomeDirectory = FilePath(pwd.pw_dir);
         Shell = pwd.pw_shell;
      }

      return Success();
   }

   UidType UserId;
   GidType GroupId;
   std::string Name;
   FilePath HomeDirectory;
   std::string Shell;
};

PRIVATE_IMPL_DELETER_IMPL(User)

User::User(bool in_isEmpty) :
   m_impl(new Impl())
{
   m_impl->Name = in_isEmpty ? "" : "*";
}

User::User(const User& in_other) :
   m_impl(new Impl(*in_other.m_impl))
{
}

Error User::getCurrentUser(User& out_currentUser)
{
   return getUserFromIdentifier(::geteuid(), out_currentUser);
}

Error User::getUserFromIdentifier(const std::string& in_username, User& out_user)
{
   User user;

   Error error = user.m_impl->populateUser<const char*>(::getpwnam_r, in_username.c_str());
   if (!error)
      out_user = user;

   return error;
}

Error User::getUserFromIdentifier(UidType in_userId, User& out_user)
{
   User user;
   Error error = user.m_impl->populateUser<UidType>(::getpwuid_r, in_userId);
   if (!error)
      out_user = user;

   return error;
}

FilePath User::getUserHomePath(const std::string& in_envOverride)
{
   // use environment override if specified
   if (!in_envOverride.empty())
   {
      using namespace boost::algorithm;
      for (split_iterator<std::string::const_iterator> it =
         make_split_iterator(in_envOverride, first_finder("|", is_iequal()));
           it != split_iterator<std::string::const_iterator>();
           ++it)
      {
         std::string envHomePath = getEnvVariable(boost::copy_range<std::string>(*it));
         if (!envHomePath.empty())
         {
            FilePath userHomePath(envHomePath);
            if (userHomePath.exists())
               return userHomePath;
         }
      }
   }

   // otherwise use standard unix HOME
   return FilePath(getEnvVariable("HOME"));
}

User& User::operator=(const User& in_other)
{
   if (this == &in_other)
      return *this;

   if ((m_impl == nullptr) && (in_other.m_impl == nullptr))
      return *this;

   if (in_other.m_impl == nullptr)
   {
      m_impl.reset();
      return *this;
   }

   if (m_impl == nullptr)
      m_impl.reset(new Impl());

   *m_impl = *in_other.m_impl;

   return *this;
}

bool User::operator==(const User& in_other) const
{
   // If one or the other is empty but not both, these objects aren't equal.
   if (isEmpty() != in_other.isEmpty())
      return false;

   // Otherwise they're both empty or they're both not, so just return true if this user is empty.
   if (isEmpty())
      return true;

   // If one or the other is all users but not both, these aren't the same user.
   if (isAllUsers() != in_other.isAllUsers())
      return false;

   // Otherwise they're both all users or they're both not, so just return true if this user is all users.
   if (isAllUsers())
      return true;

   return getUserId() == in_other.getUserId();
}

bool User::operator!=(const User &in_other) const
{
   return !(*this == in_other);
}

bool User::exists() const
{
   return !isEmpty() && !isAllUsers();
}

bool User::isAllUsers() const
{
   return m_impl->Name == "*";
}

bool User::isEmpty() const
{
   return m_impl->Name.empty();
}

const FilePath& User::getHomePath() const
{
   return m_impl->HomeDirectory;
}

GidType User::getGroupId() const
{
   return m_impl->GroupId;
}

UidType User::getUserId() const
{
   return m_impl->UserId;
}

const std::string& User::getUsername() const
{
   return m_impl->Name;
}

const std::string& User::getShell() const
{
   return m_impl->Shell;
}

} // namespace system
} // namespace core
} // namespace rstudio

<commit_msg>correct typo (and also just treat any negative value the same)<commit_after>/*
 * User.cpp
 *
 * Copyright (C) 2019-20 by RStudio, PBC
 *
 * Unless you have received this program directly from RStudio pursuant to the terms of a commercial license agreement
 * with RStudio, then this program is licensed to you under the following terms:
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
 * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 */

#include <shared_core/system/User.hpp>

#include <pwd.h>

#include <boost/algorithm/string.hpp>

#include <shared_core/Error.hpp>
#include <shared_core/FilePath.hpp>
#include <shared_core/SafeConvert.hpp>

namespace rstudio {
namespace core {
namespace system {

namespace {

inline std::string getEnvVariable(const std::string& in_name)
{
   char* value = ::getenv(in_name.c_str());
   if (value)
      return std::string(value);

   return std::string();
}

} // anonymous namespace

struct User::Impl
{
   template<class T>
   using GetPasswdFunc = std::function<int(T, struct passwd*, char*, size_t, struct passwd**)>;

   Impl() : UserId(-1), GroupId(-1)
   { };

   template<typename T>
   Error populateUser(const GetPasswdFunc<T>& in_getPasswdFunc, T in_value)
   {
      struct passwd pwd;
      struct passwd* tempPtrPwd;

      // Get the maximum size of a passwd for this system.
      long buffSize = ::sysconf(_SC_GETPW_R_SIZE_MAX);
      if (buffSize < 0)
         buffSize = 4096; // some systems return -1, be conservative!

      std::vector<char> buffer(buffSize);
      int result = in_getPasswdFunc(in_value, &pwd, &(buffer[0]), buffSize, &tempPtrPwd);
      if (tempPtrPwd == nullptr)
      {
         if (result == 0) // will happen if user is simply not found. Return EACCES (not found error).
            result = EACCES;

         Error error = systemError(result, "Failed to get user details.", ERROR_LOCATION);
         error.addProperty("user-value", safe_convert::numberToString(in_value));
         return error;
      }
      else
      {
         UserId = pwd.pw_uid;
         GroupId = pwd.pw_gid;
         Name = pwd.pw_name;
         HomeDirectory = FilePath(pwd.pw_dir);
         Shell = pwd.pw_shell;
      }

      return Success();
   }

   UidType UserId;
   GidType GroupId;
   std::string Name;
   FilePath HomeDirectory;
   std::string Shell;
};

PRIVATE_IMPL_DELETER_IMPL(User)

User::User(bool in_isEmpty) :
   m_impl(new Impl())
{
   m_impl->Name = in_isEmpty ? "" : "*";
}

User::User(const User& in_other) :
   m_impl(new Impl(*in_other.m_impl))
{
}

Error User::getCurrentUser(User& out_currentUser)
{
   return getUserFromIdentifier(::geteuid(), out_currentUser);
}

Error User::getUserFromIdentifier(const std::string& in_username, User& out_user)
{
   User user;

   Error error = user.m_impl->populateUser<const char*>(::getpwnam_r, in_username.c_str());
   if (!error)
      out_user = user;

   return error;
}

Error User::getUserFromIdentifier(UidType in_userId, User& out_user)
{
   User user;
   Error error = user.m_impl->populateUser<UidType>(::getpwuid_r, in_userId);
   if (!error)
      out_user = user;

   return error;
}

FilePath User::getUserHomePath(const std::string& in_envOverride)
{
   // use environment override if specified
   if (!in_envOverride.empty())
   {
      using namespace boost::algorithm;
      for (split_iterator<std::string::const_iterator> it =
         make_split_iterator(in_envOverride, first_finder("|", is_iequal()));
           it != split_iterator<std::string::const_iterator>();
           ++it)
      {
         std::string envHomePath = getEnvVariable(boost::copy_range<std::string>(*it));
         if (!envHomePath.empty())
         {
            FilePath userHomePath(envHomePath);
            if (userHomePath.exists())
               return userHomePath;
         }
      }
   }

   // otherwise use standard unix HOME
   return FilePath(getEnvVariable("HOME"));
}

User& User::operator=(const User& in_other)
{
   if (this == &in_other)
      return *this;

   if ((m_impl == nullptr) && (in_other.m_impl == nullptr))
      return *this;

   if (in_other.m_impl == nullptr)
   {
      m_impl.reset();
      return *this;
   }

   if (m_impl == nullptr)
      m_impl.reset(new Impl());

   *m_impl = *in_other.m_impl;

   return *this;
}

bool User::operator==(const User& in_other) const
{
   // If one or the other is empty but not both, these objects aren't equal.
   if (isEmpty() != in_other.isEmpty())
      return false;

   // Otherwise they're both empty or they're both not, so just return true if this user is empty.
   if (isEmpty())
      return true;

   // If one or the other is all users but not both, these aren't the same user.
   if (isAllUsers() != in_other.isAllUsers())
      return false;

   // Otherwise they're both all users or they're both not, so just return true if this user is all users.
   if (isAllUsers())
      return true;

   return getUserId() == in_other.getUserId();
}

bool User::operator!=(const User &in_other) const
{
   return !(*this == in_other);
}

bool User::exists() const
{
   return !isEmpty() && !isAllUsers();
}

bool User::isAllUsers() const
{
   return m_impl->Name == "*";
}

bool User::isEmpty() const
{
   return m_impl->Name.empty();
}

const FilePath& User::getHomePath() const
{
   return m_impl->HomeDirectory;
}

GidType User::getGroupId() const
{
   return m_impl->GroupId;
}

UidType User::getUserId() const
{
   return m_impl->UserId;
}

const std::string& User::getUsername() const
{
   return m_impl->Name;
}

const std::string& User::getShell() const
{
   return m_impl->Shell;
}

} // namespace system
} // namespace core
} // namespace rstudio

<|endoftext|>


<commit_before>#include "cpp_interface.h"

namespace BEEV
{
  // Does some simple caching of prior results.
  void
  Cpp_interface::checkSat(const ASTVec & assertionsSMT2)
  {
    bm.GetRunTimes()->stop(RunTimes::Parsing);

    checkInvariant();
    assert(assertionsSMT2.size() == cache.size());

    Entry& last_run = cache.back();
    if ((last_run.node_number != assertionsSMT2.back().GetNodeNum()) && (last_run.result == SOLVER_SATISFIABLE))
      {
        // extra asserts might have been added to it,
        // flipping from sat to unsat. But never from unsat to sat.
        last_run.result =  SOLVER_UNDECIDED;
      }

    // We might have run this query before, or it might already be shown to be unsat. If it was sat,
    // we've stored the result (but not the model), so we can shortcut and return what we know.
    if (!((last_run.result == SOLVER_SATISFIABLE) || last_run.result == SOLVER_UNSATISFIABLE))
        {
          resetSolver();

          ASTNode query;

          if (assertionsSMT2.size() > 1)
            query = parserInterface->CreateNode(AND, assertionsSMT2);
          else if (assertionsSMT2.size() == 1)
            query = assertionsSMT2[0];
          else
            query = bm.ASTTrue;

          SOLVER_RETURN_TYPE last_result = GlobalSTP->TopLevelSTP(query, bm.ASTFalse);

          // Store away the answer. Might be timeout, or error though..
          last_run = Entry(last_result);
          last_run.node_number = assertionsSMT2.back().GetNodeNum();

          // It's satisfiable, so everything beneath it is satisfiable too.
          if (last_result == SOLVER_SATISFIABLE)
            {
              for (int i = 0; i < cache.size(); i++)
                {
                  assert(cache[i].result != SOLVER_UNSATISFIABLE);
                  cache[i].result = SOLVER_SATISFIABLE;
                }
            }
        }

    if (bm.UserFlags.quick_statistics_flag)
      {
        bm.GetRunTimes()->print();
      }

    (GlobalSTP->tosat)->PrintOutput(last_run.result);
    bm.GetRunTimes()->start(RunTimes::Parsing);
  }
}
;
<commit_msg>Fix. Don't use the global nodefactory when we have a local one.<commit_after>#include "cpp_interface.h"

namespace BEEV
{
  // Does some simple caching of prior results.
  void
  Cpp_interface::checkSat(const ASTVec & assertionsSMT2)
  {
    bm.GetRunTimes()->stop(RunTimes::Parsing);

    checkInvariant();
    assert(assertionsSMT2.size() == cache.size());

    Entry& last_run = cache.back();
    if ((last_run.node_number != assertionsSMT2.back().GetNodeNum()) && (last_run.result == SOLVER_SATISFIABLE))
      {
        // extra asserts might have been added to it,
        // flipping from sat to unsat. But never from unsat to sat.
        last_run.result =  SOLVER_UNDECIDED;
      }

    // We might have run this query before, or it might already be shown to be unsat. If it was sat,
    // we've stored the result (but not the model), so we can shortcut and return what we know.
    if (!((last_run.result == SOLVER_SATISFIABLE) || last_run.result == SOLVER_UNSATISFIABLE))
        {
          resetSolver();

          ASTNode query;

          if (assertionsSMT2.size() > 1)
            query = nf->CreateNode(AND, assertionsSMT2);
          else if (assertionsSMT2.size() == 1)
            query = assertionsSMT2[0];
          else
            query = bm.ASTTrue;

          SOLVER_RETURN_TYPE last_result = GlobalSTP->TopLevelSTP(query, bm.ASTFalse);

          // Store away the answer. Might be timeout, or error though..
          last_run = Entry(last_result);
          last_run.node_number = assertionsSMT2.back().GetNodeNum();

          // It's satisfiable, so everything beneath it is satisfiable too.
          if (last_result == SOLVER_SATISFIABLE)
            {
              for (int i = 0; i < cache.size(); i++)
                {
                  assert(cache[i].result != SOLVER_UNSATISFIABLE);
                  cache[i].result = SOLVER_SATISFIABLE;
                }
            }
        }

    if (bm.UserFlags.quick_statistics_flag)
      {
        bm.GetRunTimes()->print();
      }

    (GlobalSTP->tosat)->PrintOutput(last_run.result);
    bm.GetRunTimes()->start(RunTimes::Parsing);
  }
}
;
<|endoftext|>


<commit_before>//! Copyright (c) 2013 ASMlover. All rights reserved.
//!
//! Redistribution and use in source and binary forms, with or without
//! modification, are permitted provided that the following conditions
//! are met:
//!
//!  * Redistributions of source code must retain the above copyright
//!    notice, this list ofconditions and the following disclaimer.
//!
//!  * Redistributions in binary form must reproduce the above copyright
//!    notice, this list of conditions and the following disclaimer in
//!    the documentation and/or other materialsprovided 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.
#if defined(_WINDOWS_) ||  defined(_MSC_VER)
# ifndef _WINDOWS_
#   include <winsock2.h>
# endif
# define EWOULDBLOCK  WSAEWOULDBLOCK
# define NErrno()     WSAGetLastError()
#endif
#include "net.h"
#include "socket.h"
#include "select_poll.h"

SelectPoll::SelectPoll(void)
  : rbytes_(kDefaultBufferLen)
  , wbytes_(kDefaultBufferLen)
  , handler_(NULL)
  , spinlock_()
{
  connectors_.clear();
  FD_ZERO(&rset_);
  FD_ZERO(&wset_);
}

SelectPoll::~SelectPoll(void)
{
  CloseAll();
}

void
SelectPoll::CloseAll(void)
{
  if (NULL == handler_)
    return;

  LockerGuard<SpinLock> gaurd(spinlock_);
  std::map<int, std::pair<int, Socket*> >::iterator it;
  for (it = connectors_.begin(); it != connectors_.end(); ++it) {
    if (NULL != it->second.second) {
      handler_->CloseEvent(it->second.second);
      it->second.second->Close();
      delete it->second.second;
    }
  }
  connectors_.clear();
}

bool
SelectPoll::Insert(int fd, int ev)
{
  if (NULL == handler_)
    return false;

  LockerGuard<SpinLock> guard(spinlock_);
  std::map<int, std::pair<int, Socket*> >::iterator it;
  it = connectors_.find(fd);
  if (it == connectors_.end()) {
    Socket* s = new Socket();
    if (NULL == s)
      return false;

    s->Attach(fd);
    s->SetNonBlock();
    s->SetKeepAlive();
    s->SetSelfReadBuffer(rbytes_);
    s->SetSelfWriteBuffer(wbytes_);

    connectors_[fd] = std::make_pair<int, Socket*>(ev, s);
  }

  return true;
}

void
SelectPoll::Remove(int fd)
{
  if (NULL == handler_)
    return;

  std::map<int, std::pair<int, Socket*> >::iterator it;
  it = connectors_.find(fd);
  if (it != connectors_.end()) {
    if (NULL != it->second.second) {
      handler_->CloseEvent(it->second.second);
      it->second.second->Close();
      delete it->second.second;
    }

    connectors_.erase(it);
  }
}

bool
SelectPoll::AddEvent(int fd, int ev)
{
  if (NULL == handler_)
    return false;

  LockerGuard<SpinLock> guard(spinlock_);
  std::map<int, std::pair<int, Socket*> >::iterator it;
  it = connectors_.find(fd);
  if (it != connectors_.end())
    it->second.first |= ev;

  return true;
}

bool
SelectPoll::DelEvent(int fd, int ev)
{
  if (NULL == handler_)
    return false;

  LockerGuard<SpinLock> gaurd(spinlock_);
  std::map<int, std::pair<int, Socket*> >::iterator it;
  it = connectors_.find(fd);
  if (it != connectors_.end())
    it->second.first &= ~ev;

  return true;
}

Socket*
SelectPoll::GetConnector(int fd)
{
  Socket* s = NULL;

  {
    LockerGuard<SpinLock> gaurd(spinlock_);
    std::map<int, std::pair<int, Socket*> >::iterator it;
    it = connectors_.find(fd);
    if (it != connectors_.end())
      s = it->second.second;
  }

  return s;
}

bool
SelectPoll::Polling(int ev, int millitm)
{
  if (NULL == handler_)
    return false;

  struct timeval timeout;
  if (-1 == millitm) {
    timeout.tv_sec = 0;
    timeout.tv_usec = 500;
  }
  else {
    timeout.tv_sec = millitm / 1000;
    timeout.tv_usec = (millitm % 1000 * 1000);
  }

  int max_fd = 0;
  int ret = 0;
  if (kEventTypeRead == ev) {
    InitSet(ev, &rset_, &max_fd);
    ret = select(max_fd + 1, &rset_, NULL, NULL, &timeout);
  }
  else if (kEventTypeWrite == ev) {
    InitSet(ev, &wset_, &max_fd);
    ret = select(max_fd + 1, NULL, &wset_, NULL, &timeout);
  }
  else {
    return false;
  }

  if (kNetTypeError == ret || 0 == ret)
    return false;

  if (!DispatchEvent(ev))
    return false;

  return true;
}

bool
SelectPoll::InitSet(int ev, fd_set* set, int* max_fd)
{
  if (NULL == set || NULL == max_fd)
    return false;

  FD_ZERO(set);
  *max_fd = 0;

  LockerGuard<SpinLock> gaurd(spinlock_);
  std::map<int, std::pair<int, Socket*> >::iterator it;
  for (it = connectors_.begin(); it != connectors_.end();) {
    if (NULL == it->second.second) {
      connectors_.erase(it++);
    }
    else if (kNetTypeInval == it->second.second->fd()) {
      delete it->second.second;
      connectors_.erase(it++);
    }
    else {
      if (it->second.first & ev)
        FD_SET(it->first, set);

      if (it->first > *max_fd)
        *max_fd = it->first;

      ++it;
    }
  }

  return true;
}

bool
SelectPoll::DispatchEvent(int ev)
{
  if (NULL == handler_)
    return false;

  int fd;
  Socket* s;

  LockerGuard<SpinLock> guard(spinlock_);
  std::map<int, std::pair<int, Socket*> >::iterator it;
  for (it = connectors_.begin(); it !=  connectors_.end(); ++it) {
    fd = it->first;
    s = it->second.second;

    if (NULL == s)
      continue;

    if (kEventTypeRead == ev) {
      if (FD_ISSET(fd, &rset_)) {
        int read_bytes = s->DealWithAsyncRead();
        if (read_bytes > 0) {
          if (s->CheckValidMessageInReadBuffer())
            handler_->ReadEvent(s);
        }
        else if (0 == read_bytes) {
          handler_->CloseEvent(s);
          s->Close();
        }
        else {
          if (EWOULDBLOCK != NErrno()) {
            handler_->CloseEvent(s);
            s->Close();
          }
        }
      }
    }
    else if (kEventTypeWrite == ev) {
      if (FD_ISSET(fd, &wset_)) {
        int write_bytes = s->DealWithAsyncWrite();
        if (write_bytes > 0)
          handler_->WriteEvent(s);
      }
    }
  }

  return true;
}
<commit_msg>improved select poll module<commit_after>//! Copyright (c) 2013 ASMlover. All rights reserved.
//!
//! Redistribution and use in source and binary forms, with or without
//! modification, are permitted provided that the following conditions
//! are met:
//!
//!  * Redistributions of source code must retain the above copyright
//!    notice, this list ofconditions and the following disclaimer.
//!
//!  * Redistributions in binary form must reproduce the above copyright
//!    notice, this list of conditions and the following disclaimer in
//!    the documentation and/or other materialsprovided 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.
#if defined(_WINDOWS_) ||  defined(_MSC_VER)
# ifndef _WINDOWS_
#   include <winsock2.h>
# endif
# define EWOULDBLOCK  WSAEWOULDBLOCK
# define NErrno()     WSAGetLastError()
#endif
#include "net.h"
#include "socket.h"
#include "select_poll.h"

SelectPoll::SelectPoll(void)
  : rbytes_(kDefaultBufferLen)
  , wbytes_(kDefaultBufferLen)
  , handler_(NULL)
  , spinlock_()
{
  connectors_.clear();
  FD_ZERO(&rset_);
  FD_ZERO(&wset_);
}

SelectPoll::~SelectPoll(void)
{
  CloseAll();
}

void
SelectPoll::CloseAll(void)
{
  if (NULL == handler_)
    return;

  LockerGuard<SpinLock> gaurd(spinlock_);
  std::map<int, std::pair<int, Socket*> >::iterator it;
  for (it = connectors_.begin(); it != connectors_.end(); ++it) {
    if (NULL != it->second.second) {
      handler_->CloseEvent(it->second.second);
      it->second.second->Close();
      delete it->second.second;
    }
  }
  connectors_.clear();
}

bool
SelectPoll::Insert(int fd, int ev)
{
  if (NULL == handler_)
    return false;

  LockerGuard<SpinLock> guard(spinlock_);
  std::map<int, std::pair<int, Socket*> >::iterator it;
  it = connectors_.find(fd);
  if (it == connectors_.end()) {
    Socket* s = new Socket();
    if (NULL == s)
      return false;

    s->Attach(fd);
    s->SetNonBlock();
    s->SetKeepAlive();
    s->SetSelfReadBuffer(rbytes_);
    s->SetSelfWriteBuffer(wbytes_);

    connectors_[fd] = std::make_pair<int, Socket*>(ev, s);
  }

  return true;
}

void
SelectPoll::Remove(int fd)
{
  if (NULL == handler_)
    return;

  std::map<int, std::pair<int, Socket*> >::iterator it;
  it = connectors_.find(fd);
  if (it != connectors_.end()) {
    if (NULL != it->second.second) {
      handler_->CloseEvent(it->second.second);
      it->second.second->Close();
      delete it->second.second;
    }

    connectors_.erase(it);
  }
}

bool
SelectPoll::AddEvent(int fd, int ev)
{
  if (NULL == handler_)
    return false;

  LockerGuard<SpinLock> guard(spinlock_);
  std::map<int, std::pair<int, Socket*> >::iterator it;
  it = connectors_.find(fd);
  if (it != connectors_.end())
    it->second.first |= ev;

  return true;
}

bool
SelectPoll::DelEvent(int fd, int ev)
{
  if (NULL == handler_)
    return false;

  LockerGuard<SpinLock> gaurd(spinlock_);
  std::map<int, std::pair<int, Socket*> >::iterator it;
  it = connectors_.find(fd);
  if (it != connectors_.end())
    it->second.first &= ~ev;

  return true;
}

Socket*
SelectPoll::GetConnector(int fd)
{
  Socket* s = NULL;

  {
    LockerGuard<SpinLock> gaurd(spinlock_);
    std::map<int, std::pair<int, Socket*> >::iterator it;
    it = connectors_.find(fd);
    if (it != connectors_.end())
      s = it->second.second;
  }

  return s;
}

bool
SelectPoll::Polling(int ev, int millitm)
{
  if (NULL == handler_)
    return false;

  struct timeval timeout;
  if (-1 == millitm) {
    timeout.tv_sec = 0;
    timeout.tv_usec = 500;
  }
  else {
    timeout.tv_sec = millitm / 1000;
    timeout.tv_usec = (millitm % 1000 * 1000);
  }

  int max_fd = 0;
  int ret = 0;
  if (kEventTypeRead == ev) {
    InitSet(ev, &rset_, &max_fd);
    ret = select(max_fd + 1, &rset_, NULL, NULL, &timeout);
  }
  else if (kEventTypeWrite == ev) {
    InitSet(ev, &wset_, &max_fd);
    ret = select(max_fd + 1, NULL, &wset_, NULL, &timeout);
  }
  else {
    return false;
  }

  if (kNetTypeError == ret || 0 == ret)
    return false;

  if (!DispatchEvent(ev))
    return false;

  return true;
}

bool
SelectPoll::InitSet(int ev, fd_set* set, int* max_fd)
{
  if (NULL == set || NULL == max_fd)
    return false;

  FD_ZERO(set);
  *max_fd = 0;

  LockerGuard<SpinLock> gaurd(spinlock_);
  std::map<int, std::pair<int, Socket*> >::iterator it;
  for (it = connectors_.begin(); it != connectors_.end();) {
    if (NULL == it->second.second) {
      connectors_.erase(it++);
    }
    else if (kNetTypeInval == it->second.second->fd()) {
      delete it->second.second;
      connectors_.erase(it++);
    }
    else {
      if (it->second.first & ev)
        FD_SET(it->first, set);

      if (it->first > *max_fd)
        *max_fd = it->first;

      ++it;
    }
  }

  return true;
}

bool
SelectPoll::DispatchEvent(int ev)
{
  if (NULL == handler_)
    return false;

  int fd;
  Socket* s;

  LockerGuard<SpinLock> guard(spinlock_);
  std::map<int, std::pair<int, Socket*> >::iterator it;
  for (it = connectors_.begin(); it !=  connectors_.end(); ++it) {
    fd = it->first;
    s = it->second.second;

    if (NULL == s)
      continue;

    if (kEventTypeRead == ev) {
      if (FD_ISSET(fd, &rset_)) {
        int read_bytes = s->DealWithAsyncRead();
        if (read_bytes > 0) {
          if (s->CheckValidMessageInReadBuffer())
            handler_->ReadEvent(s);
        }
        else if (0 == read_bytes) {
          handler_->CloseEvent(s);
          s->Close();
        }
        else {
          if (EWOULDBLOCK != NErrno()) {
            handler_->CloseEvent(s);
            s->Close();
          }
        }
      }
    }
    else if (kEventTypeWrite == ev) {
      if (FD_ISSET(fd, &wset_)) {
        int write_bytes = s->DealWithAsyncWrite();
        if (write_bytes > 0) {
          handler_->WriteEvent(s);
        }
        else if (write_bytes < 0) {
          if (EWOULDBLOCK != NErrno()) {
            handler_->CloseEvent(s);
            s->Close();
          }
        }
      }
    }
  }

  return true;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: xmlTable.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: ihi $ $Date: 2007-11-20 19:04: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 "precompiled_reportdesign.hxx"

#ifndef RPT_XMLTABLE_HXX
#include "xmlTable.hxx"
#endif
#ifndef RPT_XMLFILTER_HXX
#include "xmlfilter.hxx"
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include <xmloff/xmlnmspe.hxx>
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif
#ifndef _XMLOFF_XMLUCONV_HXX
#include <xmloff/xmluconv.hxx>
#endif
#ifndef _REPORT_RPTUIDEF_HXX
#include "RptDef.hxx"
#endif
#ifndef RPT_XMLHELPER_HXX
#include "xmlHelper.hxx"
#endif
#ifndef RPT_XMLENUMS_HXX
#include "xmlEnums.hxx"
#endif
#ifndef RPT_XMLCOLUMN_HXX
#include "xmlColumn.hxx"
#endif
#ifndef _COM_SUN_STAR_REPORT_FORCENEWPAGE_HPP_
#include <com/sun/star/report/ForceNewPage.hpp>
#endif
#ifndef RPT_XMLCONDPRTEXPR_HXX
#include "xmlCondPrtExpr.hxx"
#endif
#ifndef RPT_XMLSTYLEIMPORT_HXX
#include "xmlStyleImport.hxx"
#endif
#include "xmlstrings.hrc"
#ifndef _CONNECTIVITY_DBTOOLS_HXX_
#include <connectivity/dbtools.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef REPORTDESIGN_SHARED_XMLSTRINGS_HRC
#include "xmlstrings.hrc"
#endif
#include <com/sun/star/report/XShape.hpp>
#include <com/sun/star/report/XFixedLine.hpp>

#define MIN_WIDTH   80
#define MIN_HEIGHT  20

namespace rptxml
{
    using namespace ::xmloff;
    using namespace ::com::sun::star;
    using ::com::sun::star::uno::Reference;
    using namespace ::com::sun::star::xml::sax;
    using ::com::sun::star::xml::sax::XAttributeList;

    sal_uInt16 lcl_getForceNewPageOption(const ::rtl::OUString& _sValue)
    {
        sal_uInt16 nRet = report::ForceNewPage::NONE;
        const SvXMLEnumMapEntry* aXML_EnumMap = OXMLHelper::GetForceNewPageOptions();
        SvXMLUnitConverter::convertEnum( nRet,_sValue,aXML_EnumMap );
        return nRet;
    }
DBG_NAME( rpt_OXMLTable )

OXMLTable::OXMLTable( ORptFilter& rImport
                ,sal_uInt16 nPrfx
                ,const ::rtl::OUString& _sLocalName
                ,const Reference< XAttributeList > & _xAttrList
                ,const uno::Reference< report::XSection >& _xSection
                )
:SvXMLImportContext( rImport, nPrfx, _sLocalName )
,m_xSection(_xSection)
,m_nColSpan(1)
,m_nRowSpan(0)
,m_nRowIndex(0)
,m_nColumnIndex(0)
{
    DBG_CTOR( rpt_OXMLTable,NULL);
    OSL_ENSURE(_xAttrList.is(),"Attribute list is NULL!");
    const SvXMLNamespaceMap& rMap = rImport.GetNamespaceMap();
    const SvXMLTokenMap& rTokenMap = rImport.GetSectionElemTokenMap();

    const sal_Int16 nLength = (m_xSection.is() && _xAttrList.is()) ? _xAttrList->getLength() : 0;
    static const ::rtl::OUString s_sTRUE = ::xmloff::token::GetXMLToken(XML_TRUE);
    try
    {
        for(sal_Int16 i = 0; i < nLength; ++i)
        {
            rtl::OUString sLocalName;
            const rtl::OUString sAttrName = _xAttrList->getNameByIndex( i );
            const sal_uInt16 nPrefix = rMap.GetKeyByAttrName( sAttrName,&sLocalName );
            const rtl::OUString sValue = _xAttrList->getValueByIndex( i );

            switch( rTokenMap.Get( nPrefix, sLocalName ) )
            {
                case XML_TOK_VISIBLE:
                    m_xSection->setVisible(sValue == s_sTRUE);
                    break;
                case XML_TOK_FORCE_NEW_PAGE:
                    m_xSection->setForceNewPage(lcl_getForceNewPageOption(sValue));
                    break;
                case XML_TOK_FORCE_NEW_COLUMN:
                    m_xSection->setNewRowOrCol(lcl_getForceNewPageOption(sValue));
                    break;
                case XML_TOK_KEEP_TOGETHER:
                    m_xSection->setKeepTogether(sValue == s_sTRUE);
                    break;
                case XML_TOK_SECTION_NAME:
                    m_xSection->setName(sValue);
                    break;
                case XML_TOK_SECT_STYLE_NAME:
                    m_sStyleName = sValue;
                    break;
                default:
                    break;
            }
        }
    }
    catch(Exception&)
    {
        OSL_ENSURE(0,"Exception catched while filling the section props");
    }
}
// -----------------------------------------------------------------------------
OXMLTable::~OXMLTable()
{
    DBG_DTOR( rpt_OXMLTable,NULL);
}
// -----------------------------------------------------------------------------

SvXMLImportContext* OXMLTable::CreateChildContext(
        sal_uInt16 _nPrefix,
        const ::rtl::OUString& _rLocalName,
        const Reference< XAttributeList > & xAttrList )
{
    SvXMLImportContext *pContext = 0;
    ORptFilter& rImport = GetOwnImport();
    const SvXMLTokenMap&    rTokenMap   = rImport.GetColumnTokenMap();
    Reference<XMultiServiceFactory> xFactor = rImport.getServiceFactory();

    switch( rTokenMap.Get( _nPrefix, _rLocalName ) )
    {
        case XML_TOK_TABLE_COLUMNS:
        case XML_TOK_TABLE_ROWS:
            pContext = new OXMLRowColumn( rImport, _nPrefix, _rLocalName,xAttrList ,this);
            break;
        case XML_TOK_ROW:
            incrementRowIndex();
            rImport.GetProgressBarHelper()->Increment( PROGRESS_BAR_STEP );
            pContext = new OXMLRowColumn( rImport, _nPrefix, _rLocalName,xAttrList,this);
            break;
        case XML_TOK_COLUMN:
            rImport.GetProgressBarHelper()->Increment( PROGRESS_BAR_STEP );
            pContext = new OXMLRowColumn( rImport, _nPrefix, _rLocalName,xAttrList,this);
            break;
        case XML_TOK_CONDITIONAL_PRINT_EXPRESSION:
            pContext = new OXMLCondPrtExpr( rImport, _nPrefix, _rLocalName,xAttrList,m_xSection.get());
            break;
        default:
                break;
    }

    if( !pContext )
        pContext = new SvXMLImportContext( rImport, _nPrefix, _rLocalName );

    return pContext;
}
// -----------------------------------------------------------------------------
ORptFilter& OXMLTable::GetOwnImport()
{
    return static_cast<ORptFilter&>(GetImport());
}
// -----------------------------------------------------------------------------
void OXMLTable::EndElement()
{
    try
    {
        if ( m_xSection.is() )
        {
            if ( m_sStyleName.getLength() )
            {
                const SvXMLStylesContext* pAutoStyles = GetImport().GetAutoStyles();
                if ( pAutoStyles )
                {
                    XMLPropStyleContext* pAutoStyle = PTR_CAST(XMLPropStyleContext,pAutoStyles->FindStyleChildContext(XML_STYLE_FAMILY_TABLE_TABLE,m_sStyleName));
                    if ( pAutoStyle )
                    {
                        pAutoStyle->FillPropertySet(m_xSection.get());
                    }
                }
            } // if ( m_sStyleName.getLength() )
            // set height
            ::std::vector<sal_Int32>::iterator aIter = m_aHeight.begin();
            ::std::vector<sal_Int32>::iterator aEnd = m_aHeight.end();
            sal_Int32 nHeight = 0;
            for (; aIter != aEnd; ++aIter)
                nHeight += *aIter;
            m_xSection->setHeight( nHeight );
            // set positions, widths, and heights
            sal_Int32 nLeftMargin = rptui::getStyleProperty<sal_Int32>(m_xSection->getReportDefinition(),PROPERTY_LEFTMARGIN);
            sal_Int32 nPosY = 0;
            ::std::vector< ::std::vector<TCell> >::iterator aRowIter = m_aGrid.begin();
            ::std::vector< ::std::vector<TCell> >::iterator aRowEnd = m_aGrid.end();
            for (sal_Int32 i = 0; aRowIter != aRowEnd; ++aRowIter,++i)
            {
                sal_Int32 nPosX = nLeftMargin;
                ::std::vector<TCell>::iterator aColIter = (*aRowIter).begin();
                ::std::vector<TCell>::iterator aColEnd = (*aRowIter).end();
                for (sal_Int32 j = 0; aColIter != aColEnd; ++aColIter,++j)
                {
                    TCell& rCell = *aColIter;
                    if ( !rCell.xElements.empty())
                    {
                        ::std::vector< uno::Reference< report::XReportComponent> >::iterator aCellIter = rCell.xElements.begin();
                        const ::std::vector< uno::Reference< report::XReportComponent> >::iterator aCellEnd = rCell.xElements.end();
                        for (;aCellIter != aCellEnd ; ++aCellIter)
                        {
                            uno::Reference<report::XShape> xShape(*aCellIter,uno::UNO_QUERY);
                            if ( xShape.is() )
                            {
                                xShape->setPositionX(xShape->getPositionX() + nLeftMargin);
                            }
                            else
                            {
                                sal_Int32 nWidth = rCell.nWidth;
                                sal_Int32 nColSpan = rCell.nColSpan;
                                if ( nColSpan > 1 )
                                {
                                    ::std::vector<TCell>::iterator aWidthIter = aColIter + 1;
                                    while ( nColSpan > 1 )
                                    {
                                        nWidth += (aWidthIter++)->nWidth;
                                        --nColSpan;
                                    }
                                }
                                nHeight = rCell.nHeight;
                                sal_Int32 nRowSpan = rCell.nRowSpan;
                                if ( nRowSpan > 1 )
                                {
                                    ::std::vector< ::std::vector<TCell> >::iterator aHeightIter = aRowIter + 1;
                                    while( nRowSpan > 1)
                                    {
                                        nHeight += (*aHeightIter)[j].nHeight;
                                        ++aHeightIter;
                                        --nRowSpan;
                                    }
                                }
                                Reference<XFixedLine> xFixedLine(*aCellIter,uno::UNO_QUERY);
                                if ( xFixedLine.is() )
                                {
                                    if ( xFixedLine->getOrientation() == 1 ) // vertical
                                    {
                                        OSL_ENSURE(static_cast<sal_uInt32>(j+1) < m_aWidth.size(),"Illegal pos of col iter. There should be an empty cell for the next line part.");
                                        nWidth += m_aWidth[j+1];
                                        if ( nWidth < MIN_WIDTH )
                                            nWidth = MIN_WIDTH;
                                    }
                                    else if ( nHeight < MIN_HEIGHT )
                                        nHeight = MIN_HEIGHT;
                                }
                                try
                                {
                                    (*aCellIter)->setSize(awt::Size(nWidth,nHeight));
                                    (*aCellIter)->setPosition(awt::Point(nPosX,nPosY));
                                }
                                catch(beans::PropertyVetoException)
                                {
                                    OSL_ENSURE(0,"Could not set the correct position or size!");
                                }
                            }
                        }
                    }
                    nPosX += m_aWidth[j];
                }
                nPosY += m_aHeight[i];
            }
        } // if ( m_xComponent.is() )
    }
    catch(Exception&)
    {
        OSL_ENSURE(0,"OXMLTable::EndElement -> exception catched");
    }
}
// -----------------------------------------------------------------------------
void OXMLTable::addCell(const Reference<XReportComponent>& _xElement)
{
    uno::Reference<report::XShape> xShape(_xElement,uno::UNO_QUERY);
    OSL_ENSURE(static_cast<sal_uInt32>(m_nRowIndex-1 ) < m_aGrid.size() && static_cast<sal_uInt32>( m_nColumnIndex-1 ) < m_aGrid[m_nRowIndex-1].size(),
        "OXMLTable::addCell: Invalid column and row index");
    if ( static_cast<sal_uInt32>(m_nRowIndex-1 ) < m_aGrid.size() && static_cast<sal_uInt32>( m_nColumnIndex-1 ) < m_aGrid[m_nRowIndex-1].size() )
    {
        TCell& rCell = m_aGrid[m_nRowIndex-1][m_nColumnIndex-1];
        if ( _xElement.is() )
            rCell.xElements.push_back( _xElement );
        if ( !xShape.is() )
        {
            rCell.nWidth   = m_aWidth[m_nColumnIndex-1];
            rCell.nHeight  = m_aHeight[m_nRowIndex-1];
            rCell.nColSpan = m_nColSpan;
            rCell.nRowSpan = m_nRowSpan;
        }
    }

    if ( !xShape.is() )
        m_nColSpan = m_nRowSpan = 1;
}
// -----------------------------------------------------------------------------
void OXMLTable::incrementRowIndex()
{
    ++m_nRowIndex;
    m_nColumnIndex = 0;
    m_aGrid.push_back(::std::vector<TCell>(m_aWidth.size()));
}
//----------------------------------------------------------------------------
} // namespace rptxml
// -----------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS changefileheader (1.5.56); FILE MERGED 2008/04/01 15:23:39 thb 1.5.56.3: #i85898# Stripping all external header guards 2008/04/01 12:33:11 thb 1.5.56.2: #i85898# Stripping all external header guards 2008/03/31 13:32:12 rt 1.5.56.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: xmlTable.cxx,v $
 * $Revision: 1.6 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#include "precompiled_reportdesign.hxx"
#include "xmlTable.hxx"
#include "xmlfilter.hxx"
#include <xmloff/xmltoken.hxx>
#include <xmloff/xmlnmspe.hxx>
#include <xmloff/nmspmap.hxx>
#include <xmloff/xmluconv.hxx>
#include "RptDef.hxx"
#include "xmlHelper.hxx"
#include "xmlEnums.hxx"
#ifndef RPT_XMLCOLUMN_HXX
#include "xmlColumn.hxx"
#endif
#include <com/sun/star/report/ForceNewPage.hpp>
#include "xmlCondPrtExpr.hxx"
#include "xmlStyleImport.hxx"
#include "xmlstrings.hrc"
#include <connectivity/dbtools.hxx>
#include <tools/debug.hxx>
#ifndef REPORTDESIGN_SHARED_XMLSTRINGS_HRC
#include "xmlstrings.hrc"
#endif
#include <com/sun/star/report/XShape.hpp>
#include <com/sun/star/report/XFixedLine.hpp>

#define MIN_WIDTH   80
#define MIN_HEIGHT  20

namespace rptxml
{
    using namespace ::xmloff;
    using namespace ::com::sun::star;
    using ::com::sun::star::uno::Reference;
    using namespace ::com::sun::star::xml::sax;
    using ::com::sun::star::xml::sax::XAttributeList;

    sal_uInt16 lcl_getForceNewPageOption(const ::rtl::OUString& _sValue)
    {
        sal_uInt16 nRet = report::ForceNewPage::NONE;
        const SvXMLEnumMapEntry* aXML_EnumMap = OXMLHelper::GetForceNewPageOptions();
        SvXMLUnitConverter::convertEnum( nRet,_sValue,aXML_EnumMap );
        return nRet;
    }
DBG_NAME( rpt_OXMLTable )

OXMLTable::OXMLTable( ORptFilter& rImport
                ,sal_uInt16 nPrfx
                ,const ::rtl::OUString& _sLocalName
                ,const Reference< XAttributeList > & _xAttrList
                ,const uno::Reference< report::XSection >& _xSection
                )
:SvXMLImportContext( rImport, nPrfx, _sLocalName )
,m_xSection(_xSection)
,m_nColSpan(1)
,m_nRowSpan(0)
,m_nRowIndex(0)
,m_nColumnIndex(0)
{
    DBG_CTOR( rpt_OXMLTable,NULL);
    OSL_ENSURE(_xAttrList.is(),"Attribute list is NULL!");
    const SvXMLNamespaceMap& rMap = rImport.GetNamespaceMap();
    const SvXMLTokenMap& rTokenMap = rImport.GetSectionElemTokenMap();

    const sal_Int16 nLength = (m_xSection.is() && _xAttrList.is()) ? _xAttrList->getLength() : 0;
    static const ::rtl::OUString s_sTRUE = ::xmloff::token::GetXMLToken(XML_TRUE);
    try
    {
        for(sal_Int16 i = 0; i < nLength; ++i)
        {
            rtl::OUString sLocalName;
            const rtl::OUString sAttrName = _xAttrList->getNameByIndex( i );
            const sal_uInt16 nPrefix = rMap.GetKeyByAttrName( sAttrName,&sLocalName );
            const rtl::OUString sValue = _xAttrList->getValueByIndex( i );

            switch( rTokenMap.Get( nPrefix, sLocalName ) )
            {
                case XML_TOK_VISIBLE:
                    m_xSection->setVisible(sValue == s_sTRUE);
                    break;
                case XML_TOK_FORCE_NEW_PAGE:
                    m_xSection->setForceNewPage(lcl_getForceNewPageOption(sValue));
                    break;
                case XML_TOK_FORCE_NEW_COLUMN:
                    m_xSection->setNewRowOrCol(lcl_getForceNewPageOption(sValue));
                    break;
                case XML_TOK_KEEP_TOGETHER:
                    m_xSection->setKeepTogether(sValue == s_sTRUE);
                    break;
                case XML_TOK_SECTION_NAME:
                    m_xSection->setName(sValue);
                    break;
                case XML_TOK_SECT_STYLE_NAME:
                    m_sStyleName = sValue;
                    break;
                default:
                    break;
            }
        }
    }
    catch(Exception&)
    {
        OSL_ENSURE(0,"Exception catched while filling the section props");
    }
}
// -----------------------------------------------------------------------------
OXMLTable::~OXMLTable()
{
    DBG_DTOR( rpt_OXMLTable,NULL);
}
// -----------------------------------------------------------------------------

SvXMLImportContext* OXMLTable::CreateChildContext(
        sal_uInt16 _nPrefix,
        const ::rtl::OUString& _rLocalName,
        const Reference< XAttributeList > & xAttrList )
{
    SvXMLImportContext *pContext = 0;
    ORptFilter& rImport = GetOwnImport();
    const SvXMLTokenMap&    rTokenMap   = rImport.GetColumnTokenMap();
    Reference<XMultiServiceFactory> xFactor = rImport.getServiceFactory();

    switch( rTokenMap.Get( _nPrefix, _rLocalName ) )
    {
        case XML_TOK_TABLE_COLUMNS:
        case XML_TOK_TABLE_ROWS:
            pContext = new OXMLRowColumn( rImport, _nPrefix, _rLocalName,xAttrList ,this);
            break;
        case XML_TOK_ROW:
            incrementRowIndex();
            rImport.GetProgressBarHelper()->Increment( PROGRESS_BAR_STEP );
            pContext = new OXMLRowColumn( rImport, _nPrefix, _rLocalName,xAttrList,this);
            break;
        case XML_TOK_COLUMN:
            rImport.GetProgressBarHelper()->Increment( PROGRESS_BAR_STEP );
            pContext = new OXMLRowColumn( rImport, _nPrefix, _rLocalName,xAttrList,this);
            break;
        case XML_TOK_CONDITIONAL_PRINT_EXPRESSION:
            pContext = new OXMLCondPrtExpr( rImport, _nPrefix, _rLocalName,xAttrList,m_xSection.get());
            break;
        default:
                break;
    }

    if( !pContext )
        pContext = new SvXMLImportContext( rImport, _nPrefix, _rLocalName );

    return pContext;
}
// -----------------------------------------------------------------------------
ORptFilter& OXMLTable::GetOwnImport()
{
    return static_cast<ORptFilter&>(GetImport());
}
// -----------------------------------------------------------------------------
void OXMLTable::EndElement()
{
    try
    {
        if ( m_xSection.is() )
        {
            if ( m_sStyleName.getLength() )
            {
                const SvXMLStylesContext* pAutoStyles = GetImport().GetAutoStyles();
                if ( pAutoStyles )
                {
                    XMLPropStyleContext* pAutoStyle = PTR_CAST(XMLPropStyleContext,pAutoStyles->FindStyleChildContext(XML_STYLE_FAMILY_TABLE_TABLE,m_sStyleName));
                    if ( pAutoStyle )
                    {
                        pAutoStyle->FillPropertySet(m_xSection.get());
                    }
                }
            } // if ( m_sStyleName.getLength() )
            // set height
            ::std::vector<sal_Int32>::iterator aIter = m_aHeight.begin();
            ::std::vector<sal_Int32>::iterator aEnd = m_aHeight.end();
            sal_Int32 nHeight = 0;
            for (; aIter != aEnd; ++aIter)
                nHeight += *aIter;
            m_xSection->setHeight( nHeight );
            // set positions, widths, and heights
            sal_Int32 nLeftMargin = rptui::getStyleProperty<sal_Int32>(m_xSection->getReportDefinition(),PROPERTY_LEFTMARGIN);
            sal_Int32 nPosY = 0;
            ::std::vector< ::std::vector<TCell> >::iterator aRowIter = m_aGrid.begin();
            ::std::vector< ::std::vector<TCell> >::iterator aRowEnd = m_aGrid.end();
            for (sal_Int32 i = 0; aRowIter != aRowEnd; ++aRowIter,++i)
            {
                sal_Int32 nPosX = nLeftMargin;
                ::std::vector<TCell>::iterator aColIter = (*aRowIter).begin();
                ::std::vector<TCell>::iterator aColEnd = (*aRowIter).end();
                for (sal_Int32 j = 0; aColIter != aColEnd; ++aColIter,++j)
                {
                    TCell& rCell = *aColIter;
                    if ( !rCell.xElements.empty())
                    {
                        ::std::vector< uno::Reference< report::XReportComponent> >::iterator aCellIter = rCell.xElements.begin();
                        const ::std::vector< uno::Reference< report::XReportComponent> >::iterator aCellEnd = rCell.xElements.end();
                        for (;aCellIter != aCellEnd ; ++aCellIter)
                        {
                            uno::Reference<report::XShape> xShape(*aCellIter,uno::UNO_QUERY);
                            if ( xShape.is() )
                            {
                                xShape->setPositionX(xShape->getPositionX() + nLeftMargin);
                            }
                            else
                            {
                                sal_Int32 nWidth = rCell.nWidth;
                                sal_Int32 nColSpan = rCell.nColSpan;
                                if ( nColSpan > 1 )
                                {
                                    ::std::vector<TCell>::iterator aWidthIter = aColIter + 1;
                                    while ( nColSpan > 1 )
                                    {
                                        nWidth += (aWidthIter++)->nWidth;
                                        --nColSpan;
                                    }
                                }
                                nHeight = rCell.nHeight;
                                sal_Int32 nRowSpan = rCell.nRowSpan;
                                if ( nRowSpan > 1 )
                                {
                                    ::std::vector< ::std::vector<TCell> >::iterator aHeightIter = aRowIter + 1;
                                    while( nRowSpan > 1)
                                    {
                                        nHeight += (*aHeightIter)[j].nHeight;
                                        ++aHeightIter;
                                        --nRowSpan;
                                    }
                                }
                                Reference<XFixedLine> xFixedLine(*aCellIter,uno::UNO_QUERY);
                                if ( xFixedLine.is() )
                                {
                                    if ( xFixedLine->getOrientation() == 1 ) // vertical
                                    {
                                        OSL_ENSURE(static_cast<sal_uInt32>(j+1) < m_aWidth.size(),"Illegal pos of col iter. There should be an empty cell for the next line part.");
                                        nWidth += m_aWidth[j+1];
                                        if ( nWidth < MIN_WIDTH )
                                            nWidth = MIN_WIDTH;
                                    }
                                    else if ( nHeight < MIN_HEIGHT )
                                        nHeight = MIN_HEIGHT;
                                }
                                try
                                {
                                    (*aCellIter)->setSize(awt::Size(nWidth,nHeight));
                                    (*aCellIter)->setPosition(awt::Point(nPosX,nPosY));
                                }
                                catch(beans::PropertyVetoException)
                                {
                                    OSL_ENSURE(0,"Could not set the correct position or size!");
                                }
                            }
                        }
                    }
                    nPosX += m_aWidth[j];
                }
                nPosY += m_aHeight[i];
            }
        } // if ( m_xComponent.is() )
    }
    catch(Exception&)
    {
        OSL_ENSURE(0,"OXMLTable::EndElement -> exception catched");
    }
}
// -----------------------------------------------------------------------------
void OXMLTable::addCell(const Reference<XReportComponent>& _xElement)
{
    uno::Reference<report::XShape> xShape(_xElement,uno::UNO_QUERY);
    OSL_ENSURE(static_cast<sal_uInt32>(m_nRowIndex-1 ) < m_aGrid.size() && static_cast<sal_uInt32>( m_nColumnIndex-1 ) < m_aGrid[m_nRowIndex-1].size(),
        "OXMLTable::addCell: Invalid column and row index");
    if ( static_cast<sal_uInt32>(m_nRowIndex-1 ) < m_aGrid.size() && static_cast<sal_uInt32>( m_nColumnIndex-1 ) < m_aGrid[m_nRowIndex-1].size() )
    {
        TCell& rCell = m_aGrid[m_nRowIndex-1][m_nColumnIndex-1];
        if ( _xElement.is() )
            rCell.xElements.push_back( _xElement );
        if ( !xShape.is() )
        {
            rCell.nWidth   = m_aWidth[m_nColumnIndex-1];
            rCell.nHeight  = m_aHeight[m_nRowIndex-1];
            rCell.nColSpan = m_nColSpan;
            rCell.nRowSpan = m_nRowSpan;
        }
    }

    if ( !xShape.is() )
        m_nColSpan = m_nRowSpan = 1;
}
// -----------------------------------------------------------------------------
void OXMLTable::incrementRowIndex()
{
    ++m_nRowIndex;
    m_nColumnIndex = 0;
    m_aGrid.push_back(::std::vector<TCell>(m_aWidth.size()));
}
//----------------------------------------------------------------------------
} // namespace rptxml
// -----------------------------------------------------------------------------
<|endoftext|>