<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://www.qtsoftware.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtTest/QtTest>
#include <QByteArray>

#include <QtScript>

//TESTED_CLASS=
//TESTED_FILES=

// Uncomment the following define to have the autotest generate
// addExpectedFailure() code for all the tests that fail.
// This is useful when a whole new test (sub)suite is added.
// The code is stored in addexpectedfailures.cpp.
// Paste the contents into this file after the existing
// addExpectedFailure() calls.

//#define GENERATE_ADDEXPECTEDFAILURE_CODE

static QString readFile(const QString &filename)
{
    QFile file(filename);
    if (!file.open(QFile::ReadOnly))
        return QString();
    QTextStream stream(&file);
    stream.setCodec("UTF-8");
    return stream.readAll();
}

static void appendCString(QVector<char> *v, const char *s)
{
    char c;
    do {
        c = *(s++);
        *v << c;
    } while (c != '\0');
}

struct ExpectedFailure
{
    ExpectedFailure(const QString &name, const QString &act,
                    const QString &exp, const QString &msg)
        : testName(name), actual(act), expected(exp), message(msg)
        { }

    QString testName;
    QString actual;
    QString expected;
    QString message;
};

class tst_Suite : public QObject
{

public:
    tst_Suite();
    virtual ~tst_Suite();

    static QMetaObject staticMetaObject;
    virtual const QMetaObject *metaObject() const;
    virtual void *qt_metacast(const char *);
    virtual int qt_metacall(QMetaObject::Call, int, void **argv);

private:
    void addExpectedFailure(const QString &testName, const QString &actual,
                            const QString &expected, const QString &message);
    bool isExpectedFailure(const QString &testName, const QString &actual,
                           const QString &expected, QString *message) const;
    void addTestExclusion(const QString &testName, const QString &message);
    void addTestExclusion(const QRegExp &rx, const QString &message);
    bool isExcludedTest(const QString &testName, QString *message) const;

    QDir testsDir;
    QStringList testNames;
    QList<ExpectedFailure> expectedFailures;
    QList<QPair<QRegExp, QString> > testExclusions;
    QString mjsunitContents;
#ifdef GENERATE_ADDEXPECTEDFAILURE_CODE
    QString generatedAddExpectedFailureCode;
#endif
};

QMetaObject tst_Suite::staticMetaObject;

Q_GLOBAL_STATIC(QVector<uint>, qt_meta_data_tst_Suite)
Q_GLOBAL_STATIC(QVector<char>, qt_meta_stringdata_tst_Suite)

const QMetaObject *tst_Suite::metaObject() const
{
    return &staticMetaObject;
}

void *tst_Suite::qt_metacast(const char *_clname)
{
    if (!_clname) return 0;
    if (!strcmp(_clname, qt_meta_stringdata_tst_Suite()->constData()))
        return static_cast<void*>(const_cast<tst_Suite*>(this));
    return QObject::qt_metacast(_clname);
}

static QScriptValue qscript_fail(QScriptContext *ctx, QScriptEngine *eng)
{
    QScriptValue realFail = ctx->callee().data();
    Q_ASSERT(realFail.isFunction());
    QScriptValue ret = realFail.call(ctx->thisObject(), ctx->argumentsObject());
    Q_ASSERT(eng->hasUncaughtException());
    ret.setProperty("expected", ctx->argument(0));
    ret.setProperty("actual", ctx->argument(1));
    QScriptContextInfo info(ctx->parentContext()->parentContext());
    ret.setProperty("lineNumber", info.lineNumber());
    return ret;
}

int tst_Suite::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = QObject::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;
    if (_c == QMetaObject::InvokeMetaMethod) {
        QString name = testNames.at(_id);
        QString path = testsDir.absoluteFilePath(name + ".js");
        QString excludeMessage;
        if (isExcludedTest(name, &excludeMessage)) {
            QTest::qSkip(excludeMessage.toLatin1(), QTest::SkipAll, path.toLatin1(), -1);
        } else {
            QScriptEngine engine;
            engine.evaluate(mjsunitContents).toString();
            if (engine.hasUncaughtException()) {
                QStringList bt = engine.uncaughtExceptionBacktrace();
                QString err = engine.uncaughtException().toString();
                qWarning("%s\n%s", qPrintable(err), qPrintable(bt.join("\n")));
            } else {
                QScriptValue fakeFail = engine.newFunction(qscript_fail);
                fakeFail.setData(engine.globalObject().property("fail"));
                engine.globalObject().setProperty("fail", fakeFail);
                QString contents = readFile(path);
                QScriptValue ret = engine.evaluate(contents);
                if (engine.hasUncaughtException()) {
                    if (!ret.isError()) {
                        Q_ASSERT(ret.instanceOf(engine.globalObject().property("MjsUnitAssertionError")));
                        QString actual = ret.property("actual").toString();
                        QString expected = ret.property("expected").toString();
                        int lineNumber = ret.property("lineNumber").toInt32();
                        QString failMessage;
                        if (isExpectedFailure(name, actual, expected, &failMessage)) {
                            QTest::qExpectFail("", failMessage.toLatin1(),
                                               QTest::Continue, path.toLatin1(),
                                               lineNumber);
                        }
#ifdef GENERATE_ADDEXPECTEDFAILURE_CODE
                        else {
                            generatedAddExpectedFailureCode.append(
                                "    addExpectedFailure(\"" + name
                                + "\", \"" + actual + "\", \"" + expected
                                + "\", willFixInNextReleaseMessage);\n");
                        }
#endif
                        QTest::qCompare(actual, expected, "actual", "expect",
                                        path.toLatin1(), lineNumber);
                    } else {
                        int lineNumber = ret.property("lineNumber").toInt32();
                        QTest::qExpectFail("", ret.toString().toLatin1(),
                                           QTest::Continue, path.toLatin1(), lineNumber);
                        QTest::qVerify(false, ret.toString().toLatin1(), "", path.toLatin1(), lineNumber);
                    }
                }
            }
        }
        _id -= testNames.size();
    }
    return _id;
}

tst_Suite::tst_Suite()
{
    testsDir = QDir(SRCDIR);
    bool testsFound = testsDir.cd("tests");
    if (!testsFound) {
        qWarning("*** no tests/ dir!");
    } else {
        if (!testsDir.exists("mjsunit.js"))
            qWarning("*** no tests/mjsunit.js file!");
        else {
            mjsunitContents = readFile(testsDir.absoluteFilePath("mjsunit.js"));
            if (mjsunitContents.isEmpty())
                qWarning("*** tests/mjsunit.js is empty!");
        }
    }
    QString willFixInNextReleaseMessage = QString::fromLatin1("Will fix in next release");
    addExpectedFailure("apply", "morundefineder", "morseper", willFixInNextReleaseMessage);
    addExpectedFailure("arguments-enum", "2", "0", willFixInNextReleaseMessage);
    addExpectedFailure("array-concat", "undefined", "baz", willFixInNextReleaseMessage);
    addExpectedFailure("array-functions-prototype", "undefined", "one", willFixInNextReleaseMessage);
    addExpectedFailure("const-redecl", "undefined", "TypeError", willFixInNextReleaseMessage);
    addExpectedFailure("const", "2", "1", willFixInNextReleaseMessage);
    addExpectedFailure("declare-locally", "undefined", "42", willFixInNextReleaseMessage);
    addExpectedFailure("delay-syntax-error", "false", "true", willFixInNextReleaseMessage);
    addExpectedFailure("delete-vars-from-eval", "false", "true", willFixInNextReleaseMessage);
    addExpectedFailure("dont-enum-array-holes", "4", "2", willFixInNextReleaseMessage);
    addExpectedFailure("fun-as-prototype", "undefined", "Funky", willFixInNextReleaseMessage);
    addExpectedFailure("fun_name", "function(){}", "functionanonymous(){}", willFixInNextReleaseMessage);
    addExpectedFailure("function-caller", "undefined", "function f(match) {\n    g(match);\n}", willFixInNextReleaseMessage);
    addExpectedFailure("global-const-var-conflicts", "false", "true", willFixInNextReleaseMessage);
    addExpectedFailure("length", "3", "1", willFixInNextReleaseMessage);
    addExpectedFailure("math-min-max", "-Infinity", "Infinity", willFixInNextReleaseMessage);
    addExpectedFailure("newline-in-string", "asdf\n\nasdf\n?asdf\n\tasdf\n\\\n\n", "asdf\nasdf?asdf\tasdf\\", willFixInNextReleaseMessage);
    addExpectedFailure("number-tostring", "1111111111111111081984.00000000", "1.1111111111111111e+21", willFixInNextReleaseMessage);
    addExpectedFailure("parse-int-float", "false", "true", willFixInNextReleaseMessage);
    addExpectedFailure("regexp-multiline-stack-trace", "false", "true", willFixInNextReleaseMessage);
    addExpectedFailure("regexp-multiline", "false", "true", willFixInNextReleaseMessage);
    addExpectedFailure("regexp-standalones", "0", "2", willFixInNextReleaseMessage);
    addExpectedFailure("regexp-static", "undefined", "abc123.456def", willFixInNextReleaseMessage);
    addExpectedFailure("sparse-array-reverse", "nopcb", "nopdcba", willFixInNextReleaseMessage);
    addExpectedFailure("str-to-num", "false", "true", willFixInNextReleaseMessage);
    addExpectedFailure("string-lastindexof", "0", "-1", "test is wrong?");
    addExpectedFailure("string-split", "5", "13", "regular expression semantics");
//    addExpectedFailure("substr", "", "abcdefghijklmn", willFixInNextReleaseMessage);
    addExpectedFailure("to-precision", "1.2345e+27", "1.23450e+27", willFixInNextReleaseMessage);
    addExpectedFailure("try", "3", "4", "task 209990");
    addExpectedFailure("try_catch_scopes", "0", "1", "task 227055");
    addExpectedFailure("unusual-constructor", "false", "true", "no idea");
    addExpectedFailure("unicode-test", "13792", "13793", "test is wrong?");
    addExpectedFailure("with-leave", "false", "true", "task 233769");

    addTestExclusion("debug-*", "not applicable");
    addTestExclusion("mirror-*", "not applicable");

    addTestExclusion("array-concat", "Hangs on JSC backend");
    addTestExclusion("array-splice", "Hangs on JSC backend");
    addTestExclusion("sparse-array-reverse", "Hangs on JSC backend");

    addTestExclusion("string-case", "V8-specific behavior? (Doesn't pass on SpiderMonkey either)");

#ifdef Q_OS_WINCE
    addTestExclusion("deep-recursion", "Demands too much memory on WinCE");
    addTestExclusion("nested-repetition-count-overflow", "Demands too much memory on WinCE");
    addTestExclusion("unicode-test", "Demands too much memory on WinCE");
    addTestExclusion("mul-exhaustive", "Demands too much memory on WinCE");
#endif

    // Failures due to switch to JSC as back-end
    addExpectedFailure("date-parse", "NaN", "946713600000", willFixInNextReleaseMessage);
    addExpectedFailure("delete-global-properties", "true", "false", willFixInNextReleaseMessage);
    addExpectedFailure("delete", "false", "true", willFixInNextReleaseMessage);
    addExpectedFailure("function-arguments-null", "false", "true", willFixInNextReleaseMessage);
    addExpectedFailure("function-caller", "null", "function eval() {\n    [native code]\n}", willFixInNextReleaseMessage);
    addExpectedFailure("function-prototype", "prototype", "disconnectconnect", willFixInNextReleaseMessage);
    addExpectedFailure("number-tostring", "0", "0.0000a7c5ac471b4788", willFixInNextReleaseMessage);
    addExpectedFailure("parse-int-float", "1e+21", "1", willFixInNextReleaseMessage);
    addExpectedFailure("regexp", "false", "true", willFixInNextReleaseMessage);
    addExpectedFailure("smi-negative-zero", "-Infinity", "Infinity", willFixInNextReleaseMessage);
    addExpectedFailure("string-split", "4", "3", willFixInNextReleaseMessage);
    addExpectedFailure("substr", "abcdefghijklmn", "", willFixInNextReleaseMessage);

    QVector<uint> *data = qt_meta_data_tst_Suite();
    // content:
    *data << 1 // revision
          << 0 // classname
          << 0 << 0 // classinfo
          << 0 << 10 // methods (backpatched later)
          << 0 << 0 // properties
          << 0 << 0 // enums/sets
        ;

    QVector<char> *stringdata = qt_meta_stringdata_tst_Suite();
    appendCString(stringdata, "tst_Suite");
    appendCString(stringdata, "");

    QFileInfoList testFileInfos;
    if (testsFound)
        testFileInfos = testsDir.entryInfoList(QStringList() << "*.js", QDir::Files);
    foreach (QFileInfo tfi, testFileInfos) {
        QString name = tfi.baseName();
        // slot: signature, parameters, type, tag, flags
        QString slot = QString::fromLatin1("%0()").arg(name);
        *data << stringdata->size() << 10 << 10 << 10 << 0x08;
        appendCString(stringdata, slot.toLatin1());
        testNames.append(name);
    }

    (*data)[4] = testFileInfos.size();

    *data << 0; // eod

    // initialize staticMetaObject
    staticMetaObject.d.superdata = &QObject::staticMetaObject;
    staticMetaObject.d.stringdata = stringdata->constData();
    staticMetaObject.d.data = data->constData();
    staticMetaObject.d.extradata = 0;
}

