<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 libdui.
**
** 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 <DuiWidget>
#include "../../src/widgets/views/duilistview_p.h"
#include "duilistmodel.h"
#include "myindexedmodel.h"
#include "ut_duilistviewmulticolumn.h"

using namespace DuiListViewPrivateNamespace;

void Ut_DuiListViewMultiColumn::initTestCase()
{
    makePhoneBook();
    makePhoneBookModel();
}

void Ut_DuiListViewMultiColumn::makePhoneBook()
{
    phoneBook = new QObject;

    QObject *itemA = new QObject(phoneBook);
    itemA->setObjectName("A");

    QObject *item;
    item = new QObject(itemA);
    item->setObjectName("Adam");

    item = new QObject(itemA);
    item->setObjectName("Abby");

    item = new QObject(itemA);
    item->setObjectName("Ashley");

    QObject *itemB = new QObject(phoneBook);
    itemB->setObjectName("B");

    item = new QObject(itemB);
    item->setObjectName("Baby");

    item = new QObject(itemB);
    item->setObjectName("Bob");

    item = new QObject(itemB);
    item->setObjectName("Boby");

    item = new QObject(itemB);
    item->setObjectName("Britney");

    QObject *itemC = new QObject(phoneBook);
    itemC->setObjectName("C");

    item = new QObject(itemC);
    item->setObjectName("Cindy");
}

void Ut_DuiListViewMultiColumn::makePhoneBookModel()
{
    phoneBookModel = new MyIndexedModel(phoneBook);
}

void Ut_DuiListViewMultiColumn::cleanupTestCase()
{
    delete phoneBookModel;
}

void Ut_DuiListViewMultiColumn::init()
{
    listViewPrivate = new DuiMultiColumnListViewPrivate;
    listViewPrivate->model = phoneBookModel;
    listViewPrivate->separator = new DuiWidget;
    listViewPrivate->separator->setGeometry(0, 0, 300, 2);
    listViewPrivate->hseparator = new DuiWidget;
    listViewPrivate->hseparator->setGeometry(0, 0, 2, 100);
    listViewPrivate->itemHeight = 100;
    listViewPrivate->viewWidth = 300;

    listViewPrivate->setHeadersCreator(new DummyHeaderCreator);
    listViewPrivate->hdrHeight = GroupHeaderHeight;

    DuiListModel *model = new DuiListModel;
    model->setItemModel(phoneBookModel);
    model->setShowGroups(true);
    model->setColumns(2);
    listViewPrivate->controllerModel = model;

    listViewPrivate->updateHeadersRows();
    listViewPrivate->updateHeadersPositions();
}

void Ut_DuiListViewMultiColumn::cleanup()
{
    delete listViewPrivate;
    delete listViewPrivate->controllerModel;
}

void Ut_DuiListViewMultiColumn::testPhoneBook()
{
    // Make sure our phone book model is valid
    QCOMPARE(phoneBook->children().size(), 3);
    QCOMPARE(phoneBook->children().at(0)->children().size(), 3);
    QCOMPARE(phoneBook->children().at(1)->children().size(), 4);
    QCOMPARE(phoneBook->children().at(2)->children().size(), 1);
}

void Ut_DuiListViewMultiColumn::testUpdateHeadersRows()
{
    QCOMPARE(listViewPrivate->headersRows.size(), 3);
    QCOMPARE(listViewPrivate->headersRows[0], 0);
    QCOMPARE(listViewPrivate->headersRows[1], 4);
    QCOMPARE(listViewPrivate->headersRows[2], 9);
}

void Ut_DuiListViewMultiColumn::testUpdateHeadersPositions()
{
    QCOMPARE(listViewPrivate->headersPositions.size(), 3);
    QCOMPARE(listViewPrivate->headersPositions[0], 0);
    QCOMPARE(listViewPrivate->headersPositions[1], 242);
    QCOMPARE(listViewPrivate->headersPositions[2], 484);
}

void Ut_DuiListViewMultiColumn::testHeaderHeightShouldBeZeroIfNoHeadersCreatorSpecified()
{
    QSKIP("Failing already in group header tests...", SkipSingle);
    listViewPrivate->setHeadersCreator(NULL);
    QCOMPARE(0, listViewPrivate->headerHeight());
}

void Ut_DuiListViewMultiColumn::testHeaderHeightShouldBeZeroIfHeadersNotVisible()
{
    QSKIP("Failing already in group header tests...", SkipSingle);
    listViewPrivate->controllerModel->setShowGroups(false);
    QCOMPARE(listViewPrivate->headerHeight(), 0);
}

void Ut_DuiListViewMultiColumn::testHeaderHeight()
{
    QCOMPARE(listViewPrivate->headerHeight(), GroupHeaderHeight);
}

void Ut_DuiListViewMultiColumn::testGroupSize()
{
    QCOMPARE(listViewPrivate->groupSize(0), 202);
    QCOMPARE(listViewPrivate->groupSize(1), 202);
    QCOMPARE(listViewPrivate->groupSize(2), 100);
}

void Ut_DuiListViewMultiColumn::testRowsInGroup()
{
    QCOMPARE(listViewPrivate->rowsInGroup(0), 2);
    QCOMPARE(listViewPrivate->rowsInGroup(1), 2);
    QCOMPARE(listViewPrivate->rowsInGroup(2), 1);
}

void Ut_DuiListViewMultiColumn::testSizeHint()
{
    QCOMPARE(listViewPrivate->totalHeight(), 624);
}

void Ut_DuiListViewMultiColumn::testItemCountIndexedModel()
{
    QCOMPARE(listViewPrivate->itemsCount(), 8);
}

void Ut_DuiListViewMultiColumn::testItemCount()
{
    QCOMPARE(listViewPrivate->itemsCount(0), 3);
    QCOMPARE(listViewPrivate->itemsCount(1), 4);
    QCOMPARE(listViewPrivate->itemsCount(2), 1);
}

void Ut_DuiListViewMultiColumn::testSeparatorsCount()
{
    QCOMPARE(listViewPrivate->separatorsCount(), 5);
}

void Ut_DuiListViewMultiColumn::testLocateVisibleIndexAt0()
{
    QModelIndex index(listViewPrivate->locateVisibleIndexAt(0));
    QVERIFY(index.isValid());
    QCOMPARE(index.row(), 0);
    QVERIFY(!index.parent().isValid());
}

void Ut_DuiListViewMultiColumn::testLocateVisibleIndexAt40()
{
    QModelIndex index(listViewPrivate->locateVisibleIndexAt(40));
    QVERIFY(index.isValid());
    QCOMPARE(index.row(), 0);
    QVERIFY(index.parent().isValid());
    QCOMPARE(index.parent().row(), 0);
}

void Ut_DuiListViewMultiColumn::testLocateVisibleIndexAt142()
{
    QModelIndex index(listViewPrivate->locateVisibleIndexAt(142));
    QVERIFY(index.isValid());
    QCOMPARE(index.row(), 2);
    QVERIFY(index.parent().isValid());
    QCOMPARE(index.parent().row(), 0);
}

void Ut_DuiListViewMultiColumn::testLocateVisibleIndexAt242()
{
    QModelIndex index(listViewPrivate->locateVisibleIndexAt(242));
    QVERIFY(index.isValid());
    QCOMPARE(index.row(), 1);
    QVERIFY(!index.parent().isValid());
}

void Ut_DuiListViewMultiColumn::testLocateVisibleIndexAt282()
{
    QModelIndex index(listViewPrivate->locateVisibleIndexAt(282));
    QVERIFY(index.isValid());
    QCOMPARE(index.row(), 0);
    QVERIFY(index.parent().isValid());
    QCOMPARE(index.parent().row(), 1);
}

void Ut_DuiListViewMultiColumn::testLocateVisibleIndexAt384()
{
    QModelIndex index(listViewPrivate->locateVisibleIndexAt(384));
    QVERIFY(index.isValid());
    QCOMPARE(index.row(), 2);
    QVERIFY(index.parent().isValid());
    QCOMPARE(index.parent().row(), 1);
}

void Ut_DuiListViewMultiColumn::testLocateVisibleIndexAt484()
{
    QModelIndex index(listViewPrivate->locateVisibleIndexAt(484));
    QVERIFY(index.isValid());
    QCOMPARE(index.row(), 2);
    QVERIFY(!index.parent().isValid());
}

void Ut_DuiListViewMultiColumn::testLocateVisibleIndexAt524()
{
    QModelIndex index(listViewPrivate->locateVisibleIndexAt(524));
    QVERIFY(index.isValid());
    QCOMPARE(index.row(), 0);
    QVERIFY(index.parent().isValid());
    QCOMPARE(index.parent().row(), 2);
}

void Ut_DuiListViewMultiColumn::testLocateVisibleRowAt0()
{
    QCOMPARE(listViewPrivate->locateVisibleRowAt(0), 0);
}

void Ut_DuiListViewMultiColumn::testLocateVisibleRowAt40()
{
    QCOMPARE(listViewPrivate->locateVisibleRowAt(40), 1);
}

void Ut_DuiListViewMultiColumn::testLocateVisibleRowAt40x151()
{
    QCOMPARE(listViewPrivate->locateVisibleRowAt(40, 151), 2);
}

void Ut_DuiListViewMultiColumn::testLocateVisibleRowAt142()
{
    QCOMPARE(listViewPrivate->locateVisibleRowAt(142), 3);
}

void Ut_DuiListViewMultiColumn::testLocateVisibleRowAt242()
{
    QCOMPARE(listViewPrivate->locateVisibleRowAt(242), 4);
}

void Ut_DuiListViewMultiColumn::testLocateVisibleRowAt282()
{
    QCOMPARE(listViewPrivate->locateVisibleRowAt(282), 5);
}

void Ut_DuiListViewMultiColumn::testLocateVisibleRowAt384()
{
    QCOMPARE(listViewPrivate->locateVisibleRowAt(384), 7);
}

void Ut_DuiListViewMultiColumn::testLocateVisibleRowAt484()
{
    QCOMPARE(listViewPrivate->locateVisibleRowAt(484), 9);
}

void Ut_DuiListViewMultiColumn::testLocateVisibleRowAt524()
{
    QCOMPARE(listViewPrivate->locateVisibleRowAt(524), 10);
}

void testLocatePosOfItemAt0Row();
void testLocatePosOfItemAt1Row();
void testLocatePosOfItemAt3Row();
void testLocatePosOfItemAt4Row();
void testLocatePosOfItemAt5Row();
void testLocatePosOfItemAt7Row();
void testLocatePosOfItemAt9Row();
void testLocatePosOfItemAt10Row();

void Ut_DuiListViewMultiColumn::testLocatePosOfItemAt0Row()
{
    QCOMPARE(listViewPrivate->locatePosOfItem(0), 0);
}

