<commit_before>#pragma once
#include "dllist.cpp"

template <typename T>
class DoubleLinkedChain : public DoubleLinkedList<T>
{
protected:
    void copy(const DoubleLinkedChain<T>& other)
    {
        if (!other.front || !other.back)
            return;

        DoubleListElement<T> *pFront = other.front, *pn = pFront->prev;
        DoubleLinkedList<T> lFront;

        while (pFront && pFront->prev == pn)
        {
            lFront.insertEnd(pFront->data);
            pn = pFront;
            pFront = pFront->next;
        }

        if (pFront)
        {
            DoubleListElement<T> *pBack = other.back;
            pn = pBack->next;
            DoubleLinkedList<T> lBack;

            while (pBack && pBack->next == pn)
            {
                lBack.insertBegin(pBack->data);
                pn = pBack;
                pBack = pBack->prev;
            }

            lFront.back->next = pFront;
            lBack.front->prev = pBack;
            this->front = lFront.front;
            this->back = lBack.back;
            lBack.back = lBack.front = NULL;
        }
        else
        {
            this->front = lFront.front;
            this->back = lFront.back;
        }

        lFront.back = lFront.front = NULL;
    }

public:
    void clear()
    {
        if (!this->front || !this->back)
            return;

        DoubleListElement<T> *pFront = this->front, *prev = pFront->prev;

        while (pFront && pFront->prev == prev)
        {
            prev = pFront;
            pFront = pFront->next;
        }

        prev->next = NULL;

        DoubleListElement<T> *pBack = this->back, *next = pBack->next;

        while (pBack && pBack->next == next)
        {
            next = pBack;
            pBack = pBack->prev;
        }

        next->prev = NULL;

        DoubleLinkedList<T> lFront, lBack;
        lFront.front = this->front;
        lFront.back = prev;

        if (this->front != next && prev != this->back)
        {
            lBack.front = next;
            lBack.back = this->back;
        }

        this->back = this->front = NULL;
    }

    DoubleLinkedChain()
    {
        this->front = NULL;
        this->back = NULL;
    }

    DoubleLinkedChain(const DoubleLinkedChain& other)
    {
        copy(other);
    }

    DoubleLinkedChain& operator=(const DoubleLinkedChain& other)
    {
        if (&other != this)
        {
            clear();
            copy(other);
        }

        return *this;
    }

    ~DoubleLinkedChain()
    {
        clear();
    }

    DoubleListElement<T>* getFrontPtr() { return this->front; }
    const DoubleListElement<T>* getFrontPtr() const { return this->front; }

    DoubleListElement<T>* getBackPtr() { return this->back; }
    const DoubleListElement<T>* getBackPtr() const { return this->back; }

    bool adoptList(DoubleLinkedList<T>& l)
    {
        if (!l.front || !l.back)
            return false;

        clear();
        this->front = l.front;
        this->back = l.back;
        l.front = NULL;
        l.back = NULL;
        return true;
    }

    bool attachAtBegin(DoubleLinkedList<T>& l, I& it)
    {
        if (it)
        {
            if (this->front)
            {
                this->front->prev = it.ptr;

                if (it.ptr == l.back)
                    it.ptr->next = this->front;

                I begin = front;
                while (begin && begin.ptr->back)
                    begin--;
                front = begin.ptr;
            }
            else
            {
                this->front = l.front;
                this->back = l.back;
            }

            l.front = NULL;
            l.back = NULL;
            return true;
        }
        else
            return false;
    }

    bool attachAtEnd(DoubleLinkedList<T>& l, I& it)
    {
        if (it)
        {
            if (this->back)
            {
                this->back->next = it.ptr;

                if (it.ptr == l.front)
                    it.ptr->prev = this->back;

                I end = back;
                while (end && end.ptr->next)
                    end++;
                back = end.ptr;
            }
            else
            {
                this->front = l.front;
                this->back = l.back;
            }

            l.front = NULL;
            l.back = NULL;
            return true;
        }
        else
            return false;
    }

    bool attachListAtFront(DoubleLinkedList<T>& l, I& it)
    {
        if (it && l.front && !l.front->prev)
        {
            l.front->prev = it.ptr;

            if (it.ptr == this->back)
            {
                this->back->next = l.front;

                I end = back;
                while (end && end.ptr->next)
                    end++;
                back = end.ptr;
            }

            return true;
        }
        else
            return false;
    }

    bool attachListAtBack(DoubleLinkedList<T>& l, I& it)
    {
        if (it && l.back && !l.back->next)
        {
            l.back->next = it.ptr;

            if (it.ptr == this->front)
            {
                this->front->back = l.back;

                I begin = front;
                while (begin && begin.ptr->back)
                    begin--;
                front = begin.ptr;
            }

            return true;
        }
        else
            return false;
    }

    bool join_at(DoubleLinkedList<T>& L1, DoubleLinkedList<T>& L2, I& M1, I& M2)
    {
        return adoptList(L1) && attachListAtFront(L2, M1) &&
                                attachAtEnd(L2, M2);
    }

    bool join(DoubleLinkedList<T>& L1, DoubleLinkedList<T>& L2)
    {
        I itL1 = L1.begin(), itL2 = L2.end(), M1, M2;

        while (itL1 && itL2)
        {
            if (*itL1 == *itL2 && (!M1 || *itL1 > *M1))
            {
                M1 = itL1;
                M2 = itL2;
            }

            itL1++;
            itL2--;
        }

        itL1 = L1.end();
        itL2 = L2.begin();

        while (itL1 && itL2)
        {
            if (*itL1 == *itL2 && (!M1 || *itL1 > *M1))
            {
                M1 = itL1;
                M2 = itL2;
            }

            itL1--;
            itL2++;
        }

        return join_at(L1, L2, M1, M2);
    }

    bool isJoined() const
    {
        if (!this->front || !this->back)
            return false;

        DoubleListElement<T> *pFront = this->front, *pn = pFront->prev;

        while (pFront && pFront->prev == pn)
        {
            pn = pFront;
            pFront = pFront->next;
        }

        DoubleListElement<T> *pBack = this->back;
        pn = pBack->next;

        while (pBack && pBack->next == pn)
        {
            pn = pBack;
            pBack = pBack->prev;
        }

        return pFront && pBack;
    }

    T sum() const
    {
        T S = T();

        if (!this->front || !this->back)
            return S;

        DoubleListElement<T> *pFront = this->front, *pn = pFront->prev;

        while (pFront && pFront->prev == pn)
        {
            S += pFront->data;
            pn = pFront;
            pFront = pFront->next;
        }

        if (pFront)
        {
            DoubleListElement<T> *pBack = this->back;
            pn = pBack->next;

            while (pBack && pBack->next == pn)
            {
                S += pBack->data;
                pn = pBack;
                pBack = pBack->prev;
            }
        }

        return S;
    }
};
<commit_msg>replaced typedef I with its actual type (was defined in base class and therefore inaccessible here)<commit_after>#pragma once
#include "dllist.cpp"

template <typename T>
class DoubleLinkedChain : public DoubleLinkedList<T>
{
protected:
    void copy(const DoubleLinkedChain<T>& other)
    {
        if (!other.front || !other.back)
            return;

        DoubleListElement<T> *pFront = other.front, *pn = pFront->prev;
        DoubleLinkedList<T> lFront;

        while (pFront && pFront->prev == pn)
        {
            lFront.insertEnd(pFront->data);
            pn = pFront;
            pFront = pFront->next;
        }

        if (pFront)
        {
            DoubleListElement<T> *pBack = other.back;
            pn = pBack->next;
            DoubleLinkedList<T> lBack;

            while (pBack && pBack->next == pn)
            {
                lBack.insertBegin(pBack->data);
                pn = pBack;
                pBack = pBack->prev;
            }

            lFront.back->next = pFront;
            lBack.front->prev = pBack;
            this->front = lFront.front;
            this->back = lBack.back;
            lBack.back = lBack.front = NULL;
        }
        else
        {
            this->front = lFront.front;
            this->back = lFront.back;
        }

        lFront.back = lFront.front = NULL;
    }

public:
    void clear()
    {
        if (!this->front || !this->back)
            return;

        DoubleListElement<T> *pFront = this->front, *prev = pFront->prev;

        while (pFront && pFront->prev == prev)
        {
            prev = pFront;
            pFront = pFront->next;
        }

        prev->next = NULL;

        DoubleListElement<T> *pBack = this->back, *next = pBack->next;

        while (pBack && pBack->next == next)
        {
            next = pBack;
            pBack = pBack->prev;
        }

        next->prev = NULL;

        DoubleLinkedList<T> lFront, lBack;
        lFront.front = this->front;
        lFront.back = prev;

        if (this->front != next && prev != this->back)
        {
            lBack.front = next;
            lBack.back = this->back;
        }

        this->back = this->front = NULL;
    }

    DoubleLinkedChain()
    {
        this->front = NULL;
        this->back = NULL;
    }

    DoubleLinkedChain(const DoubleLinkedChain& other)
    {
        copy(other);
    }

    DoubleLinkedChain& operator=(const DoubleLinkedChain& other)
    {
        if (&other != this)
        {
            clear();
            copy(other);
        }

        return *this;
    }

    ~DoubleLinkedChain()
    {
        clear();
    }

    DoubleListElement<T>* getFrontPtr() { return this->front; }
    const DoubleListElement<T>* getFrontPtr() const { return this->front; }

    DoubleListElement<T>* getBackPtr() { return this->back; }
    const DoubleListElement<T>* getBackPtr() const { return this->back; }

    bool adoptList(DoubleLinkedList<T>& l)
    {
        if (!l.front || !l.back)
            return false;

        clear();
        this->front = l.front;
        this->back = l.back;
        l.front = NULL;
        l.back = NULL;
        return true;
    }

    bool attachAtBegin(DoubleLinkedList<T>& l, DoubleLinkedListIterator<T>& it)
    {
        if (it)
        {
            if (this->front)
            {
                this->front->prev = it.ptr;

                if (it.ptr == l.back)
                    it.ptr->next = this->front;

                I begin = front;
                while (begin && begin.ptr->back)
                    begin--;
                front = begin.ptr;
            }
            else
            {
                this->front = l.front;
                this->back = l.back;
            }

            l.front = NULL;
            l.back = NULL;
            return true;
        }
        else
            return false;
    }

    bool attachAtEnd(DoubleLinkedList<T>& l, DoubleLinkedListIterator<T>& it)
    {
        if (it)
        {
            if (this->back)
            {
                this->back->next = it.ptr;

                if (it.ptr == l.front)
                    it.ptr->prev = this->back;

                I end = back;
                while (end && end.ptr->next)
                    end++;
                back = end.ptr;
            }
            else
            {
                this->front = l.front;
                this->back = l.back;
            }

            l.front = NULL;
            l.back = NULL;
            return true;
        }
        else
            return false;
    }

    bool attachListAtFront(DoubleLinkedList<T>& l, DoubleLinkedListIterator<T>& it)
    {
        if (it && l.front && !l.front->prev)
        {
            l.front->prev = it.ptr;

            if (it.ptr == this->back)
            {
                this->back->next = l.front;

                I end = back;
                while (end && end.ptr->next)
                    end++;
                back = end.ptr;
            }

            return true;
        }
        else
            return false;
    }

    bool attachListAtBack(DoubleLinkedList<T>& l,
            DoubleLinkedListIterator<T>& it)
    {
        if (it && l.back && !l.back->next)
        {
            l.back->next = it.ptr;

            if (it.ptr == this->front)
            {
                this->front->back = l.back;

                I begin = front;
                while (begin && begin.ptr->back)
                    begin--;
                front = begin.ptr;
            }

            return true;
        }
        else
            return false;
    }

    bool join_at(DoubleLinkedList<T>& L1, DoubleLinkedList<T>& L2,
            DoubleLinkedListIterator<T>& M1, DoubleLinkedListIterator<T>& M2)
    {
        return adoptList(L1) && attachListAtFront(L2, M1) &&
                                attachAtEnd(L2, M2);
    }