tst_Suite::~tst_Suite()
{
#ifdef GENERATE_ADDEXPECTEDFAILURE_CODE
    if (!generatedAddExpectedFailureCode.isEmpty()) {
        QFile file("addexpectedfailures.cpp");
        file.open(QFile::WriteOnly);
        QTextStream ts(&file);
        ts << generatedAddExpectedFailureCode;
    }
#endif
}

void tst_Suite::addExpectedFailure(const QString &testName, const QString &actual,
                                   const QString &expected, const QString &message)
{
    expectedFailures.append(ExpectedFailure(testName, actual, expected, message));
}

bool tst_Suite::isExpectedFailure(const QString &testName, const QString &actual,
                                  const QString &expected, QString *message) const
{
    for (int i = 0; i < expectedFailures.size(); ++i) {
        const ExpectedFailure &ef = expectedFailures.at(i);
        if ((testName == ef.testName) && (actual == ef.actual) && (expected == ef.expected)) {
            if (message)
                *message = ef.message;
            return true;
        }
    }
    return false;
}

void tst_Suite::addTestExclusion(const QString &testName, const QString &message)
{
    testExclusions.append(qMakePair(QRegExp(testName), message));
}

void tst_Suite::addTestExclusion(const QRegExp &rx, const QString &message)
{
    testExclusions.append(qMakePair(rx, message));
}

bool tst_Suite::isExcludedTest(const QString &testName, QString *message) const
{
    for (int i = 0; i < testExclusions.size(); ++i) {
        if (testExclusions.at(i).first.indexIn(testName) != -1) {
            if (message)
                *message = testExclusions.at(i).second;
            return true;
        }
    }
    return false;
}

QTEST_MAIN(tst_Suite)
<commit_msg>remove some expected failures that don't fail with JSC back-end<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://www.qtsoftware.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtTest/QtTest>
#include <QByteArray>

#include <QtScript>

//TESTED_CLASS=
//TESTED_FILES=

// Uncomment the following define to have the autotest generate
// addExpectedFailure() code for all the tests that fail.
// This is useful when a whole new test (sub)suite is added.
// The code is stored in addexpectedfailures.cpp.
// Paste the contents into this file after the existing
// addExpectedFailure() calls.

//#define GENERATE_ADDEXPECTEDFAILURE_CODE

static QString readFile(const QString &filename)
{
    QFile file(filename);
    if (!file.open(QFile::ReadOnly))
        return QString();
    QTextStream stream(&file);
    stream.setCodec("UTF-8");
    return stream.readAll();
}

static void appendCString(QVector<char> *v, const char *s)
{
    char c;
    do {
        c = *(s++);
        *v << c;
    } while (c != '\0');
}

struct ExpectedFailure
{
    ExpectedFailure(const QString &name, const QString &act,
                    const QString &exp, const QString &msg)
        : testName(name), actual(act), expected(exp), message(msg)
        { }

    QString testName;
    QString actual;
    QString expected;
    QString message;
};

class tst_Suite : public QObject
{

public:
    tst_Suite();
    virtual ~tst_Suite();

    static QMetaObject staticMetaObject;
    virtual const QMetaObject *metaObject() const;
    virtual void *qt_metacast(const char *);
    virtual int qt_metacall(QMetaObject::Call, int, void **argv);

private:
    void addExpectedFailure(const QString &testName, const QString &actual,
                            const QString &expected, const QString &message);
    bool isExpectedFailure(const QString &testName, const QString &actual,
                           const QString &expected, QString *message) const;
    void addTestExclusion(const QString &testName, const QString &message);
    void addTestExclusion(const QRegExp &rx, const QString &message);
    bool isExcludedTest(const QString &testName, QString *message) const;

    QDir testsDir;
    QStringList testNames;
    QList<ExpectedFailure> expectedFailures;
    QList<QPair<QRegExp, QString> > testExclusions;
    QString mjsunitContents;
#ifdef GENERATE_ADDEXPECTEDFAILURE_CODE
    QString generatedAddExpectedFailureCode;
#endif
};

QMetaObject tst_Suite::staticMetaObject;

Q_GLOBAL_STATIC(QVector<uint>, qt_meta_data_tst_Suite)
Q_GLOBAL_STATIC(QVector<char>, qt_meta_stringdata_tst_Suite)

const QMetaObject *tst_Suite::metaObject() const
{
    return &staticMetaObject;
}

void *tst_Suite::qt_metacast(const char *_clname)
{
    if (!_clname) return 0;
    if (!strcmp(_clname, qt_meta_stringdata_tst_Suite()->constData()))
        return static_cast<void*>(const_cast<tst_Suite*>(this));
    return QObject::qt_metacast(_clname);
}

static QScriptValue qscript_fail(QScriptContext *ctx, QScriptEngine *eng)
{
    QScriptValue realFail = ctx->callee().data();
    Q_ASSERT(realFail.isFunction());
    QScriptValue ret = realFail.call(ctx->thisObject(), ctx->argumentsObject());
    Q_ASSERT(eng->hasUncaughtException());
    ret.setProperty("expected", ctx->argument(0));
    ret.setProperty("actual", ctx->argument(1));
    QScriptContextInfo info(ctx->parentContext()->parentContext());
    ret.setProperty("lineNumber", info.lineNumber());
    return ret;
}

int tst_Suite::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = QObject::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;
    if (_c == QMetaObject::InvokeMetaMethod) {
        QString name = testNames.at(_id);
        QString path = testsDir.absoluteFilePath(name + ".js");
        QString excludeMessage;
        if (isExcludedTest(name, &excludeMessage)) {
            QTest::qSkip(excludeMessage.toLatin1(), QTest::SkipAll, path.toLatin1(), -1);
        } else {
            QScriptEngine engine;
            engine.evaluate(mjsunitContents).toString();
            if (engine.hasUncaughtException()) {
                QStringList bt = engine.uncaughtExceptionBacktrace();
                QString err = engine.uncaughtException().toString();
                qWarning("%s\n%s", qPrintable(err), qPrintable(bt.join("\n")));
            } else {
                QScriptValue fakeFail = engine.newFunction(qscript_fail);
                fakeFail.setData(engine.globalObject().property("fail"));
                engine.globalObject().setProperty("fail", fakeFail);
                QString contents = readFile(path);
                QScriptValue ret = engine.evaluate(contents);
                if (engine.hasUncaughtException()) {
                    if (!ret.isError()) {
                        Q_ASSERT(ret.instanceOf(engine.globalObject().property("MjsUnitAssertionError")));
                        QString actual = ret.property("actual").toString();
                        QString expected = ret.property("expected").toString();
                        int lineNumber = ret.property("lineNumber").toInt32();
                        QString failMessage;
                        if (isExpectedFailure(name, actual, expected, &failMessage)) {
                            QTest::qExpectFail("", failMessage.toLatin1(),
                                               QTest::Continue, path.toLatin1(),
                                               lineNumber);
                        }
#ifdef GENERATE_ADDEXPECTEDFAILURE_CODE
                        else {
                            generatedAddExpectedFailureCode.append(
                                "    addExpectedFailure(\"" + name
                                + "\", \"" + actual + "\", \"" + expected
                                + "\", willFixInNextReleaseMessage);\n");
                        }
#endif
                        QTest::qCompare(actual, expected, "actual", "expect",
                                        path.toLatin1(), lineNumber);
                    } else {
                        int lineNumber = ret.property("lineNumber").toInt32();
                        QTest::qExpectFail("", ret.toString().toLatin1(),
                                           QTest::Continue, path.toLatin1(), lineNumber);
                        QTest::qVerify(false, ret.toString().toLatin1(), "", path.toLatin1(), lineNumber);
                    }
                }
            }
        }
        _id -= testNames.size();
    }
    return _id;
}

tst_Suite::tst_Suite()
{
    testsDir = QDir(SRCDIR);
    bool testsFound = testsDir.cd("tests");
    if (!testsFound) {
        qWarning("*** no tests/ dir!");
    } else {
        if (!testsDir.exists("mjsunit.js"))
            qWarning("*** no tests/mjsunit.js file!");
        else {
            mjsunitContents = readFile(testsDir.absoluteFilePath("mjsunit.js"));
            if (mjsunitContents.isEmpty())
                qWarning("*** tests/mjsunit.js is empty!");
        }
    }
    QString willFixInNextReleaseMessage = QString::fromLatin1("Will fix in next release");
    addExpectedFailure("arguments-enum", "2", "0", willFixInNextReleaseMessage);
    addExpectedFailure("const-redecl", "undefined", "TypeError", willFixInNextReleaseMessage);
    addExpectedFailure("global-const-var-conflicts", "false", "true", willFixInNextReleaseMessage);
    addExpectedFailure("string-lastindexof", "0", "-1", "test is wrong?");

    addTestExclusion("debug-*", "not applicable");
    addTestExclusion("mirror-*", "not applicable");

    addTestExclusion("array-concat", "Hangs on JSC backend");
    addTestExclusion("array-splice", "Hangs on JSC backend");
    addTestExclusion("sparse-array-reverse", "Hangs on JSC backend");

    addTestExclusion("string-case", "V8-specific behavior? (Doesn't pass on SpiderMonkey either)");

#ifdef Q_OS_WINCE
    addTestExclusion("deep-recursion", "Demands too much memory on WinCE");
    addTestExclusion("nested-repetition-count-overflow", "Demands too much memory on WinCE");
    addTestExclusion("unicode-test", "Demands too much memory on WinCE");
    addTestExclusion("mul-exhaustive", "Demands too much memory on WinCE");
#endif

    // Failures due to switch to JSC as back-end
    addExpectedFailure("date-parse", "NaN", "946713600000", willFixInNextReleaseMessage);
    addExpectedFailure("delete-global-properties", "true", "false", willFixInNextReleaseMessage);
    addExpectedFailure("delete", "false", "true", willFixInNextReleaseMessage);
    addExpectedFailure("function-arguments-null", "false", "true", willFixInNextReleaseMessage);
    addExpectedFailure("function-caller", "null", "function eval() {\n    [native code]\n}", willFixInNextReleaseMessage);
    addExpectedFailure("function-prototype", "prototype", "disconnectconnect", willFixInNextReleaseMessage);
    addExpectedFailure("number-tostring", "0", "0.0000a7c5ac471b4788", willFixInNextReleaseMessage);
    addExpectedFailure("parse-int-float", "1e+21", "1", willFixInNextReleaseMessage);
    addExpectedFailure("regexp", "false", "true", willFixInNextReleaseMessage);
    addExpectedFailure("smi-negative-zero", "-Infinity", "Infinity", willFixInNextReleaseMessage);
    addExpectedFailure("string-split", "4", "3", willFixInNextReleaseMessage);
    addExpectedFailure("substr", "abcdefghijklmn", "", willFixInNextReleaseMessage);

    QVector<uint> *data = qt_meta_data_tst_Suite();
    // content:
    *data << 1 // revision
          << 0 // classname
          << 0 << 0 // classinfo
          << 0 << 10 // methods (backpatched later)
          << 0 << 0 // properties
          << 0 << 0 // enums/sets
        ;

    QVector<char> *stringdata = qt_meta_stringdata_tst_Suite();
    appendCString(stringdata, "tst_Suite");
    appendCString(stringdata, "");

    QFileInfoList testFileInfos;
    if (testsFound)
        testFileInfos = testsDir.entryInfoList(QStringList() << "*.js", QDir::Files);
    foreach (QFileInfo tfi, testFileInfos) {
        QString name = tfi.baseName();
        // slot: signature, parameters, type, tag, flags
        QString slot = QString::fromLatin1("%0()").arg(name);
        *data << stringdata->size() << 10 << 10 << 10 << 0x08;
        appendCString(stringdata, slot.toLatin1());
        testNames.append(name);
    }

    (*data)[4] = testFileInfos.size();

    *data << 0; // eod

    // initialize staticMetaObject
    staticMetaObject.d.superdata = &QObject::staticMetaObject;
    staticMetaObject.d.stringdata = stringdata->constData();
    staticMetaObject.d.data = data->constData();
    staticMetaObject.d.extradata = 0;
}