void Ut_DuiListViewMultiColumn::testLocatePosOfItemAt1Row()
{
    QCOMPARE(listViewPrivate->locatePosOfItem(1), 40);
}

void Ut_DuiListViewMultiColumn::testLocatePosOfItemAt3Row()
{
    QCOMPARE(listViewPrivate->locatePosOfItem(3), 142);
}

void Ut_DuiListViewMultiColumn::testLocatePosOfItemAt4Row()
{
    QCOMPARE(listViewPrivate->locatePosOfItem(4), 242);
}

void Ut_DuiListViewMultiColumn::testLocatePosOfItemAt5Row()
{
    QCOMPARE(listViewPrivate->locatePosOfItem(5), 282);
}

void Ut_DuiListViewMultiColumn::testLocatePosOfItemAt7Row()
{
    QCOMPARE(listViewPrivate->locatePosOfItem(7), 384);
}

void Ut_DuiListViewMultiColumn::testLocatePosOfItemAt9Row()
{
    QCOMPARE(listViewPrivate->locatePosOfItem(9), 484);
}

void Ut_DuiListViewMultiColumn::testLocatePosOfItemAt10Row()
{
    QCOMPARE(listViewPrivate->locatePosOfItem(10), 524);
}

void Ut_DuiListViewMultiColumn::testLocatePosOfItemAt0Index()
{
    QModelIndex index(phoneBookModel->index(0, 0));
    QCOMPARE(listViewPrivate->locatePosOfItem(index), 0);
}

void Ut_DuiListViewMultiColumn::testLocatePosOfItemAt1Index()
{
    QModelIndex index(phoneBookModel->index(0, 0, phoneBookModel->index(0, 0)));
    QCOMPARE(listViewPrivate->locatePosOfItem(index), 40);
}

void Ut_DuiListViewMultiColumn::testLocatePosOfItemAt3Index()
{
    QModelIndex index(phoneBookModel->index(2, 0, phoneBookModel->index(0, 0)));
    QCOMPARE(listViewPrivate->locatePosOfItem(index), 142);
}

void Ut_DuiListViewMultiColumn::testLocatePosOfItemAt4Index()
{
    QModelIndex index(phoneBookModel->index(1, 0));
    QCOMPARE(listViewPrivate->locatePosOfItem(index), 242);
}

void Ut_DuiListViewMultiColumn::testLocatePosOfItemAt5Index()
{
    QModelIndex index(phoneBookModel->index(0, 0, phoneBookModel->index(1, 0)));
    QCOMPARE(listViewPrivate->locatePosOfItem(index), 282);
}

void Ut_DuiListViewMultiColumn::testLocatePosOfItemAt7Index()
{
    QModelIndex index(phoneBookModel->index(2, 0, phoneBookModel->index(1, 0)));
    QCOMPARE(listViewPrivate->locatePosOfItem(index), 384);
}

void Ut_DuiListViewMultiColumn::testLocatePosOfItemAt9Index()
{
    QModelIndex index(phoneBookModel->index(2, 0));
    QCOMPARE(listViewPrivate->locatePosOfItem(index), 484);
}

void Ut_DuiListViewMultiColumn::testLocatePosOfItemAt10Index()
{
    QModelIndex index(phoneBookModel->index(0, 0, phoneBookModel->index(2, 0)));
    QCOMPARE(listViewPrivate->locatePosOfItem(index), 524);
}

QTEST_APPLESS_MAIN(Ut_DuiListViewMultiColumn);
<commit_msg>Changes: Fixing ut_duilistmulticolumn test.<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 libdui.
**
** 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 <DuiWidget>
#include "../../src/widgets/views/duilistview_p.h"
#include "duilistmodel.h"
#include "myindexedmodel.h"
#include "ut_duilistviewmulticolumn.h"

using namespace DuiListViewPrivateNamespace;

void Ut_DuiListViewMultiColumn::initTestCase()
{
    makePhoneBook();
    makePhoneBookModel();
}

void Ut_DuiListViewMultiColumn::makePhoneBook()
{
    phoneBook = new QObject;

    QObject *itemA = new QObject(phoneBook);
    itemA->setObjectName("A");

    QObject *item;
    item = new QObject(itemA);
    item->setObjectName("Adam");

    item = new QObject(itemA);
    item->setObjectName("Abby");

    item = new QObject(itemA);
    item->setObjectName("Ashley");

    QObject *itemB = new QObject(phoneBook);
    itemB->setObjectName("B");

    item = new QObject(itemB);
    item->setObjectName("Baby");

    item = new QObject(itemB);
    item->setObjectName("Bob");

    item = new QObject(itemB);
    item->setObjectName("Boby");

    item = new QObject(itemB);
    item->setObjectName("Britney");

    QObject *itemC = new QObject(phoneBook);
    itemC->setObjectName("C");

    item = new QObject(itemC);
    item->setObjectName("Cindy");
}

void Ut_DuiListViewMultiColumn::makePhoneBookModel()
{
    phoneBookModel = new MyIndexedModel(phoneBook);
}

void Ut_DuiListViewMultiColumn::cleanupTestCase()
{
    delete phoneBookModel;
}

void Ut_DuiListViewMultiColumn::init()
{
    listViewPrivate = new DuiMultiColumnListViewPrivate;
    listViewPrivate->model = phoneBookModel;

    DuiWidget * separator = new DuiWidget;
    separator->setGeometry(0, 0, 300, 2);
    separator->setPreferredHeight(2);
    listViewPrivate->setSeparator(separator);

    listViewPrivate->hseparator = new DuiWidget;
    listViewPrivate->hseparator->setGeometry(0, 0, 2, 100);
    listViewPrivate->itemHeight = 100;
    listViewPrivate->viewWidth = 300;

    listViewPrivate->setHeadersCreator(new DummyHeaderCreator);
    listViewPrivate->hdrHeight = GroupHeaderHeight;

    DuiListModel *model = new DuiListModel;
    model->setItemModel(phoneBookModel);
    model->setShowGroups(true);
    model->setColumns(2);
    listViewPrivate->controllerModel = model;

    listViewPrivate->updateHeadersRows();
    listViewPrivate->updateHeadersPositions();
}

void Ut_DuiListViewMultiColumn::cleanup()
{
    delete listViewPrivate;
    delete listViewPrivate->controllerModel;
}

void Ut_DuiListViewMultiColumn::testPhoneBook()
{
    // Make sure our phone book model is valid
    QCOMPARE(phoneBook->children().size(), 3);
    QCOMPARE(phoneBook->children().at(0)->children().size(), 3);
    QCOMPARE(phoneBook->children().at(1)->children().size(), 4);
    QCOMPARE(phoneBook->children().at(2)->children().size(), 1);
}

void Ut_DuiListViewMultiColumn::testUpdateHeadersRows()
{
    QCOMPARE(listViewPrivate->headersRows.size(), 3);
    QCOMPARE(listViewPrivate->headersRows[0], 0);
    QCOMPARE(listViewPrivate->headersRows[1], 4);
    QCOMPARE(listViewPrivate->headersRows[2], 9);
}

void Ut_DuiListViewMultiColumn::testUpdateHeadersPositions()
{
    QCOMPARE(listViewPrivate->headersPositions.size(), 3);
    QCOMPARE(listViewPrivate->headersPositions[0], 0);
    QCOMPARE(listViewPrivate->headersPositions[1], 242);
    QCOMPARE(listViewPrivate->headersPositions[2], 484);
}

void Ut_DuiListViewMultiColumn::testHeaderHeightShouldBeZeroIfNoHeadersCreatorSpecified()
{
    QSKIP("Failing already in group header tests...", SkipSingle);
    listViewPrivate->setHeadersCreator(NULL);
    QCOMPARE(0, listViewPrivate->headerHeight());
}

void Ut_DuiListViewMultiColumn::testHeaderHeightShouldBeZeroIfHeadersNotVisible()
{
    QSKIP("Failing already in group header tests...", SkipSingle);
    listViewPrivate->controllerModel->setShowGroups(false);
    QCOMPARE(listViewPrivate->headerHeight(), 0);
}

void Ut_DuiListViewMultiColumn::testHeaderHeight()
{
    QCOMPARE(listViewPrivate->headerHeight(), GroupHeaderHeight);
}

void Ut_DuiListViewMultiColumn::testGroupSize()
{
    QCOMPARE(listViewPrivate->groupSize(0), 202);
    QCOMPARE(listViewPrivate->groupSize(1), 202);
    QCOMPARE(listViewPrivate->groupSize(2), 100);
}

void Ut_DuiListViewMultiColumn::testRowsInGroup()
{
    QCOMPARE(listViewPrivate->rowsInGroup(0), 2);
    QCOMPARE(listViewPrivate->rowsInGroup(1), 2);
    QCOMPARE(listViewPrivate->rowsInGroup(2), 1);
}

void Ut_DuiListViewMultiColumn::testSizeHint()
{
    QCOMPARE(listViewPrivate->totalHeight(), 624);
}

void Ut_DuiListViewMultiColumn::testItemCountIndexedModel()
{
    QCOMPARE(listViewPrivate->itemsCount(), 8);
}

void Ut_DuiListViewMultiColumn::testItemCount()
{
    QCOMPARE(listViewPrivate->itemsCount(0), 3);
    QCOMPARE(listViewPrivate->itemsCount(1), 4);
    QCOMPARE(listViewPrivate->itemsCount(2), 1);
}

void Ut_DuiListViewMultiColumn::testSeparatorsCount()
{
    QCOMPARE(listViewPrivate->separatorsCount(), 5);
}

void Ut_DuiListViewMultiColumn::testLocateVisibleIndexAt0()
{
    QModelIndex index(listViewPrivate->locateVisibleIndexAt(0));
    QVERIFY(index.isValid());
    QCOMPARE(index.row(), 0);
    QVERIFY(!index.parent().isValid());
}

void Ut_DuiListViewMultiColumn::testLocateVisibleIndexAt40()
{
    QModelIndex index(listViewPrivate->locateVisibleIndexAt(40));
    QVERIFY(index.isValid());
    QCOMPARE(index.row(), 0);
    QVERIFY(index.parent().isValid());
    QCOMPARE(index.parent().row(), 0);
}

void Ut_DuiListViewMultiColumn::testLocateVisibleIndexAt142()
{
    QModelIndex index(listViewPrivate->locateVisibleIndexAt(142));
    QVERIFY(index.isValid());
    QCOMPARE(index.row(), 2);
    QVERIFY(index.parent().isValid());
    QCOMPARE(index.parent().row(), 0);
}

void Ut_DuiListViewMultiColumn::testLocateVisibleIndexAt242()
{
    QModelIndex index(listViewPrivate->locateVisibleIndexAt(242));
    QVERIFY(index.isValid());
    QCOMPARE(index.row(), 1);
    QVERIFY(!index.parent().isValid());
}