    bool join(DoubleLinkedList<T>& L1, DoubleLinkedList<T>& L2)
    {
        DoubleLinkedListIterator<T> itL1 = L1.begin(), itL2 = L2.end(), M1, M2;

        while (itL1 && itL2)
        {
            if (*itL1 == *itL2 && (!M1 || *itL1 > *M1))
            {
                M1 = itL1;
                M2 = itL2;
            }

            itL1++;
            itL2--;
        }

        itL1 = L1.end();
        itL2 = L2.begin();

        while (itL1 && itL2)
        {
            if (*itL1 == *itL2 && (!M1 || *itL1 > *M1))
            {
                M1 = itL1;
                M2 = itL2;
            }

            itL1--;
            itL2++;
        }

        return join_at(L1, L2, M1, M2);
    }

    bool isJoined() const
    {
        if (!this->front || !this->back)
            return false;

        DoubleListElement<T> *pFront = this->front, *pn = pFront->prev;

        while (pFront && pFront->prev == pn)
        {
            pn = pFront;
            pFront = pFront->next;
        }

        DoubleListElement<T> *pBack = this->back;
        pn = pBack->next;

        while (pBack && pBack->next == pn)
        {
            pn = pBack;
            pBack = pBack->prev;
        }

        return pFront && pBack;
    }

    T sum() const
    {
        T S = T();

        if (!this->front || !this->back)
            return S;

        DoubleListElement<T> *pFront = this->front, *pn = pFront->prev;

        while (pFront && pFront->prev == pn)
        {
            S += pFront->data;
            pn = pFront;
            pFront = pFront->next;
        }

        if (pFront)
        {
            DoubleListElement<T> *pBack = this->back;
            pn = pBack->next;

            while (pBack && pBack->next == pn)
            {
                S += pBack->data;
                pn = pBack;
                pBack = pBack->prev;
            }
        }

        return S;
    }
};
<|endoftext|>


<commit_before>/*
 * #%L
 * %%
 * Copyright (C) 2011 - 2017 BMW Car IT GmbH
 * %%
 * 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.
 * #L%
 */

#include <gtest/gtest.h>
#include <gmock/gmock.h>

#include "joynr/JoynrClusterControllerRuntime.h"
#include "joynr/Settings.h"
#include "joynr/SystemServicesSettings.h"
#include "joynr/system/ProviderReregistrationControllerProxy.h"

using namespace ::testing;
using namespace joynr;

TEST(ProviderReregistrationControllerTest, queryProviderReregistrationControllerSucceedsOnCCRuntime)
{
    auto integrationSettings = std::make_unique<Settings>("test-resources/MqttSystemIntegrationTest1.settings");
    joynr::SystemServicesSettings systemServiceSettings(*integrationSettings);
    const std::string domain(systemServiceSettings.getDomain());

    auto runtime = std::make_shared<JoynrClusterControllerRuntime>(std::move(integrationSettings));
    runtime->init();
    runtime->start();

    auto providerReregistrationControllerProxyBuilder = runtime->createProxyBuilder<joynr::system::ProviderReregistrationControllerProxy>(domain);
    auto providerReregistrationControllerProxy = providerReregistrationControllerProxyBuilder->build();

    Semaphore finishedSemaphore;
    providerReregistrationControllerProxy->triggerGlobalProviderReregistrationAsync([&finishedSemaphore]() { finishedSemaphore.notify(); }, nullptr);
    finishedSemaphore.waitFor(std::chrono::seconds(2));

    runtime->stop();
    runtime = nullptr;
}
<commit_msg>[C++] Reproducer test for provider reregistration call issue<commit_after>/*
 * #%L
 * %%
 * Copyright (C) 2011 - 2017 BMW Car IT GmbH
 * %%
 * 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.
 * #L%
 */

#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include <chrono>

#include "joynr/JoynrClusterControllerRuntime.h"
#include "joynr/Settings.h"
#include "joynr/SystemServicesSettings.h"
#include "joynr/system/ProviderReregistrationControllerProxy.h"
#include "utils/TestLibJoynrWebSocketRuntime.h"

using namespace ::testing;
using namespace joynr;

TEST(ProviderReregistrationControllerTest, queryProviderReregistrationControllerSucceedsOnCCRuntime)
{
    auto integrationSettings = std::make_unique<Settings>("test-resources/MqttSystemIntegrationTest1.settings");
    joynr::SystemServicesSettings systemServiceSettings(*integrationSettings);
    const std::string domain(systemServiceSettings.getDomain());

    auto runtime = std::make_shared<JoynrClusterControllerRuntime>(std::move(integrationSettings));
    runtime->init();
    runtime->start();

    auto providerReregistrationControllerProxyBuilder = runtime->createProxyBuilder<joynr::system::ProviderReregistrationControllerProxy>(domain);
    auto providerReregistrationControllerProxy = providerReregistrationControllerProxyBuilder->build();

    Semaphore finishedSemaphore;
    providerReregistrationControllerProxy->triggerGlobalProviderReregistrationAsync([&finishedSemaphore]() { finishedSemaphore.notify(); }, nullptr);
    finishedSemaphore.waitFor(std::chrono::seconds(2));

    runtime->stop();
    runtime = nullptr;
}

TEST(ProviderReregistrationControllerTest, queryProviderReregistrationControllerSucceedsOnWsRuntime)
{
    auto integrationSettings = std::make_unique<Settings>("test-resources/MqttSystemIntegrationTest1.settings");
    joynr::SystemServicesSettings systemServiceSettings(*integrationSettings);
    const std::string domain(systemServiceSettings.getDomain());

    auto ccRuntime = std::make_shared<JoynrClusterControllerRuntime>(std::move(integrationSettings));
    ccRuntime->init();
    ccRuntime->start();

    auto wsRuntimeSettings = std::make_unique<Settings>("test-resources/libjoynrSystemIntegration1.settings");
    auto wsRuntime = std::make_shared<TestLibJoynrWebSocketRuntime>(std::move(wsRuntimeSettings), nullptr);
    wsRuntime->connect(std::chrono::seconds(2));

    auto providerReregistrationControllerProxyBuilder = wsRuntime->createProxyBuilder<joynr::system::ProviderReregistrationControllerProxy>(domain);
    auto providerReregistrationControllerProxy = providerReregistrationControllerProxyBuilder->build();

    Semaphore finishedSemaphore;
    providerReregistrationControllerProxy->triggerGlobalProviderReregistrationAsync([&finishedSemaphore]() { finishedSemaphore.notify(); }, [](const joynr::exceptions::JoynrRuntimeException&) { FAIL(); });
    finishedSemaphore.waitFor(std::chrono::seconds(2));

    wsRuntime = nullptr;
    ccRuntime->stop();
    ccRuntime = nullptr;
}
<|endoftext|>


<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** 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.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/

#include "baseprojectwizarddialog.h"

#include <coreplugin/basefilewizard.h>
#include <coreplugin/icore.h>
#include <coreplugin/filemanager.h>
#include <utils/projectintropage.h>

#include <QtCore/QDir>

/*!
    \class ProjectExplorer::BaseProjectWizardDialog

    \brief Base class for project wizards.

    Presents the introductory page and takes care of setting the folder chosen
    as default projects' folder should the user wish to do that.
*/

namespace ProjectExplorer {

struct BaseProjectWizardDialogPrivate {
    explicit BaseProjectWizardDialogPrivate(Utils::ProjectIntroPage *page, int id = -1);

    const int desiredIntroPageId;
    Utils::ProjectIntroPage *introPage;
    int introPageId;
};

BaseProjectWizardDialogPrivate::BaseProjectWizardDialogPrivate(Utils::ProjectIntroPage *page, int id) :
    desiredIntroPageId(id),
    introPage(page),
    introPageId(-1)
{
}

BaseProjectWizardDialog::BaseProjectWizardDialog(QWidget *parent) :
    Utils::Wizard(parent),
    d(new BaseProjectWizardDialogPrivate(new Utils::ProjectIntroPage))
{
    init();
}

BaseProjectWizardDialog::BaseProjectWizardDialog(Utils::ProjectIntroPage *introPage,
                                                 int introId,
                                                 QWidget *parent) :
    Utils::Wizard(parent),
    d(new BaseProjectWizardDialogPrivate(introPage, introId))
{
    init();
}

void BaseProjectWizardDialog::init()
{
    Core::BaseFileWizard::setupWizard(this);
    if (d->introPageId == -1) {
        d->introPageId = addPage(d->introPage);
    } else {
        d->introPageId = d->desiredIntroPageId;
        setPage(d->desiredIntroPageId, d->introPage);
    }
    wizardProgress()->item(d->introPageId)->setTitle(tr("Location"));
    connect(this, SIGNAL(accepted()), this, SLOT(slotAccepted()));
    connect(this, SIGNAL(nextClicked()), this, SLOT(nextClicked()));
}

BaseProjectWizardDialog::~BaseProjectWizardDialog()
{
    delete d;
}

QString BaseProjectWizardDialog::projectName() const
{
    return d->introPage->projectName();
}

QString BaseProjectWizardDialog::path() const
{
    return d->introPage->path();
}

void BaseProjectWizardDialog::setIntroDescription(const QString &des)
{
    d->introPage->setDescription(des);
}

void BaseProjectWizardDialog::setPath(const QString &path)
{
    d->introPage->setPath(path);
}

void BaseProjectWizardDialog::setProjectName(const QString &name)
{
    d->introPage->setProjectName(name);
}

void BaseProjectWizardDialog::slotAccepted()
{
    if (d->introPage->useAsDefaultPath()) {
        // Store the path as default path for new projects if desired.
        Core::FileManager *fm = Core::ICore::instance()->fileManager();
        fm->setProjectsDirectory(path());
        fm->setUseProjectsDirectory(true);
    }
}

void BaseProjectWizardDialog::nextClicked()
{
    if (currentId() == d->introPageId) {
        emit projectParametersChanged(d->introPage->projectName(), d->introPage->path());
    }
}

Utils::ProjectIntroPage *BaseProjectWizardDialog::introPage() const
{
    return d->introPage;
}

QString BaseProjectWizardDialog::uniqueProjectName(const QString &path)
{
    const QDir pathDir(path);
    //: File path suggestion for a new project. If you choose
    //: to translate it, make sure it is a valid path name without blanks.
    const QString prefix = tr("untitled");
    for (unsigned i = 0; ; ++i) {
        QString name = prefix;
        if (i)
            name += QString::number(i);
        if (!pathDir.exists(name))
            return name;
    }
    return prefix;
}
} // namespace ProjectExplorer
<commit_msg>Extend note about validity of default<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** 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.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/

#include "baseprojectwizarddialog.h"

#include <coreplugin/basefilewizard.h>
#include <coreplugin/icore.h>
#include <coreplugin/filemanager.h>
#include <utils/projectintropage.h>

#include <QtCore/QDir>

/*!
    \class ProjectExplorer::BaseProjectWizardDialog

    \brief Base class for project wizards.

    Presents the introductory page and takes care of setting the folder chosen
    as default projects' folder should the user wish to do that.
*/

namespace ProjectExplorer {

struct BaseProjectWizardDialogPrivate {
    explicit BaseProjectWizardDialogPrivate(Utils::ProjectIntroPage *page, int id = -1);