tst_Suite::~tst_Suite()
{
#ifdef GENERATE_ADDEXPECTEDFAILURE_CODE
    if (!generatedAddExpectedFailureCode.isEmpty()) {
        QFile file("addexpectedfailures.cpp");
        file.open(QFile::WriteOnly);
        QTextStream ts(&file);
        ts << generatedAddExpectedFailureCode;
    }
#endif
}

void tst_Suite::addExpectedFailure(const QString &testName, const QString &actual,
                                   const QString &expected, const QString &message)
{
    expectedFailures.append(ExpectedFailure(testName, actual, expected, message));
}

bool tst_Suite::isExpectedFailure(const QString &testName, const QString &actual,
                                  const QString &expected, QString *message) const
{
    for (int i = 0; i < expectedFailures.size(); ++i) {
        const ExpectedFailure &ef = expectedFailures.at(i);
        if ((testName == ef.testName) && (actual == ef.actual) && (expected == ef.expected)) {
            if (message)
                *message = ef.message;
            return true;
        }
    }
    return false;
}

void tst_Suite::addTestExclusion(const QString &testName, const QString &message)
{
    testExclusions.append(qMakePair(QRegExp(testName), message));
}

void tst_Suite::addTestExclusion(const QRegExp &rx, const QString &message)
{
    testExclusions.append(qMakePair(rx, message));
}

bool tst_Suite::isExcludedTest(const QString &testName, QString *message) const
{
    for (int i = 0; i < testExclusions.size(); ++i) {
        if (testExclusions.at(i).first.indexIn(testName) != -1) {
            if (message)
                *message = testExclusions.at(i).second;
            return true;
        }
    }
    return false;
}

QTEST_MAIN(tst_Suite)
<|endoftext|>


<commit_before>//===---- CGBuiltin.cpp - Emit LLVM Code for builtins ---------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by Anders Carlsson and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This contains code to emit Builtin calls as LLVM code.
//
//===----------------------------------------------------------------------===//

#include "CodeGenFunction.h"
#include "CodeGenModule.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Builtins.h"
#include "clang/AST/Expr.h"
#include "llvm/Constants.h"
#include "llvm/Function.h"
#include "llvm/Intrinsics.h"

using namespace clang;
using namespace CodeGen;

RValue CodeGenFunction::EmitBuiltinExpr(unsigned BuiltinID, const CallExpr *E) {
  switch (BuiltinID) {
  default:
    if (getContext().BuiltinInfo.isLibFunction(BuiltinID))
      return EmitCallExpr(CGM.getBuiltinLibFunction(BuiltinID), E);

    fprintf(stderr, "Unimplemented builtin!!\n");
    E->dump(getContext().SourceMgr);

    // Unknown builtin, for now just dump it out and return undef.
    if (hasAggregateLLVMType(E->getType()))
      return RValue::getAggregate(CreateTempAlloca(ConvertType(E->getType())));
    return RValue::get(llvm::UndefValue::get(ConvertType(E->getType())));

  case Builtin::BI__builtin___CFStringMakeConstantString: {
    const Expr *Arg = E->getArg(0);

    while (const ParenExpr *PE = dyn_cast<ParenExpr>(Arg))
      Arg = PE->getSubExpr();

    const StringLiteral *Literal = cast<StringLiteral>(Arg);
    std::string S(Literal->getStrData(), Literal->getByteLength());

    return RValue::get(CGM.GetAddrOfConstantCFString(S));
  }
  case Builtin::BI__builtin_va_start:
  case Builtin::BI__builtin_va_end: {
    llvm::Value *ArgValue = EmitScalarExpr(E->getArg(0));
    const llvm::Type *DestType = llvm::PointerType::get(llvm::Type::Int8Ty);
    if (ArgValue->getType() != DestType)
      ArgValue = Builder.CreateBitCast(ArgValue, DestType,
                                       ArgValue->getNameStart());

    llvm::Intrinsic::ID inst = (BuiltinID == Builtin::BI__builtin_va_start) ?
      llvm::Intrinsic::vastart : llvm::Intrinsic::vaend;
    llvm::Value *F = llvm::Intrinsic::getDeclaration(&CGM.getModule(), inst);
    llvm::Value *V = Builder.CreateCall(F, ArgValue);

    return RValue::get(V);
  }
  }

  return RValue::get(0);
}
<commit_msg>Generate code for __builtin_classify_type.<commit_after>//===---- CGBuiltin.cpp - Emit LLVM Code for builtins ---------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by Anders Carlsson and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This contains code to emit Builtin calls as LLVM code.
//
//===----------------------------------------------------------------------===//

#include "CodeGenFunction.h"
#include "CodeGenModule.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Builtins.h"
#include "clang/AST/Expr.h"
#include "llvm/Constants.h"
#include "llvm/Function.h"
#include "llvm/Intrinsics.h"

using namespace clang;
using namespace CodeGen;

RValue CodeGenFunction::EmitBuiltinExpr(unsigned BuiltinID, const CallExpr *E) {
  switch (BuiltinID) {
  default:
    if (getContext().BuiltinInfo.isLibFunction(BuiltinID))
      return EmitCallExpr(CGM.getBuiltinLibFunction(BuiltinID), E);

    fprintf(stderr, "Unimplemented builtin!!\n");
    E->dump(getContext().SourceMgr);

    // Unknown builtin, for now just dump it out and return undef.
    if (hasAggregateLLVMType(E->getType()))
      return RValue::getAggregate(CreateTempAlloca(ConvertType(E->getType())));
    return RValue::get(llvm::UndefValue::get(ConvertType(E->getType())));

  case Builtin::BI__builtin___CFStringMakeConstantString: {
    const Expr *Arg = E->getArg(0);

    while (const ParenExpr *PE = dyn_cast<ParenExpr>(Arg))
      Arg = PE->getSubExpr();

    const StringLiteral *Literal = cast<StringLiteral>(Arg);
    std::string S(Literal->getStrData(), Literal->getByteLength());

    return RValue::get(CGM.GetAddrOfConstantCFString(S));
  }
  case Builtin::BI__builtin_va_start:
  case Builtin::BI__builtin_va_end: {
    llvm::Value *ArgValue = EmitScalarExpr(E->getArg(0));
    const llvm::Type *DestType = llvm::PointerType::get(llvm::Type::Int8Ty);
    if (ArgValue->getType() != DestType)
      ArgValue = Builder.CreateBitCast(ArgValue, DestType,
                                       ArgValue->getNameStart());

    llvm::Intrinsic::ID inst = (BuiltinID == Builtin::BI__builtin_va_start) ?
      llvm::Intrinsic::vastart : llvm::Intrinsic::vaend;
    llvm::Value *F = llvm::Intrinsic::getDeclaration(&CGM.getModule(), inst);
    llvm::Value *V = Builder.CreateCall(F, ArgValue);

    return RValue::get(V);
  }
  case Builtin::BI__builtin_classify_type: {
    llvm::APSInt Result(32);

    if (!E->isBuiltinClassifyType(Result))
      assert(0 && "Expr not __builtin_classify_type!");

    return RValue::get(llvm::ConstantInt::get(Result));
  }
  }

  return RValue::get(0);
}
<|endoftext|>


<commit_before>#include "app.h"
#include "utils.h"
#include "linsys.h"
#include "integrate.h"
#include <apf.h>
#include <apfNumbering.h>
#include <apfDynamicVector.h>
#include <apfDynamicMatrix.h>
#include <gmi.h>
#include <PCU.h>

namespace pe {

static void addToSystem(
    apf::DynamicVector& fe,
    apf::DynamicMatrix& ke,
    apf::MeshEntity* e,
    apf::GlobalNumbering* n,
    LinSys* ls)
{
  apf::NewArray<long> numbers;
  int sz = apf::getElementNumbers(n, e, numbers);
  ls->addToVector(sz, &numbers[0], &fe[0]);
  ls->addToMatrix(sz, &numbers[0], &ke(0,0));
}

static void assembleSystem(
    int o,
    apf::Mesh* m,
    apf::Field* f,
    double (*rhs)(apf::Vector3 const& p),
    apf::GlobalNumbering* n,
    LinSys* ls)
{
  IntegrateInput in = { o, f, rhs};
  Integrate integrate(in);
  apf::MeshEntity* elem;
  apf::MeshIterator* elems = m->begin(m->getDimension());
  while ((elem = m->iterate(elems)))
  {
    apf::MeshElement* me = apf::createMeshElement(m, elem);
    integrate.process(me);
    addToSystem(integrate.fe, integrate.ke, elem, n, ls);
    apf::destroyMeshElement(me);
  }
  m->end(elems);
  ls->synchronize();
}

static void applyBCToSystem(
    apf::Mesh* m,
    apf::GlobalNumbering* gn,
    LinSys* ls)
{
  gmi_model* model = m->getModel();
  gmi_ent* boundary;
  gmi_iter* boundaries = gmi_begin(model, m->getDimension()-1);
  while ((boundary = gmi_next(model, boundaries)))
  {
    apf::DynamicArray<apf::Node> nodes;
    apf::ModelEntity* b = reinterpret_cast<apf::ModelEntity*>(boundary);
    apf::getNodesOnClosure(m, b, nodes);
    int nnodes = nodes.getSize();
    long rows[nnodes];
    for (int n=0; n < nnodes; ++n)
      rows[n] = apf::getNumber(gn, nodes[n]);
    ls->diagMatRow(nnodes, rows);
    ls->zeroToVector(nnodes, rows);
  }
  gmi_end(model, boundaries);
  ls->synchronize();
}

void App::assemble()
{
  double t0 = PCU_Time();
  assembleSystem(polynomialOrder, mesh, sol, rhs, shared, linsys);
  applyBCToSystem(mesh, shared, linsys);
  double t1 = PCU_Time();
  print("assembled in %f seconds", t1-t0);
}

}
<commit_msg>apply bcs to field nodes, not mesh nodes<commit_after>#include "app.h"
#include "utils.h"
#include "linsys.h"
#include "integrate.h"
#include <apf.h>
#include <apfNumbering.h>
#include <apfDynamicVector.h>
#include <apfDynamicMatrix.h>
#include <gmi.h>
#include <PCU.h>

