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

Licensed to the OpenCOR team under one or more contributor license agreements.
See the NOTICE.txt file distributed with this work for additional information
regarding copyright ownership. The OpenCOR team licenses this file to you under
the Apache License, Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.

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

//==============================================================================
// COMBINE support tests
//==============================================================================

#include "../../../../tests/src/testsutils.h"

//==============================================================================

#include "combinearchive.h"
#include "corecliutils.h"
#include "tests.h"

//==============================================================================

#include <QtTest/QtTest>

//==============================================================================

#include <QXmlSchema>
#include <QZipReader>

//==============================================================================

void dummyMessageHandler(QtMsgType pType, const QMessageLogContext &pContext,
                         const QString &pMessage)
{
    Q_UNUSED(pType);
    Q_UNUSED(pContext);
    Q_UNUSED(pMessage);
}

//==============================================================================

void Tests::initTestCase()
{
    // Quick trick to prevent warnings from Qt
    // Note: indeed, to call CombineArchive::load() calls Core::validXml(),
    //       which creates a QXmlSchema object. The first time a QXmlSchema
    //       object is created, Qt generates some warnings about the current
    //       thread not being the object's thread and therefore not being able
    //       to move to the target thread. We clearly have nothing to do with
    //       those warnings and, if anything, they just pollute our test output,
    //       so...

    qInstallMessageHandler(dummyMessageHandler);

    QXmlSchema schema;

    Q_UNUSED(schema);

    qInstallMessageHandler(0);

    // Create a simple COMBINE archive that contains various files

    mCombineArchive = new OpenCOR::COMBINESupport::CombineArchive(OpenCOR::Core::temporaryFileName(), true);

    int counter = 0;

    for (int i = 1; i <= 3; ++i) {
        for (int j = 1; j <= 3; ++j, ++counter) {
            mCombineArchive->addFile(OpenCOR::fileName("src/plugins/support/COMBINESupport/tests/data/dir0%1/file0%2.txt").arg(QString::number(i), QString::number(j)),
                                     QString("dir0%1/file0%2.txt").arg(QString::number(i), QString::number(j)),
                                     OpenCOR::COMBINESupport::CombineArchiveFile::Format(1+counter%5),
                                     !(counter%2));
        }
    }
}

//==============================================================================

void Tests::cleanupTestCase()
{
    // Clean up after ourselves

    QFile::remove(mCombineArchive->fileName());

    // Delete some internal objects

    delete mCombineArchive;
}

//==============================================================================

void Tests::doBasicTests(const QString &pFileName)
{
    // Save the given COMBINE archive to the given file

    QString fileName = pFileName.isEmpty()?mCombineArchive->fileName():pFileName;

    mCombineArchive->save(fileName);

    QVERIFY(QFile::exists(fileName));

    // Unzip our COMBINE archive and make sure that its manifest is correct and
    // that the various files are present

    OpenCOR::ZIPSupport::QZipReader zipReader(fileName);
    QTemporaryDir temporaryDir;

    QVERIFY(zipReader.extractAll(temporaryDir.path()));

    QCOMPARE(OpenCOR::fileContents(temporaryDir.path()+QDir::separator()+"manifest.xml"),
             OpenCOR::fileContents(OpenCOR::fileName("src/plugins/support/COMBINESupport/tests/data/manifest.xml")));

    for (int i = 1; i <= 3; ++i) {
        for (int j = 1; j <= 3; ++j)
            QVERIFY(QFile::exists(temporaryDir.path()+QDir::separator()+QString("dir0%1/file0%2.txt").arg(QString::number(i), QString::number(j))));
    }
}

//==============================================================================

void Tests::basicTests()
{
    // Some basic tests to save our COMBINE archive either directly or to a
    // different file and checking that its contents is sound

    QString otherFileName = OpenCOR::Core::temporaryFileName();

    doBasicTests();
    doBasicTests(otherFileName);

    // Check that we can load our other COMBINE archive and save it in yet
    // another file, and make sure that the SHA-1 of the two files is the same

    OpenCOR::COMBINESupport::CombineArchive otherCombineArchive(otherFileName);

    QString yetAnotherFileName = OpenCOR::Core::temporaryFileName();

    QVERIFY(otherCombineArchive.load());
    QVERIFY(otherCombineArchive.isValid());
    QVERIFY(otherCombineArchive.save(yetAnotherFileName));

    QByteArray otherFileContents;
    QByteArray yetAnotherFileContents;

    QVERIFY(OpenCOR::Core::readFileContentsFromFile(otherFileName, otherFileContents));
    QVERIFY(OpenCOR::Core::readFileContentsFromFile(yetAnotherFileName, yetAnotherFileContents));

    QCOMPARE(OpenCOR::Core::sha1(otherFileContents),
             OpenCOR::Core::sha1(yetAnotherFileContents));

    // Clean up after ourselves

    QFile::remove(otherFileName);
    QFile::remove(yetAnotherFileName);
}

//==============================================================================

void Tests::loadingErrorTests()
{
    // Try to load a non-existent COMBINE archive

    OpenCOR::COMBINESupport::CombineArchive combineArchive(OpenCOR::fileName("src/plugins/support/COMBINESupport/tests/data/nonexistent.omex"));

    QVERIFY(!combineArchive.load());
    QVERIFY(combineArchive.issues().count() == 1);
    QCOMPARE(combineArchive.issues().first().message(), QString("the archive does not exist"));

    // Try to load a non-signed COMBINE archive

    combineArchive.setFileName(OpenCOR::fileName("src/plugins/support/COMBINESupport/tests/data/notsigned.omex"));

    QVERIFY(!combineArchive.reload());
    QVERIFY(combineArchive.issues().count() == 1);
    QCOMPARE(combineArchive.issues().first().message(), QString("the archive is not signed"));

    // Try to load a badly signed COMBINE archive

    combineArchive.setFileName(OpenCOR::fileName("src/plugins/support/COMBINESupport/tests/data/badlysigned.omex"));

    QVERIFY(!combineArchive.reload());
    QVERIFY(combineArchive.issues().count() == 1);
    QCOMPARE(combineArchive.issues().first().message(), QString("the archive does not have the correct signature"));

    // Try to load a COMBINE archive with no manifest

    combineArchive.setFileName(OpenCOR::fileName("src/plugins/support/COMBINESupport/tests/data/nomanifest.omex"));

    QVERIFY(combineArchive.reload());
    QVERIFY(!combineArchive.isValid());
    QVERIFY(combineArchive.issues().count() == 1);
    QCOMPARE(combineArchive.issues().first().message(), QString("the archive does not have a manifest"));

    // Try to load a COMBINE archive which manifest is not a valid OMEX file

    combineArchive.setFileName(OpenCOR::fileName("src/plugins/support/COMBINESupport/tests/data/notvalidomex.omex"));

    QVERIFY(combineArchive.reload());
    QVERIFY(!combineArchive.isValid());
    QVERIFY(combineArchive.issues().count() == 1);
    QCOMPARE(combineArchive.issues().first().message(), QString("the manifest is not a valid OMEX file"));

    // Try to load a COMBINE archive that contains a non-existent file

    combineArchive.setFileName(OpenCOR::fileName("src/plugins/support/COMBINESupport/tests/data/nonexistentfile.omex"));

    QVERIFY(combineArchive.reload());
    QVERIFY(!combineArchive.isValid());
    QVERIFY(combineArchive.issues().count() == 1);
    QCOMPARE(combineArchive.issues().first().message(), QString("nonexistentfile.txt could not be found"));

    // Try to load a COMBINE archive which manifest doesn't reference the
    // COMBINE archive itself

    combineArchive.setFileName(OpenCOR::fileName("src/plugins/support/COMBINESupport/tests/data/nocombinearchivereference.omex"));

    QVERIFY(combineArchive.reload());
    QVERIFY(!combineArchive.isValid());
    QVERIFY(combineArchive.issues().count() == 1);
    QCOMPARE(combineArchive.issues().first().message(), QString("no reference to the COMBINE archive itself could be found"));
}

//==============================================================================

QTEST_GUILESS_MAIN(Tests)