    const int desiredIntroPageId;
    Utils::ProjectIntroPage *introPage;
    int introPageId;
};

BaseProjectWizardDialogPrivate::BaseProjectWizardDialogPrivate(Utils::ProjectIntroPage *page, int id) :
    desiredIntroPageId(id),
    introPage(page),
    introPageId(-1)
{
}

BaseProjectWizardDialog::BaseProjectWizardDialog(QWidget *parent) :
    Utils::Wizard(parent),
    d(new BaseProjectWizardDialogPrivate(new Utils::ProjectIntroPage))
{
    init();
}

BaseProjectWizardDialog::BaseProjectWizardDialog(Utils::ProjectIntroPage *introPage,
                                                 int introId,
                                                 QWidget *parent) :
    Utils::Wizard(parent),
    d(new BaseProjectWizardDialogPrivate(introPage, introId))
{
    init();
}

void BaseProjectWizardDialog::init()
{
    Core::BaseFileWizard::setupWizard(this);
    if (d->introPageId == -1) {
        d->introPageId = addPage(d->introPage);
    } else {
        d->introPageId = d->desiredIntroPageId;
        setPage(d->desiredIntroPageId, d->introPage);
    }
    wizardProgress()->item(d->introPageId)->setTitle(tr("Location"));
    connect(this, SIGNAL(accepted()), this, SLOT(slotAccepted()));
    connect(this, SIGNAL(nextClicked()), this, SLOT(nextClicked()));
}

BaseProjectWizardDialog::~BaseProjectWizardDialog()
{
    delete d;
}

QString BaseProjectWizardDialog::projectName() const
{
    return d->introPage->projectName();
}

QString BaseProjectWizardDialog::path() const
{
    return d->introPage->path();
}

void BaseProjectWizardDialog::setIntroDescription(const QString &des)
{
    d->introPage->setDescription(des);
}

void BaseProjectWizardDialog::setPath(const QString &path)
{
    d->introPage->setPath(path);
}

void BaseProjectWizardDialog::setProjectName(const QString &name)
{
    d->introPage->setProjectName(name);
}

void BaseProjectWizardDialog::slotAccepted()
{
    if (d->introPage->useAsDefaultPath()) {
        // Store the path as default path for new projects if desired.
        Core::FileManager *fm = Core::ICore::instance()->fileManager();
        fm->setProjectsDirectory(path());
        fm->setUseProjectsDirectory(true);
    }
}

void BaseProjectWizardDialog::nextClicked()
{
    if (currentId() == d->introPageId) {
        emit projectParametersChanged(d->introPage->projectName(), d->introPage->path());
    }
}

Utils::ProjectIntroPage *BaseProjectWizardDialog::introPage() const
{
    return d->introPage;
}

QString BaseProjectWizardDialog::uniqueProjectName(const QString &path)
{
    const QDir pathDir(path);
    //: File path suggestion for a new project. If you choose
    //: to translate it, make sure it is a valid path name without blanks
    //: and using only ascii chars.
    const QString prefix = tr("untitled");
    for (unsigned i = 0; ; ++i) {
        QString name = prefix;
        if (i)
            name += QString::number(i);
        if (!pathDir.exists(name))
            return name;
    }
    return prefix;
}
} // namespace ProjectExplorer
<|endoftext|>


<commit_before>#include <nan.h>
#include <node.h>
#include <string>
#include <cstring>

#include "../include/str_array_converter.h"
#include "git2/strarray.h"

using namespace v8;
using namespace node;

git_strarray *StrArrayConverter::Convert(Handle<v8::Value> val) {
  if (!val->BooleanValue()) {
    return NULL;
  }
  else if (val->IsArray()) {
    return ConvertArray(Array::Cast(*val));
  }
  else if (val->IsString() || val->IsStringObject()) {
    return ConvertString(val->ToString());
  }
  else {
    return NULL;
  }
}

git_strarray *StrArrayConverter::ConvertArray(Array *val) {
  int count = val->Length();
  char **strings = (char **)malloc(sizeof(char*) * count);
  git_strarray *result;

  for(int i = 0; i < count; i++) {
    NanUtf8String entry(val->CloneElementAt(i));
    strings[i] = *entry;
  }

  result = ConstructStrArray(count, strings);
  free(strings);
  return result;
}

git_strarray* StrArrayConverter::ConvertString(Handle<String> val) {
  char *strings[1];
  NanUtf8String utf8String(val);

  strings[0] = *utf8String;

  return ConstructStrArray(1, strings);
}

git_strarray *StrArrayConverter::ConstructStrArray(int argc, char** argv) {
  git_strarray *result = (git_strarray *)malloc(sizeof(git_strarray*));
  result->count = argc;
  result->strings = (char **)malloc(sizeof(char*) * result->count);

  for(size_t i = 0; i < result->count; i++) {
    result->strings[i] = strdup(argv[i]);
  }

  return result;
}
<commit_msg>Fix git_strarray when an actual array is passed in<commit_after>#include <nan.h>
#include <node.h>
#include <string>
#include <cstring>

#include "../include/str_array_converter.h"
#include "git2/strarray.h"

using namespace v8;
using namespace node;

git_strarray *StrArrayConverter::Convert(Handle<v8::Value> val) {
  if (!val->BooleanValue()) {
    return NULL;
  }
  else if (val->IsArray()) {
    return ConvertArray(Array::Cast(*val));
  }
  else if (val->IsString() || val->IsStringObject()) {
    return ConvertString(val->ToString());
  }
  else {
    return NULL;
  }
}

git_strarray *StrArrayConverter::ConvertArray(Array *val) {
  int count = val->Length();
  char **strings = (char **)malloc(sizeof(char*) * count);
  git_strarray *result;

  for(int i = 0; i < count; i++) {
    NanUtf8String entry(val->Get(i));
    strings[i] = *entry;
  }

  result = ConstructStrArray(count, strings);
  free(strings);
  return result;
}

git_strarray* StrArrayConverter::ConvertString(Handle<String> val) {
  char *strings[1];
  NanUtf8String utf8String(val);

  strings[0] = *utf8String;

  return ConstructStrArray(1, strings);
}

git_strarray *StrArrayConverter::ConstructStrArray(int argc, char** argv) {
  git_strarray *result = (git_strarray *)malloc(sizeof(git_strarray*));
  result->count = argc;
  result->strings = (char **)malloc(sizeof(char*) * result->count);

  for(size_t i = 0; i < result->count; i++) {
    result->strings[i] = strdup(argv[i]);
  }

  return result;
}
<|endoftext|>


<commit_before>
/* Note: This module can probably go away when we upgrade to Python 2.4.
   Python 2.3 has a heapq implementation, but it is in Python. This is
   reported to be about 20x faster. In 2.4 they reimplemented heapq in C so
   it should be comparable to this. At this time though, Python 2.4 is
   still in alpha.

   Note: This code has been bastardized to only work on Tasks temporarily.

*/

#include <Python.h>

/* Prototypes */
static PyObject * heappush(PyObject *self, PyObject *args);
static PyObject * heappop(PyObject *self, PyObject *args);
static PyObject * heapreplace(PyObject *self, PyObject *args);
static PyObject * heapify(PyObject *self, PyObject *args);
static int _siftdown(PyObject *list, int startpos, int pos);
static int _siftup(PyObject *list, int pos);

#ifdef _WIN32
extern "C" __declspec(dllexport) void initlibheapq(void);
#else
extern "C" void initlibheapq();
#endif

static PyObject *
heappush(PyObject *self, PyObject *args) {
    int len;
    PyObject *list = NULL;
    PyObject *node = NULL;

    if (!PyArg_ParseTuple(args,"O!O",&PyList_Type,&list,&node))
        return NULL;

    len = PyList_Size(list);
    if (PyList_Append(list,node))
        return NULL;

    if (_siftdown(list,0,len))
        return NULL;

    Py_INCREF(Py_None);
    return Py_None;
}

static PyObject *
heappop(PyObject *self, PyObject *args) {
    PyObject *list = NULL;
    PyObject *node = NULL;
    PyObject *returnNode = NULL;
    int len;

    if (!PyArg_ParseTuple(args,"O!",&PyList_Type,&list))
        return NULL;

    len = PyList_Size(list);
    if (len == 0) {
        /* Special-case most common failure cause */
        PyErr_SetString(PyExc_IndexError, "pop from empty list");
        return NULL;
    }

    node = PySequence_GetItem(list,-1);
    PySequence_DelItem(list,-1);

    len -= 1;
    if (len > 0) {
        returnNode = PySequence_GetItem(list,0);
        PyList_SetItem(list,0,node);
        if (_siftup(list,0))
            return NULL;
    } else {
        returnNode = node;
    }

    return returnNode;
}

static PyObject *
heapreplace(PyObject *self, PyObject *args) {
    PyObject *list = NULL;
    PyObject *node = NULL;
    PyObject *returnNode = NULL;
    int len;

    if (!PyArg_ParseTuple(args,"O!O",&PyList_Type,&list,&node))
        return NULL;

    len = PyList_Size(list);
    if (len == 0) {
        /* Special-case most common failure cause */
        PyErr_SetString(PyExc_IndexError, "replace on an empty list");
        return NULL;
    }

    returnNode = PySequence_GetItem(list,0);
    PySequence_SetItem(list,0,node);
    if (_siftup(list,0))
        return NULL;

    return returnNode;
}

static PyObject *
heapify(PyObject *self, PyObject *args) {
    int n, i;
    PyObject *list;

    if (!PyArg_ParseTuple(args,"O!",&PyList_Type,&list))
        return NULL;
    n = (PyList_Size(list)/2)-1;

    for (i=n;i>=0;i--) {
        if (_siftup(list,i))
            return NULL;
    }

    Py_INCREF(Py_None);
    return Py_None;
}

static int
_siftdown(PyObject *list, int startpos, int pos) {
    PyObject *newitem, *parent;
    int parentpos;

    newitem = PySequence_GetItem(list,pos);

    PyObject *newitem_wakeTime_obj = PyObject_GetAttrString(newitem, "wakeTime");
    double newitem_wakeTime = 0.0;
    if (newitem_wakeTime_obj != NULL) {
      newitem_wakeTime = PyFloat_AS_DOUBLE(newitem_wakeTime_obj);
      Py_DECREF(newitem_wakeTime_obj);
    }

    while (pos > startpos) {
        parentpos = (pos - 1) >> 1;
        parent = PyList_GetItem(list,parentpos);

        /*
        cmp = PyObject_RichCompareBool(parent,newitem,Py_LE);
        if (cmp > 0)
            break;
        else if (cmp < 0)
            return -1;
        */

        PyObject *parent_wakeTime_obj = PyObject_GetAttrString(parent, "wakeTime");
        double parent_wakeTime = 0.0;
        if (parent_wakeTime_obj != NULL) {
          parent_wakeTime = PyFloat_AS_DOUBLE(parent_wakeTime_obj);
          Py_DECREF(parent_wakeTime_obj);
        }

        if (parent_wakeTime <= newitem_wakeTime) {
          break;
        }

        Py_INCREF(parent);
        PyList_SetItem(list,pos,parent);
        pos = parentpos;
    }
    PyList_SetItem(list,pos,newitem);
    return 0;
}

static int
_siftup(PyObject *list, int pos) {
    PyObject *newitem, *right, *child;
    int endpos, rightpos, childpos;
    int startpos = pos;

    endpos = PyList_Size(list);
    newitem = PySequence_GetItem(list,pos);

    childpos = (2*pos)+1;
    while (childpos < endpos) {
        rightpos = childpos + 1;
        child = PySequence_Fast_GET_ITEM(list,childpos);

        PyObject *child_wakeTime_obj = PyObject_GetAttrString(child, "wakeTime");
        double child_wakeTime = 0.0;
        if (child_wakeTime_obj != NULL) {
          child_wakeTime = PyFloat_AS_DOUBLE(child_wakeTime_obj);
          Py_DECREF(child_wakeTime_obj);
        }

        if (rightpos < endpos) {
            right = PySequence_Fast_GET_ITEM(list,rightpos);

            PyObject *right_wakeTime_obj = PyObject_GetAttrString(right, "wakeTime");
            double right_wakeTime = 0.0;
            if (right_wakeTime_obj != NULL) {
              right_wakeTime = PyFloat_AS_DOUBLE(right_wakeTime_obj);
              Py_DECREF(right_wakeTime_obj);
            }

            /*
            cmp = PyObject_RichCompareBool(right,child,Py_LE);
            if (cmp > 0)
              childpos = rightpos;
            else if (cmp < 0)
              return -1;
            */

            if (right_wakeTime <= child_wakeTime) {
              childpos = rightpos;
            }
        }
        child = PySequence_GetItem(list,childpos);
        PyList_SetItem(list,pos,child);
        pos = childpos;
        childpos = (2*pos)+1;
    }
    PyList_SetItem(list,pos,newitem);

    return _siftdown(list,startpos,pos);
}

static PyMethodDef heapqcMethods[] = {
    {"heappush",heappush,METH_VARARGS},
    {"heappop",heappop,METH_VARARGS},
    {"heapreplace",heapreplace,METH_VARARGS},
    {"heapify",heapify,METH_VARARGS},
    {NULL, NULL} /* Sentinel */
};

void initlibheapq(void) {
    (void) Py_InitModule("libheapq", heapqcMethods);
};

<commit_msg>Added wrappers so that this works as libheapq or libp3heapq<commit_after>
/* Note: This module can probably go away when we upgrade to Python 2.4.
   Python 2.3 has a heapq implementation, but it is in Python. This is
   reported to be about 20x faster. In 2.4 they reimplemented heapq in C so
   it should be comparable to this. At this time though, Python 2.4 is
   still in alpha.

   Note: This code has been bastardized to only work on Tasks temporarily.

*/

#include <Python.h>