namespace pe {

static void addToSystem(
    apf::DynamicVector& fe,
    apf::DynamicMatrix& ke,
    apf::MeshEntity* e,
    apf::GlobalNumbering* n,
    LinSys* ls)
{
  apf::NewArray<long> numbers;
  int sz = apf::getElementNumbers(n, e, numbers);
  ls->addToVector(sz, &numbers[0], &fe[0]);
  ls->addToMatrix(sz, &numbers[0], &ke(0,0));
}

static void assembleSystem(
    int o,
    apf::Mesh* m,
    apf::Field* f,
    double (*rhs)(apf::Vector3 const& p),
    apf::GlobalNumbering* n,
    LinSys* ls)
{
  IntegrateInput in = { o, f, rhs};
  Integrate integrate(in);
  apf::MeshEntity* elem;
  apf::MeshIterator* elems = m->begin(m->getDimension());
  while ((elem = m->iterate(elems)))
  {
    apf::MeshElement* me = apf::createMeshElement(m, elem);
    integrate.process(me);
    addToSystem(integrate.fe, integrate.ke, elem, n, ls);
    apf::destroyMeshElement(me);
  }
  m->end(elems);
  ls->synchronize();
}

static void applyBCToSystem(
    apf::Mesh* m,
    apf::GlobalNumbering* gn,
    apf::Field* f,
    LinSys* ls)
{
  gmi_model* model = m->getModel();
  gmi_ent* boundary;
  gmi_iter* boundaries = gmi_begin(model, m->getDimension()-1);
  while ((boundary = gmi_next(model, boundaries)))
  {
    apf::DynamicArray<apf::Node> nodes;
    apf::ModelEntity* b = reinterpret_cast<apf::ModelEntity*>(boundary);
    apf::getNodesOnClosure(m, b, nodes, apf::getShape(f));
    int nnodes = nodes.getSize();
    long rows[nnodes];
    for (int n=0; n < nnodes; ++n)
      rows[n] = apf::getNumber(gn, nodes[n]);
    ls->diagMatRow(nnodes, rows);
    ls->zeroToVector(nnodes, rows);
  }
  gmi_end(model, boundaries);
  ls->synchronize();
}

void App::assemble()
{
  double t0 = PCU_Time();
  assembleSystem(polynomialOrder, mesh, sol, rhs, shared, linsys);
  applyBCToSystem(mesh, shared, sol, linsys);
  double t1 = PCU_Time();
  print("assembled in %f seconds", t1-t0);
}

}
<|endoftext|>


<commit_before>#pragma once

#include <array>
#include <chrono>
#include <cstdint>
#include <random>

// Fills @p bytes bytes of @p dest with random values
void fill_randomly(void* dest, size_t bytes);

/**
 * @brief Reads @p bytes bytes from /dev/urandom to @p dest
 *
 * @param dest destination
 * @param bytes number of bytes to read
 *
 * @return @p bytes on success, -1 on error and errno set to one of
 *   possibilities from open(2) and read(2)
 */
ssize_t read_from_dev_urandom_nothrow(void* dest, size_t bytes) noexcept;

/**
 * @brief Reads @p bytes bytes from /dev/urandom to @p dest
 *
 * @param dest destination
 * @param bytes number of bytes to read
 *
 * @errors If any error occurs an exception of type std::runtime_error is
 *   thrown
 */
void read_from_dev_urandom(void* dest, size_t bytes);

class RandomDevice {
public:
	using result_type = uint64_t;

	constexpr static result_type min() noexcept {
		return std::numeric_limits<result_type>::min();
	}

	constexpr static result_type max() noexcept {
		return std::numeric_limits<result_type>::max();
	}

private:
	std::array<result_type, 256 / sizeof(result_type)> buff{};
	size_t pos = buff.size();

	void fill_buff() {
		fill_randomly(buff.data(), buff.size() * sizeof(result_type));
		pos = 0;
	}

public:
	RandomDevice() { fill_buff(); }

	RandomDevice(const RandomDevice&) = delete;
	RandomDevice(RandomDevice&&) noexcept = default;
	RandomDevice& operator=(const RandomDevice&) = delete;
	RandomDevice& operator=(RandomDevice&&) noexcept = default;

	~RandomDevice() = default;

	result_type operator()() {
		if (pos == buff.size()) {
			fill_buff();
		}
		return buff[pos++];
	}
};

inline RandomDevice& get_random_generator() {
	static RandomDevice random_generator;
	return random_generator;
}

// Get random from [a, b]
template <class T>
constexpr T get_random(T&& a, T&& b) {
	return std::uniform_int_distribution<T>(
	   std::forward<T>(a), std::forward<T>(b))(get_random_generator());
}

template <class Iter>
void random_shuffle(Iter begin, Iter end) {
	for (auto n = end - begin, i = n - 1; i > 0; --i) {
		std::swap(begin[i], begin[get_random(0, i)]);
	}
}
<commit_msg>random.hh: fixed race condition in concurrent usage of get_random()<commit_after>#pragma once

#include <array>
#include <chrono>
#include <cstdint>
#include <random>

// Fills @p bytes bytes of @p dest with random values
void fill_randomly(void* dest, size_t bytes);

/**
 * @brief Reads @p bytes bytes from /dev/urandom to @p dest
 *
 * @param dest destination
 * @param bytes number of bytes to read
 *
 * @return @p bytes on success, -1 on error and errno set to one of
 *   possibilities from open(2) and read(2)
 */
ssize_t read_from_dev_urandom_nothrow(void* dest, size_t bytes) noexcept;

/**
 * @brief Reads @p bytes bytes from /dev/urandom to @p dest
 *
 * @param dest destination
 * @param bytes number of bytes to read
 *
 * @errors If any error occurs an exception of type std::runtime_error is
 *   thrown
 */
void read_from_dev_urandom(void* dest, size_t bytes);

class RandomDevice {
public:
	using result_type = uint64_t;

	constexpr static result_type min() noexcept {
		return std::numeric_limits<result_type>::min();
	}

	constexpr static result_type max() noexcept {
		return std::numeric_limits<result_type>::max();
	}

private:
	std::array<result_type, 256 / sizeof(result_type)> buff{};
	size_t pos = buff.size();

	void fill_buff() {
		fill_randomly(buff.data(), buff.size() * sizeof(result_type));
		pos = 0;
	}

public:
	RandomDevice() { fill_buff(); }

	RandomDevice(const RandomDevice&) = delete;
	RandomDevice(RandomDevice&&) noexcept = default;
	RandomDevice& operator=(const RandomDevice&) = delete;
	RandomDevice& operator=(RandomDevice&&) noexcept = default;

	~RandomDevice() = default;

	result_type operator()() {
		if (pos == buff.size()) {
			fill_buff();
		}
		return buff[pos++];
	}
};

inline RandomDevice& get_random_generator() {
	static thread_local RandomDevice random_generator;
	return random_generator;
}

// Get random from [a, b]
template <class T>
constexpr T get_random(T&& a, T&& b) {
	return std::uniform_int_distribution<T>(
	   std::forward<T>(a), std::forward<T>(b))(get_random_generator());
}

template <class Iter>
void random_shuffle(Iter begin, Iter end) {
	for (auto n = end - begin, i = n - 1; i > 0; --i) {
		std::swap(begin[i], begin[get_random(0, i)]);
	}
}
<|endoftext|>