//==============================================================================
// End of file
//==============================================================================
<commit_msg>Some minor cleaning up [ci skip].<commit_after>/*******************************************************************************

Licensed to the OpenCOR team under one or more contributor license agreements.
See the NOTICE.txt file distributed with this work for additional information
regarding copyright ownership. The OpenCOR team licenses this file to you under
the Apache License, Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.

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

//==============================================================================
// COMBINE support tests
//==============================================================================

#include "../../../../tests/src/testsutils.h"

//==============================================================================

#include "combinearchive.h"
#include "corecliutils.h"
#include "tests.h"

//==============================================================================

#include <QtTest/QtTest>

//==============================================================================

#include <QXmlSchema>
#include <QZipReader>

//==============================================================================

void dummyMessageHandler(QtMsgType pType, const QMessageLogContext &pContext,
                         const QString &pMessage)
{
    Q_UNUSED(pType);
    Q_UNUSED(pContext);
    Q_UNUSED(pMessage);
}

//==============================================================================

void Tests::initTestCase()
{
    // Quick trick to prevent warnings from Qt
    // Note: indeed, to call CombineArchive::load() calls Core::validXml(),
    //       which creates a QXmlSchema object. The first time a QXmlSchema
    //       object is created, Qt generates some warnings about the current
    //       thread not being the object's thread and therefore not being able
    //       to move to the target thread. We clearly have nothing to do with
    //       those warnings and, if anything, they just pollute our test output,
    //       so...

qInstallMessageHandler(dummyMessageHandler);
    QXmlSchema schema;
qInstallMessageHandler(0);

    Q_UNUSED(schema);

    // Create a simple COMBINE archive that contains various files

    mCombineArchive = new OpenCOR::COMBINESupport::CombineArchive(OpenCOR::Core::temporaryFileName(), true);

    int counter = 0;

    for (int i = 1; i <= 3; ++i) {
        for (int j = 1; j <= 3; ++j, ++counter) {
            mCombineArchive->addFile(OpenCOR::fileName("src/plugins/support/COMBINESupport/tests/data/dir0%1/file0%2.txt").arg(QString::number(i), QString::number(j)),
                                     QString("dir0%1/file0%2.txt").arg(QString::number(i), QString::number(j)),
                                     OpenCOR::COMBINESupport::CombineArchiveFile::Format(1+counter%5),
                                     !(counter%2));
        }
    }
}

//==============================================================================

void Tests::cleanupTestCase()
{
    // Clean up after ourselves

    QFile::remove(mCombineArchive->fileName());

    // Delete some internal objects

    delete mCombineArchive;
}

//==============================================================================

void Tests::doBasicTests(const QString &pFileName)
{
    // Save the given COMBINE archive to the given file

    QString fileName = pFileName.isEmpty()?mCombineArchive->fileName():pFileName;

    mCombineArchive->save(fileName);

    QVERIFY(QFile::exists(fileName));

    // Unzip our COMBINE archive and make sure that its manifest is correct and
    // that the various files are present

    OpenCOR::ZIPSupport::QZipReader zipReader(fileName);
    QTemporaryDir temporaryDir;

    QVERIFY(zipReader.extractAll(temporaryDir.path()));

    QCOMPARE(OpenCOR::fileContents(temporaryDir.path()+QDir::separator()+"manifest.xml"),
             OpenCOR::fileContents(OpenCOR::fileName("src/plugins/support/COMBINESupport/tests/data/manifest.xml")));

    for (int i = 1; i <= 3; ++i) {
        for (int j = 1; j <= 3; ++j)
            QVERIFY(QFile::exists(temporaryDir.path()+QDir::separator()+QString("dir0%1/file0%2.txt").arg(QString::number(i), QString::number(j))));
    }
}

//==============================================================================

void Tests::basicTests()
{
    // Some basic tests to save our COMBINE archive either directly or to a
    // different file and checking that its contents is sound

    QString otherFileName = OpenCOR::Core::temporaryFileName();

    doBasicTests();
    doBasicTests(otherFileName);

    // Check that we can load our other COMBINE archive and save it in yet
    // another file, and make sure that the SHA-1 of the two files is the same

    OpenCOR::COMBINESupport::CombineArchive otherCombineArchive(otherFileName);

    QString yetAnotherFileName = OpenCOR::Core::temporaryFileName();

    QVERIFY(otherCombineArchive.load());
    QVERIFY(otherCombineArchive.isValid());
    QVERIFY(otherCombineArchive.save(yetAnotherFileName));

    QByteArray otherFileContents;
    QByteArray yetAnotherFileContents;

    QVERIFY(OpenCOR::Core::readFileContentsFromFile(otherFileName, otherFileContents));
    QVERIFY(OpenCOR::Core::readFileContentsFromFile(yetAnotherFileName, yetAnotherFileContents));

    QCOMPARE(OpenCOR::Core::sha1(otherFileContents),
             OpenCOR::Core::sha1(yetAnotherFileContents));

    // Clean up after ourselves

    QFile::remove(otherFileName);
    QFile::remove(yetAnotherFileName);
}

//==============================================================================

void Tests::loadingErrorTests()
{
    // Try to load a non-existent COMBINE archive

    OpenCOR::COMBINESupport::CombineArchive combineArchive(OpenCOR::fileName("src/plugins/support/COMBINESupport/tests/data/nonexistent.omex"));

    QVERIFY(!combineArchive.load());
    QVERIFY(combineArchive.issues().count() == 1);
    QCOMPARE(combineArchive.issues().first().message(), QString("the archive does not exist"));

    // Try to load a non-signed COMBINE archive

    combineArchive.setFileName(OpenCOR::fileName("src/plugins/support/COMBINESupport/tests/data/notsigned.omex"));

    QVERIFY(!combineArchive.reload());
    QVERIFY(combineArchive.issues().count() == 1);
    QCOMPARE(combineArchive.issues().first().message(), QString("the archive is not signed"));

    // Try to load a badly signed COMBINE archive

    combineArchive.setFileName(OpenCOR::fileName("src/plugins/support/COMBINESupport/tests/data/badlysigned.omex"));

    QVERIFY(!combineArchive.reload());
    QVERIFY(combineArchive.issues().count() == 1);
    QCOMPARE(combineArchive.issues().first().message(), QString("the archive does not have the correct signature"));

    // Try to load a COMBINE archive with no manifest

    combineArchive.setFileName(OpenCOR::fileName("src/plugins/support/COMBINESupport/tests/data/nomanifest.omex"));

    QVERIFY(combineArchive.reload());
    QVERIFY(!combineArchive.isValid());
    QVERIFY(combineArchive.issues().count() == 1);
    QCOMPARE(combineArchive.issues().first().message(), QString("the archive does not have a manifest"));

    // Try to load a COMBINE archive which manifest is not a valid OMEX file

    combineArchive.setFileName(OpenCOR::fileName("src/plugins/support/COMBINESupport/tests/data/notvalidomex.omex"));

    QVERIFY(combineArchive.reload());
    QVERIFY(!combineArchive.isValid());
    QVERIFY(combineArchive.issues().count() == 1);
    QCOMPARE(combineArchive.issues().first().message(), QString("the manifest is not a valid OMEX file"));

    // Try to load a COMBINE archive that contains a non-existent file

    combineArchive.setFileName(OpenCOR::fileName("src/plugins/support/COMBINESupport/tests/data/nonexistentfile.omex"));

    QVERIFY(combineArchive.reload());
    QVERIFY(!combineArchive.isValid());
    QVERIFY(combineArchive.issues().count() == 1);
    QCOMPARE(combineArchive.issues().first().message(), QString("nonexistentfile.txt could not be found"));

    // Try to load a COMBINE archive which manifest doesn't reference the
    // COMBINE archive itself

    combineArchive.setFileName(OpenCOR::fileName("src/plugins/support/COMBINESupport/tests/data/nocombinearchivereference.omex"));

    QVERIFY(combineArchive.reload());
    QVERIFY(!combineArchive.isValid());
    QVERIFY(combineArchive.issues().count() == 1);
    QCOMPARE(combineArchive.issues().first().message(), QString("no reference to the COMBINE archive itself could be found"));
}

//==============================================================================

QTEST_GUILESS_MAIN(Tests)

//==============================================================================
// End of file
//==============================================================================
<|endoftext|>


<commit_before>#include "../framework.h"

void ZeroTest(lc3::sim & sim)
{
    // Setup
    for(uint32_t i = 0x7f50; i < 0x8050; i += 1) {
        sim.setPC(0x3000);
        sim.setMem(0x4000, i);
        sim.setMem(0x4001, 0x8000);

        // Run
        sim.setRunInstLimit(1000);
        sim.run();

        // Verify
        if(i >= 0x8010) {
            VERIFY(sim.getMem(0x3200) == 0x8000);
        } else {
            VERIFY(sim.getMem(0x3200) == 0x0000);
        }
    }
}

void testBringup(lc3::sim & sim) { }

void testTeardown(lc3::sim & sim) { }

void setup(void)
{
    REGISTER_TEST(Zero, ZeroTest, 70);
}
<commit_msg>[grader] Update s18_lab1 grader<commit_after>#include "../framework.h"

void Helper(lc3::sim & sim, uint32_t a, uint32_t b)
{
    sim.setPC(0x3000);
    sim.setMem(0x4000, a);
    sim.setMem(0x4001, b);
}

void SimpleTest(lc3::sim & sim)
{
    // Setup
    Helper(sim, 0x0000, 0x0000);

    // Run
    sim.setRunInstLimit(2000);
    sim.run();

    // Verify
    VERIFY(sim.getMem(0x3200) == 0x0000);
}

void ExampleTest1(lc3::sim & sim)
{
    // Setup
    Helper(sim, 0x8000, 0x8000);

    // Run
    sim.setRunInstLimit(2000);
    sim.run();

    // Verify
    VERIFY(sim.getMem(0x3200) == 0x8000);
}

void ExampleTest2(lc3::sim & sim)
{
    // Setup
    Helper(sim, 0x1234, 0x5678);

    // Run
    sim.setRunInstLimit(2000);
    sim.run();

    // Verify
    VERIFY(sim.getMem(0x3200) == 0x0000);
}

void PositiveTest(lc3::sim & sim)
{
    // Setup
    Helper(sim, 0x7FFF, 0x7FFF);

    // Run
    sim.setRunInstLimit(2000);
    sim.run();

    // Verify
    VERIFY(sim.getMem(0x3200) == 0x8000);
}

void NegativeTest(lc3::sim & sim)
{
    // Setup
    Helper(sim, 0x8000, 0xFFFF);

    // Run
    sim.setRunInstLimit(2000);
    sim.run();

    // Verify
    VERIFY(sim.getMem(0x3200) == 0x8000);
}

void All_Ones_Test(lc3::sim & sim)
{
    // Setup
    Helper(sim, 0xFFFF, 0xFFFF);

    // Run
    sim.setRunInstLimit(2000);
    sim.run();

    // Verify
    VERIFY(sim.getMem(0x3200) == 0x0000);
}

void Add_One_Test(lc3::sim & sim)
{
    // Setup
    Helper(sim, 0x7FFF, 0x0001);

    // Run
    sim.setRunInstLimit(2000);
    sim.run();

    // Verify
    VERIFY(sim.getMem(0x3200) == 0x8000);
}

void Sub_One_Test(lc3::sim & sim)
{
    // Setup
    Helper(sim, 0x7FFF, 0xFFFF);

    // Run
    sim.setRunInstLimit(2000);
    sim.run();

    // Verify
    VERIFY(sim.getMem(0x3200) == 0x0000);
}

void testBringup(lc3::sim & sim) { }

void testTeardown(lc3::sim & sim) { }

void setup(void)
{
    REGISTER_TEST(Zero_Case, SimpleTest, 5);
    REGISTER_RANDOM_TEST(Zero_Case_Random, SimpleTest, 5);
    REGISTER_TEST(Example1, ExampleTest1, 10);
    REGISTER_RANDOM_TEST(Example1_Random, ExampleTest1, 10);
    REGISTER_TEST(Example2, ExampleTest2, 10);
    REGISTER_RANDOM_TEST(Example2_Random, ExampleTest2, 10);
    REGISTER_TEST(Positive_Overflow,PositiveTest, 5);
    REGISTER_RANDOM_TEST(Positive_Overflow__Random, PositiveTest, 5);
    REGISTER_TEST(Negative_Overflow,NegativeTest, 5);
    REGISTER_RANDOM_TEST(Negative_Overflow_Random, NegativeTest, 5);
    REGISTER_TEST(All_Ones,All_Ones_Test, 5);
    REGISTER_RANDOM_TEST(All_Ones_Random, All_Ones_Test, 5);
    REGISTER_TEST(Add_One,Add_One_Test, 5);
    REGISTER_RANDOM_TEST(Add_One_Random, Add_One_Test, 5);
    REGISTER_TEST(Sub_One,Sub_One_Test, 5);
    REGISTER_RANDOM_TEST(Sub_One_Random, Sub_One_Test, 5);
}
<|endoftext|>


<commit_before>/**
 * @cond ___LICENSE___
 *
 * Copyright (c) 2016 Koen Visscher, Paul Visscher and individual contributors.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * @endcond
 */

#include "common/environment.h"
#include "common/directory.h"
#include "common/path.h"

#include "preproc/env.h"

#include "api/console.h"