/* Prototypes */
static PyObject * heappush(PyObject *self, PyObject *args);
static PyObject * heappop(PyObject *self, PyObject *args);
static PyObject * heapreplace(PyObject *self, PyObject *args);
static PyObject * heapify(PyObject *self, PyObject *args);
static int _siftdown(PyObject *list, int startpos, int pos);
static int _siftup(PyObject *list, int pos);

#ifdef _WIN32
extern "C" __declspec(dllexport) void initlibheapq(void);
extern "C" __declspec(dllexport) void initlibp3heapq(void);
#else
extern "C" void initlibheapq();
extern "C" void initlibp3heapq();
#endif

static PyObject *
heappush(PyObject *self, PyObject *args) {
    int len;
    PyObject *list = NULL;
    PyObject *node = NULL;

    if (!PyArg_ParseTuple(args,"O!O",&PyList_Type,&list,&node))
        return NULL;

    len = PyList_Size(list);
    if (PyList_Append(list,node))
        return NULL;

    if (_siftdown(list,0,len))
        return NULL;

    Py_INCREF(Py_None);
    return Py_None;
}

static PyObject *
heappop(PyObject *self, PyObject *args) {
    PyObject *list = NULL;
    PyObject *node = NULL;
    PyObject *returnNode = NULL;
    int len;

    if (!PyArg_ParseTuple(args,"O!",&PyList_Type,&list))
        return NULL;

    len = PyList_Size(list);
    if (len == 0) {
        /* Special-case most common failure cause */
        PyErr_SetString(PyExc_IndexError, "pop from empty list");
        return NULL;
    }

    node = PySequence_GetItem(list,-1);
    PySequence_DelItem(list,-1);

    len -= 1;
    if (len > 0) {
        returnNode = PySequence_GetItem(list,0);
        PyList_SetItem(list,0,node);
        if (_siftup(list,0))
            return NULL;
    } else {
        returnNode = node;
    }

    return returnNode;
}

static PyObject *
heapreplace(PyObject *self, PyObject *args) {
    PyObject *list = NULL;
    PyObject *node = NULL;
    PyObject *returnNode = NULL;
    int len;

    if (!PyArg_ParseTuple(args,"O!O",&PyList_Type,&list,&node))
        return NULL;

    len = PyList_Size(list);
    if (len == 0) {
        /* Special-case most common failure cause */
        PyErr_SetString(PyExc_IndexError, "replace on an empty list");
        return NULL;
    }

    returnNode = PySequence_GetItem(list,0);
    PySequence_SetItem(list,0,node);
    if (_siftup(list,0))
        return NULL;

    return returnNode;
}

static PyObject *
heapify(PyObject *self, PyObject *args) {
    int n, i;
    PyObject *list;

    if (!PyArg_ParseTuple(args,"O!",&PyList_Type,&list))
        return NULL;
    n = (PyList_Size(list)/2)-1;

    for (i=n;i>=0;i--) {
        if (_siftup(list,i))
            return NULL;
    }

    Py_INCREF(Py_None);
    return Py_None;
}

static int
_siftdown(PyObject *list, int startpos, int pos) {
    PyObject *newitem, *parent;
    int parentpos;

    newitem = PySequence_GetItem(list,pos);

    PyObject *newitem_wakeTime_obj = PyObject_GetAttrString(newitem, "wakeTime");
    double newitem_wakeTime = 0.0;
    if (newitem_wakeTime_obj != NULL) {
      newitem_wakeTime = PyFloat_AS_DOUBLE(newitem_wakeTime_obj);
      Py_DECREF(newitem_wakeTime_obj);
    }

    while (pos > startpos) {
        parentpos = (pos - 1) >> 1;
        parent = PyList_GetItem(list,parentpos);

        /*
        cmp = PyObject_RichCompareBool(parent,newitem,Py_LE);
        if (cmp > 0)
            break;
        else if (cmp < 0)
            return -1;
        */

        PyObject *parent_wakeTime_obj = PyObject_GetAttrString(parent, "wakeTime");
        double parent_wakeTime = 0.0;
        if (parent_wakeTime_obj != NULL) {
          parent_wakeTime = PyFloat_AS_DOUBLE(parent_wakeTime_obj);
          Py_DECREF(parent_wakeTime_obj);
        }

        if (parent_wakeTime <= newitem_wakeTime) {
          break;
        }

        Py_INCREF(parent);
        PyList_SetItem(list,pos,parent);
        pos = parentpos;
    }
    PyList_SetItem(list,pos,newitem);
    return 0;
}

static int
_siftup(PyObject *list, int pos) {
    PyObject *newitem, *right, *child;
    int endpos, rightpos, childpos;
    int startpos = pos;

    endpos = PyList_Size(list);
    newitem = PySequence_GetItem(list,pos);

    childpos = (2*pos)+1;
    while (childpos < endpos) {
        rightpos = childpos + 1;
        child = PySequence_Fast_GET_ITEM(list,childpos);

        PyObject *child_wakeTime_obj = PyObject_GetAttrString(child, "wakeTime");
        double child_wakeTime = 0.0;
        if (child_wakeTime_obj != NULL) {
          child_wakeTime = PyFloat_AS_DOUBLE(child_wakeTime_obj);
          Py_DECREF(child_wakeTime_obj);
        }

        if (rightpos < endpos) {
            right = PySequence_Fast_GET_ITEM(list,rightpos);

            PyObject *right_wakeTime_obj = PyObject_GetAttrString(right, "wakeTime");
            double right_wakeTime = 0.0;
            if (right_wakeTime_obj != NULL) {
              right_wakeTime = PyFloat_AS_DOUBLE(right_wakeTime_obj);
              Py_DECREF(right_wakeTime_obj);
            }

            /*
            cmp = PyObject_RichCompareBool(right,child,Py_LE);
            if (cmp > 0)
              childpos = rightpos;
            else if (cmp < 0)
              return -1;
            */

            if (right_wakeTime <= child_wakeTime) {
              childpos = rightpos;
            }
        }
        child = PySequence_GetItem(list,childpos);
        PyList_SetItem(list,pos,child);
        pos = childpos;
        childpos = (2*pos)+1;
    }
    PyList_SetItem(list,pos,newitem);

    return _siftdown(list,startpos,pos);
}

static PyMethodDef heapqcMethods[] = {
    {"heappush",heappush,METH_VARARGS},
    {"heappop",heappop,METH_VARARGS},
    {"heapreplace",heapreplace,METH_VARARGS},
    {"heapify",heapify,METH_VARARGS},
    {NULL, NULL} /* Sentinel */
};

void initlibheapq(void) {
    (void) Py_InitModule("libheapq", heapqcMethods);
};

void initlibp3heapq(void) {
    (void) Py_InitModule("libp3heapq", heapqcMethods);
};

<|endoftext|>


<commit_before>// HotkeyPrompt.cpp : implementation file
//

#include "stdafx.h"
#include "SettingsUI.h"
#include "HotkeyPrompt.h"
#include "afxdialogex.h"

// HotkeyPrompt dialog

IMPLEMENT_DYNAMIC(HotkeyPrompt, CDialog)

HotkeyPrompt::HotkeyPrompt(CWnd* pParent /*=NULL*/)
	: CDialog(HotkeyPrompt::IDD, pParent)
{

}

HotkeyPrompt::~HotkeyPrompt()
{
}

BOOL HotkeyPrompt::OnInitDialog() {
    CDialog::OnInitDialog();
    KeyGrabber::Instance()->Grab(_keys.m_hWnd);
    return TRUE;
}

BEGIN_MESSAGE_MAP(HotkeyPrompt, CDialog)
END_MESSAGE_MAP()

// HotkeyPrompt message handlers
<commit_msg>Reformat code<commit_after>#include "stdafx.h"
#include "SettingsUI.h"
#include "HotkeyPrompt.h"
#include "afxdialogex.h"

#include "KeyGrabber.h"

IMPLEMENT_DYNAMIC(HotkeyPrompt, CDialog)

HotkeyPrompt::HotkeyPrompt(CWnd* pParent /*=NULL*/) :
CDialog(HotkeyPrompt::IDD, pParent) {

}

HotkeyPrompt::~HotkeyPrompt() {

}

BOOL HotkeyPrompt::OnInitDialog() {
    CDialog::OnInitDialog();
    KeyGrabber::Instance()->Grab(_keys.m_hWnd);
    return TRUE;
}

void HotkeyPrompt::DoDataExchange(CDataExchange* pDX) {
    CDialog::DoDataExchange(pDX);
    DDX_Control(pDX, LBL_KEYS, _keys);
    DDX_Control(pDX, BTN_SAVE, _save);
}

BEGIN_MESSAGE_MAP(HotkeyPrompt, CDialog)
END_MESSAGE_MAP()

<|endoftext|>


<commit_before>#include "itkQEMesh.h"
#include "itkQEUtils.txx"

int AddFaceTest2(int , char *[])
{
  typedef itkQE::Mesh< double, 3 >        MeshType;
  typedef MeshType::Pointer               MeshPointer;
  typedef MeshType::QEType                QEType;
  typedef MeshType::PointIdentifier       PointIdentifier;
  typedef MeshType::CellType              CellType;
  typedef itkQE::PolygonCell< CellType >  QEPolygonCellType;

  int numPts = 7;
  int numCells = 4;

  std::cout << "numPts= " << numPts << std::endl;
  std::cout << "numCells= " << numCells << std::endl;

  int oddConnectivityCells[12] =
  { 0, 1, 2,
    3, 4, 5,
    6, 4, 0,
    0, 4, 6, };

  // Configuration of odd_connectivity mesh:
  // numVertices=7 , numEdges=9, numFaces=3, numBoundary=1, Chi=1
  //
  //    5 ---------- 4 ---------- 0 ---------- 1
  //    |  [2]   __/ |   [3]  __/   \__  [1]   |
  //    |     __/    |     __/         \__     |
  //    |  __/       |  __/               \__  |
  //    | /          | /                     \ |
  //    3            6                         2
  //
  // First we add the three triangles [0 1 2], [3 4 5], [6 4 0].
  // Then we try to add a fourth triangle, which is the third triangle
  // inverted i.e. [0 4 6]. This triangle can not be added.

  MeshPointer  mesh = MeshType::New();

  MeshType::PointType pts[7];

  pts[0][0] = 2.0;  pts[0][1] = 1.0;  pts[0][2] = 0.0;
  pts[1][0] = 3.0;  pts[1][1] = 1.0;  pts[1][2] = 0.0;
  pts[2][0] = 3.0;  pts[2][1] = 0.0;  pts[2][2] = 0.0;
  pts[3][0] = 0.0;  pts[3][1] = 0.0;  pts[3][2] = 0.0;
  pts[4][0] = 1.0;  pts[4][1] = 1.0;  pts[4][2] = 0.0;
  pts[5][0] = 0.0;  pts[5][1] = 1.0;  pts[5][2] = 0.0;
  pts[6][0] = 1.0;  pts[6][1] = 0.0;  pts[6][2] = 0.0;

  for(int i=0; i<numPts; i++)
    {
    mesh->SetPoint( i, pts[i] );
    }

  int computedNumPts = mesh->GetNumberOfPoints();
  std::cout << "computedNumPts= " << computedNumPts << std::endl;

  CellType::CellAutoPointer cellpointer;
  QEPolygonCellType *poly;

  for(int i=0; i<numCells; i++)
    {
    poly = new QEPolygonCellType(3);
    cellpointer.TakeOwnership( poly );
    cellpointer->SetPointId( 0, oddConnectivityCells[3*i] );
    cellpointer->SetPointId( 1, oddConnectivityCells[3*i+1] );
    cellpointer->SetPointId( 2, oddConnectivityCells[3*i+2] );
    mesh->SetCell( i, cellpointer );
    }

  int computedNumCells = mesh->GetNumberOfCells();
  std::cout << "computedNumCells= " << computedNumCells << std::endl;

  std::cout << "Test whether the fourth face was rejected" << std::endl;

  if( itkQE::AssertTopologicalInvariants< MeshType >
      ( mesh, 7, 9, 3, 1, 1 ) )
    {
    std::cout << "Passed" << std::endl;
    }
  else
    {
    std::cout << "Failed" << std::endl;
    return EXIT_FAILURE;
    }

  return EXIT_SUCCESS;
}
<commit_msg>BUG: fix test for adding a face with opposite orientation<commit_after>#include "itkQEMesh.h"
#include "itkQEUtils.txx"