void Ut_DuiListViewMultiColumn::testLocateVisibleIndexAt282()
{
    QModelIndex index(listViewPrivate->locateVisibleIndexAt(282));
    QVERIFY(index.isValid());
    QCOMPARE(index.row(), 0);
    QVERIFY(index.parent().isValid());
    QCOMPARE(index.parent().row(), 1);
}

void Ut_DuiListViewMultiColumn::testLocateVisibleIndexAt384()
{
    QModelIndex index(listViewPrivate->locateVisibleIndexAt(384));
    QVERIFY(index.isValid());
    QCOMPARE(index.row(), 2);
    QVERIFY(index.parent().isValid());
    QCOMPARE(index.parent().row(), 1);
}

void Ut_DuiListViewMultiColumn::testLocateVisibleIndexAt484()
{
    QModelIndex index(listViewPrivate->locateVisibleIndexAt(484));
    QVERIFY(index.isValid());
    QCOMPARE(index.row(), 2);
    QVERIFY(!index.parent().isValid());
}

void Ut_DuiListViewMultiColumn::testLocateVisibleIndexAt524()
{
    QModelIndex index(listViewPrivate->locateVisibleIndexAt(524));
    QVERIFY(index.isValid());
    QCOMPARE(index.row(), 0);
    QVERIFY(index.parent().isValid());
    QCOMPARE(index.parent().row(), 2);
}

void Ut_DuiListViewMultiColumn::testLocateVisibleRowAt0()
{
    QCOMPARE(listViewPrivate->locateVisibleRowAt(0), 0);
}

void Ut_DuiListViewMultiColumn::testLocateVisibleRowAt40()
{
    QCOMPARE(listViewPrivate->locateVisibleRowAt(40), 1);
}

void Ut_DuiListViewMultiColumn::testLocateVisibleRowAt40x151()
{
    QCOMPARE(listViewPrivate->locateVisibleRowAt(40, 151), 2);
}

void Ut_DuiListViewMultiColumn::testLocateVisibleRowAt142()
{
    QCOMPARE(listViewPrivate->locateVisibleRowAt(142), 3);
}

void Ut_DuiListViewMultiColumn::testLocateVisibleRowAt242()
{
    QCOMPARE(listViewPrivate->locateVisibleRowAt(242), 4);
}

void Ut_DuiListViewMultiColumn::testLocateVisibleRowAt282()
{
    QCOMPARE(listViewPrivate->locateVisibleRowAt(282), 5);
}

void Ut_DuiListViewMultiColumn::testLocateVisibleRowAt384()
{
    QCOMPARE(listViewPrivate->locateVisibleRowAt(384), 7);
}

void Ut_DuiListViewMultiColumn::testLocateVisibleRowAt484()
{
    QCOMPARE(listViewPrivate->locateVisibleRowAt(484), 9);
}

void Ut_DuiListViewMultiColumn::testLocateVisibleRowAt524()
{
    QCOMPARE(listViewPrivate->locateVisibleRowAt(524), 10);
}

void testLocatePosOfItemAt0Row();
void testLocatePosOfItemAt1Row();
void testLocatePosOfItemAt3Row();
void testLocatePosOfItemAt4Row();
void testLocatePosOfItemAt5Row();
void testLocatePosOfItemAt7Row();
void testLocatePosOfItemAt9Row();
void testLocatePosOfItemAt10Row();

void Ut_DuiListViewMultiColumn::testLocatePosOfItemAt0Row()
{
    QCOMPARE(listViewPrivate->locatePosOfItem(0), 0);
}

void Ut_DuiListViewMultiColumn::testLocatePosOfItemAt1Row()
{
    QCOMPARE(listViewPrivate->locatePosOfItem(1), 40);
}

void Ut_DuiListViewMultiColumn::testLocatePosOfItemAt3Row()
{
    QCOMPARE(listViewPrivate->locatePosOfItem(3), 142);
}

void Ut_DuiListViewMultiColumn::testLocatePosOfItemAt4Row()
{
    QCOMPARE(listViewPrivate->locatePosOfItem(4), 242);
}

void Ut_DuiListViewMultiColumn::testLocatePosOfItemAt5Row()
{
    QCOMPARE(listViewPrivate->locatePosOfItem(5), 282);
}

void Ut_DuiListViewMultiColumn::testLocatePosOfItemAt7Row()
{
    QCOMPARE(listViewPrivate->locatePosOfItem(7), 384);
}

void Ut_DuiListViewMultiColumn::testLocatePosOfItemAt9Row()
{
    QCOMPARE(listViewPrivate->locatePosOfItem(9), 484);
}

void Ut_DuiListViewMultiColumn::testLocatePosOfItemAt10Row()
{
    QCOMPARE(listViewPrivate->locatePosOfItem(10), 524);
}

void Ut_DuiListViewMultiColumn::testLocatePosOfItemAt0Index()
{
    QModelIndex index(phoneBookModel->index(0, 0));
    QCOMPARE(listViewPrivate->locatePosOfItem(index), 0);
}

void Ut_DuiListViewMultiColumn::testLocatePosOfItemAt1Index()
{
    QModelIndex index(phoneBookModel->index(0, 0, phoneBookModel->index(0, 0)));
    QCOMPARE(listViewPrivate->locatePosOfItem(index), 40);
}

void Ut_DuiListViewMultiColumn::testLocatePosOfItemAt3Index()
{
    QModelIndex index(phoneBookModel->index(2, 0, phoneBookModel->index(0, 0)));
    QCOMPARE(listViewPrivate->locatePosOfItem(index), 142);
}

void Ut_DuiListViewMultiColumn::testLocatePosOfItemAt4Index()
{
    QModelIndex index(phoneBookModel->index(1, 0));
    QCOMPARE(listViewPrivate->locatePosOfItem(index), 242);
}

void Ut_DuiListViewMultiColumn::testLocatePosOfItemAt5Index()
{
    QModelIndex index(phoneBookModel->index(0, 0, phoneBookModel->index(1, 0)));
    QCOMPARE(listViewPrivate->locatePosOfItem(index), 282);
}

void Ut_DuiListViewMultiColumn::testLocatePosOfItemAt7Index()
{
    QModelIndex index(phoneBookModel->index(2, 0, phoneBookModel->index(1, 0)));
    QCOMPARE(listViewPrivate->locatePosOfItem(index), 384);
}

void Ut_DuiListViewMultiColumn::testLocatePosOfItemAt9Index()
{
    QModelIndex index(phoneBookModel->index(2, 0));
    QCOMPARE(listViewPrivate->locatePosOfItem(index), 484);
}

void Ut_DuiListViewMultiColumn::testLocatePosOfItemAt10Index()
{
    QModelIndex index(phoneBookModel->index(0, 0, phoneBookModel->index(2, 0)));
    QCOMPARE(listViewPrivate->locatePosOfItem(index), 524);
}

QTEST_APPLESS_MAIN(Ut_DuiListViewMultiColumn);
<|endoftext|>


<commit_before>// balst_stacktraceresolver_filehelper.cpp                            -*-C++-*-

// ----------------------------------------------------------------------------
//                                   NOTICE
//
// This component is not up to date with current BDE coding standards, and
// should not be used as an example for new development.
// ----------------------------------------------------------------------------

#include <balst_stacktraceresolver_filehelper.h>

#include <bsls_ident.h>
BSLS_IDENT_RCSID(balst_stacktraceresolver_filehelper_cpp,"$Id$ $CSID$")

#include <balst_objectfileformat.h>

#include <bdls_filesystemutil.h>
#include <bdlb_string.h>

#include <bslma_allocator.h>
#include <bsls_assert.h>

#include <bsl_cstring.h>

#if defined(BALST_OBJECTFILEFORMAT_RESOLVER_ELF) || \
    defined(BALST_OBJECTFILEFORMAT_RESOLVER_XCOFF)

namespace BloombergLP {
namespace balst {
                        // -----------------------------
                        // StackTraceResolver_FileHelper
                        // -----------------------------

// CREATORS
StackTraceResolver_FileHelper::StackTraceResolver_FileHelper()
: d_fd(FilesystemUtil::k_INVALID_FD)
{}

StackTraceResolver_FileHelper::~StackTraceResolver_FileHelper()
{
    if (FilesystemUtil::k_INVALID_FD != d_fd) {
        FilesystemUtil::close(d_fd);
        d_fd = FilesystemUtil::k_INVALID_FD;
    }
}

// MANIPULATOR
int StackTraceResolver_FileHelper::initialize(const char *fileName)
{
    if (!fileName) {
        return -1;                                                    // RETURN
    }

    if (FilesystemUtil::k_INVALID_FD != d_fd) {
        FilesystemUtil::close(d_fd);
    }

    d_fd = FilesystemUtil::open(fileName,
                                FilesystemUtil::e_OPEN,       // already exists
                                FilesystemUtil::e_READ_ONLY); // not writable

    return FilesystemUtil::k_INVALID_FD == d_fd;    // 0 on success
}

// ACCESSORS
char *StackTraceResolver_FileHelper::loadString(
                                    Offset                offset,
                                    char                 *scratchBuf,
                                    bsls::Types::UintPtr  scratchBufLength,
                                    bslma::Allocator     *basicAllocator) const
{
    // We do not know the length of the string and we don't want to read a full
    // 'scratchBufLength' (typically > 32000) bytes every time we read a
    // symbol, so first read 256 bytes, then read more and more up to
    // 'scratchBufLength - 1' bytes, until we get the symbol.  If the length of
    // the symbol is greater than or equal to 'scratchBufLength - 1', it will
    // be truncated.  Allocate a buffer of memory just long enough to fit the
    // 0 terminated string, copy the string into it, and return a pointer to
    // the buffer.

    BSLS_ASSERT(scratchBuf);
    BSLS_ASSERT(scratchBufLength > 0);

    enum {
        k_START_LEN = 256
    };

    const IntPtr maxString = scratchBufLength - 1;

    IntPtr stringLen;
    for (IntPtr readLen = k_START_LEN; true; readLen *= 4) {
        if (readLen > maxString) {
            readLen = maxString;
        }

        IntPtr bytes = readBytes(scratchBuf, readLen, offset);
        if (0 == bytes) {
            // We can't read.  Return "".

            stringLen = 0;
            break;
        }

        BSLS_ASSERT(bytes <= readLen);
        scratchBuf[bytes] = 0;
        stringLen = bsl::strlen(scratchBuf);
        if (stringLen < bytes || bytes < readLen || maxString == readLen) {
            break;
        }
    }

    return bdlb::String::copy(scratchBuf,
                              static_cast<int>(stringLen),
                              basicAllocator);
}

bsls::Types::UintPtr StackTraceResolver_FileHelper::readBytes(
                                                         void    *buf,
                                                         UintPtr  numBytes,
                                                         Offset   offset) const
{
    BSLS_ASSERT(buf);
    BSLS_ASSERT(offset >= 0);

    Offset seekDest = FilesystemUtil::seek(
                                        d_fd,
                                        offset,
                                        FilesystemUtil::e_SEEK_FROM_BEGINNING);
    if (seekDest != offset) {
        return 0;                                                     // RETURN
    }

    int res = FilesystemUtil::read(d_fd, buf, static_cast<int>(numBytes));
    return (res <= 0 ? 0 : res);
}

}  // close package namespace
}  // close enterprise namespace