#include "config.h"

#if OS_IS_WINDOWS
#   include <windows.h>
#else
#   include <unistd.h>
#endif

namespace Path
{
    std::string Get( const std::string &path, Type type /*= Type::Game */ )
    {
        std::string from;
        bool resolve = true;

        switch ( type )
        {
        case Path::Type::Program:
            from = Path::GetProgramDirectory();
            break;

        case Path::Type::Data:
            from = Path::GetProgramDataDirectory();
            break;

        case Path::Type::SharedData:
            from = Path::GetProgramSharedDataDirectory();
            break;

        case Path::Type::Temp:
            from = Path::GetProgramTempDirectory();
            break;

        case Path::Type::Editor:
            from = Path::GetProgramDirectory();
            break;

        case Path::Type::None:
            resolve = false;
            break;
        }

        return resolve ? Path::ResolveRelative( from, path ) : path;
    }

    std::string ResolveRelative( const std::string &from, const std::string &to, bool sameRoot /*= true */ )
    {
        if ( sameRoot )
        {
            // Just add the relative path to the from path an normalise :)
            return Canonical( FixStyle( boost::filesystem::path( from ).parent_path().generic_string() ) + to );
        }
        else
        {
            // Cheers - http://stackoverflow.com/questions/10167382/boostfilesystem-get-relative-path

            boost::filesystem::path fsFrom, fsTo, result;

            fsFrom  = boost::filesystem::absolute( from ).parent_path();
            fsTo    = boost::filesystem::absolute( to );

            boost::filesystem::path::const_iterator itrFrom( fsFrom.begin() ), itrTo( fsTo.begin() );

            // Find common base
            /// @todo itrTo != toEnd always true
            for ( boost::filesystem::path::const_iterator toEnd( fsTo.end() ), fromEnd( fsFrom.end() ) ;
                    itrTo != toEnd && itrFrom != fromEnd && *itrFrom == *itrTo; ++itrFrom, ++itrTo );

            // Navigate backwards in directory to reach previously found base
            for ( boost::filesystem::path::const_iterator fromEnd( fsFrom.end() ); itrFrom != fromEnd; ++itrFrom )
            {
                if ( ( *itrFrom ) != "." )
                {
                    result /= "..";
                }
            }

            // Now navigate down the directory branch
            for ( ; itrTo != fsTo.end() ; ++itrTo )
            {
                result /= *itrTo;
            }

            return Canonical( result.generic_string() );
        }
    }

    std::string FixStyle( const std::string &filePath )
    {
        const boost::filesystem::path path( filePath );
        std::string newPath = path.generic_string();

        if ( !( path.has_stem() && path.has_extension() ) )
        {
            if ( path.empty() || newPath.back() != '/' )
            {
                newPath += '/';
            }
        }

#if !(OS_IS_WINDOWS)
        std::replace( newPath.begin(), newPath.end(), L'\\', L'/' );
#endif
        return newPath;
    }

    std::string Canonical( const std::string &path, bool absolute /*= false */ )
    {
        if ( ( path == "." || path == "./" ) && !absolute )
        {
            return path;
        }

        // Again Cheers - http://stackoverflow.com/questions/1746136/how-do-i-normalize-a-pathname-using-boostfilesystem
        boost::filesystem::path fsPath( path );

        if ( absolute )
        {
            fsPath = boost::filesystem::absolute( fsPath );
        }

        boost::filesystem::path result;

        for ( auto it = fsPath.begin(), end = fsPath.end(); it != end; ++it )
        {
            const std::string part = it->generic_string();

            if ( part == ".." )
            {
                if ( result.filename() == ".." )
                {
                    result /= *it;
                }
                else
                {
                    if ( result != "" )
                    {
                        result = result.parent_path();
                    }
                    else
                    {
                        result /= "..";
                    }
                }
            }
            else if ( part == "." )
            {
                // Ignore
            }
            else
            {
                // Just cat other path entries
                result /= *it;
            }
        }

        return FixStyle( result.generic_string() );
    }

    bool IsParent( const std::string &from, const std::string &to )
    {
        const std::string canFrom = Canonical( from, true );
        const std::string canTo = Canonical( to, true );
        const std::string relative = Canonical( canFrom + ResolveRelative( canFrom, canTo, false ), true );

        return relative.find( canFrom ) == 0;
    }

    std::string GetFileName( const std::string &path, const bool stripExtension /*= false */ )
    {
        const boost::filesystem::path fsPath( path );
        std::string filename;

        if ( !stripExtension )
        {
            filename = fsPath.filename().generic_string();
        }
        else
        {
            filename = fsPath.stem().generic_string();
        }

        return filename;
    }

    std::string GetDirectory( const std::string &path )
    {
        return FixStyle( boost::filesystem::path( path ).parent_path().generic_string() );
    }

    std::string GetExtension( const std::string &filepath, const bool addDot /*= false */ )
    {
        const std::string fullExtension = boost::filesystem::path( filepath ).extension().generic_string();

        return addDot || fullExtension == "" ? fullExtension : fullExtension.substr( 1 );
    }

    bool HasExtension( const std::string &filepath )
    {
        return boost::filesystem::path( filepath ).has_extension();
    }

    std::string GetUniqueFileName( const std::string &extension /*= ".tmp" */ )
    {
        return FixStyle( boost::filesystem::unique_path( "%%%%-%%%%-%%%%-%%%%" + extension ).generic_string() );
    }

    std::string GetUniqueDirectory()
    {
        return FixStyle( boost::filesystem::unique_path( "%%%%-%%%%-%%%%" ).generic_string() );
    }

    std::string GetTempDirectory()
    {
        return FixStyle( boost::filesystem::temp_directory_path().generic_string() );
    }

    std::string GetExeDirectory()
    {
        return FixStyle( boost::filesystem::path( GetExeFile() ).parent_path().generic_string() );
    }

    std::string GetExeFile()
    {
#if OS_IS_WINDOWS
        char result[ MAX_PATH ];
        return Canonical( std::string( result, GetModuleFileNameA( nullptr, result, MAX_PATH ) ) );
#elif OS_IS_LINUX
        char result[ PATH_MAX ];
        size_t count = readlink( "/proc/self/exe", result, PATH_MAX );
        return std::string( result, ( count > 0 ) ? count : 0 );
#else
#error
#endif
    }

    std::string GetDataDirectory()
    {
#if OS_IS_WINDOWS
        return FixStyle( Environment::GetVariable( "APPDATA" ) );
#elif OS_IS_LINUX
        return FixStyle( "~/local/share/" );
#elif OS_IS_MACOS
        return "~/Library/Application Support/";
#endif
    }

    std::string GetSharedDataDirectory()
    {
#if OS_IS_WINDOWS
        return FixStyle( Environment::GetVariable( "ALLUSERSPROFILE" ) );
#elif OS_IS_LINUX
        return "/usr/local/";
#elif OS_IS_MACOS
        return "/usr/local/";
#endif
    }

    std::string GetProgramDirectory()
    {
        return GetExeDirectory();
    }

    std::string GetProgramTempDirectory()
    {
        return String::Format( "%s%s/%s/", GetTempDirectory(), std::string( PROGRAM_COMPANY ), std::string( PROGRAM_NAME ) );
    }

    std::string GetProgramDataDirectory()
    {
        return String::Format( "%s%s/%s/", GetDataDirectory(), std::string( PROGRAM_COMPANY ), std::string( PROGRAM_NAME ) );
    }

    std::string GetProgramSharedDataDirectory()
    {
        return String::Format( "%s%s/%s/", GetSharedDataDirectory(),
                               std::string( PROGRAM_COMPANY ),
                               std::string( PROGRAM_NAME ) );
    }

    std::vector< boost::filesystem::path > List( const std::string &directory, bool recursive /*= false */ )
    {
        std::vector< boost::filesystem::path > contents;

        if ( !Directory::Exists( directory ) )
        {
            return contents;
        }

        if ( recursive )
        {
            boost::filesystem::recursive_directory_iterator it( directory ), end;

            for ( ; it != end; ++it )
            {
                contents.push_back( *it );
            }
        }
        else
        {
            boost::filesystem::directory_iterator it( directory ), end;

            for ( ; it != end; ++it )
            {
                contents.push_back( *it );
            }
        }

        return contents;
    }

    std::vector< std::string > ListContent( const std::string &directory, bool recursive /*= false */ )
    {
        const std::vector< boost::filesystem::path > contents = List( directory, recursive );
        std::vector< std::string > result;
        result.reserve( contents.size() );

        for ( auto it = contents.begin(), end = contents.end(); it != end; ++it )
        {
            result.push_back( FixStyle( it->generic_string() ) );
        }

        return result;
    }

    std::string GetWorkingDirectory()
    {
        return Path::FixStyle( boost::filesystem::current_path().generic_string() );
    }

    bool SetWorkingDirectory( const std::string &workingDirectory )
    {
        bool success = true;

        try
        {
            boost::filesystem::current_path( workingDirectory );
        }
        catch ( boost::filesystem::filesystem_error & )
        {
            success = false;
        }

        return success;
    }

    void DeleteAll( const std::string &path )
    {
        boost::filesystem::remove_all( path );
    }

}<commit_msg>Windows to linux paths<commit_after>/**
 * @cond ___LICENSE___
 *
 * Copyright (c) 2016 Koen Visscher, Paul Visscher and individual contributors.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * @endcond
 */

#include "common/environment.h"
#include "common/directory.h"
#include "common/path.h"

#include "preproc/env.h"

#include "api/console.h"

#include "config.h"

#if OS_IS_WINDOWS
#   include <windows.h>
#else
#   include <unistd.h>
#endif

namespace Path
{
    std::string Get( const std::string &path, Type type /*= Type::Game */ )
    {
        std::string from;
        bool resolve = true;

        switch ( type )
        {
        case Path::Type::Program:
            from = Path::GetProgramDirectory();
            break;

        case Path::Type::Data:
            from = Path::GetProgramDataDirectory();
            break;

        case Path::Type::SharedData:
            from = Path::GetProgramSharedDataDirectory();
            break;

        case Path::Type::Temp:
            from = Path::GetProgramTempDirectory();
            break;

        case Path::Type::Editor:
            from = Path::GetProgramDirectory();
            break;

        case Path::Type::None:
            resolve = false;
            break;
        }

        return resolve ? Path::ResolveRelative( from, path ) : path;
    }