int AddFaceTest2(int , char *[])
{
  typedef itkQE::Mesh< double, 3 >        MeshType;
  typedef MeshType::Pointer               MeshPointer;
  typedef MeshType::QEType                QEType;
  typedef MeshType::PointIdentifier       PointIdentifier;
  typedef MeshType::CellType              CellType;
  typedef itkQE::PolygonCell< CellType >  QEPolygonCellType;

  int numPts = 7;
  int numCells = 4;

  std::cout << "numPts= " << numPts << std::endl;
  std::cout << "numCells= " << numCells << std::endl;

  int oddConnectivityCells[12] =
  { 0, 1, 2,
    3, 4, 5,
    6, 4, 0,
    0, 4, 6, };

  // Configuration of odd_connectivity mesh:
  // numVertices=7, numEdges=9, numFaces=3, numBoundaries=1, Chi=2
  //
  //    5 ---------- 4 ---------- 0 ---------- 1
  //    |  [2]   __/ |   [3]  __/   \__  [1]   |
  //    |     __/    |     __/         \__     |
  //    |  __/       |  __/               \__  |
  //    | /          | /                     \ |
  //    3            6                         2
  //
  // First we add the three triangles [0 1 2], [3 4 5], [6 4 0].
  // Then we try to add a fourth triangle, which is the third triangle
  // inverted i.e. [0 4 6]. This triangle can not be added.

  MeshPointer  mesh = MeshType::New();

  MeshType::PointType pts[7];

  pts[0][0] = 2.0;  pts[0][1] = 1.0;  pts[0][2] = 0.0;
  pts[1][0] = 3.0;  pts[1][1] = 1.0;  pts[1][2] = 0.0;
  pts[2][0] = 3.0;  pts[2][1] = 0.0;  pts[2][2] = 0.0;
  pts[3][0] = 0.0;  pts[3][1] = 0.0;  pts[3][2] = 0.0;
  pts[4][0] = 1.0;  pts[4][1] = 1.0;  pts[4][2] = 0.0;
  pts[5][0] = 0.0;  pts[5][1] = 1.0;  pts[5][2] = 0.0;
  pts[6][0] = 1.0;  pts[6][1] = 0.0;  pts[6][2] = 0.0;

  for(int i=0; i<numPts; i++)
    {
    mesh->SetPoint( i, pts[i] );
    }

  int computedNumPts = mesh->GetNumberOfPoints();
  std::cout << "computedNumPts= " << computedNumPts << std::endl;

  CellType::CellAutoPointer cellpointer;
  QEPolygonCellType *poly;

  for(int i=0; i<numCells; i++)
    {
    poly = new QEPolygonCellType(3);
    cellpointer.TakeOwnership( poly );
    cellpointer->SetPointId( 0, oddConnectivityCells[3*i] );
    cellpointer->SetPointId( 1, oddConnectivityCells[3*i+1] );
    cellpointer->SetPointId( 2, oddConnectivityCells[3*i+2] );
    mesh->SetCell( i, cellpointer );
    }

  int computedNumFaces = mesh->ComputeNumberOfFaces();
  std::cout << "computedNumFaces= " << computedNumFaces << std::endl;

  std::cout << "Test whether the fourth face was rejected" << std::endl;

  if( itkQE::AssertTopologicalInvariants< MeshType >
      ( mesh, 7, 9, 3, 3, -1 ) )
    {
    std::cout << "Passed" << std::endl;
    }
  else
    {
    std::cout << "Failed" << std::endl;
    return EXIT_FAILURE;
    }

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>#include "imgui-SFML.h"
#include <imgui.h>

#include <SFML/OpenGL.hpp>
#include <SFML/Graphics/Color.hpp>
#include <SFML/Graphics/RenderTarget.hpp>
#include <SFML/Graphics/RenderWindow.hpp>
#include <SFML/Graphics/Sprite.hpp>
#include <SFML/Graphics/Texture.hpp>
#include <SFML/System/Clock.hpp>
#include <SFML/Window/Event.hpp>
#include <SFML/Window/Window.hpp>

#include <cstddef> // offsetof

static sf::Window* s_window = nullptr;
static sf::RenderTarget* s_renderTarget = nullptr;
static sf::Texture* s_fontTexture = nullptr;

static sf::Clock s_deltaClock;
static bool s_mousePressed[5] = { false, false, false, false, false };

namespace
{

ImVec2 getDisplaySize()
{
    assert(s_renderTarget);
    sf::Vector2f size = static_cast<sf::Vector2f>(s_renderTarget->getSize());
    return ImVec2(size);
}

void RenderDrawLists(ImDrawData* draw_data); // rendering callback function prototype

// Implementation of ImageButton overload
bool imageButtonImpl(const sf::Texture& texture, const sf::FloatRect& textureRect, const sf::Vector2f& size, const int framePadding,
                     const sf::Color& bgColor, const sf::Color& tintColor);

} // anonymous namespace for helper / "private" functions

namespace ImGui
{
namespace SFML
{

void Init(sf::Window& window, sf::RenderTarget& target)
{
    s_window = &window;

    ImGuiIO& io = ImGui::GetIO();

    // init keyboard mapping
    io.KeyMap[ImGuiKey_Tab] = sf::Keyboard::Tab;
    io.KeyMap[ImGuiKey_LeftArrow] = sf::Keyboard::Left;
    io.KeyMap[ImGuiKey_RightArrow] = sf::Keyboard::Right;
    io.KeyMap[ImGuiKey_UpArrow] = sf::Keyboard::Up;
    io.KeyMap[ImGuiKey_DownArrow] = sf::Keyboard::Down;
    io.KeyMap[ImGuiKey_Home] = sf::Keyboard::Home;
    io.KeyMap[ImGuiKey_End] = sf::Keyboard::End;
    io.KeyMap[ImGuiKey_Delete] = sf::Keyboard::Delete;
    io.KeyMap[ImGuiKey_Backspace] = sf::Keyboard::BackSpace;
    io.KeyMap[ImGuiKey_Enter] = sf::Keyboard::Return;
    io.KeyMap[ImGuiKey_Escape] = sf::Keyboard::Escape;
    io.KeyMap[ImGuiKey_A] = sf::Keyboard::A;
    io.KeyMap[ImGuiKey_C] = sf::Keyboard::C;
    io.KeyMap[ImGuiKey_V] = sf::Keyboard::V;
    io.KeyMap[ImGuiKey_X] = sf::Keyboard::X;
    io.KeyMap[ImGuiKey_Y] = sf::Keyboard::Y;
    io.KeyMap[ImGuiKey_Z] = sf::Keyboard::Z;

    s_deltaClock.restart();

    // init rendering
    s_renderTarget = ⌖
    io.DisplaySize = getDisplaySize();
    io.RenderDrawListsFn = RenderDrawLists; // set render callback

    // create font texture
    unsigned char* pixels;
    int width, height;
    io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);

    if (s_fontTexture) { // was already created, delete it
        delete s_fontTexture;
    }

    s_fontTexture = new sf::Texture;
    s_fontTexture->create(width, height);
    s_fontTexture->update(pixels);
    io.Fonts->TexID = (void*)s_fontTexture;

    io.Fonts->ClearInputData();
    io.Fonts->ClearTexData();
}

void Init(sf::RenderWindow& window)
{
    Init(window, window);
}

void ProcessEvent(const sf::Event& event)
{
    ImGuiIO& io = ImGui::GetIO();
    switch (event.type)
    {
        case sf::Event::MouseButtonPressed: // fall-through
        case sf::Event::MouseButtonReleased:
            s_mousePressed[event.mouseButton.button] = (event.type == sf::Event::MouseButtonPressed);
            break;
        case sf::Event::MouseWheelMoved:
            io.MouseWheel += (float)event.mouseWheel.delta;
            break;
        case sf::Event::KeyPressed: // fall-through
        case sf::Event::KeyReleased:
            io.KeysDown[event.key.code] = (event.type == sf::Event::KeyPressed);
            io.KeyCtrl = event.key.control;
            io.KeyShift = event.key.shift;
            io.KeyAlt = event.key.alt;
            break;
        case sf::Event::TextEntered:
            if (event.text.unicode > 0 && event.text.unicode < 0x10000) {
                io.AddInputCharacter(event.text.unicode);
            }
            break;
        default:
            break;
    }
}

void Update()
{
    ImGuiIO& io = ImGui::GetIO();
    io.DisplaySize = getDisplaySize();
    io.DeltaTime = s_deltaClock.restart().asSeconds(); // restart the clock and get delta
    s_window->setMouseCursorVisible(!io.MouseDrawCursor); // don't draw mouse cursor if ImGui draws it

    // update mouse
    assert(s_window);
    sf::Vector2f mousePos = static_cast<sf::Vector2f>(sf::Mouse::getPosition(*s_window));
    io.MousePos = ImVec2(mousePos.x, mousePos.y);
    io.MouseDown[0] = s_mousePressed[0] || sf::Mouse::isButtonPressed(sf::Mouse::Left);
    io.MouseDown[1] = s_mousePressed[1] || sf::Mouse::isButtonPressed(sf::Mouse::Right);
    io.MouseDown[2] = s_mousePressed[2] || sf::Mouse::isButtonPressed(sf::Mouse::Middle);
    s_mousePressed[0] = s_mousePressed[1] = s_mousePressed[2] = false;

    ImGui::NewFrame();
}

void Shutdown()
{
    ImGuiIO& io = ImGui::GetIO();
    io.Fonts->TexID = nullptr;
    delete s_fontTexture;

    s_renderTarget = nullptr;
    s_window = nullptr;
    ImGui::Shutdown();
}

void SetWindow(sf::Window& window)
{
    s_window = &window;
}

void SetRenderTarget(sf::RenderTarget& target)
{
    s_renderTarget = ⌖
}

} // end of namespace SFML

void Image(const sf::Texture& texture)
{
    Image(texture, static_cast<sf::Vector2f>(texture.getSize()));
}

void Image(const sf::Texture& texture, const sf::Vector2f& size)
{
    ImGui::Image((void*)&texture, size);
}

void Image(const sf::Sprite& sprite)
{
    sf::FloatRect bounds = sprite.getGlobalBounds();
    Image(sprite, sf::Vector2f(bounds.width, bounds.height));
}

void Image(const sf::Sprite& sprite, const sf::Vector2f& size)
{
    const sf::Texture* texturePtr = sprite.getTexture();
    // sprite without texture cannot be drawn
    if (!texturePtr)
        return;

    sf::Vector2f textureSize = static_cast<sf::Vector2f>(texturePtr->getSize());
    sf::IntRect textureRect = sprite.getTextureRect();
    ImVec2 uv0(textureRect.left / textureSize.x, textureRect.top / textureSize.y);
    ImVec2 uv1((textureRect.left + textureRect.width) / textureSize.x,
               (textureRect.top + textureRect.height) / textureSize.y);

    ImGui::Image((void*)texturePtr, size, uv0, uv1);
}

bool ImageButton(const sf::Texture& texture, const int framePadding, const sf::Color& bgColor, const sf::Color& tintColor)
{
    return ImageButton(texture, static_cast<sf::Vector2f>(texture.getSize()), framePadding, bgColor, tintColor);
}

bool ImageButton(const sf::Texture& texture, const sf::Vector2f& size, const int framePadding, const sf::Color& bgColor, const sf::Color& tintColor)
{
    sf::Vector2f textureSize = static_cast<sf::Vector2f>(texture.getSize());
    return ::imageButtonImpl(texture, sf::FloatRect(0.f, 0.f, textureSize.x, textureSize.y), size, framePadding, bgColor, tintColor);
}

bool ImageButton(const sf::Sprite& sprite, const int framePadding, const sf::Color& bgColor, const sf::Color& tintColor)
{
    sf::FloatRect spriteSize = sprite.getGlobalBounds();
    return ImageButton(sprite, sf::Vector2f(spriteSize.width, spriteSize.height), framePadding, bgColor, tintColor);
}

bool ImageButton(const sf::Sprite& sprite, const sf::Vector2f& size, const int framePadding, const sf::Color& bgColor, const sf::Color& tintColor)
{
    const sf::Texture* texturePtr = sprite.getTexture();
    if (!texturePtr)
        return false;
    return ::imageButtonImpl(*texturePtr, static_cast<sf::FloatRect>(sprite.getTextureRect()), size, framePadding, bgColor, tintColor);
}

} // end of namespace ImGui