#endif

// ----------------------------------------------------------------------------
// Copyright 2018 Bloomberg Finance L.P.
//
// 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.
// ----------------------------- END-OF-FILE ----------------------------------
<commit_msg>balst_stacktraceresolver_filehelper: add include file<commit_after>// balst_stacktraceresolver_filehelper.cpp                            -*-C++-*-

// ----------------------------------------------------------------------------
//                                   NOTICE
//
// This component is not up to date with current BDE coding standards, and
// should not be used as an example for new development.
// ----------------------------------------------------------------------------

#include <balst_stacktraceresolver_filehelper.h>

#include <bsls_ident.h>
BSLS_IDENT_RCSID(balst_stacktraceresolver_filehelper_cpp,"$Id$ $CSID$")

#include <balst_objectfileformat.h>

#include <bdls_filesystemutil.h>
#include <bdlb_string.h>

#include <bslma_allocator.h>
#include <bsls_assert.h>

#include <bsl_cstddef.h>
#include <bsl_cstring.h>

#if defined(BALST_OBJECTFILEFORMAT_RESOLVER_ELF) || \
    defined(BALST_OBJECTFILEFORMAT_RESOLVER_XCOFF)

namespace BloombergLP {
namespace balst {
                        // -----------------------------
                        // StackTraceResolver_FileHelper
                        // -----------------------------

// CREATORS
StackTraceResolver_FileHelper::StackTraceResolver_FileHelper()
: d_fd(FilesystemUtil::k_INVALID_FD)
{}

StackTraceResolver_FileHelper::~StackTraceResolver_FileHelper()
{
    if (FilesystemUtil::k_INVALID_FD != d_fd) {
        FilesystemUtil::close(d_fd);
        d_fd = FilesystemUtil::k_INVALID_FD;
    }
}

// MANIPULATOR
int StackTraceResolver_FileHelper::initialize(const char *fileName)
{
    if (!fileName) {
        return -1;                                                    // RETURN
    }

    if (FilesystemUtil::k_INVALID_FD != d_fd) {
        FilesystemUtil::close(d_fd);
    }

    d_fd = FilesystemUtil::open(fileName,
                                FilesystemUtil::e_OPEN,       // already exists
                                FilesystemUtil::e_READ_ONLY); // not writable

    return FilesystemUtil::k_INVALID_FD == d_fd;    // 0 on success
}

// ACCESSORS
char *StackTraceResolver_FileHelper::loadString(
                                    Offset                offset,
                                    char                 *scratchBuf,
                                    bsls::Types::UintPtr  scratchBufLength,
                                    bslma::Allocator     *basicAllocator) const
{
    // We do not know the length of the string and we don't want to read a full
    // 'scratchBufLength' (typically > 32000) bytes every time we read a
    // symbol, so first read 256 bytes, then read more and more up to
    // 'scratchBufLength - 1' bytes, until we get the symbol.  If the length of
    // the symbol is greater than or equal to 'scratchBufLength - 1', it will
    // be truncated.  Allocate a buffer of memory just long enough to fit the
    // 0 terminated string, copy the string into it, and return a pointer to
    // the buffer.

    BSLS_ASSERT(scratchBuf);
    BSLS_ASSERT(scratchBufLength > 0);

    enum {
        k_START_LEN = 256
    };

    const IntPtr maxString = scratchBufLength - 1;

    IntPtr stringLen;
    for (IntPtr readLen = k_START_LEN; true; readLen *= 4) {
        if (readLen > maxString) {
            readLen = maxString;
        }

        IntPtr bytes = readBytes(scratchBuf, readLen, offset);
        if (0 == bytes) {
            // We can't read.  Return "".

            stringLen = 0;
            break;
        }

        BSLS_ASSERT(bytes <= readLen);
        scratchBuf[bytes] = 0;
        stringLen = bsl::strlen(scratchBuf);
        if (stringLen < bytes || bytes < readLen || maxString == readLen) {
            break;
        }
    }

    return bdlb::String::copy(scratchBuf,
                              static_cast<int>(stringLen),
                              basicAllocator);
}

bsls::Types::UintPtr StackTraceResolver_FileHelper::readBytes(
                                                         void    *buf,
                                                         UintPtr  numBytes,
                                                         Offset   offset) const
{
    BSLS_ASSERT(buf);
    BSLS_ASSERT(offset >= 0);

    Offset seekDest = FilesystemUtil::seek(
                                        d_fd,
                                        offset,
                                        FilesystemUtil::e_SEEK_FROM_BEGINNING);
    if (seekDest != offset) {
        return 0;                                                     // RETURN
    }

    int res = FilesystemUtil::read(d_fd, buf, static_cast<int>(numBytes));
    return (res <= 0 ? 0 : res);
}

}  // close package namespace
}  // close enterprise namespace

#endif

// ----------------------------------------------------------------------------
// Copyright 2018 Bloomberg Finance L.P.
//
// 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.
// ----------------------------- END-OF-FILE ----------------------------------
<|endoftext|>


<commit_before>// For conditions of distribution and use, see copyright notice in license.txt

#include "StableHeaders.h"
#include "Poco/Base64Encoder.h"
#include <memory>
#include <iostream>

#include "NetworkEvents.h"
#include "RealXtend/RexProtocolMsgIDs.h"
#include "ProtocolModuleOpenSim.h"
#include "AssetEvents.h"
#include "AssetManager.h"
#include "AssetModule.h"
#include "RexAsset.h"
#include "RexTypes.h"
#include "HttpAssetProvider.h"
#include "AssetServiceInterface.h"

using namespace OpenSimProtocol;
using namespace RexTypes;

namespace Asset
{
	const Real HttpAssetProvider::DEFAULT_ASSET_TIMEOUT = 120.0;

	HttpAssetProvider::HttpAssetProvider(Foundation::Framework* framework) : framework_(framework)
	{
		asset_timeout_ = framework_->GetDefaultConfig().DeclareSetting("AssetSystem", "http_timeout", DEFAULT_ASSET_TIMEOUT);

		Foundation::EventManagerPtr event_manager = framework_->GetEventManager();

        // Assume that the asset manager has been instantiated at this point
        event_category_ = event_manager->QueryEventCategory("Asset");
        if (!event_category_)
        {
            AssetModule::LogWarning("Could not get event category for Asset events");
        }
	}

	HttpAssetProvider::~HttpAssetProvider()
	{
	}

	const std::string& HttpAssetProvider::Name()
	{
        static const std::string name("Http asset provider");
        return name;
	}

    bool HttpAssetProvider::IsValidId(const std::string& asset_url)
    {
	    // Differentiate between UDP & URL based requests
        //! \todo check URL validity in more sophisticated way, if desired
        if (asset_url.find("://") == std::string::npos)
            return false;
        else
            return true;
    }

	bool HttpAssetProvider::RequestAsset(const std::string& asset_id, const std::string& asset_type, request_tag_t tag)
	{
	    if (!IsValidId(asset_id))
	        return false;

        asset_type_t asset_type_int = GetAssetTypeFromTypeName(asset_type);
        if (asset_type_int < 0)
            return false;

		HttpAssetTransfer* transfer = GetTransfer(asset_id);
		if (transfer)
		{
			transfer->InsertTag(tag);
			return true;
		}

		HttpAssetTransfer* t = new HttpAssetTransfer();
		t->SetAssetId(asset_id);
		t->SetAssetType(asset_type_int);
		t->InsertTag(tag);
		asset_transfers_[asset_id] = HttpAssetTransferPtr(t);
		t->StartTransfer();
        return true;
	}

    bool HttpAssetProvider::InProgress(const std::string& asset_id)
    {
        HttpAssetTransfer* transfer = GetTransfer(asset_id);
        return (transfer != 0);
		return false;
    }

	Foundation::AssetPtr HttpAssetProvider::GetIncompleteAsset(const std::string& asset_id, const std::string& asset_type, uint received)
    {
        HttpAssetTransfer* transfer = GetTransfer(asset_id);

        if ((transfer) && (transfer->GetReceivedContinuous() >= received))
        {
            // Make new temporary asset for the incomplete data
            RexAsset* new_asset = new RexAsset(transfer->GetAssetId(), GetTypeNameFromAssetType(transfer->GetAssetType()));
            Foundation::AssetPtr asset_ptr(new_asset);

            RexAsset::AssetDataVector& data = new_asset->GetDataInternal();
            data.resize(transfer->GetReceivedContinuous());
            transfer->AssembleData(&data[0]);

            return asset_ptr;
        }

        return Foundation::AssetPtr();
    }

    bool HttpAssetProvider::QueryAssetStatus(const std::string& asset_id, uint& size, uint& received, uint& received_continuous)
    {
        HttpAssetTransfer* transfer = GetTransfer(asset_id);

        if (transfer)
        {
            size = transfer->GetSize();
            received = transfer->GetReceived();
            received_continuous = transfer->GetReceivedContinuous();

            return true;
        }

        return false;
    }

	void HttpAssetProvider::Update(f64 frametime)
	{
		HttpAssetTransferMap::iterator i = asset_transfers_.begin();
		while (i != asset_transfers_.end())
		{
			HttpAssetTransferPtr t = i->second;

			if (t->IsFailed())
			{
				std::stringstream buf;
				buf << "HttpAssetTransfer is failed for: ";
				buf << t->GetAssetId();
				AssetModule::LogError(buf.str());

				SendAssetCanceled(*t.get());

		        asset_transfers_.erase(i);
				return;
			}

			t->Update(frametime);
			SendAssetProgress(*t.get());

			if (t->Ready())
			{
				StoreAsset(*t.get());
		        asset_transfers_.erase(i);
				return;
			}
			else
			{
				t->AddTime(frametime);
				if (t->GetTime() > asset_timeout_)
				{
					std::stringstream buf;
					buf << "HttpAssetTransfer time out for: ";
					buf << t->GetAssetId();
					AssetModule::LogError(buf.str());

					SendAssetCanceled(*t.get());

					asset_transfers_.erase(i);
					return;
				}
			}
			i++;
		}
	}

    HttpAssetTransfer* HttpAssetProvider::GetTransfer(const std::string& asset_id)
    {
        HttpAssetTransferMap::iterator j = asset_transfers_.begin();
        while (j != asset_transfers_.end())
        {
            if (j->second->GetAssetId() == asset_id)
                return (j->second).get();
            ++j;
        }

        return 0;
    }