    std::string ResolveRelative( const std::string &from, const std::string &to, bool sameRoot /*= true */ )
    {
        if ( sameRoot )
        {
            // Just add the relative path to the from path an normalise :)
            return Canonical( FixStyle( boost::filesystem::path( from ).parent_path().generic_string() ) + to );
        }
        else
        {
            // Cheers - http://stackoverflow.com/questions/10167382/boostfilesystem-get-relative-path

            boost::filesystem::path fsFrom, fsTo, result;

            fsFrom  = boost::filesystem::absolute( from ).parent_path();
            fsTo    = boost::filesystem::absolute( to );

            boost::filesystem::path::const_iterator itrFrom( fsFrom.begin() ), itrTo( fsTo.begin() );

            // Find common base
            /// @todo itrTo != toEnd always true
            for ( boost::filesystem::path::const_iterator toEnd( fsTo.end() ), fromEnd( fsFrom.end() ) ;
                    itrTo != toEnd && itrFrom != fromEnd && *itrFrom == *itrTo; ++itrFrom, ++itrTo );

            // Navigate backwards in directory to reach previously found base
            for ( boost::filesystem::path::const_iterator fromEnd( fsFrom.end() ); itrFrom != fromEnd; ++itrFrom )
            {
                if ( ( *itrFrom ) != "." )
                {
                    result /= "..";
                }
            }

            // Now navigate down the directory branch
            for ( ; itrTo != fsTo.end() ; ++itrTo )
            {
                result /= *itrTo;
            }

            return Canonical( result.generic_string() );
        }
    }

    std::string FixStyle( const std::string &filePath )
    {
        const boost::filesystem::path path( filePath );
        std::string newPath = path.generic_string();

        if ( !( path.has_stem() && path.has_extension() ) )
        {
            if ( path.empty() || newPath.back() != '/' )
            {
                newPath += '/';
            }
        }

#if !(OS_IS_WINDOWS)
        newPath = String::Replace( newPath, "\\", "/" );
        newPath = String::Replace( newPath, "//", "/" );
#endif
        return newPath;
    }

    std::string Canonical( const std::string &path, bool absolute /*= false */ )
    {
        if ( ( path == "." || path == "./" ) && !absolute )
        {
            return path;
        }

        // Again Cheers - http://stackoverflow.com/questions/1746136/how-do-i-normalize-a-pathname-using-boostfilesystem
        boost::filesystem::path fsPath( path );

        if ( absolute )
        {
            fsPath = boost::filesystem::absolute( fsPath );
        }

        boost::filesystem::path result;

        for ( auto it = fsPath.begin(), end = fsPath.end(); it != end; ++it )
        {
            const std::string part = it->generic_string();

            if ( part == ".." )
            {
                if ( result.filename() == ".." )
                {
                    result /= *it;
                }
                else
                {
                    if ( result != "" )
                    {
                        result = result.parent_path();
                    }
                    else
                    {
                        result /= "..";
                    }
                }
            }
            else if ( part == "." )
            {
                // Ignore
            }
            else
            {
                // Just cat other path entries
                result /= *it;
            }
        }

        return FixStyle( result.generic_string() );
    }

    bool IsParent( const std::string &from, const std::string &to )
    {
        const std::string canFrom = Canonical( from, true );
        const std::string canTo = Canonical( to, true );
        const std::string relative = Canonical( canFrom + ResolveRelative( canFrom, canTo, false ), true );

        return relative.find( canFrom ) == 0;
    }

    std::string GetFileName( const std::string &path, const bool stripExtension /*= false */ )
    {
        const boost::filesystem::path fsPath( path );
        std::string filename;

        if ( !stripExtension )
        {
            filename = fsPath.filename().generic_string();
        }
        else
        {
            filename = fsPath.stem().generic_string();
        }

        return filename;
    }

    std::string GetDirectory( const std::string &path )
    {
        return FixStyle( boost::filesystem::path( path ).parent_path().generic_string() );
    }

    std::string GetExtension( const std::string &filepath, const bool addDot /*= false */ )
    {
        const std::string fullExtension = boost::filesystem::path( filepath ).extension().generic_string();

        return addDot || fullExtension == "" ? fullExtension : fullExtension.substr( 1 );
    }

    bool HasExtension( const std::string &filepath )
    {
        return boost::filesystem::path( filepath ).has_extension();
    }

    std::string GetUniqueFileName( const std::string &extension /*= ".tmp" */ )
    {
        return FixStyle( boost::filesystem::unique_path( "%%%%-%%%%-%%%%-%%%%" + extension ).generic_string() );
    }

    std::string GetUniqueDirectory()
    {
        return FixStyle( boost::filesystem::unique_path( "%%%%-%%%%-%%%%" ).generic_string() );
    }

    std::string GetTempDirectory()
    {
        return FixStyle( boost::filesystem::temp_directory_path().generic_string() );
    }

    std::string GetExeDirectory()
    {
        return FixStyle( boost::filesystem::path( GetExeFile() ).parent_path().generic_string() );
    }

    std::string GetExeFile()
    {
#if OS_IS_WINDOWS
        char result[ MAX_PATH ];
        return Canonical( std::string( result, GetModuleFileNameA( nullptr, result, MAX_PATH ) ) );
#elif OS_IS_LINUX
        char result[ PATH_MAX ];
        size_t count = readlink( "/proc/self/exe", result, PATH_MAX );
        return std::string( result, ( count > 0 ) ? count : 0 );
#else
#error
#endif
    }

    std::string GetDataDirectory()
    {
#if OS_IS_WINDOWS
        return FixStyle( Environment::GetVariable( "APPDATA" ) );
#elif OS_IS_LINUX
        return FixStyle( "~/local/share/" );
#elif OS_IS_MACOS
        return "~/Library/Application Support/";
#endif
    }

    std::string GetSharedDataDirectory()
    {
#if OS_IS_WINDOWS
        return FixStyle( Environment::GetVariable( "ALLUSERSPROFILE" ) );
#elif OS_IS_LINUX
        return "/usr/local/";
#elif OS_IS_MACOS
        return "/usr/local/";
#endif
    }

    std::string GetProgramDirectory()
    {
        return GetExeDirectory();
    }

    std::string GetProgramTempDirectory()
    {
        return String::Format( "%s%s/%s/", GetTempDirectory(), std::string( PROGRAM_COMPANY ), std::string( PROGRAM_NAME ) );
    }

    std::string GetProgramDataDirectory()
    {
        return String::Format( "%s%s/%s/", GetDataDirectory(), std::string( PROGRAM_COMPANY ), std::string( PROGRAM_NAME ) );
    }

    std::string GetProgramSharedDataDirectory()
    {
        return String::Format( "%s%s/%s/", GetSharedDataDirectory(),
                               std::string( PROGRAM_COMPANY ),
                               std::string( PROGRAM_NAME ) );
    }

    std::vector< boost::filesystem::path > List( const std::string &directory, bool recursive /*= false */ )
    {
        std::vector< boost::filesystem::path > contents;

        if ( !Directory::Exists( directory ) )
        {
            return contents;
        }

        if ( recursive )
        {
            boost::filesystem::recursive_directory_iterator it( directory ), end;

            for ( ; it != end; ++it )
            {
                contents.push_back( *it );
            }
        }
        else
        {
            boost::filesystem::directory_iterator it( directory ), end;

            for ( ; it != end; ++it )
            {
                contents.push_back( *it );
            }
        }

        return contents;
    }

    std::vector< std::string > ListContent( const std::string &directory, bool recursive /*= false */ )
    {
        const std::vector< boost::filesystem::path > contents = List( directory, recursive );
        std::vector< std::string > result;
        result.reserve( contents.size() );

        for ( auto it = contents.begin(), end = contents.end(); it != end; ++it )
        {
            result.push_back( FixStyle( it->generic_string() ) );
        }

        return result;
    }

    std::string GetWorkingDirectory()
    {
        return Path::FixStyle( boost::filesystem::current_path().generic_string() );
    }

    bool SetWorkingDirectory( const std::string &workingDirectory )
    {
        bool success = true;

        try
        {
            boost::filesystem::current_path( workingDirectory );
        }
        catch ( boost::filesystem::filesystem_error & )
        {
            success = false;
        }

        return success;
    }

    void DeleteAll( const std::string &path )
    {
        boost::filesystem::remove_all( path );
    }

}<|endoftext|>


<commit_before>//
//  yas_cf_ref.cpp
//

#include "yas_cf_ref.h"

using namespace yas;

cf_ref_impl::cf_ref_impl() : _obj(nullptr) {
}

cf_ref_impl::cf_ref_impl(CFTypeRef const obj) : _obj(obj) {
    CFRetain(obj);
}

cf_ref_impl::cf_ref_impl(std::nullptr_t) : _obj(nullptr) {
}

cf_ref_impl::~cf_ref_impl() {
    if (_obj) {
        CFRelease(_obj);
        _obj = nullptr;
    }
}

void cf_ref_impl::set_object(CFTypeRef const obj) {
    std::lock_guard<std::recursive_mutex> lock(_mutex);
    if (obj) {
        CFRetain(obj);
    }

    if (_obj) {
        CFRelease(_obj);
    }

    _obj = obj;
}

void cf_ref_impl::move_object(CFTypeRef const obj) {
    std::lock_guard<std::recursive_mutex> lock(_mutex);

    if (_obj) {
        CFRelease(_obj);
    }

    _obj = obj;
}

CFTypeRef cf_ref_impl::object() {
    std::lock_guard<std::recursive_mutex> lock(_mutex);
    return _obj;
}

CFTypeRef cf_ref_impl::retained_object() {
    std::lock_guard<std::recursive_mutex> lock(_mutex);
    if (_obj) {
        return CFRetain(_obj);
    }
    return nullptr;
}

CFTypeRef cf_ref_impl::autoreleased_object() {
    std::lock_guard<std::recursive_mutex> lock(_mutex);
    if (_obj) {
        return CFAutorelease(CFRetain(_obj));
    }
    return nullptr;
}
<commit_msg>cf_ref this<commit_after>//
//  yas_cf_ref.cpp
//

#include "yas_cf_ref.h"

using namespace yas;

cf_ref_impl::cf_ref_impl() : _obj(nullptr) {
}

cf_ref_impl::cf_ref_impl(CFTypeRef const obj) : _obj(obj) {
    CFRetain(obj);
}

cf_ref_impl::cf_ref_impl(std::nullptr_t) : _obj(nullptr) {
}

cf_ref_impl::~cf_ref_impl() {
    if (this->_obj) {
        CFRelease(this->_obj);
        this->_obj = nullptr;
    }
}

void cf_ref_impl::set_object(CFTypeRef const obj) {
    std::lock_guard<std::recursive_mutex> lock(this->_mutex);
    if (obj) {
        CFRetain(obj);
    }

    if (this->_obj) {
        CFRelease(this->_obj);
    }

    this->_obj = obj;
}

void cf_ref_impl::move_object(CFTypeRef const obj) {
    std::lock_guard<std::recursive_mutex> lock(this->_mutex);

    if (this->_obj) {
        CFRelease(this->_obj);
    }

    this->_obj = obj;
}