<commit_before>/* -*- mode: c++; indent-tabs-mode: nil -*- */
/*
  QoreOracleStatement.cpp

  Qore Programming Language

  Copyright (C) 2003 - 2012 David Nichols

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

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  Lesser General Public License for more details.

  You should have received a copy of the GNU Lesser General Public
  License along with this library; if not, write to the Free Software
  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include "oracle.h"

static inline bool wasInTransaction(Datasource *ds) {
#ifdef _QORE_HAS_DATASOURCE_ACTIVETRANSACTION
   return ds->activeTransaction();
#else
   return ds->isInTransaction();
#endif
}

int QoreOracleStatement::execute(const char *who, ExceptionSink *xsink) {
   QoreOracleConnection *conn = (QoreOracleConnection *)ds->getPrivateData();

   assert(conn->svchp);
   int status = OCIStmtExecute(conn->svchp, stmthp, conn->errhp, is_select ? 0 : 1, 0, 0, 0, OCI_DEFAULT);

   //printd(0, "QoreOracleStatement::execute() stmthp=%p status=%d (OCI_ERROR=%d)\n", stmthp, status, OCI_ERROR);
   if (status == OCI_ERROR) {
      // see if server is connected
      int ping = OCI_Ping(&conn->ocilib, conn->ocilib_cn, xsink);

      if (*xsink) {
         if (ping)
            ping = 0;
#ifdef DEBUG
         xsink->handleExceptions();
#endif
         xsink->clear();
      }

      if (!ping) {
	 // check if a transaction was in progress
         if (wasInTransaction(ds))
	    xsink->raiseException("DBI:ORACLE:TRANSACTION-ERROR", "connection to Oracle database server %s@%s lost while in a transaction; transaction has been lost", ds.getUsername(), ds.getDBName());

	 // try to reconnect
	 conn->logoff();

	 //printd(0, "QoreOracleStatement::execute() about to execute OCILogon() for reconnect\n");
	 if (conn->logon(xsink)) {
            //printd(5, "QoreOracleStatement::execute() conn=%p reconnect failed, marking connection as closed\n", conn);
	    // close datasource and remove private data
	    ds->connectionAborted();
	    return -1;
	 }
         if (conn->checkWarnings(xsink)) {
             //printd(5, "QoreOracleStatement::execute() conn=%p reconnect failed, marking connection as closed\n", conn);
            // close datasource and remove private data
            ds->connectionAborted();
            return -1;
         }

         // don't execute again if the connection was aborted while in a transaction
         if (wasInTransaction(ds))
	    return -1;

	 //printd(0, "QoreOracleStatement::execute() returned from OCILogon() status=%d\n", status);
	 status = OCIStmtExecute(conn->svchp, stmthp, conn->errhp, is_select ? 0 : 1, 0, 0, 0, OCI_DEFAULT);
	 if (status && conn->checkerr(status, who, xsink))
	    return -1;
      }
      else {
	 //printd(0, "QoreOracleStatement::execute() error, but it's connected; status=%d who=%s\n", status, who);
	 conn->checkerr(status, who, xsink);
	 return -1;
      }
   }
   else if (status && conn->checkerr(status, who, xsink))
      return -1;

   return 0;
}

QoreHashNode *QoreOracleStatement::fetchRow(OraResultSet &resultset, ExceptionSink *xsink) {
   if (!fetch_done) {
      xsink->raiseException("ORACLE-FETCH-ROW-ERROR", "call SQLStatement::next() before calling SQLStatement::fetchRow()");
      return 0;
   }

   // set up hash for row
   ReferenceHolder<QoreHashNode> h(new QoreHashNode, xsink);

   // copy data or perform per-value processing if needed
   for (clist_t::iterator i = resultset.clist.begin(), e = resultset.clist.end(); i != e; ++i) {
      OraColumnBuffer *w = *i;
      // assign value to hash
      AbstractQoreNode* n = w->getValue(true, xsink);
      if (*xsink) {
         assert(!n);
         return 0;
      }
      h->setKeyValue(w->name, n, xsink);
      if (*xsink)
	 return 0;
   }

   return h.release();
}

QoreListNode *QoreOracleStatement::fetchRows(ExceptionSink *xsink) {
   OraResultSetHelper resultset(*this, "QoreOracleStatement::fetchRows():params", xsink);
   if (*xsink)
      return 0;

   return fetchRows(**resultset, -1, xsink);
}

QoreListNode *QoreOracleStatement::fetchRows(OraResultSet &resultset, int rows, ExceptionSink *xsink) {
   ReferenceHolder<QoreListNode> l(new QoreListNode, xsink);

   // setup temporary row to accept values
   if (resultset.define("QoreOracleStatement::fetchRows():define", xsink))
      return 0;

   int num_rows = 0;

   // now finally fetch the data
   while (next(xsink)) {
      QoreHashNode *h = fetchRow(resultset, xsink);
      if (!h)
	 return 0;

      // add row to list
      l->push(h);

      ++num_rows;
      if (rows > 0 && num_rows == rows)
	 break;
   }
   //printd(2, "QoreOracleStatement::fetchRows(): %d column(s), %d row(s) retrieved as output\n", resultset.size(), l->size());
   if (!*xsink) {
      if (!fetch_done)
         fetch_done = true;
      return l.release();
   }
   return 0;
}

#ifdef _QORE_HAS_DBI_SELECT_ROW
QoreHashNode *QoreOracleStatement::fetchSingleRow(ExceptionSink *xsink) {
   OraResultSetHelper resultset(*this, "QoreOracleStatement::fetchRow():params", xsink);
   if (*xsink)
      return 0;

   ReferenceHolder<QoreHashNode> rv(xsink);

   // setup temporary row to accept values
   if (resultset->define("QoreOracleStatement::fetchRows():define", xsink))
      return 0;

   //printd(2, "QoreOracleStatement::fetchRow(): %d column(s) retrieved as output\n", resultset->size());

   // now finally fetch the data
   if (!next(xsink))
      return 0;

   rv = fetchRow(**resultset, xsink);
   if (!rv)
      return 0;

   if (!fetch_done)
      fetch_done = true;

   if (next(xsink)) {
      xsink->raiseExceptionArg("ORACLE-SELECT-ROW-ERROR", rv.release(), "SQL passed to selectRow() returned more than 1 row");
      return 0;
   }

   return rv.release();
}
#endif

// retrieve results from statement and return hash
QoreHashNode *QoreOracleStatement::fetchColumns(ExceptionSink *xsink) {
   OraResultSetHelper resultset(*this, "QoreOracleStatement::fetchColumns():params", xsink);
   if (*xsink)
      return 0;

   return fetchColumns(**resultset, -1, xsink);
}

// retrieve results from statement and return hash
QoreHashNode *QoreOracleStatement::fetchColumns(OraResultSet &resultset, int rows, ExceptionSink *xsink) {
   // allocate result hash for result value
   ReferenceHolder<QoreHashNode> h(new QoreHashNode, xsink);

   // create hash elements for each column, assign empty list
   for (clist_t::iterator i = resultset.clist.begin(), e = resultset.clist.end(); i != e; ++i) {
      //printd(5, "QoreOracleStatement::fetchColumns() allocating list for '%s' column\n", w->name);
      h->setKeyValue((*i)->name, new QoreListNode, xsink);
   }

   // setup temporary row to accept values
   if (resultset.define("QoreOracleStatement::fetchColumns():define", xsink))
      return 0;

   int num_rows = 0;

   // now finally fetch the data
   while (next(xsink)) {
      // copy data or perform per-value processing if needed
      for (unsigned i = 0; i < resultset.clist.size(); ++i) {
	 OraColumnBuffer *w = resultset.clist[i];
	 // get pointer to value of target node
	 QoreListNode *l = reinterpret_cast<QoreListNode *>(h->getKeyValue(w->name, xsink));
	 if (!l)
	    break;
         AbstractQoreNode* n = w->getValue(false, xsink);
         if (*xsink) {
            assert(!n);
            break;
         }

	 l->push(n);
	 if (*xsink)
	    break;
      }

      ++num_rows;
      if (rows > 0 && num_rows == rows)
	 break;
   }
   //printd(2, "QoreOracleStatement::fetchColumns(rows: %d): %d column(s), %d row(s) retrieved as output\n", rows, resultset.size(), num_rows);
   if (!*xsink) {
      if (!fetch_done)
         fetch_done = true;
      return h.release();
   }
   return 0;
}
<commit_msg>fix for last commit<commit_after>/* -*- mode: c++; indent-tabs-mode: nil -*- */
/*
  QoreOracleStatement.cpp

  Qore Programming Language

  Copyright (C) 2003 - 2012 David Nichols

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

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  Lesser General Public License for more details.

  You should have received a copy of the GNU Lesser General Public
  License along with this library; if not, write to the Free Software
  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include "oracle.h"

static inline bool wasInTransaction(Datasource *ds) {
#ifdef _QORE_HAS_DATASOURCE_ACTIVETRANSACTION
   return ds->activeTransaction();
#else
   return ds->isInTransaction();
#endif
}

int QoreOracleStatement::execute(const char *who, ExceptionSink *xsink) {
   QoreOracleConnection *conn = (QoreOracleConnection *)ds->getPrivateData();

   assert(conn->svchp);
   int status = OCIStmtExecute(conn->svchp, stmthp, conn->errhp, is_select ? 0 : 1, 0, 0, 0, OCI_DEFAULT);

   //printd(0, "QoreOracleStatement::execute() stmthp=%p status=%d (OCI_ERROR=%d)\n", stmthp, status, OCI_ERROR);
   if (status == OCI_ERROR) {
      // see if server is connected
      int ping = OCI_Ping(&conn->ocilib, conn->ocilib_cn, xsink);

      if (*xsink) {
         if (ping)
            ping = 0;
#ifdef DEBUG
         xsink->handleExceptions();
#endif
         xsink->clear();
      }

      if (!ping) {
	 // check if a transaction was in progress
         if (wasInTransaction(ds))
	    xsink->raiseException("DBI:ORACLE:TRANSACTION-ERROR", "connection to Oracle database server %s@%s lost while in a transaction; transaction has been lost", ds->getUsername(), ds->getDBName());

	 // try to reconnect
	 conn->logoff();

	 //printd(0, "QoreOracleStatement::execute() about to execute OCILogon() for reconnect\n");
	 if (conn->logon(xsink)) {
            //printd(5, "QoreOracleStatement::execute() conn=%p reconnect failed, marking connection as closed\n", conn);
	    // close datasource and remove private data
	    ds->connectionAborted();
	    return -1;
	 }
         if (conn->checkWarnings(xsink)) {
             //printd(5, "QoreOracleStatement::execute() conn=%p reconnect failed, marking connection as closed\n", conn);
            // close datasource and remove private data
            ds->connectionAborted();
            return -1;
         }

         // don't execute again if the connection was aborted while in a transaction
         if (wasInTransaction(ds))
	    return -1;

	 //printd(0, "QoreOracleStatement::execute() returned from OCILogon() status=%d\n", status);
	 status = OCIStmtExecute(conn->svchp, stmthp, conn->errhp, is_select ? 0 : 1, 0, 0, 0, OCI_DEFAULT);
	 if (status && conn->checkerr(status, who, xsink))
	    return -1;
      }
      else {
	 //printd(0, "QoreOracleStatement::execute() error, but it's connected; status=%d who=%s\n", status, who);
	 conn->checkerr(status, who, xsink);
	 return -1;
      }
   }
   else if (status && conn->checkerr(status, who, xsink))
      return -1;

   return 0;
}

QoreHashNode *QoreOracleStatement::fetchRow(OraResultSet &resultset, ExceptionSink *xsink) {
   if (!fetch_done) {
      xsink->raiseException("ORACLE-FETCH-ROW-ERROR", "call SQLStatement::next() before calling SQLStatement::fetchRow()");
      return 0;
   }

   // set up hash for row
   ReferenceHolder<QoreHashNode> h(new QoreHashNode, xsink);

   // copy data or perform per-value processing if needed
   for (clist_t::iterator i = resultset.clist.begin(), e = resultset.clist.end(); i != e; ++i) {
      OraColumnBuffer *w = *i;
      // assign value to hash
      AbstractQoreNode* n = w->getValue(true, xsink);
      if (*xsink) {
         assert(!n);
         return 0;
      }
      h->setKeyValue(w->name, n, xsink);
      if (*xsink)
	 return 0;
   }

   return h.release();
}

QoreListNode *QoreOracleStatement::fetchRows(ExceptionSink *xsink) {
   OraResultSetHelper resultset(*this, "QoreOracleStatement::fetchRows():params", xsink);
   if (*xsink)
      return 0;

   return fetchRows(**resultset, -1, xsink);
}

QoreListNode *QoreOracleStatement::fetchRows(OraResultSet &resultset, int rows, ExceptionSink *xsink) {
   ReferenceHolder<QoreListNode> l(new QoreListNode, xsink);

   // setup temporary row to accept values
   if (resultset.define("QoreOracleStatement::fetchRows():define", xsink))
      return 0;

   int num_rows = 0;

   // now finally fetch the data
   while (next(xsink)) {
      QoreHashNode *h = fetchRow(resultset, xsink);
      if (!h)
	 return 0;

      // add row to list
      l->push(h);

      ++num_rows;
      if (rows > 0 && num_rows == rows)
	 break;
   }
   //printd(2, "QoreOracleStatement::fetchRows(): %d column(s), %d row(s) retrieved as output\n", resultset.size(), l->size());
   if (!*xsink) {
      if (!fetch_done)
         fetch_done = true;
      return l.release();
   }
   return 0;
}

#ifdef _QORE_HAS_DBI_SELECT_ROW
QoreHashNode *QoreOracleStatement::fetchSingleRow(ExceptionSink *xsink) {
   OraResultSetHelper resultset(*this, "QoreOracleStatement::fetchRow():params", xsink);
   if (*xsink)
      return 0;

   ReferenceHolder<QoreHashNode> rv(xsink);

   // setup temporary row to accept values
   if (resultset->define("QoreOracleStatement::fetchRows():define", xsink))
      return 0;

   //printd(2, "QoreOracleStatement::fetchRow(): %d column(s) retrieved as output\n", resultset->size());

   // now finally fetch the data
   if (!next(xsink))
      return 0;

   rv = fetchRow(**resultset, xsink);
   if (!rv)
      return 0;

   if (!fetch_done)
      fetch_done = true;

   if (next(xsink)) {
      xsink->raiseExceptionArg("ORACLE-SELECT-ROW-ERROR", rv.release(), "SQL passed to selectRow() returned more than 1 row");
      return 0;
   }

   return rv.release();
}
#endif

// retrieve results from statement and return hash
QoreHashNode *QoreOracleStatement::fetchColumns(ExceptionSink *xsink) {
   OraResultSetHelper resultset(*this, "QoreOracleStatement::fetchColumns():params", xsink);
   if (*xsink)
      return 0;

   return fetchColumns(**resultset, -1, xsink);
}

// retrieve results from statement and return hash
QoreHashNode *QoreOracleStatement::fetchColumns(OraResultSet &resultset, int rows, ExceptionSink *xsink) {
   // allocate result hash for result value
   ReferenceHolder<QoreHashNode> h(new QoreHashNode, xsink);

   // create hash elements for each column, assign empty list
   for (clist_t::iterator i = resultset.clist.begin(), e = resultset.clist.end(); i != e; ++i) {
      //printd(5, "QoreOracleStatement::fetchColumns() allocating list for '%s' column\n", w->name);
      h->setKeyValue((*i)->name, new QoreListNode, xsink);
   }

   // setup temporary row to accept values
   if (resultset.define("QoreOracleStatement::fetchColumns():define", xsink))
      return 0;

   int num_rows = 0;

   // now finally fetch the data
   while (next(xsink)) {
      // copy data or perform per-value processing if needed
      for (unsigned i = 0; i < resultset.clist.size(); ++i) {
	 OraColumnBuffer *w = resultset.clist[i];
	 // get pointer to value of target node
	 QoreListNode *l = reinterpret_cast<QoreListNode *>(h->getKeyValue(w->name, xsink));
	 if (!l)
	    break;
         AbstractQoreNode* n = w->getValue(false, xsink);
         if (*xsink) {
            assert(!n);
            break;
         }

	 l->push(n);
	 if (*xsink)
	    break;
      }

      ++num_rows;
      if (rows > 0 && num_rows == rows)
	 break;
   }
   //printd(2, "QoreOracleStatement::fetchColumns(rows: %d): %d column(s), %d row(s) retrieved as output\n", rows, resultset.size(), num_rows);
   if (!*xsink) {
      if (!fetch_done)
         fetch_done = true;
      return h.release();
   }
   return 0;
}
<|endoftext|>


<commit_before>/************************************************************************
*
* vapor3D Engine  (2008-2010)
*
*	<http://www.vapor3d.org>
*
************************************************************************/