// Rendering callback

namespace
{

void RenderDrawLists(ImDrawData* draw_data)
{
    assert(s_renderTarget);
    if (draw_data->CmdListsCount == 0) {
        return;
    }

    // scale stuff (needed for proper handling of window resize)
    ImGuiIO& io = ImGui::GetIO();
    int fb_width = (int)(io.DisplaySize.x * io.DisplayFramebufferScale.x);
    int fb_height = (int)(io.DisplaySize.y * io.DisplayFramebufferScale.y);
    if (fb_width == 0 || fb_height == 0) { return; }
    draw_data->ScaleClipRects(io.DisplayFramebufferScale);

    s_renderTarget->pushGLStates();

    // save state
    GLint last_viewport[4]; glGetIntegerv(GL_VIEWPORT, last_viewport);
    GLint last_texture;
    glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);

    // do GL stuff
    glPushAttrib(GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT | GL_TRANSFORM_BIT);
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glDisable(GL_CULL_FACE);
    glDisable(GL_DEPTH_TEST);
    glEnable(GL_SCISSOR_TEST);
    glEnableClientState(GL_VERTEX_ARRAY);
    glEnableClientState(GL_TEXTURE_COORD_ARRAY);
    glEnableClientState(GL_COLOR_ARRAY);
    glEnable(GL_TEXTURE_2D);

    glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height);
    glMatrixMode(GL_PROJECTION);
    glPushMatrix();
    glLoadIdentity();
    glOrtho(0.0f, io.DisplaySize.x, io.DisplaySize.y, 0.0f, -1.0f, +1.0f);
    glMatrixMode(GL_MODELVIEW);
    glPushMatrix();
    glLoadIdentity();

    for (int n = 0; n < draw_data->CmdListsCount; ++n) {
        const ImDrawList* cmd_list = draw_data->CmdLists[n];
        const unsigned char* vtx_buffer = (const unsigned char*)&cmd_list->VtxBuffer.front();
        const ImDrawIdx* idx_buffer = &cmd_list->IdxBuffer.front();

        glVertexPointer(2, GL_FLOAT, sizeof(ImDrawVert), (void*)(vtx_buffer + offsetof(ImDrawVert, pos)));
        glTexCoordPointer(2, GL_FLOAT, sizeof(ImDrawVert), (void*)(vtx_buffer + offsetof(ImDrawVert, uv)));
        glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(ImDrawVert), (void*)(vtx_buffer + offsetof(ImDrawVert, col)));

        for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.size(); ++cmd_i) {
            const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
            if (pcmd->UserCallback) {
                pcmd->UserCallback(cmd_list, pcmd);
            } else {
                sf::Texture* texture = (sf::Texture*)pcmd->TextureId;
                sf::Vector2u win_size = s_renderTarget->getSize();
                sf::Texture::bind(texture);
                glScissor((int)pcmd->ClipRect.x, (int)(win_size.y - pcmd->ClipRect.w),
                    (int)(pcmd->ClipRect.z - pcmd->ClipRect.x), (int)(pcmd->ClipRect.w - pcmd->ClipRect.y));
                glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, GL_UNSIGNED_SHORT, idx_buffer);
            }
            idx_buffer += pcmd->ElemCount;
        }
    }

    // Restore modified state
    glDisableClientState(GL_COLOR_ARRAY);
    glDisableClientState(GL_TEXTURE_COORD_ARRAY);
    glDisableClientState(GL_VERTEX_ARRAY);
    glBindTexture(GL_TEXTURE_2D, last_texture);
    glMatrixMode(GL_MODELVIEW);
    glPopMatrix();
    glMatrixMode(GL_PROJECTION);
    glPopMatrix();
    glPopAttrib();
    glViewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2], (GLsizei)last_viewport[3]);

    s_renderTarget->popGLStates();
    s_renderTarget->resetGLStates();
}

bool imageButtonImpl(const sf::Texture& texture, const sf::FloatRect& textureRect, const sf::Vector2f& size, const int framePadding,
                     const sf::Color& bgColor, const sf::Color& tintColor)
{
    sf::Vector2f textureSize = static_cast<sf::Vector2f>(texture.getSize());

    ImVec2 uv0(textureRect.left / textureSize.x, textureRect.top / textureSize.y);
    ImVec2 uv1((textureRect.left + textureRect.width)  / textureSize.x,
               (textureRect.top  + textureRect.height) / textureSize.y);

    return ImGui::ImageButton((void*)&texture, size, uv0, uv1, framePadding, ImVec4(bgColor.r, bgColor.g, bgColor.b, bgColor.a),
                       ImVec4(tintColor.r, tintColor.g, tintColor.b, tintColor.a));
}

} // end of anonymous namespace
<commit_msg>* Don't process input when window loses focus * Some refactoring<commit_after>#include "imgui-SFML.h"
#include <imgui.h>

#include <SFML/OpenGL.hpp>
#include <SFML/Graphics/Color.hpp>
#include <SFML/Graphics/RenderTarget.hpp>
#include <SFML/Graphics/RenderWindow.hpp>
#include <SFML/Graphics/Sprite.hpp>
#include <SFML/Graphics/Texture.hpp>
#include <SFML/System/Clock.hpp>
#include <SFML/Window/Event.hpp>
#include <SFML/Window/Window.hpp>

#include <cstddef> // offsetof

static sf::Window* s_window = nullptr;
static sf::RenderTarget* s_renderTarget = nullptr;
static sf::Texture* s_fontTexture = nullptr;
static bool s_windowHasFocus = true;

static sf::Clock s_deltaClock;
static bool s_mousePressed[5] = { false, false, false, false, false };

namespace
{

ImVec2 getDisplaySize()
{
    assert(s_renderTarget);
    sf::Vector2f size = static_cast<sf::Vector2f>(s_renderTarget->getSize());
    return ImVec2(size);
}

void RenderDrawLists(ImDrawData* draw_data); // rendering callback function prototype

// Implementation of ImageButton overload
bool imageButtonImpl(const sf::Texture& texture, const sf::FloatRect& textureRect, const sf::Vector2f& size, const int framePadding,
                     const sf::Color& bgColor, const sf::Color& tintColor);

} // anonymous namespace for helper / "private" functions

namespace ImGui
{
namespace SFML
{

void Init(sf::Window& window, sf::RenderTarget& target)
{
    s_window = &window;

    ImGuiIO& io = ImGui::GetIO();

    // init keyboard mapping
    io.KeyMap[ImGuiKey_Tab] = sf::Keyboard::Tab;
    io.KeyMap[ImGuiKey_LeftArrow] = sf::Keyboard::Left;
    io.KeyMap[ImGuiKey_RightArrow] = sf::Keyboard::Right;
    io.KeyMap[ImGuiKey_UpArrow] = sf::Keyboard::Up;
    io.KeyMap[ImGuiKey_DownArrow] = sf::Keyboard::Down;
    io.KeyMap[ImGuiKey_Home] = sf::Keyboard::Home;
    io.KeyMap[ImGuiKey_End] = sf::Keyboard::End;
    io.KeyMap[ImGuiKey_Delete] = sf::Keyboard::Delete;
    io.KeyMap[ImGuiKey_Backspace] = sf::Keyboard::BackSpace;
    io.KeyMap[ImGuiKey_Enter] = sf::Keyboard::Return;
    io.KeyMap[ImGuiKey_Escape] = sf::Keyboard::Escape;
    io.KeyMap[ImGuiKey_A] = sf::Keyboard::A;
    io.KeyMap[ImGuiKey_C] = sf::Keyboard::C;
    io.KeyMap[ImGuiKey_V] = sf::Keyboard::V;
    io.KeyMap[ImGuiKey_X] = sf::Keyboard::X;
    io.KeyMap[ImGuiKey_Y] = sf::Keyboard::Y;
    io.KeyMap[ImGuiKey_Z] = sf::Keyboard::Z;

    s_deltaClock.restart();

    // init rendering
    s_renderTarget = ⌖
    io.DisplaySize = getDisplaySize();
    io.RenderDrawListsFn = RenderDrawLists; // set render callback

    // create font texture
    unsigned char* pixels;
    int width, height;
    io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);

    if (s_fontTexture) { // was already created, delete it
        delete s_fontTexture;
    }

    s_fontTexture = new sf::Texture;
    s_fontTexture->create(width, height);
    s_fontTexture->update(pixels);
    io.Fonts->TexID = (void*)s_fontTexture;

    io.Fonts->ClearInputData();
    io.Fonts->ClearTexData();
}

void Init(sf::RenderWindow& window)
{
    Init(window, window);
}

void ProcessEvent(const sf::Event& event)
{
    ImGuiIO& io = ImGui::GetIO();
    if (s_windowHasFocus) {
        switch (event.type)
        {
            case sf::Event::MouseButtonPressed: // fall-through
            case sf::Event::MouseButtonReleased:
                s_mousePressed[event.mouseButton.button] = (event.type == sf::Event::MouseButtonPressed);
                break;
            case sf::Event::MouseWheelMoved:
                io.MouseWheel += static_cast<float>(event.mouseWheel.delta);
                break;
            case sf::Event::KeyPressed: // fall-through
            case sf::Event::KeyReleased:
                io.KeysDown[event.key.code] = (event.type == sf::Event::KeyPressed);
                io.KeyCtrl = event.key.control;
                io.KeyShift = event.key.shift;
                io.KeyAlt = event.key.alt;
                break;
            case sf::Event::TextEntered:
                if (event.text.unicode > 0 && event.text.unicode < 0x10000) {
                    io.AddInputCharacter(event.text.unicode);
                }
                break;
        }
    }

    switch (event.type)
    {
        case sf::Event::LostFocus:
            s_windowHasFocus = false;
            break;
        case sf::Event::GainedFocus:
            s_windowHasFocus = true;
            break;
        default:
            break;
    }
}

void Update()
{
    ImGuiIO& io = ImGui::GetIO();
    io.DisplaySize = getDisplaySize();
    io.DeltaTime = s_deltaClock.restart().asSeconds(); // restart the clock and get delta
    s_window->setMouseCursorVisible(!io.MouseDrawCursor); // don't draw mouse cursor if ImGui draws it

    // update mouse
    assert(s_window);
    if (s_windowHasFocus) {
        io.MousePos = sf::Mouse::getPosition(*s_window);
        io.MouseDown[0] = s_mousePressed[0] || sf::Mouse::isButtonPressed(sf::Mouse::Left);
        io.MouseDown[1] = s_mousePressed[1] || sf::Mouse::isButtonPressed(sf::Mouse::Right);
        io.MouseDown[2] = s_mousePressed[2] || sf::Mouse::isButtonPressed(sf::Mouse::Middle);
        s_mousePressed[0] = s_mousePressed[1] = s_mousePressed[2] = false;
    }

    ImGui::NewFrame();
}

void Shutdown()
{
    ImGuiIO& io = ImGui::GetIO();
    io.Fonts->TexID = nullptr;
    delete s_fontTexture;

    s_renderTarget = nullptr;
    s_window = nullptr;
    ImGui::Shutdown();
}

void SetWindow(sf::Window& window)
{
    s_window = &window;
}

void SetRenderTarget(sf::RenderTarget& target)
{
    s_renderTarget = ⌖
}

} // end of namespace SFML

void Image(const sf::Texture& texture)
{
    Image(texture, static_cast<sf::Vector2f>(texture.getSize()));
}

void Image(const sf::Texture& texture, const sf::Vector2f& size)
{
    ImGui::Image((void*)&texture, size);
}

void Image(const sf::Sprite& sprite)
{
    sf::FloatRect bounds = sprite.getGlobalBounds();
    Image(sprite, sf::Vector2f(bounds.width, bounds.height));
}

void Image(const sf::Sprite& sprite, const sf::Vector2f& size)
{
    const sf::Texture* texturePtr = sprite.getTexture();
    // sprite without texture cannot be drawn
    if (!texturePtr)
        return;

    sf::Vector2f textureSize = static_cast<sf::Vector2f>(texturePtr->getSize());
    sf::IntRect textureRect = sprite.getTextureRect();
    ImVec2 uv0(textureRect.left / textureSize.x, textureRect.top / textureSize.y);
    ImVec2 uv1((textureRect.left + textureRect.width) / textureSize.x,
               (textureRect.top + textureRect.height) / textureSize.y);

    ImGui::Image((void*)texturePtr, size, uv0, uv1);
}