CFTypeRef cf_ref_impl::object() {
    std::lock_guard<std::recursive_mutex> lock(this->_mutex);
    return this->_obj;
}

CFTypeRef cf_ref_impl::retained_object() {
    std::lock_guard<std::recursive_mutex> lock(this->_mutex);
    if (this->_obj) {
        return CFRetain(this->_obj);
    }
    return nullptr;
}

CFTypeRef cf_ref_impl::autoreleased_object() {
    std::lock_guard<std::recursive_mutex> lock(this->_mutex);
    if (this->_obj) {
        return CFAutorelease(CFRetain(this->_obj));
    }
    return nullptr;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: dlgeps.cxx,v $
 *
 *  $Revision: 1.12 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 15:44:09 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_goodies.hxx"
#ifndef GCC
#endif

#include <tools/ref.hxx>
#include <vcl/msgbox.hxx>
#include <svtools/FilterConfigItem.hxx>
#include "dlgeps.hxx"
#include "dlgeps.hrc"
#include "strings.hrc"

/*************************************************************************
|*
|* Ctor
|*
\************************************************************************/

DlgExportEPS::DlgExportEPS( FltCallDialogParameter& rPara ) :
                ModalDialog         ( rPara.pWindow, ResId( DLG_EXPORT_EPS, rPara.pResMgr ) ),
                rFltCallPara        ( rPara ),
                aGrpPreview         ( this, ResId( GRP_PREVIEW ) ),
                aCBPreviewTiff      ( this, ResId( CB_PREVIEW_TIFF ) ),
                aCBPreviewEPSI      ( this, ResId( CB_PREVIEW_EPSI ) ),
                aGrpVersion         ( this, ResId( GRP_VERSION ) ),
                aRBLevel1           ( this, ResId( RB_LEVEL1 ) ),
                aRBLevel2           ( this, ResId( RB_LEVEL2 ) ),
                aGrpColor           ( this, ResId( GRP_COLOR ) ),
                aRBColor            ( this, ResId( RB_COLOR ) ),
                aRBGrayscale        ( this, ResId( RB_GRAYSCALE ) ),
                aGrpCompression     ( this, ResId( GRP_COMPRESSION ) ),
                aRBCompressionLZW   ( this, ResId( RB_COMPRESSION_LZW ) ),
                aRBCompressionNone  ( this, ResId( RB_COMPRESSION_NONE ) ),
                aBtnOK              ( this, ResId( BTN_OK ) ),
                aBtnCancel          ( this, ResId( BTN_CANCEL ) ),
                aBtnHelp            ( this, ResId( BTN_HELP ) ),
                pMgr                ( rPara.pResMgr )
{
    FreeResource();

    String  aFilterConfigPath( RTL_CONSTASCII_USTRINGPARAM( "Office.Common/Filter/Graphic/Export/EPS" ) );
    pConfigItem = new FilterConfigItem( aFilterConfigPath, &rPara.aFilterData );

    // Config-Parameter lesen
    String sPreview( RTL_CONSTASCII_USTRINGPARAM( "Preview" ) );
    String sVersion( RTL_CONSTASCII_USTRINGPARAM( "Version" ) );
    String sColorFormat( RTL_CONSTASCII_USTRINGPARAM( "ColorFormat" ) );
    String sCompressionMode( RTL_CONSTASCII_USTRINGPARAM( "CompressionMode" ) );
    String sTextMode( RTL_CONSTASCII_USTRINGPARAM( "TextMode" ) );

    sal_Int32   nPreview = pConfigItem->ReadInt32( sPreview, 0 );
    sal_Int32   nVersion = pConfigItem->ReadInt32( sVersion, 2 );
    sal_Int32   nColor = pConfigItem->ReadInt32( sColorFormat, 0 );
    sal_Int32   nCompr = pConfigItem->ReadInt32( sCompressionMode, 2 );

    /* SJ: The following line is not superfluous, reading the item will also    #106652#
       create the corresponding FilterData Property. Since all filter
       are no longer accessing the configuration itself, we have fill the
       FilterData sequence with all available configuration items */
    pConfigItem->ReadInt32( sTextMode, 0 );

    BOOL bCheck = FALSE;
    if ( nPreview & 1 )
        bCheck = TRUE;
    aCBPreviewTiff.Check( bCheck );
    if ( nPreview & 2 )
        bCheck = TRUE;
    aCBPreviewEPSI.Check( bCheck );

    bCheck = FALSE;
    if ( nVersion == 1 )
        bCheck ^= TRUE;
    aRBLevel1.Check( bCheck );
    bCheck ^= TRUE;
    aRBLevel2.Check( bCheck );

    bCheck = FALSE;
    if ( nColor == 1 )
        bCheck ^= TRUE;
    aRBColor.Check( bCheck );
    bCheck ^= TRUE;
    aRBGrayscale.Check( bCheck );

    bCheck = FALSE;
    if ( nCompr == 1 )
        bCheck ^= TRUE;
    aRBCompressionLZW.Check( bCheck );
    bCheck ^= TRUE;
    aRBCompressionNone.Check( bCheck );

    if ( aRBLevel1.IsChecked() )
    {
        aRBColor.Disable();
        aRBGrayscale.Disable();
        aRBCompressionNone.Disable();
        aRBCompressionLZW.Disable();
        aRBCompressionNone.Disable();
    }

    aBtnOK.SetClickHdl( LINK( this, DlgExportEPS, OK ) );
    aRBLevel1.SetClickHdl( LINK( this, DlgExportEPS, LEVEL1 ) );
    aRBLevel2.SetClickHdl( LINK( this, DlgExportEPS, LEVEL2 ) );
}

DlgExportEPS::~DlgExportEPS()
{
    delete pConfigItem;
}

/*************************************************************************
|*
|* Speichert eingestellte Werte in ini-Datei
|*
\************************************************************************/

IMPL_LINK( DlgExportEPS, OK, void *, EMPTYARG )
{

    // Config-Parameter schreiben
    sal_Int32 nCheck = 0;
    if ( aCBPreviewTiff.IsChecked() )
        nCheck++;
    if ( aCBPreviewEPSI.IsChecked() )
        nCheck += 2;

    String sPreview( RTL_CONSTASCII_USTRINGPARAM( "Preview" ) );
    pConfigItem->WriteInt32( sPreview, nCheck );

    nCheck = 1;
    if ( aRBLevel2.IsChecked() )
        nCheck++;
    String sVersion( RTL_CONSTASCII_USTRINGPARAM( "Version" ) );
    pConfigItem->WriteInt32( sVersion, nCheck );

    nCheck = 1;
    if ( aRBGrayscale.IsChecked() )
        nCheck++;
    String sColorFormat( RTL_CONSTASCII_USTRINGPARAM( "ColorFormat" ) );
    pConfigItem->WriteInt32( sColorFormat, nCheck );

    nCheck = 1;
    if ( aRBCompressionNone.IsChecked() )
        nCheck++;
    String sCompressionMode( RTL_CONSTASCII_USTRINGPARAM( "CompressionMode" ) );
    pConfigItem->WriteInt32( sCompressionMode, nCheck );

    rFltCallPara.aFilterData = pConfigItem->GetFilterData();
    EndDialog( RET_OK );

    return 0;
}

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

IMPL_LINK( DlgExportEPS, LEVEL1, void*, EMPTYARG )
{
    if ( aRBLevel1.IsChecked() )
    {
        aRBColor.Disable();
        aRBGrayscale.Disable();
        aRBCompressionLZW.Disable();
        aRBCompressionNone.Disable();
    }
    return 0;
}

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

IMPL_LINK( DlgExportEPS, LEVEL2, void*, EMPTYARG )
{
    if ( aRBLevel2.IsChecked() )
    {
        aRBColor.Enable();
        aRBGrayscale.Enable();
        aRBCompressionLZW.Enable();
        aRBCompressionNone.Enable();
    }
    return 0;
}
<commit_msg>INTEGRATION: CWS residcleanup (1.12.72); FILE MERGED 2007/02/18 19:58:11 pl 1.12.72.1: #i74635# get rid of implicit global ResMgr<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: dlgeps.cxx,v $
 *
 *  $Revision: 1.13 $
 *
 *  last change: $Author: rt $ $Date: 2007-04-26 10:01:18 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_goodies.hxx"
#ifndef GCC
#endif

#include <tools/ref.hxx>
#include <vcl/msgbox.hxx>
#include <svtools/FilterConfigItem.hxx>
#include "dlgeps.hxx"
#include "dlgeps.hrc"
#include "strings.hrc"

/*************************************************************************
|*
|* Ctor
|*
\************************************************************************/

DlgExportEPS::DlgExportEPS( FltCallDialogParameter& rPara ) :
                ModalDialog         ( rPara.pWindow, ResId( DLG_EXPORT_EPS, *rPara.pResMgr ) ),
                rFltCallPara        ( rPara ),
                aGrpPreview         ( this, ResId( GRP_PREVIEW, *rPara.pResMgr ) ),
                aCBPreviewTiff      ( this, ResId( CB_PREVIEW_TIFF, *rPara.pResMgr ) ),
                aCBPreviewEPSI      ( this, ResId( CB_PREVIEW_EPSI, *rPara.pResMgr ) ),
                aGrpVersion         ( this, ResId( GRP_VERSION, *rPara.pResMgr ) ),
                aRBLevel1           ( this, ResId( RB_LEVEL1, *rPara.pResMgr ) ),
                aRBLevel2           ( this, ResId( RB_LEVEL2, *rPara.pResMgr ) ),
                aGrpColor           ( this, ResId( GRP_COLOR, *rPara.pResMgr ) ),
                aRBColor            ( this, ResId( RB_COLOR, *rPara.pResMgr ) ),
                aRBGrayscale        ( this, ResId( RB_GRAYSCALE, *rPara.pResMgr ) ),
                aGrpCompression     ( this, ResId( GRP_COMPRESSION, *rPara.pResMgr ) ),
                aRBCompressionLZW   ( this, ResId( RB_COMPRESSION_LZW, *rPara.pResMgr ) ),
                aRBCompressionNone  ( this, ResId( RB_COMPRESSION_NONE, *rPara.pResMgr ) ),
                aBtnOK              ( this, ResId( BTN_OK, *rPara.pResMgr ) ),
                aBtnCancel          ( this, ResId( BTN_CANCEL, *rPara.pResMgr ) ),
                aBtnHelp            ( this, ResId( BTN_HELP, *rPara.pResMgr ) ),
                pMgr                ( rPara.pResMgr )
{
    FreeResource();

    String  aFilterConfigPath( RTL_CONSTASCII_USTRINGPARAM( "Office.Common/Filter/Graphic/Export/EPS" ) );
    pConfigItem = new FilterConfigItem( aFilterConfigPath, &rPara.aFilterData );

    // Config-Parameter lesen
    String sPreview( RTL_CONSTASCII_USTRINGPARAM( "Preview" ) );
    String sVersion( RTL_CONSTASCII_USTRINGPARAM( "Version" ) );
    String sColorFormat( RTL_CONSTASCII_USTRINGPARAM( "ColorFormat" ) );
    String sCompressionMode( RTL_CONSTASCII_USTRINGPARAM( "CompressionMode" ) );
    String sTextMode( RTL_CONSTASCII_USTRINGPARAM( "TextMode" ) );

    sal_Int32   nPreview = pConfigItem->ReadInt32( sPreview, 0 );
    sal_Int32   nVersion = pConfigItem->ReadInt32( sVersion, 2 );
    sal_Int32   nColor = pConfigItem->ReadInt32( sColorFormat, 0 );
    sal_Int32   nCompr = pConfigItem->ReadInt32( sCompressionMode, 2 );

    /* SJ: The following line is not superfluous, reading the item will also    #106652#
       create the corresponding FilterData Property. Since all filter
       are no longer accessing the configuration itself, we have fill the
       FilterData sequence with all available configuration items */
    pConfigItem->ReadInt32( sTextMode, 0 );

    BOOL bCheck = FALSE;
    if ( nPreview & 1 )
        bCheck = TRUE;
    aCBPreviewTiff.Check( bCheck );
    if ( nPreview & 2 )
        bCheck = TRUE;
    aCBPreviewEPSI.Check( bCheck );

    bCheck = FALSE;
    if ( nVersion == 1 )
        bCheck ^= TRUE;
    aRBLevel1.Check( bCheck );
    bCheck ^= TRUE;
    aRBLevel2.Check( bCheck );

    bCheck = FALSE;
    if ( nColor == 1 )
        bCheck ^= TRUE;
    aRBColor.Check( bCheck );
    bCheck ^= TRUE;
    aRBGrayscale.Check( bCheck );

    bCheck = FALSE;
    if ( nCompr == 1 )
        bCheck ^= TRUE;
    aRBCompressionLZW.Check( bCheck );
    bCheck ^= TRUE;
    aRBCompressionNone.Check( bCheck );

    if ( aRBLevel1.IsChecked() )
    {
        aRBColor.Disable();
        aRBGrayscale.Disable();
        aRBCompressionNone.Disable();
        aRBCompressionLZW.Disable();
        aRBCompressionNone.Disable();
    }

    aBtnOK.SetClickHdl( LINK( this, DlgExportEPS, OK ) );
    aRBLevel1.SetClickHdl( LINK( this, DlgExportEPS, LEVEL1 ) );
    aRBLevel2.SetClickHdl( LINK( this, DlgExportEPS, LEVEL2 ) );
}

DlgExportEPS::~DlgExportEPS()
{
    delete pConfigItem;
}

/*************************************************************************
|*
|* Speichert eingestellte Werte in ini-Datei
|*
\************************************************************************/

IMPL_LINK( DlgExportEPS, OK, void *, EMPTYARG )
{

    // Config-Parameter schreiben
    sal_Int32 nCheck = 0;
    if ( aCBPreviewTiff.IsChecked() )
        nCheck++;
    if ( aCBPreviewEPSI.IsChecked() )
        nCheck += 2;

    String sPreview( RTL_CONSTASCII_USTRINGPARAM( "Preview" ) );
    pConfigItem->WriteInt32( sPreview, nCheck );

    nCheck = 1;
    if ( aRBLevel2.IsChecked() )
        nCheck++;
    String sVersion( RTL_CONSTASCII_USTRINGPARAM( "Version" ) );
    pConfigItem->WriteInt32( sVersion, nCheck );

    nCheck = 1;
    if ( aRBGrayscale.IsChecked() )
        nCheck++;
    String sColorFormat( RTL_CONSTASCII_USTRINGPARAM( "ColorFormat" ) );
    pConfigItem->WriteInt32( sColorFormat, nCheck );

    nCheck = 1;
    if ( aRBCompressionNone.IsChecked() )
        nCheck++;
    String sCompressionMode( RTL_CONSTASCII_USTRINGPARAM( "CompressionMode" ) );
    pConfigItem->WriteInt32( sCompressionMode, nCheck );

    rFltCallPara.aFilterData = pConfigItem->GetFilterData();
    EndDialog( RET_OK );

    return 0;
}

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

IMPL_LINK( DlgExportEPS, LEVEL1, void*, EMPTYARG )
{
    if ( aRBLevel1.IsChecked() )
    {
        aRBColor.Disable();
        aRBGrayscale.Disable();
        aRBCompressionLZW.Disable();
        aRBCompressionNone.Disable();
    }
    return 0;
}

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

IMPL_LINK( DlgExportEPS, LEVEL2, void*, EMPTYARG )
{
    if ( aRBLevel2.IsChecked() )
    {
        aRBColor.Enable();
        aRBGrayscale.Enable();
        aRBCompressionLZW.Enable();
        aRBCompressionNone.Enable();
    }
    return 0;
}
<|endoftext|>


<commit_before>/*
 *
 * Copyright 2017 gRPC authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

/* Test out pollset latencies */

#include <grpc/grpc.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/useful.h>

extern "C" {
#include "src/core/lib/iomgr/ev_posix.h"
#include "src/core/lib/iomgr/pollset.h"
#include "src/core/lib/iomgr/port.h"
#include "src/core/lib/iomgr/wakeup_fd_posix.h"
}

#include "test/cpp/microbenchmarks/helpers.h"
#include "third_party/benchmark/include/benchmark/benchmark.h"

#include <string.h>

#ifdef GRPC_LINUX_MULTIPOLL_WITH_EPOLL
#include <sys/epoll.h>
#include <sys/eventfd.h>
#include <unistd.h>
#endif

auto& force_library_initialization = Library::get();

static void shutdown_ps(grpc_exec_ctx* exec_ctx, void* ps, grpc_error* error) {
  grpc_pollset_destroy(exec_ctx, static_cast<grpc_pollset*>(ps));
}

static void BM_CreateDestroyPollset(benchmark::State& state) {
  TrackCounters track_counters;
  size_t ps_sz = grpc_pollset_size();
  grpc_pollset* ps = static_cast<grpc_pollset*>(gpr_malloc(ps_sz));
  gpr_mu* mu;
  grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;
  grpc_closure shutdown_ps_closure;
  GRPC_CLOSURE_INIT(&shutdown_ps_closure, shutdown_ps, ps,
                    grpc_schedule_on_exec_ctx);
  while (state.KeepRunning()) {
    memset(ps, 0, ps_sz);
    grpc_pollset_init(ps, &mu);
    gpr_mu_lock(mu);
    grpc_pollset_shutdown(&exec_ctx, ps, &shutdown_ps_closure);
    gpr_mu_unlock(mu);
    grpc_exec_ctx_flush(&exec_ctx);
  }
  grpc_exec_ctx_finish(&exec_ctx);
  gpr_free(ps);
  track_counters.Finish(state);
}
BENCHMARK(BM_CreateDestroyPollset);

#ifdef GRPC_LINUX_MULTIPOLL_WITH_EPOLL
static void BM_PollEmptyPollset_SpeedOfLight(benchmark::State& state) {
  // equivalent to BM_PollEmptyPollset, but just use the OS primitives to guage
  // what the speed of light would be if we abstracted perfectly
  TrackCounters track_counters;
  int epfd = epoll_create1(0);
  GPR_ASSERT(epfd != -1);
  size_t nev = state.range(0);
  size_t nfd = state.range(1);
  epoll_event* ev = new epoll_event[nev];
  std::vector<int> fds;
  for (size_t i = 0; i < nfd; i++) {
    fds.push_back(eventfd(0, 0));
    epoll_event ev;
    ev.events = EPOLLIN;
    epoll_ctl(epfd, EPOLL_CTL_ADD, fds.back(), &ev);
  }
  while (state.KeepRunning()) {
    epoll_wait(epfd, ev, nev, 0);
  }
  for (auto fd : fds) {
    close(fd);
  }
  close(epfd);
  delete[] ev;
  track_counters.Finish(state);
}
BENCHMARK(BM_PollEmptyPollset_SpeedOfLight)
    ->Args({1, 0})
    ->Args({1, 1})
    ->Args({1, 10})
    ->Args({1, 100})
    ->Args({1, 1000})
    ->Args({1, 10000})
    ->Args({1, 100000})
    ->Args({10, 1})
    ->Args({100, 1})
    ->Args({1000, 1});
#endif

static void BM_PollEmptyPollset(benchmark::State& state) {
  TrackCounters track_counters;
  size_t ps_sz = grpc_pollset_size();
  grpc_pollset* ps = static_cast<grpc_pollset*>(gpr_zalloc(ps_sz));
  gpr_mu* mu;
  grpc_pollset_init(ps, &mu);
  grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;
  gpr_timespec now = gpr_time_0(GPR_CLOCK_MONOTONIC);
  gpr_timespec deadline = gpr_inf_past(GPR_CLOCK_MONOTONIC);
  gpr_mu_lock(mu);
  while (state.KeepRunning()) {
    GRPC_ERROR_UNREF(grpc_pollset_work(&exec_ctx, ps, NULL, now, deadline));
  }
  grpc_closure shutdown_ps_closure;
  GRPC_CLOSURE_INIT(&shutdown_ps_closure, shutdown_ps, ps,
                    grpc_schedule_on_exec_ctx);
  grpc_pollset_shutdown(&exec_ctx, ps, &shutdown_ps_closure);
  gpr_mu_unlock(mu);
  grpc_exec_ctx_finish(&exec_ctx);
  gpr_free(ps);
  track_counters.Finish(state);
}
BENCHMARK(BM_PollEmptyPollset);

static void BM_PollAddFd(benchmark::State& state) {
  TrackCounters track_counters;
  size_t ps_sz = grpc_pollset_size();
  grpc_pollset* ps = static_cast<grpc_pollset*>(gpr_zalloc(ps_sz));
  gpr_mu* mu;
  grpc_pollset_init(ps, &mu);
  grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;
  grpc_wakeup_fd wakeup_fd;
  GPR_ASSERT(
      GRPC_LOG_IF_ERROR("wakeup_fd_init", grpc_wakeup_fd_init(&wakeup_fd)));
  grpc_fd* fd = grpc_fd_create(wakeup_fd.read_fd, "xxx");
  while (state.KeepRunning()) {
    grpc_pollset_add_fd(&exec_ctx, ps, fd);
    grpc_exec_ctx_flush(&exec_ctx);
  }
  grpc_fd_orphan(&exec_ctx, fd, NULL, NULL, "xxx");
  grpc_closure shutdown_ps_closure;
  GRPC_CLOSURE_INIT(&shutdown_ps_closure, shutdown_ps, ps,
                    grpc_schedule_on_exec_ctx);
  gpr_mu_lock(mu);
  grpc_pollset_shutdown(&exec_ctx, ps, &shutdown_ps_closure);
  gpr_mu_unlock(mu);
  grpc_exec_ctx_finish(&exec_ctx);
  gpr_free(ps);
  track_counters.Finish(state);
}
BENCHMARK(BM_PollAddFd);

class Closure : public grpc_closure {
 public:
  virtual ~Closure() {}
};

template <class F>
Closure* MakeClosure(F f, grpc_closure_scheduler* scheduler) {
  struct C : public Closure {
    C(F f, grpc_closure_scheduler* scheduler) : f_(f) {
      GRPC_CLOSURE_INIT(this, C::cbfn, this, scheduler);
    }
    static void cbfn(grpc_exec_ctx* exec_ctx, void* arg, grpc_error* error) {
      C* p = static_cast<C*>(arg);
      p->f_();
    }
    F f_;
  };
  return new C(f, scheduler);
}

#ifdef GRPC_LINUX_MULTIPOLL_WITH_EPOLL
static void BM_SingleThreadPollOneFd_SpeedOfLight(benchmark::State& state) {
  // equivalent to BM_PollEmptyPollset, but just use the OS primitives to guage
  // what the speed of light would be if we abstracted perfectly
  TrackCounters track_counters;
  int epfd = epoll_create1(0);
  GPR_ASSERT(epfd != -1);
  epoll_event ev[100];
  int fd = eventfd(0, EFD_NONBLOCK);
  ev[0].events = EPOLLIN;
  epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &ev[0]);
  while (state.KeepRunning()) {
    int err;
    do {
      err = eventfd_write(fd, 1);
    } while (err < 0 && errno == EINTR);
    GPR_ASSERT(err == 0);
    do {
      err = epoll_wait(epfd, ev, GPR_ARRAY_SIZE(ev), 0);
    } while (err < 0 && errno == EINTR);
    GPR_ASSERT(err == 1);
    eventfd_t value;
    do {
      err = eventfd_read(fd, &value);
    } while (err < 0 && errno == EINTR);
    GPR_ASSERT(err == 0);
  }
  close(fd);
  close(epfd);
  track_counters.Finish(state);
}
BENCHMARK(BM_SingleThreadPollOneFd_SpeedOfLight);
#endif