#include "Resources/API.h"
#include "Resources/Animation.h"
#include "Resources/Bone.h"
#include "Math/Helpers.h"

NAMESPACE_RESOURCES_BEGIN

//-----------------------------------//

Animation::Animation()
	: looped(true)
{ }

//-----------------------------------//

void Animation::setKeyFrames(const BonePtr& bone, const KeyFramesVector& frames)
{
	keyFrames[bone] = frames;

	for( size_t i = 0; i < frames.size(); i++ )
	{
		const KeyFrame& frame = frames[i];
		keyFramesVector.push_back(frame);
	}
}

//-----------------------------------//

float Animation::getTotalTime() const
{
	if( keyFrames.empty() )
		return 0;

	float min = LimitsFloatMaximum;
	float max = 0;

	for( size_t i = 0; i < keyFramesVector.size(); i++ )
	{
		const KeyFrame& keyFrame = keyFramesVector[i];

		min = std::min(min, keyFrame.time);
		max = std::max(max, keyFrame.time);
	}

	if( min == LimitsFloatMaximum )
		return 0;

	return max - min;
}

//-----------------------------------//

bool Animation::isLooped()
{
	return looped;
}

//-----------------------------------//

//#define VAPOR_ANIMATION_INTERPOLATION_LINEAR

Matrix4x3 Animation::getKeyFrameMatrix(const BonePtr& bone, float time)
{
	if( !bone || keyFrames.empty() )
		return Matrix4x3::Identity;

	const KeyFramesVector& boneKeyFrames = keyFrames[bone];

	if( boneKeyFrames.empty() )
		return Matrix4x3::Identity;

	uint endIndex = 0;

	for( size_t i = 0; i < boneKeyFrames.size(); i++ )
	{
		if( boneKeyFrames[i].time > time )
		{
			endIndex = i;
			break;
		}
	}

	Vector3 position;

#ifdef VAPOR_ANIMATION_INTERPOLATION_LINEAR
	EulerAngles rotation;
#else
	Quaternion rotation;
#endif

	if( endIndex == 0 || endIndex == boneKeyFrames.size() )
	{
		endIndex -= (endIndex != 0) ? 1 : 0;
		position = boneKeyFrames[endIndex].position;
		rotation = boneKeyFrames[endIndex].rotation;
	}
	else
	{
		int startIndex = endIndex - 1;

		const KeyFrame& keyL = boneKeyFrames[startIndex];
		const KeyFrame& keyR = boneKeyFrames[endIndex];

		float timeDelta = keyR.time - keyL.time;
		float interpolator = ((float) time - keyL.time) / timeDelta;

		position = keyL.position.lerp(keyR.position, interpolator);

#ifdef VAPOR_ANIMATION_INTERPOLATION_LINEAR
		rotation = (EulerAngles&)
			((Vector3&) keyL.rotation).lerp(
			(Vector3&) keyR.rotation, interpolator);
#else
		Quaternion quatL( keyL.rotation );
		Quaternion quatR( keyR.rotation );
		rotation = quatL.slerp(quatR, interpolator);
#endif
	}

	Matrix4x3 interp =
#ifdef VAPOR_ANIMATION_INTERPOLATION_LINEAR
		Matrix4x3::createRotation(rotation) *
#else
		Matrix4x3::createFromQuaternion(rotation) *
#endif
		Matrix4x3::createTranslation(position);

	return interp;
}

//-----------------------------------//

NAMESPACE_RESOURCES_END<commit_msg>Renamed macro to get rid of vapor name.<commit_after>/************************************************************************
*
* vapor3D Engine  (2008-2010)
*
*	<http://www.vapor3d.org>
*
************************************************************************/

#include "Resources/API.h"
#include "Resources/Animation.h"
#include "Resources/Bone.h"
#include "Math/Helpers.h"

NAMESPACE_RESOURCES_BEGIN

//-----------------------------------//

Animation::Animation()
	: looped(true)
{ }

//-----------------------------------//

void Animation::setKeyFrames(const BonePtr& bone, const KeyFramesVector& frames)
{
	keyFrames[bone] = frames;

	for( size_t i = 0; i < frames.size(); i++ )
	{
		const KeyFrame& frame = frames[i];
		keyFramesVector.push_back(frame);
	}
}

//-----------------------------------//

float Animation::getTotalTime() const
{
	if( keyFrames.empty() )
		return 0;

	float min = LimitsFloatMaximum;
	float max = 0;

	for( size_t i = 0; i < keyFramesVector.size(); i++ )
	{
		const KeyFrame& keyFrame = keyFramesVector[i];

		min = std::min(min, keyFrame.time);
		max = std::max(max, keyFrame.time);
	}

	if( min == LimitsFloatMaximum )
		return 0;

	return max - min;
}

//-----------------------------------//

bool Animation::isLooped()
{
	return looped;
}

//-----------------------------------//

//#define ENABLE_ANIMATION_INTERPOLATION_LINEAR

Matrix4x3 Animation::getKeyFrameMatrix(const BonePtr& bone, float time)
{
	if( !bone || keyFrames.empty() )
		return Matrix4x3::Identity;

	const KeyFramesVector& boneKeyFrames = keyFrames[bone];

	if( boneKeyFrames.empty() )
		return Matrix4x3::Identity;

	uint endIndex = 0;

	for( size_t i = 0; i < boneKeyFrames.size(); i++ )
	{
		if( boneKeyFrames[i].time > time )
		{
			endIndex = i;
			break;
		}
	}

	Vector3 position;

#ifdef ENABLE_ANIMATION_INTERPOLATION_LINEAR
	EulerAngles rotation;
#else
	Quaternion rotation;
#endif

	if( endIndex == 0 || endIndex == boneKeyFrames.size() )
	{
		endIndex -= (endIndex != 0) ? 1 : 0;
		position = boneKeyFrames[endIndex].position;
		rotation = boneKeyFrames[endIndex].rotation;
	}
	else
	{
		int startIndex = endIndex - 1;

		const KeyFrame& keyL = boneKeyFrames[startIndex];
		const KeyFrame& keyR = boneKeyFrames[endIndex];

		float timeDelta = keyR.time - keyL.time;
		float interpolator = ((float) time - keyL.time) / timeDelta;

		position = keyL.position.lerp(keyR.position, interpolator);

#ifdef ENABLE_ANIMATION_INTERPOLATION_LINEAR
		rotation = (EulerAngles&)
			((Vector3&) keyL.rotation).lerp(
			(Vector3&) keyR.rotation, interpolator);
#else
		Quaternion quatL( keyL.rotation );
		Quaternion quatR( keyR.rotation );
		rotation = quatL.slerp(quatR, interpolator);
#endif
	}

	Matrix4x3 interp =
#ifdef ENABLE_ANIMATION_INTERPOLATION_LINEAR
		Matrix4x3::createRotation(rotation) *
#else
		Matrix4x3::createFromQuaternion(rotation) *
#endif
		Matrix4x3::createTranslation(position);

	return interp;
}

//-----------------------------------//

NAMESPACE_RESOURCES_END<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* libmspub
 * Version: MPL 1.1 / GPLv2+ / LGPLv2+
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License or as specified alternatively below. You may obtain a copy of
 * the License at http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * Major Contributor(s):
 * Copyright (C) 2012 Fridrich Strba <fridrich.strba@bluewin.ch>
 *
 *
 * All Rights Reserved.
 *
 * For minor contributions see the git repository.
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPLv2+"), or
 * the GNU Lesser General Public License Version 2 or later (the "LGPLv2+"),
 * in which case the provisions of the GPLv2+ or the LGPLv2+ are applicable
 * instead of those above.
 */

#include "MSPUBCollector.h"
#include "libmspub_utils.h"
#include "MSPUBConstants.h"
#include "MSPUBTypes.h"

libmspub::MSPUBCollector::MSPUBCollector(libwpg::WPGPaintInterface *painter) :
  m_painter(painter), contentChunkReferences(), m_width(0), m_height(0),
  m_widthSet(false), m_heightSet(false), m_commonPageProperties(),
  m_numPages(0), textStringsById(), pagesBySeqNum(), textShapesBySeqNum(),
  imgShapesBySeqNum(), images(), possibleImageShapes(),
  colors(), defaultColor(0, 0, 0), fonts(),
  defaultCharStyles(), defaultParaStyles()
{
}

libmspub::MSPUBCollector::~MSPUBCollector()
{
}

void libmspub::MSPUBCollector::setDefaultColor(unsigned char r, unsigned char g, unsigned char b)
{
  defaultColor = Color(r, g, b);
}

libmspub::ContentChunkReference::ContentChunkReference(libmspub::MSPUBContentChunkType type,
    unsigned long offset, unsigned long end,
    unsigned seqNum, unsigned parentSeqNum) :
  type(type), offset(offset), end(end), seqNum(seqNum), parentSeqNum(parentSeqNum)
{
}

void libmspub::MSPUBCollector::addDefaultCharacterStyle(const CharacterStyle &st)
{
  defaultCharStyles.push_back(st);
}

void libmspub::MSPUBCollector::addDefaultParagraphStyle(const ParagraphStyle &st)
{
  defaultParaStyles.push_back(st);
}

bool libmspub::MSPUBCollector::addPage(unsigned seqNum)
{
  if (! (m_widthSet && m_heightSet) )
  {
    return false;
  }
  MSPUB_DEBUG_MSG(("Adding page of seqnum 0x%x\n", seqNum));
  pagesBySeqNum[seqNum] = PageInfo();
  return true;
}

bool libmspub::MSPUBCollector::addTextShape(unsigned stringId, unsigned seqNum, unsigned pageSeqNum)
{
  std::map<unsigned, PageInfo>::iterator i_page = pagesBySeqNum.find(pageSeqNum);
  if (i_page == pagesBySeqNum.end())
  {
    MSPUB_DEBUG_MSG(("Page of seqnum 0x%x not found in addTextShape!\n", pageSeqNum));
    return false;
  }
  else
  {
    std::map<unsigned, std::vector<TextParagraph> >::iterator i_str = textStringsById.find(stringId);
    if (i_str == textStringsById.end())
    {
      MSPUB_DEBUG_MSG(("Text string of id 0x%x not found in addTextShape!\n", stringId));
      return false;
    }
    else
    {
      std::pair<std::map<unsigned, TextShapeInfo>::iterator, bool> result =
        textShapesBySeqNum.insert(std::pair<const unsigned, TextShapeInfo>(seqNum, TextShapeInfo(i_str->second)));
      if (result.second)
      {
        i_page->second.textShapeReferences.push_back(result.first);
        MSPUB_DEBUG_MSG(("addTextShape succeeded with id 0x%x\n", stringId));
        return true;
      }
      MSPUB_DEBUG_MSG(("already tried to add the text shape of seqnum 0x%x to this page!\n", seqNum));
      return false;
    }
  }
}