	void HttpAssetProvider::SendAssetProgress(HttpAssetTransfer& transfer)
    {
        Foundation::EventManagerPtr event_manager = framework_->GetEventManager();
        Events::AssetProgress event_data(transfer.GetAssetId(), GetTypeNameFromAssetType(transfer.GetAssetType()), transfer.GetSize(), transfer.GetReceived(), transfer.GetReceivedContinuous());
        event_manager->SendEvent(event_category_, Events::ASSET_PROGRESS, &event_data);
    }

    void HttpAssetProvider::SendAssetCanceled(HttpAssetTransfer& transfer)
    {
        Foundation::EventManagerPtr event_manager = framework_->GetEventManager();
        Events::AssetCanceled event_data(transfer.GetAssetId(), GetTypeNameFromAssetType(transfer.GetAssetType()));
        event_manager->SendEvent(event_category_, Events::ASSET_CANCELED, &event_data);
    }

    void HttpAssetProvider::StoreAsset(HttpAssetTransfer& transfer)
    {
        Foundation::ServiceManagerPtr service_manager = framework_->GetServiceManager();

        boost::shared_ptr<Foundation::AssetServiceInterface> asset_service = service_manager->GetService<Foundation::AssetServiceInterface>(Foundation::Service::ST_Asset).lock();
        if (asset_service)
        {
            const std::string& asset_id = transfer.GetAssetId();

            Foundation::AssetPtr new_asset = Foundation::AssetPtr(new RexAsset(asset_id, GetTypeNameFromAssetType(transfer.GetAssetType())));
            RexAsset::AssetDataVector& data = checked_static_cast<RexAsset*>(new_asset.get())->GetDataInternal();
            data.resize(transfer.GetReceived());
            transfer.AssembleData(&data[0]);

#ifdef unix
	    RexAssetMetadata* m = dynamic_cast<RexAssetMetadata*>(new_asset->GetMetadata());
#else
	    Foundation::AssetMetadataInterface* metadata = new_asset->GetMetadata();
	    RexAssetMetadata* m = static_cast<RexAssetMetadata*>(metadata);
#endif
	    m->DesesrializeFromJSON(transfer.GetAssetMetadata());

            asset_service->StoreAsset(new_asset);

            // Send asset ready event for each request tag
            Foundation::EventManagerPtr event_manager = framework_->GetEventManager();
            const RequestTagVector& tags = transfer.GetTags();
            for (uint i = 0; i < tags.size(); ++i)
            {
                Events::AssetReady event_data(new_asset->GetId(), new_asset->GetType(), new_asset, tags[i]);
                event_manager->SendEvent(event_category_, Events::ASSET_READY, &event_data);
            }
        }
        else
        {
            AssetModule::LogError("Asset service not found, could not store asset to cache");
        }
    }

	std::string HttpAssetProvider::SerializeToJSON(Foundation::AssetPtr asset) const
	{
#ifdef unix
		RexAssetMetadata* metadata = dynamic_cast<RexAssetMetadata*>(asset->GetMetadata());
#else
		RexAssetMetadata* metadata = static_cast<RexAssetMetadata*>(asset->GetMetadata());
#endif
		std::stringstream s;

		s << "{";
		s << "\"id\":\"" << metadata->GetId() << "\",";
		s << "\"name\":\"" << metadata->GetName() << "\",";
		s << "\"description\":\"" << metadata->GetDescription() << "\",";
		s << "\"type\":\"" << metadata->GetContentType() << "\",";
		if (metadata->IsTemporary())
			s << "\"temporary\":" << "true" << ",";
		else
			s << "\"temporary\":" << "false" << ",";
		s << "\"data\":\"";
		Poco::Base64Encoder encoder(s);

		encoder.write((char*)asset->GetData(),asset->GetSize());
		encoder.flush();
		encoder.close();
		s << "\"";
		s << "}";

		std::string t = s.str();

		return s.str();
	}

} // end of namespace
<commit_msg>change unix check to gcc check<commit_after>// For conditions of distribution and use, see copyright notice in license.txt

#include "StableHeaders.h"
#include "Poco/Base64Encoder.h"
#include <memory>
#include <iostream>

#include "NetworkEvents.h"
#include "RealXtend/RexProtocolMsgIDs.h"
#include "ProtocolModuleOpenSim.h"
#include "AssetEvents.h"
#include "AssetManager.h"
#include "AssetModule.h"
#include "RexAsset.h"
#include "RexTypes.h"
#include "HttpAssetProvider.h"
#include "AssetServiceInterface.h"

using namespace OpenSimProtocol;
using namespace RexTypes;

namespace Asset
{
	const Real HttpAssetProvider::DEFAULT_ASSET_TIMEOUT = 120.0;

	HttpAssetProvider::HttpAssetProvider(Foundation::Framework* framework) : framework_(framework)
	{
		asset_timeout_ = framework_->GetDefaultConfig().DeclareSetting("AssetSystem", "http_timeout", DEFAULT_ASSET_TIMEOUT);

		Foundation::EventManagerPtr event_manager = framework_->GetEventManager();

        // Assume that the asset manager has been instantiated at this point
        event_category_ = event_manager->QueryEventCategory("Asset");
        if (!event_category_)
        {
            AssetModule::LogWarning("Could not get event category for Asset events");
        }
	}

	HttpAssetProvider::~HttpAssetProvider()
	{
	}

	const std::string& HttpAssetProvider::Name()
	{
        static const std::string name("Http asset provider");
        return name;
	}

    bool HttpAssetProvider::IsValidId(const std::string& asset_url)
    {
	    // Differentiate between UDP & URL based requests
        //! \todo check URL validity in more sophisticated way, if desired
        if (asset_url.find("://") == std::string::npos)
            return false;
        else
            return true;
    }

	bool HttpAssetProvider::RequestAsset(const std::string& asset_id, const std::string& asset_type, request_tag_t tag)
	{
	    if (!IsValidId(asset_id))
	        return false;

        asset_type_t asset_type_int = GetAssetTypeFromTypeName(asset_type);
        if (asset_type_int < 0)
            return false;

		HttpAssetTransfer* transfer = GetTransfer(asset_id);
		if (transfer)
		{
			transfer->InsertTag(tag);
			return true;
		}

		HttpAssetTransfer* t = new HttpAssetTransfer();
		t->SetAssetId(asset_id);
		t->SetAssetType(asset_type_int);
		t->InsertTag(tag);
		asset_transfers_[asset_id] = HttpAssetTransferPtr(t);
		t->StartTransfer();
        return true;
	}

    bool HttpAssetProvider::InProgress(const std::string& asset_id)
    {
        HttpAssetTransfer* transfer = GetTransfer(asset_id);
        return (transfer != 0);
		return false;
    }

	Foundation::AssetPtr HttpAssetProvider::GetIncompleteAsset(const std::string& asset_id, const std::string& asset_type, uint received)
    {
        HttpAssetTransfer* transfer = GetTransfer(asset_id);

        if ((transfer) && (transfer->GetReceivedContinuous() >= received))
        {
            // Make new temporary asset for the incomplete data
            RexAsset* new_asset = new RexAsset(transfer->GetAssetId(), GetTypeNameFromAssetType(transfer->GetAssetType()));
            Foundation::AssetPtr asset_ptr(new_asset);

            RexAsset::AssetDataVector& data = new_asset->GetDataInternal();
            data.resize(transfer->GetReceivedContinuous());
            transfer->AssembleData(&data[0]);

            return asset_ptr;
        }

        return Foundation::AssetPtr();
    }

    bool HttpAssetProvider::QueryAssetStatus(const std::string& asset_id, uint& size, uint& received, uint& received_continuous)
    {
        HttpAssetTransfer* transfer = GetTransfer(asset_id);

        if (transfer)
        {
            size = transfer->GetSize();
            received = transfer->GetReceived();
            received_continuous = transfer->GetReceivedContinuous();

            return true;
        }

        return false;
    }

	void HttpAssetProvider::Update(f64 frametime)
	{
		HttpAssetTransferMap::iterator i = asset_transfers_.begin();
		while (i != asset_transfers_.end())
		{
			HttpAssetTransferPtr t = i->second;

			if (t->IsFailed())
			{
				std::stringstream buf;
				buf << "HttpAssetTransfer is failed for: ";
				buf << t->GetAssetId();
				AssetModule::LogError(buf.str());

				SendAssetCanceled(*t.get());

		        asset_transfers_.erase(i);
				return;
			}

			t->Update(frametime);
			SendAssetProgress(*t.get());

			if (t->Ready())
			{
				StoreAsset(*t.get());
		        asset_transfers_.erase(i);
				return;
			}
			else
			{
				t->AddTime(frametime);
				if (t->GetTime() > asset_timeout_)
				{
					std::stringstream buf;
					buf << "HttpAssetTransfer time out for: ";
					buf << t->GetAssetId();
					AssetModule::LogError(buf.str());

					SendAssetCanceled(*t.get());

					asset_transfers_.erase(i);
					return;
				}
			}
			i++;
		}
	}

    HttpAssetTransfer* HttpAssetProvider::GetTransfer(const std::string& asset_id)
    {
        HttpAssetTransferMap::iterator j = asset_transfers_.begin();
        while (j != asset_transfers_.end())
        {
            if (j->second->GetAssetId() == asset_id)
                return (j->second).get();
            ++j;
        }

        return 0;
    }

	void HttpAssetProvider::SendAssetProgress(HttpAssetTransfer& transfer)
    {
        Foundation::EventManagerPtr event_manager = framework_->GetEventManager();
        Events::AssetProgress event_data(transfer.GetAssetId(), GetTypeNameFromAssetType(transfer.GetAssetType()), transfer.GetSize(), transfer.GetReceived(), transfer.GetReceivedContinuous());
        event_manager->SendEvent(event_category_, Events::ASSET_PROGRESS, &event_data);
    }

    void HttpAssetProvider::SendAssetCanceled(HttpAssetTransfer& transfer)
    {
        Foundation::EventManagerPtr event_manager = framework_->GetEventManager();
        Events::AssetCanceled event_data(transfer.GetAssetId(), GetTypeNameFromAssetType(transfer.GetAssetType()));
        event_manager->SendEvent(event_category_, Events::ASSET_CANCELED, &event_data);
    }