bool ImageButton(const sf::Texture& texture, const int framePadding, const sf::Color& bgColor, const sf::Color& tintColor)
{
    return ImageButton(texture, static_cast<sf::Vector2f>(texture.getSize()), framePadding, bgColor, tintColor);
}

bool ImageButton(const sf::Texture& texture, const sf::Vector2f& size, const int framePadding, const sf::Color& bgColor, const sf::Color& tintColor)
{
    sf::Vector2f textureSize = static_cast<sf::Vector2f>(texture.getSize());
    return ::imageButtonImpl(texture, sf::FloatRect(0.f, 0.f, textureSize.x, textureSize.y), size, framePadding, bgColor, tintColor);
}

bool ImageButton(const sf::Sprite& sprite, const int framePadding, const sf::Color& bgColor, const sf::Color& tintColor)
{
    sf::FloatRect spriteSize = sprite.getGlobalBounds();
    return ImageButton(sprite, sf::Vector2f(spriteSize.width, spriteSize.height), framePadding, bgColor, tintColor);
}

bool ImageButton(const sf::Sprite& sprite, const sf::Vector2f& size, const int framePadding, const sf::Color& bgColor, const sf::Color& tintColor)
{
    const sf::Texture* texturePtr = sprite.getTexture();
    if (!texturePtr)
        return false;
    return ::imageButtonImpl(*texturePtr, static_cast<sf::FloatRect>(sprite.getTextureRect()), size, framePadding, bgColor, tintColor);
}

} // end of namespace ImGui

// Rendering callback

namespace
{

void RenderDrawLists(ImDrawData* draw_data)
{
    assert(s_renderTarget);
    if (draw_data->CmdListsCount == 0) {
        return;
    }

    // scale stuff (needed for proper handling of window resize)
    ImGuiIO& io = ImGui::GetIO();
    int fb_width = static_cast<int>(io.DisplaySize.x * io.DisplayFramebufferScale.x);
    int fb_height = static_cast<int>(io.DisplaySize.y * io.DisplayFramebufferScale.y);
    if (fb_width == 0 || fb_height == 0) { return; }
    draw_data->ScaleClipRects(io.DisplayFramebufferScale);

    s_renderTarget->pushGLStates();

    // save state
    GLint last_viewport[4]; glGetIntegerv(GL_VIEWPORT, last_viewport);
    GLint last_texture;
    glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);

    // do GL stuff
    glPushAttrib(GL_ENABLE_BIT | GL_COLOR_BUFFER_BIT | GL_TRANSFORM_BIT);
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glDisable(GL_CULL_FACE);
    glDisable(GL_DEPTH_TEST);
    glEnable(GL_SCISSOR_TEST);
    glEnableClientState(GL_VERTEX_ARRAY);
    glEnableClientState(GL_TEXTURE_COORD_ARRAY);
    glEnableClientState(GL_COLOR_ARRAY);
    glEnable(GL_TEXTURE_2D);

    glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height);
    glMatrixMode(GL_PROJECTION);
    glPushMatrix();
    glLoadIdentity();
    glOrtho(0.0f, io.DisplaySize.x, io.DisplaySize.y, 0.0f, -1.0f, +1.0f);
    glMatrixMode(GL_MODELVIEW);
    glPushMatrix();
    glLoadIdentity();

    for (int n = 0; n < draw_data->CmdListsCount; ++n) {
        const ImDrawList* cmd_list = draw_data->CmdLists[n];
        const unsigned char* vtx_buffer = (const unsigned char*)&cmd_list->VtxBuffer.front();
        const ImDrawIdx* idx_buffer = &cmd_list->IdxBuffer.front();

        glVertexPointer(2, GL_FLOAT, sizeof(ImDrawVert), (void*)(vtx_buffer + offsetof(ImDrawVert, pos)));
        glTexCoordPointer(2, GL_FLOAT, sizeof(ImDrawVert), (void*)(vtx_buffer + offsetof(ImDrawVert, uv)));
        glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(ImDrawVert), (void*)(vtx_buffer + offsetof(ImDrawVert, col)));

        for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.size(); ++cmd_i) {
            const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
            if (pcmd->UserCallback) {
                pcmd->UserCallback(cmd_list, pcmd);
            } else {
                sf::Texture* texture = (sf::Texture*)pcmd->TextureId;
                sf::Vector2u win_size = s_renderTarget->getSize();
                sf::Texture::bind(texture);
                glScissor((int)pcmd->ClipRect.x, (int)(win_size.y - pcmd->ClipRect.w),
                    (int)(pcmd->ClipRect.z - pcmd->ClipRect.x), (int)(pcmd->ClipRect.w - pcmd->ClipRect.y));
                glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, GL_UNSIGNED_SHORT, idx_buffer);
            }
            idx_buffer += pcmd->ElemCount;
        }
    }

    // Restore modified state
    glDisableClientState(GL_COLOR_ARRAY);
    glDisableClientState(GL_TEXTURE_COORD_ARRAY);
    glDisableClientState(GL_VERTEX_ARRAY);
    glBindTexture(GL_TEXTURE_2D, last_texture);
    glMatrixMode(GL_MODELVIEW);
    glPopMatrix();
    glMatrixMode(GL_PROJECTION);
    glPopMatrix();
    glPopAttrib();
    glViewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2], (GLsizei)last_viewport[3]);

    s_renderTarget->popGLStates();
    s_renderTarget->resetGLStates();
}

bool imageButtonImpl(const sf::Texture& texture, const sf::FloatRect& textureRect, const sf::Vector2f& size, const int framePadding,
                     const sf::Color& bgColor, const sf::Color& tintColor)
{
    sf::Vector2f textureSize = static_cast<sf::Vector2f>(texture.getSize());

    ImVec2 uv0(textureRect.left / textureSize.x, textureRect.top / textureSize.y);
    ImVec2 uv1((textureRect.left + textureRect.width)  / textureSize.x,
               (textureRect.top  + textureRect.height) / textureSize.y);

    return ImGui::ImageButton((void*)&texture, size, uv0, uv1, framePadding, bgColor, tintColor);
}

} // end of anonymous namespace
<|endoftext|>


<commit_before>#pragma once

#include <LinearMath/btVector3.h>
#include <glm/glm.hpp>
#include <memory>

class btBroadphaseInterface;
class btDefaultCollisionConfiguration;
class btCollisionDispatcher;
class btSequentialImpulseConstraintSolver;
class btDiscreteDynamicsWorld;
class btCollisionShape;
class btDefaultMotionState;
class btRigidBody;

namespace Physics {

    class RigidBody;

    /// Simulates interactions among given objects.
    class Simulator {
        public:
            /// Constructor
            Simulator();

            /// Destructor
            ~Simulator();

            /// Adds a rigid body to the simulation world.
            /**
             * @param body The rigid body to simulate.
             */
            void Enable(RigidBody& body);

            /// Removes a rigid body from the simulation world.
            /**
             * @param body The rigid body to remove.
             */
            void Disable(RigidBody& body);

            /// Alters a rigid body to have a sphere shape.
            /**
             * @param body The rigid body to change shape of.
             * @param radius Radius in meters of the sphere.
             */
            void UseSphere(RigidBody& body, float radius);

            /// Alters a rigid body to have a plane shape.
            /**
             * @param body The rigid body to change shape of.
             * @param normal Plane normal.
             * @param planeConstant Plane constant.
             */
            void UsePlane(RigidBody& body, glm::vec3 normal, float planeConstant);

        protected:
            /// Execute a frame
            /**
             * @param dt Elapsed time in seconds since last simulation frame.
             */
            void Simulate(float dt);

        private:
            Simulator(const Simulator & other) = delete;
            btBroadphaseInterface* broadphase = nullptr;
            btDefaultCollisionConfiguration* collisionConfiguration = nullptr;
            btCollisionDispatcher* dispatcher = nullptr;
            btSequentialImpulseConstraintSolver* solver = nullptr;
            btDiscreteDynamicsWorld* dynamicsWorld = nullptr;
    };

}
<commit_msg>Remove old header file that still lingers around.<commit_after><|endoftext|>


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

 Program:   ORFEO Toolbox
 Language:  C++
 Date:      $Date$
 Version:   $Revision$

 Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
 See OTBCopyright.txt for details.

 This software is distributed WITHOUT ANY WARRANTY; without even
 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
 PURPOSE.  See the above copyright notices for more information.

 =========================================================================*/
#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"

#include "otbOGRDataToClassStatisticsFilter.h"
#include "otbStatisticsXMLFileWriter.h"

namespace otb
{
namespace Wrapper
{

class PolygonClassStatistics : public Application
{
public:
  /** Standard class typedefs. */
  typedef PolygonClassStatistics        Self;
  typedef Application                   Superclass;
  typedef itk::SmartPointer<Self>       Pointer;
  typedef itk::SmartPointer<const Self> ConstPointer;

  /** Standard macro */
  itkNewMacro(Self);

  itkTypeMacro(PolygonClassStatistics, otb::Application);

  /** Filters typedef */
  typedef otb::OGRDataToClassStatisticsFilter<FloatVectorImageType,UInt8ImageType> FilterType;

  typedef otb::StatisticsXMLFileWriter<FloatVectorImageType::PixelType> StatWriterType;

private:
  PolygonClassStatistics()
    {

    }

  void DoInit()
  {
    SetName("PolygonClassStatistics");
    SetDescription("Computes statistics on a training polygon set.");

    // Documentation
    SetDocName("Polygon Class Statistics");
    SetDocLongDescription("The application processes a set of geometries "
      "intended for training (they should have a field giving the associated "
      "class). The geometries are analysed against a support image to compute "
      "statistics : \n"
      "  - number of samples per class\n"
      "  - number of samples per geometry\n"
      "An optional raster mask can be used to discard samples. Different types"
      " of geometry are supported : polygons, lines, points. The behaviour is "
      "different for each type of geometry :\n"
      "  - polygon: select pixels whose center is inside the polygon\n"
      "  - lines  : select pixels intersecting the line\n"
      "  - points : select closest pixel to the point\n");
    SetDocLimitations("None");
    SetDocAuthors("OTB-Team");
    SetDocSeeAlso(" ");

    AddDocTag(Tags::Learning);

    AddParameter(ParameterType_InputImage,  "in",   "InputImage");
    SetParameterDescription("in", "Support image that will be classified");

    AddParameter(ParameterType_InputImage,  "mask",   "InputMask");
    SetParameterDescription("mask", "Validity mask (only pixels corresponding to a mask value greater than 0 will be used for statistics)");
    MandatoryOff("mask");

    AddParameter(ParameterType_InputFilename, "vec", "Input vectors");
    SetParameterDescription("vec","Input geometries to analyse");

    AddParameter(ParameterType_OutputFilename, "out", "Output Statistics");
    SetParameterDescription("out","Output file to store statistics (XML format)");

    AddParameter(ParameterType_String, "field", "Field Name");
    SetParameterDescription("field","Name of the field carrying the class name in the input vectors.");
    MandatoryOff("field");
    SetParameterString("field", "class");

    AddParameter(ParameterType_Int, "layer", "Layer Index");
    SetParameterDescription("layer", "Layer index to read in the input vector file.");
    MandatoryOff("layer");
    SetDefaultParameterInt("layer",0);

    AddRAMParameter();

    // Doc example parameter settings
    SetDocExampleParameterValue("in", "support_image.tif");
    SetDocExampleParameterValue("vec", "variousVectors.sqlite");
    SetDocExampleParameterValue("field", "label")
    SetDocExampleParameterValue("out","polygonStat.xml");
  }

  void DoUpdateParameters()
  {
    // Nothing to do
  }

  void DoExecute()
  {
  otb::ogr::DataSource::Pointer vectors =
    otb::ogr::DataSource::New(this->GetParameterString("vec"));
  std::string fieldName = this->GetParameterString("field");

  FilterType::Pointer filter = FilterType::New();
  filter->SetInput(this->GetParameterImage("in"));
  if (IsParameterEnabled("mask") && HasValue("mask"))
    {
    filter->SetMask(this->GetParameterImage<UInt8ImageType>("mask"));
    }
  filter->SetOGRData(vectors);
  filter->SetFieldName(fieldName);
  filter->SetLayerIndex(this->GetParameterInt("layer"));
  filter->Update();

  FilterType::ClassCountMapType &classCount = filter->GetClassCountOutput()->Get();
  FilterType::PolygonSizeMapType &polySize = filter->GetPolygonSizeOutput()->Get();

  StatWriterType::Pointer statWriter = StatWriterType::New();
  statWriter->SetFileName(this->GetParameterString("out"));
  statWriter->AddInputMap<FilterType::ClassCountMapType>("samplesPerClass",classCount);
  statWriter->AddInputMap<FilterType::PolygonSizeMapType>("samplesPerVector",polySize);
  statWriter->Update();
  }

};

} // end of namespace Wrapper
} // end of namespace otb