static void BM_SingleThreadPollOneFd(benchmark::State& state) {
  TrackCounters track_counters;
  size_t ps_sz = grpc_pollset_size();
  grpc_pollset* ps = static_cast<grpc_pollset*>(gpr_zalloc(ps_sz));
  gpr_mu* mu;
  grpc_pollset_init(ps, &mu);
  grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;
  gpr_timespec now = gpr_time_0(GPR_CLOCK_MONOTONIC);
  gpr_timespec deadline = gpr_inf_future(GPR_CLOCK_MONOTONIC);
  grpc_wakeup_fd wakeup_fd;
  GRPC_ERROR_UNREF(grpc_wakeup_fd_init(&wakeup_fd));
  grpc_fd* wakeup = grpc_fd_create(wakeup_fd.read_fd, "wakeup_read");
  grpc_pollset_add_fd(&exec_ctx, ps, wakeup);
  bool done = false;
  Closure* continue_closure = MakeClosure(
      [&]() {
        GRPC_ERROR_UNREF(grpc_wakeup_fd_consume_wakeup(&wakeup_fd));
        if (!state.KeepRunning()) {
          done = true;
          return;
        }
        GRPC_ERROR_UNREF(grpc_wakeup_fd_wakeup(&wakeup_fd));
        grpc_fd_notify_on_read(&exec_ctx, wakeup, continue_closure);
      },
      grpc_schedule_on_exec_ctx);
  GRPC_ERROR_UNREF(grpc_wakeup_fd_wakeup(&wakeup_fd));
  grpc_fd_notify_on_read(&exec_ctx, wakeup, continue_closure);
  gpr_mu_lock(mu);
  while (!done) {
    GRPC_ERROR_UNREF(grpc_pollset_work(&exec_ctx, ps, NULL, now, deadline));
  }
  grpc_fd_orphan(&exec_ctx, wakeup, NULL, NULL, "done");
  wakeup_fd.read_fd = 0;
  grpc_closure shutdown_ps_closure;
  GRPC_CLOSURE_INIT(&shutdown_ps_closure, shutdown_ps, ps,
                    grpc_schedule_on_exec_ctx);
  grpc_pollset_shutdown(&exec_ctx, ps, &shutdown_ps_closure);
  gpr_mu_unlock(mu);
  grpc_exec_ctx_finish(&exec_ctx);
  grpc_wakeup_fd_destroy(&wakeup_fd);
  gpr_free(ps);
  track_counters.Finish(state);
  delete continue_closure;
}
BENCHMARK(BM_SingleThreadPollOneFd);