bool libmspub::MSPUBCollector::setShapeImgIndex(unsigned seqNum, unsigned index)
{
  MSPUB_DEBUG_MSG(("Setting image index of shape with seqnum 0x%x to 0x%x\n", seqNum, index));
  std::map<unsigned, UnknownShapeInfo>::iterator i = possibleImageShapes.find(seqNum);
  if (i != possibleImageShapes.end())
  {
    i->second.imgIndex = index;
    return true;
  }
  return false;
}

bool libmspub::MSPUBCollector::setShapeCoordinatesInEmu(unsigned seqNum, int xs, int ys, int xe, int ye)
{
  if (! (m_widthSet && m_heightSet))
  {
    return false;
  }
  WPXPropertyList *propsToEdit;
  std::map<unsigned, TextShapeInfo>::iterator elt = textShapesBySeqNum.find(seqNum);
  if (elt != textShapesBySeqNum.end())
  {
    propsToEdit = &(elt->second.props);
  }
  else
  {
    std::map<unsigned, UnknownShapeInfo>::iterator elt = possibleImageShapes.find(seqNum);
    if (elt != possibleImageShapes.end())
    {
      propsToEdit = &(elt->second.props);
    }
    else
    {
      return false;
    }
  }
  double x_center = m_commonPageProperties["svg:width"]->getDouble() / 2;
  double y_center = m_commonPageProperties["svg:height"]->getDouble() / 2;
  propsToEdit->insert("svg:x", x_center + (double)xs / EMUS_IN_INCH);
  propsToEdit->insert("svg:y", y_center + (double)ys / EMUS_IN_INCH);
  propsToEdit->insert("svg:width", (double)(xe - xs) / EMUS_IN_INCH);
  propsToEdit->insert("svg:height", (double)(ye - ys) / EMUS_IN_INCH);
  return true;
}

void libmspub::MSPUBCollector::addFont(std::vector<unsigned char> name)
{
  fonts.push_back(name);
}

void libmspub::MSPUBCollector::assignImages()
{
  for (std::map<unsigned, UnknownShapeInfo>::const_iterator i = possibleImageShapes.begin(); i != possibleImageShapes.end(); ++i)
  {
    if (i->second.imgIndex > 0 && i->second.imgIndex <= images.size())
    {
      std::pair<std::map<unsigned, ImgShapeInfo>::iterator, bool> result =
        imgShapesBySeqNum.insert(std::pair<unsigned, ImgShapeInfo>(i->first, ImgShapeInfo(images[i->second.imgIndex - 1].first, images[i->second.imgIndex - 1].second, i->second.props)));
      if (result.second)
      {
        std::map<unsigned, PageInfo>::iterator i_pg = pagesBySeqNum.find(i->second.pageSeqNum);
        if (i_pg != pagesBySeqNum.end())
        {
          i_pg->second.imgShapeReferences.push_back(result.first);
        }
      }
    }
  }
}

WPXPropertyList libmspub::MSPUBCollector::getParaStyleProps(const ParagraphStyle &style, unsigned defaultParaStyleIndex)
{
  ParagraphStyle _nothing;
  const ParagraphStyle &defaultParaStyle = defaultParaStyleIndex < defaultParaStyles.size() ? defaultParaStyles[defaultParaStyleIndex] : _nothing;
  WPXPropertyList ret;
  Alignment align = style.align >= 0 ? style.align : defaultParaStyle.align;
  switch (align)
  {
  case RIGHT:
    ret.insert("fo:text-align", "right");
    break;
  case CENTER:
    ret.insert("fo:text-align", "center");
    break;
  case JUSTIFY:
    ret.insert("fo:text-align", "justify");
    break;
  case LEFT:
  default:
    ret.insert("fo:text-align", "left");
    break;
  }
  return ret;
}

WPXPropertyList libmspub::MSPUBCollector::getCharStyleProps(const CharacterStyle &style, unsigned defaultCharStyleIndex)
{
  CharacterStyle _nothing = CharacterStyle(false, false, false);
  const CharacterStyle &defaultCharStyle = defaultCharStyleIndex < defaultCharStyles.size() ? defaultCharStyles[defaultCharStyleIndex] : _nothing;
  WPXPropertyList ret;
  if (style.italic)
  {
    ret.insert("fo:font-style", "italic");
  }
  if (style.bold)
  {
    ret.insert("fo:font-weight", "bold");
  }
  if (style.underline)
  {
    ret.insert("style:text-underline-type", "single");
  }
  if (style.textSizeInPt != -1)
  {
    ret.insert("fo:font-size", style.textSizeInPt);
  }
  else if (defaultCharStyle.textSizeInPt != -1)
  {
    ret.insert("fo:font-size", defaultCharStyle.textSizeInPt);
  }
  if (style.colorIndex >= 0 && (size_t)style.colorIndex < colors.size())
  {
    ret.insert("fo:color", getColorString(colors[style.colorIndex]));
  }
  else
  {
    ret.insert("fo:color", getColorString(defaultColor));
  }
  if (style.fontIndex < fonts.size())
  {
    WPXString str;
    appendCharacters(str, fonts[style.fontIndex]);
    ret.insert("style:font-name", str);
  }
  return ret;
}

WPXString libmspub::MSPUBCollector::getColorString(const Color &color)
{
  WPXString ret;
  ret.sprintf("#%.2x%.2x%.2x",(unsigned char)color.r, (unsigned char)color.g, (unsigned char)color.b);
  MSPUB_DEBUG_MSG(("String for r: 0x%x, g: 0x%x, b: 0x%x is %s\n", color.r, color.g, color.b, ret.cstr()));
  return ret;
}

bool libmspub::MSPUBCollector::go()
{
  assignImages();
  for (std::map<unsigned, PageInfo>::const_iterator i = pagesBySeqNum.begin(); i != pagesBySeqNum.end(); ++i)
  {
    if (i->second.textShapeReferences.size() >  0 || i->second.imgShapeReferences.size() > 0)
    {
      m_painter->startGraphics(m_commonPageProperties);
      for (std::vector<std::map<unsigned, TextShapeInfo>::const_iterator>::const_iterator j = i->second.textShapeReferences.begin();
           j != i->second.textShapeReferences.end(); ++j)
      {
        m_painter->startTextObject((*j)->second.props, WPXPropertyListVector());
        for (std::vector<TextParagraph>::const_iterator k = (*j)->second.str.begin(); k != (*j)->second.str.end(); ++k)
        {
          WPXPropertyList paraProps = getParaStyleProps(k->style, k->style.defaultCharStyleIndex);
          m_painter->startTextLine(paraProps);
          for (std::vector<TextSpan>::const_iterator l = k->spans.begin(); l != k->spans.end(); ++l)
          {
            WPXString text;
            appendCharacters(text, l->chars);
            WPXPropertyList charProps = getCharStyleProps(l->style, k->style.defaultCharStyleIndex);
            m_painter->startTextSpan(charProps);
            m_painter->insertText(text);
            m_painter->endTextSpan();
          }
          m_painter->endTextLine();
        }
        m_painter->endTextObject();
      }
      for (std::vector<std::map<unsigned, ImgShapeInfo>::const_iterator>::const_iterator j = i->second.imgShapeReferences.begin();
           j != i->second.imgShapeReferences.end(); ++j)
      {
        m_painter->drawGraphicObject((*j)->second.props, (*j)->second.img);
      }
      m_painter->endGraphics();
    }
  }
  return true;
}

bool libmspub::MSPUBCollector::addTextString(const std::vector<TextParagraph> &str, unsigned id)
{
  MSPUB_DEBUG_MSG(("addTextString, id: 0x%x\n", id));
  textStringsById[id] = str;
  return true; //FIXME: Warn if the string already existed in the map.
}

void libmspub::MSPUBCollector::setWidthInEmu(unsigned long widthInEmu)
{
  //FIXME: Warn if this is called twice
  m_width = widthInEmu;
  m_commonPageProperties.insert("svg:width", ((double)widthInEmu)/EMUS_IN_INCH);
  m_widthSet = true;
}

void libmspub::MSPUBCollector::setHeightInEmu(unsigned long heightInEmu)
{
  //FIXME: Warn if this is called twice
  m_height = heightInEmu;
  m_commonPageProperties.insert("svg:height", ((double)heightInEmu)/EMUS_IN_INCH);
  m_heightSet = true;
}

bool libmspub::MSPUBCollector::addImage(unsigned index, ImgType type, WPXBinaryData img)
{
  MSPUB_DEBUG_MSG(("Image at index %d and of type 0x%x added.\n", index, type));
  while (images.size() < index)
  {
    images.push_back(std::pair<ImgType, WPXBinaryData>(UNKNOWN, WPXBinaryData()));
  }
  images[index - 1] = std::pair<ImgType, WPXBinaryData>(type, img);
  return true;
}

bool libmspub::MSPUBCollector::addShape(unsigned seqNum, unsigned pageSeqNum)
{
  possibleImageShapes.insert(std::pair<unsigned, UnknownShapeInfo>(seqNum, UnknownShapeInfo(pageSeqNum)));
  return true;
}

void libmspub::MSPUBCollector::addColor(unsigned char r, unsigned char g, unsigned char b)
{
  colors.push_back(Color(r, g, b));
}

/* vim:set shiftwidth=2 softtabstop=2 expandtab: */
<commit_msg>Fix text color in styles that don't use the default color -- I hope I never have to touch text color again ;)<commit_after>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* libmspub
 * Version: MPL 1.1 / GPLv2+ / LGPLv2+
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License or as specified alternatively below. You may obtain a copy of
 * the License at http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * Major Contributor(s):
 * Copyright (C) 2012 Fridrich Strba <fridrich.strba@bluewin.ch>
 *
 *
 * All Rights Reserved.
 *
 * For minor contributions see the git repository.
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPLv2+"), or
 * the GNU Lesser General Public License Version 2 or later (the "LGPLv2+"),
 * in which case the provisions of the GPLv2+ or the LGPLv2+ are applicable
 * instead of those above.
 */

#include "MSPUBCollector.h"
#include "libmspub_utils.h"
#include "MSPUBConstants.h"
#include "MSPUBTypes.h"

libmspub::MSPUBCollector::MSPUBCollector(libwpg::WPGPaintInterface *painter) :
  m_painter(painter), contentChunkReferences(), m_width(0), m_height(0),
  m_widthSet(false), m_heightSet(false), m_commonPageProperties(),
  m_numPages(0), textStringsById(), pagesBySeqNum(), textShapesBySeqNum(),
  imgShapesBySeqNum(), images(), possibleImageShapes(),
  colors(), defaultColor(0, 0, 0), fonts(),
  defaultCharStyles(), defaultParaStyles()
{
}

libmspub::MSPUBCollector::~MSPUBCollector()
{
}

void libmspub::MSPUBCollector::setDefaultColor(unsigned char r, unsigned char g, unsigned char b)
{
  defaultColor = Color(r, g, b);
}