    void HttpAssetProvider::StoreAsset(HttpAssetTransfer& transfer)
    {
        Foundation::ServiceManagerPtr service_manager = framework_->GetServiceManager();

        boost::shared_ptr<Foundation::AssetServiceInterface> asset_service = service_manager->GetService<Foundation::AssetServiceInterface>(Foundation::Service::ST_Asset).lock();
        if (asset_service)
        {
            const std::string& asset_id = transfer.GetAssetId();

            Foundation::AssetPtr new_asset = Foundation::AssetPtr(new RexAsset(asset_id, GetTypeNameFromAssetType(transfer.GetAssetType())));
            RexAsset::AssetDataVector& data = checked_static_cast<RexAsset*>(new_asset.get())->GetDataInternal();
            data.resize(transfer.GetReceived());
            transfer.AssembleData(&data[0]);

#if defined(__GNUC__)
	    RexAssetMetadata* m = dynamic_cast<RexAssetMetadata*>(new_asset->GetMetadata());
#else
	    Foundation::AssetMetadataInterface* metadata = new_asset->GetMetadata();
	    RexAssetMetadata* m = static_cast<RexAssetMetadata*>(metadata);
#endif
	    m->DesesrializeFromJSON(transfer.GetAssetMetadata());

            asset_service->StoreAsset(new_asset);

            // Send asset ready event for each request tag
            Foundation::EventManagerPtr event_manager = framework_->GetEventManager();
            const RequestTagVector& tags = transfer.GetTags();
            for (uint i = 0; i < tags.size(); ++i)
            {
                Events::AssetReady event_data(new_asset->GetId(), new_asset->GetType(), new_asset, tags[i]);
                event_manager->SendEvent(event_category_, Events::ASSET_READY, &event_data);
            }
        }
        else
        {
            AssetModule::LogError("Asset service not found, could not store asset to cache");
        }
    }

	std::string HttpAssetProvider::SerializeToJSON(Foundation::AssetPtr asset) const
	{
#if defined(__GNUC__)
		RexAssetMetadata* metadata = dynamic_cast<RexAssetMetadata*>(asset->GetMetadata());
#else
		RexAssetMetadata* metadata = static_cast<RexAssetMetadata*>(asset->GetMetadata());
#endif
		std::stringstream s;

		s << "{";
		s << "\"id\":\"" << metadata->GetId() << "\",";
		s << "\"name\":\"" << metadata->GetName() << "\",";
		s << "\"description\":\"" << metadata->GetDescription() << "\",";
		s << "\"type\":\"" << metadata->GetContentType() << "\",";
		if (metadata->IsTemporary())
			s << "\"temporary\":" << "true" << ",";
		else
			s << "\"temporary\":" << "false" << ",";
		s << "\"data\":\"";
		Poco::Base64Encoder encoder(s);

		encoder.write((char*)asset->GetData(),asset->GetSize());
		encoder.flush();
		encoder.close();
		s << "\"";
		s << "}";

		std::string t = s.str();

		return s.str();
	}

} // end of namespace
<|endoftext|>


<commit_before>#include "drake/systems/plants/RigidBodySystem.h"

#include <iostream>

#include <gtest/gtest.h>

#include "drake/systems/plants/RigidBodyFrame.h"
#include "drake/util/eigen_matrix_compare.h"
#include "drake/util/testUtil.h"

using std::make_shared;
using Drake::RigidBodySystem;
using Eigen::VectorXd;
using drake::util::MatrixCompareType;

namespace drake {
namespace systems {
namespace plants {
namespace {

std::string model_file_1, model_file_2;
std::shared_ptr<RigidBodyFrame> model_pose_in_world;

TEST(CompareRigidBodySystemsTest, TestAll) {
  auto r1 = make_shared<RigidBodySystem>();
  r1->addRobotFromFile(model_file_1, DrakeJoint::QUATERNION);

  auto r2 = make_shared<RigidBodySystem>();
  r2->addRobotFromFile(model_file_2, DrakeJoint::QUATERNION, model_pose_in_world);

  // for debugging:
  // r1->getRigidBodyTree()->drawKinematicTree("/tmp/r1.dot");
  // r2->getRigidBodyTree()->drawKinematicTree("/tmp/r2.dot");
  // I ran this at the console to see the output:
  // dot -Tpng -O /tmp/r1.dot; dot -Tpng -O /tmp/r2.dot; open /tmp/r1.dot.png
  // /tmp/r2.dot.png

  EXPECT_EQ(r1->getNumStates(), r2->getNumStates());
  EXPECT_EQ(r1->getNumInputs(), r2->getNumInputs());
  EXPECT_EQ(r1->getNumOutputs(), r2->getNumOutputs());

  for (int i = 0; i < 1000; i++) {
    double t = 0.0;
    VectorXd x = getInitialState(*r1);
    VectorXd u = VectorXd::Random(r1->getNumInputs());

    auto xdot1 = r1->dynamics(t, x, u);
    auto xdot2 = r2->dynamics(t, x, u);

    std::string explanation;
    EXPECT_TRUE(drake::util::CompareMatrices(
        xdot1, xdot2, 1e-8, MatrixCompareType::relative, &explanation))
        << "Model mismatch!" << std::endl
        << "  - initial state:" << std::endl
        << x << std::endl
        << "  - inputs (joint torques?):" << std::endl
        << u << std::endl
        << "  - xdot1:" << std::endl
        << xdot1.transpose() << std::endl
        << "  - xdot2:" << std::endl
        << xdot2.transpose() << std::endl
        << "  - error message:" << std::endl
        << explanation;
  }
}

}  // namespace
}  // namespace plants
}  // namespace systems
}  // namespace drake

int main(int argc, char **argv) {
  std::cout << "Running main() from compareRigidBodySystems.cpp" << std::endl;
  // ::testing::GTEST_FLAG(output) = "xml:hello.xml";

  std::cout << "Calling testing::InitGoogleTest(...)" << std::endl;
  testing::InitGoogleTest(&argc, argv);

  std::cout << "argc = " << argc << std::endl;
  if (argc < 3) {
    std::cerr << "Usage: " << argv[0]
              << " [options] full_path_to_robot1 full_path_to_robot2 x y z\n"
              << " The x y z parameters are optional and specify the position"
              << " of robot2 in the world, which is useful for URDF"
              << " models)" << std::endl;
    return 1;
  }

  drake::systems::plants::model_file_1 = argv[1];
  drake::systems::plants::model_file_2 = argv[2];

  if (argc > 3) {
    drake::systems::plants::model_pose_in_world =
        std::allocate_shared<RigidBodyFrame>(
            Eigen::aligned_allocator<RigidBodyFrame>(), "world",
            nullptr,  // not used since the robot is attached to the world
            Eigen::Vector3d(std::stod(argv[3]), std::stod(argv[4]),
                            std::stod(argv[5])),  // xyz of the car's root link
            Eigen::Vector3d(0, 0, 0));            // rpy of the car's root link
  } else {
    drake::systems::plants::model_pose_in_world =
        std::allocate_shared<RigidBodyFrame>(
            Eigen::aligned_allocator<RigidBodyFrame>(), "world", nullptr,
            Eigen::Isometry3d::Identity());
  }

  return RUN_ALL_TESTS();
}
<commit_msg>Manually fix some overly-long line(s).<commit_after>#include "drake/systems/plants/RigidBodySystem.h"

#include <iostream>

#include <gtest/gtest.h>

#include "drake/systems/plants/RigidBodyFrame.h"
#include "drake/util/eigen_matrix_compare.h"
#include "drake/util/testUtil.h"

using std::make_shared;
using Drake::RigidBodySystem;
using Eigen::VectorXd;
using drake::util::MatrixCompareType;

namespace drake {
namespace systems {
namespace plants {
namespace {

std::string model_file_1, model_file_2;
std::shared_ptr<RigidBodyFrame> model_pose_in_world;

TEST(CompareRigidBodySystemsTest, TestAll) {
  auto r1 = make_shared<RigidBodySystem>();
  r1->addRobotFromFile(model_file_1, DrakeJoint::QUATERNION);

  auto r2 = make_shared<RigidBodySystem>();
  r2->addRobotFromFile(model_file_2, DrakeJoint::QUATERNION,
                       model_pose_in_world);

  // for debugging:
  // r1->getRigidBodyTree()->drawKinematicTree("/tmp/r1.dot");
  // r2->getRigidBodyTree()->drawKinematicTree("/tmp/r2.dot");
  // I ran this at the console to see the output:
  // dot -Tpng -O /tmp/r1.dot; dot -Tpng -O /tmp/r2.dot; open /tmp/r1.dot.png
  // /tmp/r2.dot.png

  EXPECT_EQ(r1->getNumStates(), r2->getNumStates());
  EXPECT_EQ(r1->getNumInputs(), r2->getNumInputs());
  EXPECT_EQ(r1->getNumOutputs(), r2->getNumOutputs());

  for (int i = 0; i < 1000; i++) {
    double t = 0.0;
    VectorXd x = getInitialState(*r1);
    VectorXd u = VectorXd::Random(r1->getNumInputs());

    auto xdot1 = r1->dynamics(t, x, u);
    auto xdot2 = r2->dynamics(t, x, u);

    std::string explanation;
    EXPECT_TRUE(drake::util::CompareMatrices(
        xdot1, xdot2, 1e-8, MatrixCompareType::relative, &explanation))
        << "Model mismatch!" << std::endl
        << "  - initial state:" << std::endl
        << x << std::endl
        << "  - inputs (joint torques?):" << std::endl
        << u << std::endl
        << "  - xdot1:" << std::endl
        << xdot1.transpose() << std::endl
        << "  - xdot2:" << std::endl
        << xdot2.transpose() << std::endl
        << "  - error message:" << std::endl
        << explanation;
  }
}

}  // namespace
}  // namespace plants
}  // namespace systems
}  // namespace drake

int main(int argc, char **argv) {
  std::cout << "Running main() from compareRigidBodySystems.cpp" << std::endl;
  // ::testing::GTEST_FLAG(output) = "xml:hello.xml";

  std::cout << "Calling testing::InitGoogleTest(...)" << std::endl;
  testing::InitGoogleTest(&argc, argv);

  std::cout << "argc = " << argc << std::endl;
  if (argc < 3) {
    std::cerr << "Usage: " << argv[0]
              << " [options] full_path_to_robot1 full_path_to_robot2 x y z\n"
              << " The x y z parameters are optional and specify the position"
              << " of robot2 in the world, which is useful for URDF"
              << " models)" << std::endl;
    return 1;
  }

  drake::systems::plants::model_file_1 = argv[1];
  drake::systems::plants::model_file_2 = argv[2];

  if (argc > 3) {
    drake::systems::plants::model_pose_in_world =
        std::allocate_shared<RigidBodyFrame>(
            Eigen::aligned_allocator<RigidBodyFrame>(), "world",
            nullptr,  // not used since the robot is attached to the world
            Eigen::Vector3d(std::stod(argv[3]), std::stod(argv[4]),
                            std::stod(argv[5])),  // xyz of the car's root link
            Eigen::Vector3d(0, 0, 0));            // rpy of the car's root link
  } else {
    drake::systems::plants::model_pose_in_world =
        std::allocate_shared<RigidBodyFrame>(
            Eigen::aligned_allocator<RigidBodyFrame>(), "world", nullptr,
            Eigen::Isometry3d::Identity());
  }

  return RUN_ALL_TESTS();
}
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2016-present, Facebook, Inc.
 *
 * 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 "caffe2/core/typeid.h"