BENCHMARK_MAIN();
<commit_msg>Update bm_pollset with the fd_orphan change<commit_after>/*
 *
 * Copyright 2017 gRPC authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

/* Test out pollset latencies */

#include <grpc/grpc.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/useful.h>

extern "C" {
#include "src/core/lib/iomgr/ev_posix.h"
#include "src/core/lib/iomgr/pollset.h"
#include "src/core/lib/iomgr/port.h"
#include "src/core/lib/iomgr/wakeup_fd_posix.h"
}

#include "test/cpp/microbenchmarks/helpers.h"
#include "third_party/benchmark/include/benchmark/benchmark.h"

#include <string.h>

#ifdef GRPC_LINUX_MULTIPOLL_WITH_EPOLL
#include <sys/epoll.h>
#include <sys/eventfd.h>
#include <unistd.h>
#endif

auto& force_library_initialization = Library::get();

static void shutdown_ps(grpc_exec_ctx* exec_ctx, void* ps, grpc_error* error) {
  grpc_pollset_destroy(exec_ctx, static_cast<grpc_pollset*>(ps));
}

static void BM_CreateDestroyPollset(benchmark::State& state) {
  TrackCounters track_counters;
  size_t ps_sz = grpc_pollset_size();
  grpc_pollset* ps = static_cast<grpc_pollset*>(gpr_malloc(ps_sz));
  gpr_mu* mu;
  grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;
  grpc_closure shutdown_ps_closure;
  GRPC_CLOSURE_INIT(&shutdown_ps_closure, shutdown_ps, ps,
                    grpc_schedule_on_exec_ctx);
  while (state.KeepRunning()) {
    memset(ps, 0, ps_sz);
    grpc_pollset_init(ps, &mu);
    gpr_mu_lock(mu);
    grpc_pollset_shutdown(&exec_ctx, ps, &shutdown_ps_closure);
    gpr_mu_unlock(mu);
    grpc_exec_ctx_flush(&exec_ctx);
  }
  grpc_exec_ctx_finish(&exec_ctx);
  gpr_free(ps);
  track_counters.Finish(state);
}
BENCHMARK(BM_CreateDestroyPollset);

#ifdef GRPC_LINUX_MULTIPOLL_WITH_EPOLL
static void BM_PollEmptyPollset_SpeedOfLight(benchmark::State& state) {
  // equivalent to BM_PollEmptyPollset, but just use the OS primitives to guage
  // what the speed of light would be if we abstracted perfectly
  TrackCounters track_counters;
  int epfd = epoll_create1(0);
  GPR_ASSERT(epfd != -1);
  size_t nev = state.range(0);
  size_t nfd = state.range(1);
  epoll_event* ev = new epoll_event[nev];
  std::vector<int> fds;
  for (size_t i = 0; i < nfd; i++) {
    fds.push_back(eventfd(0, 0));
    epoll_event ev;
    ev.events = EPOLLIN;
    epoll_ctl(epfd, EPOLL_CTL_ADD, fds.back(), &ev);
  }
  while (state.KeepRunning()) {
    epoll_wait(epfd, ev, nev, 0);
  }
  for (auto fd : fds) {
    close(fd);
  }
  close(epfd);
  delete[] ev;
  track_counters.Finish(state);
}
BENCHMARK(BM_PollEmptyPollset_SpeedOfLight)
    ->Args({1, 0})
    ->Args({1, 1})
    ->Args({1, 10})
    ->Args({1, 100})
    ->Args({1, 1000})
    ->Args({1, 10000})
    ->Args({1, 100000})
    ->Args({10, 1})
    ->Args({100, 1})
    ->Args({1000, 1});
#endif

static void BM_PollEmptyPollset(benchmark::State& state) {
  TrackCounters track_counters;
  size_t ps_sz = grpc_pollset_size();
  grpc_pollset* ps = static_cast<grpc_pollset*>(gpr_zalloc(ps_sz));
  gpr_mu* mu;
  grpc_pollset_init(ps, &mu);
  grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;
  gpr_timespec now = gpr_time_0(GPR_CLOCK_MONOTONIC);
  gpr_timespec deadline = gpr_inf_past(GPR_CLOCK_MONOTONIC);
  gpr_mu_lock(mu);
  while (state.KeepRunning()) {
    GRPC_ERROR_UNREF(grpc_pollset_work(&exec_ctx, ps, NULL, now, deadline));
  }
  grpc_closure shutdown_ps_closure;
  GRPC_CLOSURE_INIT(&shutdown_ps_closure, shutdown_ps, ps,
                    grpc_schedule_on_exec_ctx);
  grpc_pollset_shutdown(&exec_ctx, ps, &shutdown_ps_closure);
  gpr_mu_unlock(mu);
  grpc_exec_ctx_finish(&exec_ctx);
  gpr_free(ps);
  track_counters.Finish(state);
}
BENCHMARK(BM_PollEmptyPollset);

static void BM_PollAddFd(benchmark::State& state) {
  TrackCounters track_counters;
  size_t ps_sz = grpc_pollset_size();
  grpc_pollset* ps = static_cast<grpc_pollset*>(gpr_zalloc(ps_sz));
  gpr_mu* mu;
  grpc_pollset_init(ps, &mu);
  grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;
  grpc_wakeup_fd wakeup_fd;
  GPR_ASSERT(
      GRPC_LOG_IF_ERROR("wakeup_fd_init", grpc_wakeup_fd_init(&wakeup_fd)));
  grpc_fd* fd = grpc_fd_create(wakeup_fd.read_fd, "xxx");
  while (state.KeepRunning()) {
    grpc_pollset_add_fd(&exec_ctx, ps, fd);
    grpc_exec_ctx_flush(&exec_ctx);
  }
  grpc_fd_orphan(&exec_ctx, fd, NULL, NULL, false /* already_closed */, "xxx");
  grpc_closure shutdown_ps_closure;
  GRPC_CLOSURE_INIT(&shutdown_ps_closure, shutdown_ps, ps,
                    grpc_schedule_on_exec_ctx);
  gpr_mu_lock(mu);
  grpc_pollset_shutdown(&exec_ctx, ps, &shutdown_ps_closure);
  gpr_mu_unlock(mu);
  grpc_exec_ctx_finish(&exec_ctx);
  gpr_free(ps);
  track_counters.Finish(state);
}
BENCHMARK(BM_PollAddFd);