libmspub::ContentChunkReference::ContentChunkReference(libmspub::MSPUBContentChunkType type,
    unsigned long offset, unsigned long end,
    unsigned seqNum, unsigned parentSeqNum) :
  type(type), offset(offset), end(end), seqNum(seqNum), parentSeqNum(parentSeqNum)
{
}

void libmspub::MSPUBCollector::addDefaultCharacterStyle(const CharacterStyle &st)
{
  defaultCharStyles.push_back(st);
}

void libmspub::MSPUBCollector::addDefaultParagraphStyle(const ParagraphStyle &st)
{
  defaultParaStyles.push_back(st);
}

bool libmspub::MSPUBCollector::addPage(unsigned seqNum)
{
  if (! (m_widthSet && m_heightSet) )
  {
    return false;
  }
  MSPUB_DEBUG_MSG(("Adding page of seqnum 0x%x\n", seqNum));
  pagesBySeqNum[seqNum] = PageInfo();
  return true;
}

bool libmspub::MSPUBCollector::addTextShape(unsigned stringId, unsigned seqNum, unsigned pageSeqNum)
{
  std::map<unsigned, PageInfo>::iterator i_page = pagesBySeqNum.find(pageSeqNum);
  if (i_page == pagesBySeqNum.end())
  {
    MSPUB_DEBUG_MSG(("Page of seqnum 0x%x not found in addTextShape!\n", pageSeqNum));
    return false;
  }
  else
  {
    std::map<unsigned, std::vector<TextParagraph> >::iterator i_str = textStringsById.find(stringId);
    if (i_str == textStringsById.end())
    {
      MSPUB_DEBUG_MSG(("Text string of id 0x%x not found in addTextShape!\n", stringId));
      return false;
    }
    else
    {
      std::pair<std::map<unsigned, TextShapeInfo>::iterator, bool> result =
        textShapesBySeqNum.insert(std::pair<const unsigned, TextShapeInfo>(seqNum, TextShapeInfo(i_str->second)));
      if (result.second)
      {
        i_page->second.textShapeReferences.push_back(result.first);
        MSPUB_DEBUG_MSG(("addTextShape succeeded with id 0x%x\n", stringId));
        return true;
      }
      MSPUB_DEBUG_MSG(("already tried to add the text shape of seqnum 0x%x to this page!\n", seqNum));
      return false;
    }
  }
}

bool libmspub::MSPUBCollector::setShapeImgIndex(unsigned seqNum, unsigned index)
{
  MSPUB_DEBUG_MSG(("Setting image index of shape with seqnum 0x%x to 0x%x\n", seqNum, index));
  std::map<unsigned, UnknownShapeInfo>::iterator i = possibleImageShapes.find(seqNum);
  if (i != possibleImageShapes.end())
  {
    i->second.imgIndex = index;
    return true;
  }
  return false;
}

bool libmspub::MSPUBCollector::setShapeCoordinatesInEmu(unsigned seqNum, int xs, int ys, int xe, int ye)
{
  if (! (m_widthSet && m_heightSet))
  {
    return false;
  }
  WPXPropertyList *propsToEdit;
  std::map<unsigned, TextShapeInfo>::iterator elt = textShapesBySeqNum.find(seqNum);
  if (elt != textShapesBySeqNum.end())
  {
    propsToEdit = &(elt->second.props);
  }
  else
  {
    std::map<unsigned, UnknownShapeInfo>::iterator elt = possibleImageShapes.find(seqNum);
    if (elt != possibleImageShapes.end())
    {
      propsToEdit = &(elt->second.props);
    }
    else
    {
      return false;
    }
  }
  double x_center = m_commonPageProperties["svg:width"]->getDouble() / 2;
  double y_center = m_commonPageProperties["svg:height"]->getDouble() / 2;
  propsToEdit->insert("svg:x", x_center + (double)xs / EMUS_IN_INCH);
  propsToEdit->insert("svg:y", y_center + (double)ys / EMUS_IN_INCH);
  propsToEdit->insert("svg:width", (double)(xe - xs) / EMUS_IN_INCH);
  propsToEdit->insert("svg:height", (double)(ye - ys) / EMUS_IN_INCH);
  return true;
}

void libmspub::MSPUBCollector::addFont(std::vector<unsigned char> name)
{
  fonts.push_back(name);
}

void libmspub::MSPUBCollector::assignImages()
{
  for (std::map<unsigned, UnknownShapeInfo>::const_iterator i = possibleImageShapes.begin(); i != possibleImageShapes.end(); ++i)
  {
    if (i->second.imgIndex > 0 && i->second.imgIndex <= images.size())
    {
      std::pair<std::map<unsigned, ImgShapeInfo>::iterator, bool> result =
        imgShapesBySeqNum.insert(std::pair<unsigned, ImgShapeInfo>(i->first, ImgShapeInfo(images[i->second.imgIndex - 1].first, images[i->second.imgIndex - 1].second, i->second.props)));
      if (result.second)
      {
        std::map<unsigned, PageInfo>::iterator i_pg = pagesBySeqNum.find(i->second.pageSeqNum);
        if (i_pg != pagesBySeqNum.end())
        {
          i_pg->second.imgShapeReferences.push_back(result.first);
        }
      }
    }
  }
}

WPXPropertyList libmspub::MSPUBCollector::getParaStyleProps(const ParagraphStyle &style, unsigned defaultParaStyleIndex)
{
  ParagraphStyle _nothing;
  const ParagraphStyle &defaultParaStyle = defaultParaStyleIndex < defaultParaStyles.size() ? defaultParaStyles[defaultParaStyleIndex] : _nothing;
  WPXPropertyList ret;
  Alignment align = style.align >= 0 ? style.align : defaultParaStyle.align;
  switch (align)
  {
  case RIGHT:
    ret.insert("fo:text-align", "right");
    break;
  case CENTER:
    ret.insert("fo:text-align", "center");
    break;
  case JUSTIFY:
    ret.insert("fo:text-align", "justify");
    break;
  case LEFT:
  default:
    ret.insert("fo:text-align", "left");
    break;
  }
  return ret;
}

WPXPropertyList libmspub::MSPUBCollector::getCharStyleProps(const CharacterStyle &style, unsigned defaultCharStyleIndex)
{
  CharacterStyle _nothing = CharacterStyle(false, false, false);
  const CharacterStyle &defaultCharStyle = defaultCharStyleIndex < defaultCharStyles.size() ? defaultCharStyles[defaultCharStyleIndex] : _nothing;
  WPXPropertyList ret;
  if (style.italic)
  {
    ret.insert("fo:font-style", "italic");
  }
  if (style.bold)
  {
    ret.insert("fo:font-weight", "bold");
  }
  if (style.underline)
  {
    ret.insert("style:text-underline-type", "single");
  }
  if (style.textSizeInPt != -1)
  {
    ret.insert("fo:font-size", style.textSizeInPt);
  }
  else if (defaultCharStyle.textSizeInPt != -1)
  {
    ret.insert("fo:font-size", defaultCharStyle.textSizeInPt);
  }
  if (style.colorIndex >= 0 && (size_t)style.colorIndex < colors.size())
  {
    ret.insert("fo:color", getColorString(colors[style.colorIndex]));
  }
  else if (defaultCharStyle.colorIndex >= 0 && (size_t)defaultCharStyle.colorIndex < colors.size())
  {
    ret.insert("fo:color", getColorString(colors[defaultCharStyle.colorIndex]));
  }
  else
  {
    ret.insert("fo:color", getColorString(defaultColor));
  }
  if (style.fontIndex < fonts.size())
  {
    WPXString str;
    appendCharacters(str, fonts[style.fontIndex]);
    ret.insert("style:font-name", str);
  }
  return ret;
}

WPXString libmspub::MSPUBCollector::getColorString(const Color &color)
{
  WPXString ret;
  ret.sprintf("#%.2x%.2x%.2x",(unsigned char)color.r, (unsigned char)color.g, (unsigned char)color.b);
  MSPUB_DEBUG_MSG(("String for r: 0x%x, g: 0x%x, b: 0x%x is %s\n", color.r, color.g, color.b, ret.cstr()));
  return ret;
}

bool libmspub::MSPUBCollector::go()
{
  assignImages();
  for (std::map<unsigned, PageInfo>::const_iterator i = pagesBySeqNum.begin(); i != pagesBySeqNum.end(); ++i)
  {
    if (i->second.textShapeReferences.size() >  0 || i->second.imgShapeReferences.size() > 0)
    {
      m_painter->startGraphics(m_commonPageProperties);
      for (std::vector<std::map<unsigned, TextShapeInfo>::const_iterator>::const_iterator j = i->second.textShapeReferences.begin();
           j != i->second.textShapeReferences.end(); ++j)
      {
        m_painter->startTextObject((*j)->second.props, WPXPropertyListVector());
        for (std::vector<TextParagraph>::const_iterator k = (*j)->second.str.begin(); k != (*j)->second.str.end(); ++k)
        {
          WPXPropertyList paraProps = getParaStyleProps(k->style, k->style.defaultCharStyleIndex);
          m_painter->startTextLine(paraProps);
          for (std::vector<TextSpan>::const_iterator l = k->spans.begin(); l != k->spans.end(); ++l)
          {
            WPXString text;
            appendCharacters(text, l->chars);
            WPXPropertyList charProps = getCharStyleProps(l->style, k->style.defaultCharStyleIndex);
            m_painter->startTextSpan(charProps);
            m_painter->insertText(text);
            m_painter->endTextSpan();
          }
          m_painter->endTextLine();
        }
        m_painter->endTextObject();
      }
      for (std::vector<std::map<unsigned, ImgShapeInfo>::const_iterator>::const_iterator j = i->second.imgShapeReferences.begin();
           j != i->second.imgShapeReferences.end(); ++j)
      {
        m_painter->drawGraphicObject((*j)->second.props, (*j)->second.img);
      }
      m_painter->endGraphics();
    }
  }
  return true;
}

bool libmspub::MSPUBCollector::addTextString(const std::vector<TextParagraph> &str, unsigned id)
{
  MSPUB_DEBUG_MSG(("addTextString, id: 0x%x\n", id));
  textStringsById[id] = str;
  return true; //FIXME: Warn if the string already existed in the map.
}

void libmspub::MSPUBCollector::setWidthInEmu(unsigned long widthInEmu)
{
  //FIXME: Warn if this is called twice
  m_width = widthInEmu;
  m_commonPageProperties.insert("svg:width", ((double)widthInEmu)/EMUS_IN_INCH);
  m_widthSet = true;
}

void libmspub::MSPUBCollector::setHeightInEmu(unsigned long heightInEmu)
{
  //FIXME: Warn if this is called twice
  m_height = heightInEmu;
  m_commonPageProperties.insert("svg:height", ((double)heightInEmu)/EMUS_IN_INCH);
  m_heightSet = true;
}

bool libmspub::MSPUBCollector::addImage(unsigned index, ImgType type, WPXBinaryData img)
{
  MSPUB_DEBUG_MSG(("Image at index %d and of type 0x%x added.\n", index, type));
  while (images.size() < index)
  {
    images.push_back(std::pair<ImgType, WPXBinaryData>(UNKNOWN, WPXBinaryData()));
  }
  images[index - 1] = std::pair<ImgType, WPXBinaryData>(type, img);
  return true;
}

bool libmspub::MSPUBCollector::addShape(unsigned seqNum, unsigned pageSeqNum)
{
  possibleImageShapes.insert(std::pair<unsigned, UnknownShapeInfo>(seqNum, UnknownShapeInfo(pageSeqNum)));
  return true;
}

void libmspub::MSPUBCollector::addColor(unsigned char r, unsigned char g, unsigned char b)
{
  colors.push_back(Color(r, g, b));
}

/* vim:set shiftwidth=2 softtabstop=2 expandtab: */
<|endoftext|>