OTB_APPLICATION_EXPORT(otb::Wrapper::PolygonClassStatistics)
<commit_msg>COMP: PolygonClassStatistics<commit_after>/*=========================================================================

 Program:   ORFEO Toolbox
 Language:  C++
 Date:      $Date$
 Version:   $Revision$

 Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
 See OTBCopyright.txt for details.

 This software is distributed WITHOUT ANY WARRANTY; without even
 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
 PURPOSE.  See the above copyright notices for more information.

 =========================================================================*/
#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"

#include "otbOGRDataToClassStatisticsFilter.h"
#include "otbStatisticsXMLFileWriter.h"

namespace otb
{
namespace Wrapper
{

class PolygonClassStatistics : public Application
{
public:
  /** Standard class typedefs. */
  typedef PolygonClassStatistics        Self;
  typedef Application                   Superclass;
  typedef itk::SmartPointer<Self>       Pointer;
  typedef itk::SmartPointer<const Self> ConstPointer;

  /** Standard macro */
  itkNewMacro(Self);

  itkTypeMacro(PolygonClassStatistics, otb::Application);

  /** Filters typedef */
  typedef otb::OGRDataToClassStatisticsFilter<FloatVectorImageType,UInt8ImageType> FilterType;

  typedef otb::StatisticsXMLFileWriter<FloatVectorImageType::PixelType> StatWriterType;

private:
  PolygonClassStatistics()
    {

    }

  void DoInit()
  {
    SetName("PolygonClassStatistics");
    SetDescription("Computes statistics on a training polygon set.");

    // Documentation
    SetDocName("Polygon Class Statistics");
    SetDocLongDescription("The application processes a set of geometries "
      "intended for training (they should have a field giving the associated "
      "class). The geometries are analysed against a support image to compute "
      "statistics : \n"
      "  - number of samples per class\n"
      "  - number of samples per geometry\n"
      "An optional raster mask can be used to discard samples. Different types"
      " of geometry are supported : polygons, lines, points. The behaviour is "
      "different for each type of geometry :\n"
      "  - polygon: select pixels whose center is inside the polygon\n"
      "  - lines  : select pixels intersecting the line\n"
      "  - points : select closest pixel to the point\n");
    SetDocLimitations("None");
    SetDocAuthors("OTB-Team");
    SetDocSeeAlso(" ");

    AddDocTag(Tags::Learning);

    AddParameter(ParameterType_InputImage,  "in",   "InputImage");
    SetParameterDescription("in", "Support image that will be classified");

    AddParameter(ParameterType_InputImage,  "mask",   "InputMask");
    SetParameterDescription("mask", "Validity mask (only pixels corresponding to a mask value greater than 0 will be used for statistics)");
    MandatoryOff("mask");

    AddParameter(ParameterType_InputFilename, "vec", "Input vectors");
    SetParameterDescription("vec","Input geometries to analyse");

    AddParameter(ParameterType_OutputFilename, "out", "Output Statistics");
    SetParameterDescription("out","Output file to store statistics (XML format)");

    AddParameter(ParameterType_String, "field", "Field Name");
    SetParameterDescription("field","Name of the field carrying the class name in the input vectors.");
    MandatoryOff("field");
    SetParameterString("field", "class");

    AddParameter(ParameterType_Int, "layer", "Layer Index");
    SetParameterDescription("layer", "Layer index to read in the input vector file.");
    MandatoryOff("layer");
    SetDefaultParameterInt("layer",0);

    AddRAMParameter();

    // Doc example parameter settings
    SetDocExampleParameterValue("in", "support_image.tif");
    SetDocExampleParameterValue("vec", "variousVectors.sqlite");
    SetDocExampleParameterValue("field", "label");
    SetDocExampleParameterValue("out","polygonStat.xml");
  }

  void DoUpdateParameters()
  {
    // Nothing to do
  }

  void DoExecute()
  {
  otb::ogr::DataSource::Pointer vectors =
    otb::ogr::DataSource::New(this->GetParameterString("vec"));
  std::string fieldName = this->GetParameterString("field");

  FilterType::Pointer filter = FilterType::New();
  filter->SetInput(this->GetParameterImage("in"));
  if (IsParameterEnabled("mask") && HasValue("mask"))
    {
    filter->SetMask(this->GetParameterImage<UInt8ImageType>("mask"));
    }
  filter->SetOGRData(vectors);
  filter->SetFieldName(fieldName);
  filter->SetLayerIndex(this->GetParameterInt("layer"));
  filter->Update();

  FilterType::ClassCountMapType &classCount = filter->GetClassCountOutput()->Get();
  FilterType::PolygonSizeMapType &polySize = filter->GetPolygonSizeOutput()->Get();

  StatWriterType::Pointer statWriter = StatWriterType::New();
  statWriter->SetFileName(this->GetParameterString("out"));
  statWriter->AddInputMap<FilterType::ClassCountMapType>("samplesPerClass",classCount);
  statWriter->AddInputMap<FilterType::PolygonSizeMapType>("samplesPerVector",polySize);
  statWriter->Update();
  }

};

} // end of namespace Wrapper
} // end of namespace otb

OTB_APPLICATION_EXPORT(otb::Wrapper::PolygonClassStatistics)
<|endoftext|>


<commit_before>#ifndef CLOTHO_VARIABLE_SUBSET_ITERATOR_HELPER_HPP_
#define CLOTHO_VARIABLE_SUBSET_ITERATOR_HELPER_HPP_

#include "clotho/utility/iterator_helper.hpp"
#include "clotho/powersets/variable_subset.hpp"

namespace clotho {
namespace utility {

template < class E, class B, class BK, class EK >
class element_iterator< clotho::powersets::variable_subset< E, B, BK, EK > > {
public:
    typedef clotho::powersets::variable_subset< E, B, BK, EK > container_type;
    typedef element_iterator< container_type > self_type;
    typedef E       value_type;

    typedef typename container_type::bitset_type::size_type size_type;

    typedef typename container_type::powerset_type::variable_iterator  iterator;

    element_iterator( container_type & con, size_type idx = container_type::bitset_type::npos ) :
        m_container( &con )
        , m_idx(idx)
        , m_var(con.getParent()->variable_begin())
    { }

    element_iterator( const self_type & other ) :
        m_container( other.m_container )
        , m_idx( other.m_idx )
        , m_var( other.m_var )
    {}

    self_type & operator++() {
        if( m_idx != container_type::bitset_type::npos ) {
            m_idx = m_container->find_next(m_idx);
        }
        return *this;
    }

    self_type operator++( int ) {
        self_type tmp(*this);
        operator++();
        return tmp;
    }

    value_type &  operator*() {
        assert( m_idx != container_type::bitset_type::npos );

        return (*(m_var + m_idx));
    }

    bool operator==( const self_type & rhs ) {
        return (m_container == rhs.m_container && m_idx == rhs.m_idx);
    }

    bool operator!=( const self_type & rhs ) {
        return (m_container != rhs.m_container || m_idx != rhs.m_idx);
    }

    virtual ~element_iterator() {}
protected:
    container_type  * m_container;
    size_type       m_idx;
    iterator        m_var;
};

template < class E, class B, class BK, class EK >
struct iterator_helper< clotho::powersets::variable_subset< E, B, BK, EK > > {
    typedef clotho::powersets::variable_subset< E, B, BK, EK > subset_type;
    typedef element_iterator< subset_type > type;

    static type make_first( subset_type & s ) {
        return type( s, s.find_first() );
    }

    static type make_last( subset_type & s ) {
        return type(s);
    }
};

}   // namespace utility {
}   // namespace clotho {
#endif  // CLOTHO_VARIABLE_SUBSET_ITERATOR_HELPER_HPP_
<commit_msg>Added shared_ptr specialization<commit_after>#ifndef CLOTHO_VARIABLE_SUBSET_ITERATOR_HELPER_HPP_
#define CLOTHO_VARIABLE_SUBSET_ITERATOR_HELPER_HPP_

#include "clotho/utility/iterator_helper.hpp"
#include "clotho/powerset/variable_subset.hpp"

namespace clotho {
namespace utility {

template < class E, class B, class BK, class EK >
class element_iterator< clotho::powersets::variable_subset< E, B, BK, EK > > {
public:
    typedef clotho::powersets::variable_subset< E, B, BK, EK > container_type;
    typedef element_iterator< container_type > self_type;
    typedef E       value_type;

    typedef typename container_type::bitset_type::size_type size_type;

    typedef typename container_type::powerset_type::variable_iterator  iterator;

    element_iterator( container_type & con, size_type idx = container_type::bitset_type::npos ) :
        m_container( &con )
        , m_idx(idx)
        , m_var(con.getParent()->variable_begin())
    { }

    element_iterator( const self_type & other ) :
        m_container( other.m_container )
        , m_idx( other.m_idx )
        , m_var( other.m_var )
    {}

    self_type & operator++() {
        if( m_idx != container_type::bitset_type::npos ) {
            m_idx = m_container->find_next(m_idx);
        }
        return *this;
    }

    self_type operator++( int ) {
        self_type tmp(*this);
        operator++();
        return tmp;
    }

    value_type &  operator*() {
        assert( m_idx != container_type::bitset_type::npos );

        return (*(m_var + m_idx));
    }

    bool operator==( const self_type & rhs ) const {
        return (m_container == rhs.m_container && m_idx == rhs.m_idx);
    }

    bool operator!=( const self_type & rhs ) const {
        return (m_container != rhs.m_container || m_idx != rhs.m_idx);
    }

    virtual ~element_iterator() {}
protected:
    container_type  * m_container;
    size_type       m_idx;
    iterator        m_var;
};

/*
template < class E, class B, class BK, class EK >
class element_iterator< std::shared_ptr< clotho::powersets::variable_subset< E, B, BK, EK > > > {
public:
    typedef clotho::powersets::variable_subset< E, B, BK, EK > container_type;
    typedef element_iterator< std::shared_ptr< container_type > > self_type;
    typedef E       value_type;

    typedef typename container_type::bitset_type::size_type size_type;

    typedef typename container_type::powerset_type::variable_iterator  iterator;

    element_iterator( std::shared_ptr< container_type > con, size_type idx = container_type::bitset_type::npos ) :
        m_container( &con )
        , m_idx(idx)
        , m_var(con.getParent()->variable_begin())
    { }

    element_iterator( const self_type & other ) :
        m_container( other.m_container )
        , m_idx( other.m_idx )
        , m_var( other.m_var )
    {}

    self_type & operator++() {
        if( m_idx != container_type::bitset_type::npos ) {
            m_idx = m_container->find_next(m_idx);
        }
        return *this;
    }

    self_type operator++( int ) {
        self_type tmp(*this);
        operator++();
        return tmp;
    }

    value_type &  operator*() {
        assert( m_idx != container_type::bitset_type::npos );

        return (*(m_var + m_idx));
    }

    bool operator==( const self_type & rhs ) const {
        return (m_container == rhs.m_container && m_idx == rhs.m_idx);
    }

    bool operator!=( const self_type & rhs ) const {
        return (m_container != rhs.m_container || m_idx != rhs.m_idx);
    }

    virtual ~element_iterator() {}
protected:
    std::shared_ptr< container_type >  m_container;
    size_type       m_idx;
    iterator        m_var;
};*/
template < class E, class B, class BK, class EK >
struct iterator_helper< clotho::powersets::variable_subset< E, B, BK, EK > > {
    typedef clotho::powersets::variable_subset< E, B, BK, EK > subset_type;
    typedef element_iterator< subset_type > type;

    static type make_first( subset_type & s ) {
        return type( s, s.find_first() );
    }

    static type make_last( subset_type & s ) {
        return type(s);
    }
};

}   // namespace utility {
}   // namespace clotho {
#endif  // CLOTHO_VARIABLE_SUBSET_ITERATOR_HELPER_HPP_
<|endoftext|>