class Closure : public grpc_closure {
 public:
  virtual ~Closure() {}
};

template <class F>
Closure* MakeClosure(F f, grpc_closure_scheduler* scheduler) {
  struct C : public Closure {
    C(F f, grpc_closure_scheduler* scheduler) : f_(f) {
      GRPC_CLOSURE_INIT(this, C::cbfn, this, scheduler);
    }
    static void cbfn(grpc_exec_ctx* exec_ctx, void* arg, grpc_error* error) {
      C* p = static_cast<C*>(arg);
      p->f_();
    }
    F f_;
  };
  return new C(f, scheduler);
}

#ifdef GRPC_LINUX_MULTIPOLL_WITH_EPOLL
static void BM_SingleThreadPollOneFd_SpeedOfLight(benchmark::State& state) {
  // equivalent to BM_PollEmptyPollset, but just use the OS primitives to guage
  // what the speed of light would be if we abstracted perfectly
  TrackCounters track_counters;
  int epfd = epoll_create1(0);
  GPR_ASSERT(epfd != -1);
  epoll_event ev[100];
  int fd = eventfd(0, EFD_NONBLOCK);
  ev[0].events = EPOLLIN;
  epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &ev[0]);
  while (state.KeepRunning()) {
    int err;
    do {
      err = eventfd_write(fd, 1);
    } while (err < 0 && errno == EINTR);
    GPR_ASSERT(err == 0);
    do {
      err = epoll_wait(epfd, ev, GPR_ARRAY_SIZE(ev), 0);
    } while (err < 0 && errno == EINTR);
    GPR_ASSERT(err == 1);
    eventfd_t value;
    do {
      err = eventfd_read(fd, &value);
    } while (err < 0 && errno == EINTR);
    GPR_ASSERT(err == 0);
  }
  close(fd);
  close(epfd);
  track_counters.Finish(state);
}
BENCHMARK(BM_SingleThreadPollOneFd_SpeedOfLight);
#endif

static void BM_SingleThreadPollOneFd(benchmark::State& state) {
  TrackCounters track_counters;
  size_t ps_sz = grpc_pollset_size();
  grpc_pollset* ps = static_cast<grpc_pollset*>(gpr_zalloc(ps_sz));
  gpr_mu* mu;
  grpc_pollset_init(ps, &mu);
  grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;
  gpr_timespec now = gpr_time_0(GPR_CLOCK_MONOTONIC);
  gpr_timespec deadline = gpr_inf_future(GPR_CLOCK_MONOTONIC);
  grpc_wakeup_fd wakeup_fd;
  GRPC_ERROR_UNREF(grpc_wakeup_fd_init(&wakeup_fd));
  grpc_fd* wakeup = grpc_fd_create(wakeup_fd.read_fd, "wakeup_read");
  grpc_pollset_add_fd(&exec_ctx, ps, wakeup);
  bool done = false;
  Closure* continue_closure = MakeClosure(
      [&]() {
        GRPC_ERROR_UNREF(grpc_wakeup_fd_consume_wakeup(&wakeup_fd));
        if (!state.KeepRunning()) {
          done = true;
          return;
        }
        GRPC_ERROR_UNREF(grpc_wakeup_fd_wakeup(&wakeup_fd));
        grpc_fd_notify_on_read(&exec_ctx, wakeup, continue_closure);
      },
      grpc_schedule_on_exec_ctx);
  GRPC_ERROR_UNREF(grpc_wakeup_fd_wakeup(&wakeup_fd));
  grpc_fd_notify_on_read(&exec_ctx, wakeup, continue_closure);
  gpr_mu_lock(mu);
  while (!done) {
    GRPC_ERROR_UNREF(grpc_pollset_work(&exec_ctx, ps, NULL, now, deadline));
  }
  grpc_fd_orphan(&exec_ctx, wakeup, NULL, NULL, false /* already_closed */,
                 "done");
  wakeup_fd.read_fd = 0;
  grpc_closure shutdown_ps_closure;
  GRPC_CLOSURE_INIT(&shutdown_ps_closure, shutdown_ps, ps,
                    grpc_schedule_on_exec_ctx);
  grpc_pollset_shutdown(&exec_ctx, ps, &shutdown_ps_closure);
  gpr_mu_unlock(mu);
  grpc_exec_ctx_finish(&exec_ctx);
  grpc_wakeup_fd_destroy(&wakeup_fd);
  gpr_free(ps);
  track_counters.Finish(state);
  delete continue_closure;
}
BENCHMARK(BM_SingleThreadPollOneFd);

BENCHMARK_MAIN();
<|endoftext|>


<commit_before>/*
 *	This file is part of qpOASES.
 *
 *	qpOASES -- An Implementation of the Online Active Set Strategy.
 *	Copyright (C) 2007-2014 by Hans Joachim Ferreau, Andreas Potschka,
 *	Christian Kirches et al. All rights reserved.
 *
 *	qpOASES 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.
 *
 *	qpOASES 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 qpOASES; if not, write to the Free Software
 *	Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 */

/**
 *	\file testing/cpp/test_bench.cpp
 *	\author Andreas Potschka, Christian Kirches, Hans Joachim Ferreau
 *	\version 3.0
 *	\date 2010-2014
 *
 *	Unit test running all benchmark examples stored in problems directory.
 */

#include <dirent.h>
#include <cstring>
#include <cstdlib>
#include <qpOASES.hpp>
#include <qpOASES/UnitTesting.hpp>

/** Run benchmark examples. */
int main( int argc, char *argv[] )
{
	USING_NAMESPACE_QPOASES

	/* 1) Define benchmark arguments. */
	BooleanType isSparse = BT_FALSE;
	//BooleanType isSparse = BT_TRUE;
	Options options;
 	options.setToDefault();
	//options.setToMPC();
	//options.setToReliable();
	//options.printLevel = PL_LOW;
	//options.printLevel = PL_MEDIUM;
	options.printLevel = PL_TABULAR;

	int nWSR;
	real_t maxCPUtime; /* seconds */
	real_t maxStationarity = 0.0, maxFeasibility = 0.0, maxComplementarity = 0.0;

	char OQPproblem[MAX_STRING_LENGTH];
	char problem[] = "HS268";
	returnValue returnvalue;

	/* 3) Run benchmark. */
	fprintf(stdFile, "%-10s ", problem);
	fflush(stdFile);

	snprintf(OQPproblem, MAX_STRING_LENGTH, "../testing/cpp/data/problems/%s/", problem);
	maxCPUtime = 100.0;
	nWSR = 100;

	returnvalue = runOQPbenchmark(	OQPproblem, isSparse, options,
									nWSR, maxCPUtime, maxStationarity, maxFeasibility, maxComplementarity
									);

	printf( "\n" );
	printf( "stat:  %e\n", maxStationarity    );
	printf( "feas:  %e\n", maxFeasibility     );
	printf( "cmpl:  %e\n", maxComplementarity );

	QPOASES_TEST_FOR_TOL( maxStationarity,    1e-11 );
	QPOASES_TEST_FOR_TOL( maxFeasibility,     1e-14 );
	QPOASES_TEST_FOR_TOL( maxComplementarity, 1e-14 );

	return 0;
}

/*
 *	end of file
 */
<commit_msg>added a check for 'returnvalue' in test_hs268<commit_after>/*
 *	This file is part of qpOASES.
 *
 *	qpOASES -- An Implementation of the Online Active Set Strategy.
 *	Copyright (C) 2007-2014 by Hans Joachim Ferreau, Andreas Potschka,
 *	Christian Kirches et al. All rights reserved.
 *
 *	qpOASES 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.
 *
 *	qpOASES 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 qpOASES; if not, write to the Free Software
 *	Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 */

/**
 *	\file testing/cpp/test_bench.cpp
 *	\author Andreas Potschka, Christian Kirches, Hans Joachim Ferreau
 *	\version 3.0
 *	\date 2010-2014
 *
 *	Unit test running all benchmark examples stored in problems directory.
 */

#include <dirent.h>
#include <cstring>
#include <cstdlib>
#include <qpOASES.hpp>
#include <qpOASES/UnitTesting.hpp>

/** Run benchmark examples. */
int main( int argc, char *argv[] )
{
	USING_NAMESPACE_QPOASES

	/* 1) Define benchmark arguments. */
	BooleanType isSparse = BT_FALSE;
	//BooleanType isSparse = BT_TRUE;
	Options options;
 	options.setToDefault();
	//options.setToMPC();
	//options.setToReliable();
	//options.printLevel = PL_LOW;
	//options.printLevel = PL_MEDIUM;
	options.printLevel = PL_TABULAR;

	int nWSR;
	int npass = 0;
	real_t maxCPUtime; /* seconds */
	real_t maxStationarity = 0.0, maxFeasibility = 0.0, maxComplementarity = 0.0;

	char OQPproblem[MAX_STRING_LENGTH];
	char problem[] = "HS268";
	returnValue returnvalue;

	/* 3) Run benchmark. */
	fprintf(stdFile, "%-10s ", problem);
	fflush(stdFile);

	snprintf(OQPproblem, MAX_STRING_LENGTH, "../testing/cpp/data/problems/%s/", problem);
	maxCPUtime = 100.0;
	nWSR = 100;

	returnvalue = runOQPbenchmark(	OQPproblem, isSparse, options,
									nWSR, maxCPUtime, maxStationarity, maxFeasibility, maxComplementarity
									);

	if(returnvalue == SUCCESSFUL_RETURN) {
		npass += 1;
	}

	QPOASES_TEST_FOR_TRUE( npass >= 1 );

	printf( "\n" );
	printf( "stat:  %e\n", maxStationarity    );
	printf( "feas:  %e\n", maxFeasibility     );
	printf( "cmpl:  %e\n", maxComplementarity );

	QPOASES_TEST_FOR_TOL( maxStationarity,    1e-11 );
	QPOASES_TEST_FOR_TOL( maxFeasibility,     1e-14 );
	QPOASES_TEST_FOR_TOL( maxComplementarity, 1e-14 );

	return 0;
}

/*
 *	end of file
 */
<|endoftext|>