#include "caffe2/core/types.h"
#include <gtest/gtest.h>

namespace caffe2 {
namespace {

class TypeMetaTestFoo {};
class TypeMetaTestBar {};
}

CAFFE_KNOWN_TYPE(TypeMetaTestFoo);
CAFFE_KNOWN_TYPE(TypeMetaTestBar);

namespace {

TEST(TypeMetaTest, TypeMetaStatic) {
  EXPECT_EQ(TypeMeta::ItemSize<int>(), sizeof(int));
  EXPECT_EQ(TypeMeta::ItemSize<float>(), sizeof(float));
  EXPECT_EQ(TypeMeta::ItemSize<TypeMetaTestFoo>(), sizeof(TypeMetaTestFoo));
  EXPECT_EQ(TypeMeta::ItemSize<TypeMetaTestBar>(), sizeof(TypeMetaTestBar));
  EXPECT_NE(TypeMeta::Id<int>(), TypeMeta::Id<float>());
  EXPECT_NE(TypeMeta::Id<int>(), TypeMeta::Id<TypeMetaTestFoo>());
  EXPECT_NE(TypeMeta::Id<TypeMetaTestFoo>(), TypeMeta::Id<TypeMetaTestBar>());
  EXPECT_EQ(TypeMeta::Id<int>(), TypeMeta::Id<int>());
  EXPECT_EQ(TypeMeta::Id<TypeMetaTestFoo>(), TypeMeta::Id<TypeMetaTestFoo>());
}

TEST(TypeMetaTest, Names) {
  TypeMeta null_meta;
  EXPECT_TRUE(string(null_meta.name()) == "nullptr (uninitialized)");
  TypeMeta int_meta = TypeMeta::Make<int>();
  TypeMeta string_meta = TypeMeta::Make<string>();
  EXPECT_TRUE(string(int_meta.name()) == "int");
#ifdef __GXX_RTTI
  // For string, we should have a demangled name.
  EXPECT_TRUE(
      string(string_meta.name()) != typeid(string).name());
  EXPECT_TRUE(
      string(string_meta.name()) == Demangle(typeid(string).name()));
#endif  // __GXX_RTTI
}

TEST(TypeMetaTest, TypeMeta) {
  TypeMeta int_meta = TypeMeta::Make<int>();
  TypeMeta float_meta = TypeMeta::Make<float>();
  TypeMeta foo_meta = TypeMeta::Make<TypeMetaTestFoo>();
  TypeMeta bar_meta = TypeMeta::Make<TypeMetaTestBar>();

  TypeMeta another_int_meta = TypeMeta::Make<int>();
  TypeMeta another_foo_meta = TypeMeta::Make<TypeMetaTestFoo>();

  EXPECT_EQ(int_meta, another_int_meta);
  EXPECT_EQ(foo_meta, another_foo_meta);
  EXPECT_NE(int_meta, float_meta);
  EXPECT_NE(int_meta, foo_meta);
  EXPECT_NE(foo_meta, bar_meta);
  EXPECT_TRUE(int_meta.Match<int>());
  EXPECT_TRUE(foo_meta.Match<TypeMetaTestFoo>());
  EXPECT_FALSE(int_meta.Match<float>());
  EXPECT_FALSE(int_meta.Match<TypeMetaTestFoo>());
  EXPECT_FALSE(foo_meta.Match<int>());
  EXPECT_FALSE(foo_meta.Match<TypeMetaTestBar>());
  EXPECT_EQ(int_meta.id(), TypeMeta::Id<int>());
  EXPECT_EQ(float_meta.id(), TypeMeta::Id<float>());
  EXPECT_EQ(foo_meta.id(), TypeMeta::Id<TypeMetaTestFoo>());
  EXPECT_EQ(bar_meta.id(), TypeMeta::Id<TypeMetaTestBar>());
  EXPECT_EQ(int_meta.itemsize(), TypeMeta::ItemSize<int>());
  EXPECT_EQ(float_meta.itemsize(), TypeMeta::ItemSize<float>());
  EXPECT_EQ(foo_meta.itemsize(), TypeMeta::ItemSize<TypeMetaTestFoo>());
  EXPECT_EQ(bar_meta.itemsize(), TypeMeta::ItemSize<TypeMetaTestBar>());
  EXPECT_STREQ(int_meta.name(), "int");
  EXPECT_STREQ(float_meta.name(), "float");
#ifdef __GXX_RTTI
  EXPECT_NE(
      std::string(foo_meta.name()).find("TypeMetaTestFoo"), std::string::npos);
  EXPECT_NE(
      std::string(bar_meta.name()).find("TypeMetaTestBar"), std::string::npos);
#endif
}

class ClassAllowAssignment {
 public:
  ClassAllowAssignment() : x(42) {}
  ClassAllowAssignment(const ClassAllowAssignment& src) : x(src.x) {}
  ClassAllowAssignment& operator=(const ClassAllowAssignment& src) = default;
  int x;
};

class ClassNoAssignment {
 public:
  ClassNoAssignment() : x(42) {}
  ClassNoAssignment(const ClassNoAssignment& src) = delete;
  ClassNoAssignment& operator=(const ClassNoAssignment& src) = delete;
  int x;
};
}

CAFFE_KNOWN_TYPE(ClassAllowAssignment);
CAFFE_KNOWN_TYPE(ClassNoAssignment);

namespace {

TEST(TypeMetaTest, CtorDtorAndCopy) {
  TypeMeta fundamental_meta = TypeMeta::Make<int>();
  EXPECT_EQ(fundamental_meta.ctor(), nullptr);
  EXPECT_EQ(fundamental_meta.dtor(), nullptr);
  EXPECT_EQ(fundamental_meta.copy(), nullptr);

  TypeMeta meta_a = TypeMeta::Make<ClassAllowAssignment>();
  EXPECT_TRUE(meta_a.ctor() != nullptr);
  EXPECT_TRUE(meta_a.dtor() != nullptr);
  EXPECT_TRUE(meta_a.copy() != nullptr);
  ClassAllowAssignment src;
  src.x = 10;
  ClassAllowAssignment dst;
  EXPECT_EQ(dst.x, 42);
  meta_a.copy()(&src, &dst, 1);
  EXPECT_EQ(dst.x, 10);

  TypeMeta meta_b = TypeMeta::Make<ClassNoAssignment>();

  EXPECT_TRUE(meta_b.ctor() != nullptr);
  EXPECT_TRUE(meta_b.dtor() != nullptr);
#ifndef __clang__
  // gtest seems to have some problem with function pointers and
  // clang right now... Disabling it.
  // TODO: figure out the real cause.
  EXPECT_EQ(meta_b.copy(),
            &(TypeMeta::_CopyNotAllowed<ClassNoAssignment>));
#endif
}

TEST(TypeMetaTest, Float16IsNotUint16) {
  EXPECT_NE(TypeMeta::Id<uint16_t>(), TypeMeta::Id<float16>());
}

}  // namespace
}  // namespace caffe2
<commit_msg>fix Android typeid_test.cc build error<commit_after>/**
 * Copyright (c) 2016-present, Facebook, Inc.
 *
 * 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 "caffe2/core/typeid.h"
#include "caffe2/core/types.h"
#include <gtest/gtest.h>

namespace caffe2 {
namespace {

class TypeMetaTestFoo {};
class TypeMetaTestBar {};
}

CAFFE_KNOWN_TYPE(TypeMetaTestFoo);
CAFFE_KNOWN_TYPE(TypeMetaTestBar);

namespace {

TEST(TypeMetaTest, TypeMetaStatic) {
  EXPECT_EQ(TypeMeta::ItemSize<int>(), sizeof(int));
  EXPECT_EQ(TypeMeta::ItemSize<float>(), sizeof(float));
  EXPECT_EQ(TypeMeta::ItemSize<TypeMetaTestFoo>(), sizeof(TypeMetaTestFoo));
  EXPECT_EQ(TypeMeta::ItemSize<TypeMetaTestBar>(), sizeof(TypeMetaTestBar));
  EXPECT_NE(TypeMeta::Id<int>(), TypeMeta::Id<float>());
  EXPECT_NE(TypeMeta::Id<int>(), TypeMeta::Id<TypeMetaTestFoo>());
  EXPECT_NE(TypeMeta::Id<TypeMetaTestFoo>(), TypeMeta::Id<TypeMetaTestBar>());
  EXPECT_EQ(TypeMeta::Id<int>(), TypeMeta::Id<int>());
  EXPECT_EQ(TypeMeta::Id<TypeMetaTestFoo>(), TypeMeta::Id<TypeMetaTestFoo>());
}

TEST(TypeMetaTest, Names) {
  TypeMeta null_meta;
  EXPECT_TRUE(string(null_meta.name()) == "nullptr (uninitialized)");
  TypeMeta int_meta = TypeMeta::Make<int>();
  EXPECT_TRUE(string(int_meta.name()) == "int");
#ifdef __GXX_RTTI
  TypeMeta string_meta = TypeMeta::Make<string>();
  // For string, we should have a demangled name.
  EXPECT_TRUE(
      string(string_meta.name()) != typeid(string).name());
  EXPECT_TRUE(
      string(string_meta.name()) == Demangle(typeid(string).name()));
#endif  // __GXX_RTTI
}

TEST(TypeMetaTest, TypeMeta) {
  TypeMeta int_meta = TypeMeta::Make<int>();
  TypeMeta float_meta = TypeMeta::Make<float>();
  TypeMeta foo_meta = TypeMeta::Make<TypeMetaTestFoo>();
  TypeMeta bar_meta = TypeMeta::Make<TypeMetaTestBar>();

  TypeMeta another_int_meta = TypeMeta::Make<int>();
  TypeMeta another_foo_meta = TypeMeta::Make<TypeMetaTestFoo>();

  EXPECT_EQ(int_meta, another_int_meta);
  EXPECT_EQ(foo_meta, another_foo_meta);
  EXPECT_NE(int_meta, float_meta);
  EXPECT_NE(int_meta, foo_meta);
  EXPECT_NE(foo_meta, bar_meta);
  EXPECT_TRUE(int_meta.Match<int>());
  EXPECT_TRUE(foo_meta.Match<TypeMetaTestFoo>());
  EXPECT_FALSE(int_meta.Match<float>());
  EXPECT_FALSE(int_meta.Match<TypeMetaTestFoo>());
  EXPECT_FALSE(foo_meta.Match<int>());
  EXPECT_FALSE(foo_meta.Match<TypeMetaTestBar>());
  EXPECT_EQ(int_meta.id(), TypeMeta::Id<int>());
  EXPECT_EQ(float_meta.id(), TypeMeta::Id<float>());
  EXPECT_EQ(foo_meta.id(), TypeMeta::Id<TypeMetaTestFoo>());
  EXPECT_EQ(bar_meta.id(), TypeMeta::Id<TypeMetaTestBar>());
  EXPECT_EQ(int_meta.itemsize(), TypeMeta::ItemSize<int>());
  EXPECT_EQ(float_meta.itemsize(), TypeMeta::ItemSize<float>());
  EXPECT_EQ(foo_meta.itemsize(), TypeMeta::ItemSize<TypeMetaTestFoo>());
  EXPECT_EQ(bar_meta.itemsize(), TypeMeta::ItemSize<TypeMetaTestBar>());
  EXPECT_STREQ(int_meta.name(), "int");
  EXPECT_STREQ(float_meta.name(), "float");
#ifdef __GXX_RTTI
  EXPECT_NE(
      std::string(foo_meta.name()).find("TypeMetaTestFoo"), std::string::npos);
  EXPECT_NE(
      std::string(bar_meta.name()).find("TypeMetaTestBar"), std::string::npos);
#endif
}

class ClassAllowAssignment {
 public:
  ClassAllowAssignment() : x(42) {}
  ClassAllowAssignment(const ClassAllowAssignment& src) : x(src.x) {}
  ClassAllowAssignment& operator=(const ClassAllowAssignment& src) = default;
  int x;
};

class ClassNoAssignment {
 public:
  ClassNoAssignment() : x(42) {}
  ClassNoAssignment(const ClassNoAssignment& src) = delete;
  ClassNoAssignment& operator=(const ClassNoAssignment& src) = delete;
  int x;
};
}

CAFFE_KNOWN_TYPE(ClassAllowAssignment);
CAFFE_KNOWN_TYPE(ClassNoAssignment);

namespace {

TEST(TypeMetaTest, CtorDtorAndCopy) {
  TypeMeta fundamental_meta = TypeMeta::Make<int>();
  EXPECT_EQ(fundamental_meta.ctor(), nullptr);
  EXPECT_EQ(fundamental_meta.dtor(), nullptr);
  EXPECT_EQ(fundamental_meta.copy(), nullptr);

  TypeMeta meta_a = TypeMeta::Make<ClassAllowAssignment>();
  EXPECT_TRUE(meta_a.ctor() != nullptr);
  EXPECT_TRUE(meta_a.dtor() != nullptr);
  EXPECT_TRUE(meta_a.copy() != nullptr);
  ClassAllowAssignment src;
  src.x = 10;
  ClassAllowAssignment dst;
  EXPECT_EQ(dst.x, 42);
  meta_a.copy()(&src, &dst, 1);
  EXPECT_EQ(dst.x, 10);

  TypeMeta meta_b = TypeMeta::Make<ClassNoAssignment>();

  EXPECT_TRUE(meta_b.ctor() != nullptr);
  EXPECT_TRUE(meta_b.dtor() != nullptr);
#ifndef __clang__
  // gtest seems to have some problem with function pointers and
  // clang right now... Disabling it.
  // TODO: figure out the real cause.
  EXPECT_EQ(meta_b.copy(),
            &(TypeMeta::_CopyNotAllowed<ClassNoAssignment>));
#endif
}

TEST(TypeMetaTest, Float16IsNotUint16) {
  EXPECT_NE(TypeMeta::Id<uint16_t>(), TypeMeta::Id<float16>());
}

}  // namespace
}  // namespace caffe2
<|endoftext|>


<commit_before>//===- RWMutex.cpp - Reader/Writer Mutual Exclusion Lock --------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the llvm::sys::RWMutex class.
//
//===----------------------------------------------------------------------===//

#include "llvm/Support/Allocator.h"
#include "llvm/Support/RWMutex.h"
#include "llvm/Config/llvm-config.h"

//===----------------------------------------------------------------------===//
//=== WARNING: Implementation here must contain only TRULY operating system
//===          independent code.
//===----------------------------------------------------------------------===//

#if !defined(LLVM_ENABLE_THREADS) || LLVM_ENABLE_THREADS == 0
// Define all methods as no-ops if threading is explicitly disabled

using namespace llvm;
using namespace sys;

RWMutexImpl::RWMutexImpl() = default;
RWMutexImpl::~RWMutexImpl() = default;

bool RWMutexImpl::reader_acquire() { return true; }
bool RWMutexImpl::reader_release() { return true; }
bool RWMutexImpl::writer_acquire() { return true; }
bool RWMutexImpl::writer_release() { return true; }

#else

#if defined(HAVE_PTHREAD_H) && defined(HAVE_PTHREAD_RWLOCK_INIT)

#include <cassert>
#include <cstdlib>
#include <pthread.h>

using namespace llvm;
using namespace sys;

// Construct a RWMutex using pthread calls
RWMutexImpl::RWMutexImpl()
{
  // Declare the pthread_rwlock data structures
  pthread_rwlock_t* rwlock =
    static_cast<pthread_rwlock_t*>(safe_malloc(sizeof(pthread_rwlock_t)));

#ifdef __APPLE__
  // Workaround a bug/mis-feature in Darwin's pthread_rwlock_init.
  bzero(rwlock, sizeof(pthread_rwlock_t));
#endif

  // Initialize the rwlock
  int errorcode = pthread_rwlock_init(rwlock, nullptr);
  (void)errorcode;
  assert(errorcode == 0);

  // Assign the data member
  data_ = rwlock;
}

// Destruct a RWMutex
RWMutexImpl::~RWMutexImpl()
{
  pthread_rwlock_t* rwlock = static_cast<pthread_rwlock_t*>(data_);
  assert(rwlock != nullptr);
  pthread_rwlock_destroy(rwlock);
  free(rwlock);
}

bool
RWMutexImpl::reader_acquire()
{
  pthread_rwlock_t* rwlock = static_cast<pthread_rwlock_t*>(data_);
  assert(rwlock != nullptr);

  int errorcode = pthread_rwlock_rdlock(rwlock);
  return errorcode == 0;
}

bool
RWMutexImpl::reader_release()
{
  pthread_rwlock_t* rwlock = static_cast<pthread_rwlock_t*>(data_);
  assert(rwlock != nullptr);

  int errorcode = pthread_rwlock_unlock(rwlock);
  return errorcode == 0;
}

bool
RWMutexImpl::writer_acquire()
{
  pthread_rwlock_t* rwlock = static_cast<pthread_rwlock_t*>(data_);
  assert(rwlock != nullptr);

  int errorcode = pthread_rwlock_wrlock(rwlock);
  return errorcode == 0;
}

bool
RWMutexImpl::writer_release()
{
  pthread_rwlock_t* rwlock = static_cast<pthread_rwlock_t*>(data_);
  assert(rwlock != nullptr);

  int errorcode = pthread_rwlock_unlock(rwlock);
  return errorcode == 0;
}

#elif defined(LLVM_ON_UNIX)
#include "Unix/RWMutex.inc"
#elif defined( _WIN32)
#include "Windows/RWMutex.inc"
#else
#warning Neither LLVM_ON_UNIX nor _WIN32 was set in Support/Mutex.cpp
#endif
#endif
<commit_msg>Fix include of config.h that was incorrectly changed in r331184<commit_after>//===- RWMutex.cpp - Reader/Writer Mutual Exclusion Lock --------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the llvm::sys::RWMutex class.
//
//===----------------------------------------------------------------------===//

#include "llvm/Support/Allocator.h"
#include "llvm/Support/RWMutex.h"
#include "llvm/Config/config.h"

//===----------------------------------------------------------------------===//
//=== WARNING: Implementation here must contain only TRULY operating system
//===          independent code.
//===----------------------------------------------------------------------===//

#if !defined(LLVM_ENABLE_THREADS) || LLVM_ENABLE_THREADS == 0
// Define all methods as no-ops if threading is explicitly disabled

using namespace llvm;
using namespace sys;

RWMutexImpl::RWMutexImpl() = default;
RWMutexImpl::~RWMutexImpl() = default;

bool RWMutexImpl::reader_acquire() { return true; }
bool RWMutexImpl::reader_release() { return true; }
bool RWMutexImpl::writer_acquire() { return true; }
bool RWMutexImpl::writer_release() { return true; }

#else

#if defined(HAVE_PTHREAD_H) && defined(HAVE_PTHREAD_RWLOCK_INIT)

#include <cassert>
#include <cstdlib>
#include <pthread.h>

using namespace llvm;
using namespace sys;

// Construct a RWMutex using pthread calls
RWMutexImpl::RWMutexImpl()
{
  // Declare the pthread_rwlock data structures
  pthread_rwlock_t* rwlock =
    static_cast<pthread_rwlock_t*>(safe_malloc(sizeof(pthread_rwlock_t)));

#ifdef __APPLE__
  // Workaround a bug/mis-feature in Darwin's pthread_rwlock_init.
  bzero(rwlock, sizeof(pthread_rwlock_t));
#endif

  // Initialize the rwlock
  int errorcode = pthread_rwlock_init(rwlock, nullptr);
  (void)errorcode;
  assert(errorcode == 0);

  // Assign the data member
  data_ = rwlock;
}

// Destruct a RWMutex
RWMutexImpl::~RWMutexImpl()
{
  pthread_rwlock_t* rwlock = static_cast<pthread_rwlock_t*>(data_);
  assert(rwlock != nullptr);
  pthread_rwlock_destroy(rwlock);
  free(rwlock);
}

bool
RWMutexImpl::reader_acquire()
{
  pthread_rwlock_t* rwlock = static_cast<pthread_rwlock_t*>(data_);
  assert(rwlock != nullptr);

  int errorcode = pthread_rwlock_rdlock(rwlock);
  return errorcode == 0;
}

bool
RWMutexImpl::reader_release()
{
  pthread_rwlock_t* rwlock = static_cast<pthread_rwlock_t*>(data_);
  assert(rwlock != nullptr);

  int errorcode = pthread_rwlock_unlock(rwlock);
  return errorcode == 0;
}

bool
RWMutexImpl::writer_acquire()
{
  pthread_rwlock_t* rwlock = static_cast<pthread_rwlock_t*>(data_);
  assert(rwlock != nullptr);

  int errorcode = pthread_rwlock_wrlock(rwlock);
  return errorcode == 0;
}

bool
RWMutexImpl::writer_release()
{
  pthread_rwlock_t* rwlock = static_cast<pthread_rwlock_t*>(data_);
  assert(rwlock != nullptr);

  int errorcode = pthread_rwlock_unlock(rwlock);
  return errorcode == 0;
}

#elif defined(LLVM_ON_UNIX)
#include "Unix/RWMutex.inc"
#elif defined( _WIN32)
#include "Windows/RWMutex.inc"
#else
#warning Neither LLVM_ON_UNIX nor _WIN32 was set in Support/Mutex.cpp
#endif
#endif
<|endoftext|>