<commit_before>/*
    Copyright (c) 2011, Alexandre Abadie <Alexandre.Abadie@irisa.fr>
    All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions are met:
        * Redistributions of source code must retain the above copyright
        notice, this list of conditions and the following disclaimer.
        * Redistributions in binary form must reproduce the above copyright
        notice, this list of conditions and the following disclaimer in the
        documentation and/or other materials provided with the distribution.
        * Neither the name of the <organization> nor the
        names of its contributors may be used to endorse or promote products
        derived from this software without specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY Alexandre <email> ''AS IS'' AND ANY
    EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
    DISCLAIMED. IN NO EVENT SHALL Alexandre <email> BE LIABLE FOR ANY
    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "medHomepageArea.h"

#include <medViewerArea.h>
#include <medHomepageButton.h>
#include <medGui/medViewerConfiguration.h>
#include <medGui/medViewerConfigurationFactory.h>

class medHomepageAreaPrivate
{
public:
    QGraphicsScene * configurationsButtonsScene;
    QGraphicsProxyWidget * configurationsButtonsProxyWidget;
    QWidget * configurationsButtonsWidget;

    QGraphicsScene * userButtonsScene;
    QGraphicsProxyWidget * userButtonsProxyWidget;
    QWidget * userButtonsWidget;

    QGraphicsScene * infoScene;
    QGraphicsProxyWidget * infoProxyWidget;
    QWidget * infoWidget;

    QPropertyAnimation * configurationAnimation;
    QPropertyAnimation * userAnimation;
    QPropertyAnimation * infoAnimation;

    QParallelAnimationGroup * animation;

    medViewerArea * viewerArea;
};

medHomepageArea::medHomepageArea ( QWidget * parent ) : QWidget ( parent ), d ( new medHomepageAreaPrivate )
{
    d->viewerArea = NULL;
    setupUi ( this );

//     d->configurationsButtonsView = new QGraphicsView ( this );
    d->configurationsButtonsScene = new QGraphicsScene ( configurationsGraphicsView );
    configurationsGraphicsView->setScene ( d->configurationsButtonsScene );
    configurationsGraphicsView->setStyleSheet ( "background: #313131;border: 0px;padding: 0px 0px 0px 0px;" );
    configurationsGraphicsView->setFocusPolicy ( Qt::NoFocus );

    //Configurations buttons (browser, visualization, registration, diffusion, etc)
    d->configurationsButtonsWidget = new QWidget ( configurationsGraphicsView );
    d->configurationsButtonsWidget->setMinimumWidth ( 200 );

    d->userButtonsScene = new QGraphicsScene ( infoGraphicsView );
    userGraphicsView->setScene ( d->userButtonsScene );
    userGraphicsView->setStyleSheet ( "background: #313131;border: 0px;padding: 0px 0px 0px 0px;" );
    userGraphicsView->setFocusPolicy ( Qt::NoFocus );

    //Configurations buttons (Help, about, settings)
    d->userButtonsWidget = new QWidget ( userGraphicsView );
    d->userButtonsWidget->setMinimumWidth ( 200 );

    d->infoScene = new QGraphicsScene ( userGraphicsView );
    infoGraphicsView->setScene ( d->infoScene );
    infoGraphicsView->setStyleSheet ( "background: #313131;border: 0px;padding: 0px 0px 0px 0px;" );
    infoGraphicsView->setFocusPolicy ( Qt::NoFocus );

    QHBoxLayout * userButtonsLayout = new QHBoxLayout ( userGraphicsView );
//     QPushButton * helpButton = new QPushButton(userGraphicsView);
    medHomepageButton * helpButton = new medHomepageButton ( userGraphicsView );
    helpButton->setText ( "Help" );
    helpButton->setMinimumHeight ( 30 );
    helpButton->setMaximumWidth ( 150 );
    helpButton->setMinimumWidth ( 150 );
    helpButton->setFocusPolicy ( Qt::NoFocus );
    helpButton->setIcon(QIcon(":icons/help.svg"));
    helpButton->setToolButtonStyle ( Qt::ToolButtonTextBesideIcon );
    QObject::connect ( helpButton,SIGNAL ( clicked() ),this, SLOT ( onShowHelp() ) );

//     QPushButton * aboutButton = new QPushButton(userGraphicsView);
    medHomepageButton * aboutButton = new medHomepageButton ( userGraphicsView );
    aboutButton->setText ( "About" );
    aboutButton->setMinimumHeight ( 30 );
    aboutButton->setMaximumWidth ( 150 );
    aboutButton->setMinimumWidth ( 150 );
    aboutButton->setFocusPolicy ( Qt::NoFocus );
    aboutButton->setIcon(QIcon(":icons/about.png"));
    aboutButton->setToolButtonStyle ( Qt::ToolButtonTextBesideIcon );
    QObject::connect ( aboutButton,SIGNAL ( clicked() ),this, SLOT ( onShowAbout() ) );

//     QPushButton * settingsButton = new QPushButton(userGraphicsView);
    medHomepageButton * settingsButton = new medHomepageButton ( userGraphicsView );
    settingsButton->setText ( "Settings" );
    settingsButton->setMinimumHeight ( 30 );
    settingsButton->setMaximumWidth ( 150 );
    settingsButton->setMinimumWidth ( 150 );
    settingsButton->setFocusPolicy ( Qt::NoFocus );
    settingsButton->setIcon(QIcon(":icons/settings.svg"));
    settingsButton->setToolButtonStyle ( Qt::ToolButtonTextBesideIcon );
    QObject::connect ( settingsButton,SIGNAL ( clicked() ),this, SLOT ( onShowSettings() ) );

    userButtonsLayout->insertWidget ( 0, settingsButton );
    userButtonsLayout->insertWidget ( 1, aboutButton );
    userButtonsLayout->insertWidget ( 2, helpButton );

    d->userButtonsWidget->setLayout ( userButtonsLayout );

    d->userButtonsProxyWidget = d->userButtonsScene->addWidget ( d->userButtonsWidget );

    d->userButtonsProxyWidget->setPos ( d->userButtonsScene->width() - 100, 0 );

    //     //Special widget : image, text, etc. QtWebkit ?
    d->infoWidget = new QWidget ( infoGraphicsView );
    QVBoxLayout * infoLayout = new QVBoxLayout ( this );
    QLabel * medinriaLabel = new QLabel ( this );
    medinriaLabel->setPixmap ( QPixmap ( ":pixmaps/medinria-logo.png" ).scaled ( 300,100 ) );
    QLabel * textLabel = new QLabel;
    textLabel->setText ( "The ultimate medical imaging platform" );
    infoLayout->insertWidget ( 0,medinriaLabel );
    infoLayout->insertWidget ( 1, textLabel );

    d->infoWidget->setLayout ( infoLayout );

    d->infoProxyWidget = d->infoScene->addWidget ( d->infoWidget );

    d->animation = new QParallelAnimationGroup ( this );
    d->configurationAnimation = new QPropertyAnimation ( d->configurationsButtonsWidget, "pos" );
    d->configurationAnimation->setDuration ( 750 );
    d->configurationAnimation->setEasingCurve ( QEasingCurve::OutCubic );

    d->userAnimation = new QPropertyAnimation ( d->userButtonsWidget, "pos" );
    d->userAnimation->setDuration ( 750 );
    d->userAnimation->setEasingCurve ( QEasingCurve::OutCubic );
    d->userAnimation->setStartValue ( QPoint ( ( d->userButtonsScene->width() / 2 ) + 250, 0 ) );
    d->userAnimation->setEndValue ( QPoint ( ( d->userButtonsScene->width() / 2 ) ,  0 ) );

    d->infoAnimation = new QPropertyAnimation ( d->infoWidget, "pos" );
    d->infoAnimation->setDuration ( 900 );
    d->infoAnimation->setEasingCurve ( QEasingCurve::OutCubic );
    d->infoAnimation->setStartValue ( QPoint ( ( d->infoScene->width() / 2 ) + 1000 , 250 ) );
    d->infoAnimation->setEndValue ( QPoint ( ( d->infoScene->width() / 2 ) + 300 ,  250 ) );

    d->animation->addAnimation(d->configurationAnimation);
    d->animation->addAnimation(d->userAnimation);
    d->animation->addAnimation(d->infoAnimation);
}

medHomepageArea::~medHomepageArea()
{
    delete d;

    d = NULL;
}

void medHomepageArea::initPage ( void )
{
    QList<QString> configList = medViewerConfigurationFactory::instance()->configurations();
    QVBoxLayout * configurationButtonsLayout = new QVBoxLayout ( this );
    QLabel * configurationLabel = new QLabel("Available workspaces:");
    configurationButtonsLayout->addWidget(configurationLabel);

// //     QPushButton * buttonBrowser = new QPushButton ( this );
    medHomepageButton * browserButton = new medHomepageButton ( this );
    browserButton->setToolButtonStyle ( Qt::ToolButtonTextUnderIcon );
    browserButton->setIcon ( QIcon ( ":/icons/folder.png" ) );
    browserButton->setText ( "Browser" );
    browserButton->setMinimumHeight ( 30 );
    browserButton->setMaximumWidth ( 200 );
    browserButton->setMinimumWidth ( 200 );
    browserButton->setFocusPolicy ( Qt::NoFocus );
    configurationButtonsLayout->addWidget ( browserButton);
    QObject::connect ( browserButton, SIGNAL ( clicked() ),this, SLOT ( onShowBrowser() ) );

    for ( int i = 0; i< configList.size(); i++ )
    {
//         QPushButton * button = new QPushButton ( this );
        medHomepageButton * button = new medHomepageButton ( this );
        button->setText ( configList.at ( i ) );
        button->setFocusPolicy ( Qt::NoFocus );
        button->setToolButtonStyle ( Qt::ToolButtonTextUnderIcon );
        button->setMinimumHeight ( 30 );
        button->setMaximumWidth ( 200 );
        button->setMinimumWidth ( 200 );;
//         configurationButtonsLayout->addWidget ( button,i + 1,0 );
        configurationButtonsLayout->addWidget ( button);
        QObject::connect ( button, SIGNAL ( clicked ( QString ) ),this, SLOT ( onShowConfiguration ( QString ) ) );
    }
    d->configurationsButtonsWidget->setLayout ( configurationButtonsLayout );
    d->configurationsButtonsProxyWidget = d->configurationsButtonsScene->addWidget ( d->configurationsButtonsWidget );

    d->configurationAnimation->setStartValue ( QPoint ( ( d->configurationsButtonsScene->width() / 2 ) - 250, 250 ) );
    d->configurationAnimation->setEndValue ( QPoint ( ( d->configurationsButtonsScene->width() / 2 ) + 100 ,  250 ) );
}

QParallelAnimationGroup* medHomepageArea::getAnimation ( void )
{
    return d->animation;
}

void medHomepageArea::setViewerArea ( medViewerArea* viewer )
{
    d->viewerArea = viewer;
}

void medHomepageArea::onShowBrowser ( void )
{
    emit showBrowser();
}

void medHomepageArea::onShowConfiguration ( QString configuration )
{
    emit showViewer();
    emit showConfiguration ( configuration );
}

void medHomepageArea::onShowAbout ( void )
{
//     emit showAbout();
    QMessageBox * msgBox = new QMessageBox ( QApplication::activeWindow() );
    msgBox->setIcon ( QMessageBox::Information );
    msgBox->setText ( "This is an ultimate medical imaging platform" );
    msgBox->exec();
    delete msgBox;
}

void medHomepageArea::onShowHelp ( void )
{
//     emit showHelp();
    QMessageBox * msgBox = new QMessageBox ( QApplication::activeWindow() );
    msgBox->setIcon ( QMessageBox::Information );
    msgBox->setText ( "Help ! Help !" );
    msgBox->exec();
    delete msgBox;
}

void medHomepageArea::onShowSettings ( void )
{
    emit showSettings();
}

<commit_msg>some cosmetic improvements of the home page<commit_after>/*
    Copyright (c) 2011, Alexandre Abadie <Alexandre.Abadie@irisa.fr>
    All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions are met:
        * Redistributions of source code must retain the above copyright
        notice, this list of conditions and the following disclaimer.
        * Redistributions in binary form must reproduce the above copyright
        notice, this list of conditions and the following disclaimer in the
        documentation and/or other materials provided with the distribution.
        * Neither the name of the <organization> nor the
        names of its contributors may be used to endorse or promote products
        derived from this software without specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY Alexandre <email> ''AS IS'' AND ANY
    EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
    DISCLAIMED. IN NO EVENT SHALL Alexandre <email> BE LIABLE FOR ANY
    DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
    (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "medHomepageArea.h"

#include <medViewerArea.h>
#include <medHomepageButton.h>
#include <medGui/medViewerConfiguration.h>
#include <medGui/medViewerConfigurationFactory.h>

class medHomepageAreaPrivate
{
public:
    QGraphicsScene * configurationsButtonsScene;
    QGraphicsProxyWidget * configurationsButtonsProxyWidget;
    QWidget * configurationsButtonsWidget;

    QGraphicsScene * userButtonsScene;
    QGraphicsProxyWidget * userButtonsProxyWidget;
    QWidget * userButtonsWidget;

    QGraphicsScene * infoScene;
    QGraphicsProxyWidget * infoProxyWidget;
    QWidget * infoWidget;

    QPropertyAnimation * configurationAnimation;
    QPropertyAnimation * userAnimation;
    QPropertyAnimation * infoAnimation;

    QParallelAnimationGroup * animation;

    medViewerArea * viewerArea;
};

medHomepageArea::medHomepageArea ( QWidget * parent ) : QWidget ( parent ), d ( new medHomepageAreaPrivate )
{
    d->viewerArea = NULL;
    setupUi ( this );

//     d->configurationsButtonsView = new QGraphicsView ( this );
    d->configurationsButtonsScene = new QGraphicsScene ( configurationsGraphicsView );
    configurationsGraphicsView->setScene ( d->configurationsButtonsScene );
    configurationsGraphicsView->setStyleSheet ( "background: #313131;border: 0px;padding: 0px 0px 0px 0px;" );
    configurationsGraphicsView->setFocusPolicy ( Qt::NoFocus );

    //Configurations buttons (browser, visualization, registration, diffusion, etc)
    d->configurationsButtonsWidget = new QWidget ( configurationsGraphicsView );
    d->configurationsButtonsWidget->setMinimumWidth ( 200 );

    d->userButtonsScene = new QGraphicsScene ( infoGraphicsView );
    userGraphicsView->setScene ( d->userButtonsScene );
    userGraphicsView->setStyleSheet ( "background: #313131;border: 0px;padding: 0px 0px 0px 0px;" );
    userGraphicsView->setFocusPolicy ( Qt::NoFocus );

    //Configurations buttons (Help, about, settings)
    d->userButtonsWidget = new QWidget ( userGraphicsView );
    d->userButtonsWidget->setMinimumWidth ( 200 );

    d->infoScene = new QGraphicsScene ( userGraphicsView );
    infoGraphicsView->setScene ( d->infoScene );
    infoGraphicsView->setStyleSheet ( "background: #313131;border: 0px;padding: 0px 0px 0px 0px;" );
    infoGraphicsView->setFocusPolicy ( Qt::NoFocus );

    QHBoxLayout * userButtonsLayout = new QHBoxLayout ( userGraphicsView );
//     QPushButton * helpButton = new QPushButton(userGraphicsView);
    medHomepageButton * helpButton = new medHomepageButton ( userGraphicsView );
    helpButton->setText ( "Help" );
    helpButton->setMinimumHeight ( 30 );
    helpButton->setMaximumWidth ( 150 );
    helpButton->setMinimumWidth ( 150 );
    helpButton->setFocusPolicy ( Qt::NoFocus );
    helpButton->setIcon(QIcon(":icons/help.svg"));
    helpButton->setToolButtonStyle ( Qt::ToolButtonTextBesideIcon );
    QObject::connect ( helpButton,SIGNAL ( clicked() ),this, SLOT ( onShowHelp() ) );

//     QPushButton * aboutButton = new QPushButton(userGraphicsView);
    medHomepageButton * aboutButton = new medHomepageButton ( userGraphicsView );
    aboutButton->setText ( "About" );
    aboutButton->setMinimumHeight ( 30 );
    aboutButton->setMaximumWidth ( 150 );
    aboutButton->setMinimumWidth ( 150 );
    aboutButton->setFocusPolicy ( Qt::NoFocus );
    aboutButton->setIcon(QIcon(":icons/about.png"));
    aboutButton->setToolButtonStyle ( Qt::ToolButtonTextBesideIcon );
    QObject::connect ( aboutButton,SIGNAL ( clicked() ),this, SLOT ( onShowAbout() ) );

//     QPushButton * settingsButton = new QPushButton(userGraphicsView);
    medHomepageButton * settingsButton = new medHomepageButton ( userGraphicsView );
    settingsButton->setText ( "Settings" );
    settingsButton->setMinimumHeight ( 30 );
    settingsButton->setMaximumWidth ( 150 );
    settingsButton->setMinimumWidth ( 150 );
    settingsButton->setFocusPolicy ( Qt::NoFocus );
    settingsButton->setIcon(QIcon(":icons/settings.svg"));
    settingsButton->setToolButtonStyle ( Qt::ToolButtonTextBesideIcon );
    QObject::connect ( settingsButton,SIGNAL ( clicked() ),this, SLOT ( onShowSettings() ) );

    userButtonsLayout->insertWidget ( 0, settingsButton );
    userButtonsLayout->insertWidget ( 1, aboutButton );
    userButtonsLayout->insertWidget ( 2, helpButton );

    d->userButtonsWidget->setLayout ( userButtonsLayout );

    d->userButtonsProxyWidget = d->userButtonsScene->addWidget ( d->userButtonsWidget );

    d->userButtonsProxyWidget->setPos ( d->userButtonsScene->width() - 100, 0 );

    //     //Special widget : image, text, etc. QtWebkit ?
    d->infoWidget = new QWidget ( infoGraphicsView );
    QVBoxLayout * infoLayout = new QVBoxLayout ( this );
    QLabel * medinriaLabel = new QLabel ( this );
    medinriaLabel->setPixmap ( QPixmap ( ":pixmaps/medinria-logo.png" ).scaled ( 300,100 ) );
    QLabel * textLabel = new QLabel;
    textLabel->setText ( "The ultimate medical imaging platform" );
    infoLayout->insertWidget ( 0,medinriaLabel );
    infoLayout->insertWidget ( 1, textLabel );

    d->infoWidget->setLayout ( infoLayout );

    d->infoProxyWidget = d->infoScene->addWidget ( d->infoWidget );

    d->animation = new QParallelAnimationGroup ( this );
    d->configurationAnimation = new QPropertyAnimation ( d->configurationsButtonsWidget, "pos" );
    d->configurationAnimation->setDuration ( 750 );
    d->configurationAnimation->setEasingCurve ( QEasingCurve::OutCubic );

    d->userAnimation = new QPropertyAnimation ( d->userButtonsWidget, "pos" );
    d->userAnimation->setDuration ( 750 );
    d->userAnimation->setEasingCurve ( QEasingCurve::OutCubic );
    d->userAnimation->setStartValue ( QPoint ( ( d->userButtonsScene->width() / 2 ) + 250, 0 ) );
    d->userAnimation->setEndValue ( QPoint ( ( d->userButtonsScene->width() / 2 ) ,  0 ) );

    d->infoAnimation = new QPropertyAnimation ( d->infoWidget, "pos" );
    d->infoAnimation->setDuration ( 900 );
    d->infoAnimation->setEasingCurve ( QEasingCurve::OutCubic );
    d->infoAnimation->setStartValue ( QPoint ( ( d->infoScene->width() / 2 ) + 1000 , 250 ) );
    d->infoAnimation->setEndValue ( QPoint ( ( d->infoScene->width() / 2 ) + 300 ,  250 ) );

    d->animation->addAnimation(d->configurationAnimation);
    d->animation->addAnimation(d->userAnimation);
    d->animation->addAnimation(d->infoAnimation);
}

medHomepageArea::~medHomepageArea()
{
    delete d;

    d = NULL;
}

void medHomepageArea::initPage ( void )
{
    QList<QString> configList = medViewerConfigurationFactory::instance()->configurations();
    QVBoxLayout * configurationButtonsLayout = new QVBoxLayout ( this );
    QLabel * configurationLabel = new QLabel("Available workspaces:");
    configurationButtonsLayout->addWidget(configurationLabel);

// //     QPushButton * buttonBrowser = new QPushButton ( this );
    medHomepageButton * browserButton = new medHomepageButton ( this );
    browserButton->setToolButtonStyle ( Qt::ToolButtonTextUnderIcon );
    browserButton->setIcon ( QIcon ( ":/icons/folder.png" ) );
    browserButton->setText ( "Browser" );
    browserButton->setMinimumHeight ( 30 );
    browserButton->setMaximumWidth ( 200 );
    browserButton->setMinimumWidth ( 200 );
    browserButton->setFocusPolicy ( Qt::NoFocus );
    configurationButtonsLayout->addWidget ( browserButton);
    QObject::connect ( browserButton, SIGNAL ( clicked() ),this, SLOT ( onShowBrowser() ) );

    for ( int i = 0; i< configList.size(); i++ )
    {
//         QPushButton * button = new QPushButton ( this );
        medHomepageButton * button = new medHomepageButton ( this );
        button->setText ( configList.at ( i ) );
        button->setFocusPolicy ( Qt::NoFocus );
        button->setToolButtonStyle ( Qt::ToolButtonTextUnderIcon );
        button->setMinimumHeight ( 30 );
        button->setMaximumWidth ( 200 );
        button->setMinimumWidth ( 200 );;
        configurationButtonsLayout->addWidget ( button);
        QObject::connect ( button, SIGNAL ( clicked ( QString ) ),this, SLOT ( onShowConfiguration ( QString ) ) );
    }
    d->configurationsButtonsWidget->setLayout ( configurationButtonsLayout );
    d->configurationsButtonsProxyWidget = d->configurationsButtonsScene->addWidget ( d->configurationsButtonsWidget );

    d->configurationAnimation->setStartValue ( QPoint ( ( d->configurationsButtonsScene->width() / 2 ) - 250, 250 ) );
    d->configurationAnimation->setEndValue ( QPoint ( ( d->configurationsButtonsScene->width() / 2 ) + 100 ,  250 ) );
}

QParallelAnimationGroup* medHomepageArea::getAnimation ( void )
{
    return d->animation;
}

void medHomepageArea::setViewerArea ( medViewerArea* viewer )
{
    d->viewerArea = viewer;
}

void medHomepageArea::onShowBrowser ( void )
{
    emit showBrowser();
}

void medHomepageArea::onShowConfiguration ( QString configuration )
{
    emit showViewer();
    emit showConfiguration ( configuration );
}

void medHomepageArea::onShowAbout ( void )
{
    QString aboutMessage("This is an ultimate medical imaging platform");
    QMessageBox::about(this,"About Medinria", aboutMessage);
//     QMessageBox * msgBox = new QMessageBox ( QApplication::activeWindow() );
//     msgBox->setIcon ( QMessageBox::Information );
//     msgBox->setText ( "This is an ultimate medical imaging platform" );
//     msgBox->exec();
//     delete msgBox;
}

void medHomepageArea::onShowHelp ( void )
{
//     emit showHelp();
    QMessageBox * msgBox = new QMessageBox ( QApplication::activeWindow() );
    msgBox->setIcon ( QMessageBox::Information );
    msgBox->setText ( "Help ! Help !" );
    msgBox->exec();
    delete msgBox;
}

void medHomepageArea::onShowSettings ( void )
{
    emit showSettings();
}

<|endoftext|>


<commit_before>#ifndef ENTT_POLY_POLY_HPP
#define ENTT_POLY_POLY_HPP

#include <cstddef>
#include <functional>
#include <tuple>
#include <type_traits>
#include <utility>
#include "../config/config.h"
#include "../core/any.hpp"
#include "../core/type_info.hpp"
#include "../core/type_traits.hpp"
#include "fwd.hpp"

namespace entt {

/*! @brief Inspector class used to infer the type of the virtual table. */
struct poly_inspector {
    /**
     * @brief Generic conversion operator (definition only).
     * @tparam Type Type to which conversion is requested.
     */
    template <class Type>
    operator Type &&() const;

    /**
     * @brief Dummy invocation function (definition only).
     * @tparam Member Index of the function to invoke.
     * @tparam Args Types of arguments to pass to the function.
     * @param args The arguments to pass to the function.
     * @return A poly inspector convertible to any type.
     */
    template<auto Member, typename... Args>
    poly_inspector invoke(Args &&... args) const;

    /*! @copydoc invoke */
    template<auto Member, typename... Args>
    poly_inspector invoke(Args &&... args);
};

/**
 * @brief Static virtual table factory.
 * @tparam Concept Concept descriptor.
 * @tparam Len Size of the storage reserved for the small buffer optimization.
 */
template<typename Concept, std::size_t Len>
class poly_vtable {
    using inspector = typename Concept::template type<poly_inspector>;

    template<typename Ret, typename... Args>
    static auto vtable_entry(Ret(*)(inspector &, Args...)) -> Ret(*)(basic_any<Len> &, Args...);

    template<typename Ret, typename... Args>
    static auto vtable_entry(Ret(*)(const inspector &, Args...)) -> Ret(*)(const basic_any<Len> &, Args...);

    template<typename Ret, typename... Args>
    static auto vtable_entry(Ret(*)(Args...)) -> Ret(*)(const basic_any<Len> &, Args...);

    template<typename Ret, typename... Args>
    static auto vtable_entry(Ret(inspector:: *)(Args...)) -> Ret(*)(basic_any<Len> &, Args...);

    template<typename Ret, typename... Args>
    static auto vtable_entry(Ret(inspector:: *)(Args...) const) -> Ret(*)(const basic_any<Len> &, Args...);

    template<auto... Candidate>
    static auto make_vtable(value_list<Candidate...>)
    -> std::tuple<decltype(vtable_entry(Candidate))...>;

    template<typename... Func>
    [[nodiscard]] static constexpr auto make_vtable(type_list<Func...>)  {
        if constexpr(sizeof...(Func) == 0) {
            return decltype(make_vtable(typename Concept::template impl<inspector>{})){};
        } else if constexpr((std::is_function_v<Func> && ...)) {
            return decltype(std::make_tuple(vtable_entry(std::declval<Func inspector:: *>())...)){};
        }
    }

    template<typename Type, auto Candidate, typename Ret, typename Any, typename... Args>
    static void fill_vtable_entry(Ret(* &entry)(Any &, Args...)) {
        if constexpr(std::is_invocable_r_v<Ret, decltype(Candidate), Args...>) {
            entry = +[](Any &, Args... args) -> Ret {
                return std::invoke(Candidate, std::forward<Args>(args)...);
            };
        } else {
            entry = +[](Any &instance, Args... args) -> Ret {
                return static_cast<Ret>(std::invoke(Candidate, any_cast<constness_as_t<Type, Any> &>(instance), std::forward<Args>(args)...));
            };
        }
    }

    template<typename Type, auto... Index>
    [[nodiscard]] static auto fill_vtable(std::index_sequence<Index...>) {
        type impl{};
        (fill_vtable_entry<Type, value_list_element_v<Index, typename Concept::template impl<Type>>>(std::get<Index>(impl)), ...);
        return impl;
    }

public:
    /*! @brief Virtual table type. */
    using type = decltype(make_vtable(Concept{}));

    /**
     * @brief Returns a static virtual table for a specific concept and type.
     * @tparam Type The type for which to generate the virtual table.
     * @return A static virtual table for the given concept and type.
     */
    template<typename Type>
    [[nodiscard]] static const auto * instance() {
        static_assert(std::is_same_v<Type, std::decay_t<Type>>, "Type differs from its decayed form");
        static const auto vtable = fill_vtable<Type>(std::make_index_sequence<Concept::template impl<Type>::size>{});
        return &vtable;
    }
};

/**
 * @brief Poly base class used to inject functionalities into concepts.
 * @tparam Poly The outermost poly class.
 */
template<typename Poly>
struct poly_base {
    /**
     * @brief Invokes a function from the static virtual table.
     * @tparam Member Index of the function to invoke.
     * @tparam Args Types of arguments to pass to the function.
     * @param self A reference to the poly object that made the call.
     * @param args The arguments to pass to the function.
     * @return The return value of the invoked function, if any.
     */
    template<auto Member, typename... Args>
    [[nodiscard]] decltype(auto) invoke(const poly_base &self, Args &&... args) const {
        const auto &poly = static_cast<const Poly &>(self);
        return std::get<Member>(*poly.vtable)(poly.storage, std::forward<Args>(args)...);
    }

    /*! @copydoc invoke */
    template<auto Member, typename... Args>
    [[nodiscard]] decltype(auto) invoke(poly_base &self, Args &&... args) {
        auto &poly = static_cast<Poly &>(self);
        return std::get<Member>(*poly.vtable)(poly.storage, std::forward<Args>(args)...);
    }
};

/**
 * @brief Shortcut for calling `poly_base<Type>::invoke`.
 * @tparam Member Index of the function to invoke.
 * @tparam Poly A fully defined poly object.
 * @tparam Args Types of arguments to pass to the function.
 * @param self A reference to the poly object that made the call.
 * @param args The arguments to pass to the function.
 * @return The return value of the invoked function, if any.
 */
template<auto Member, typename Poly, typename... Args>
decltype(auto) poly_call(Poly &&self, Args &&... args) {
    return std::forward<Poly>(self).template invoke<Member>(self, std::forward<Args>(args)...);
}

/**
 * @brief Static polymorphism made simple and within everyone's reach.
 *
 * Static polymorphism is a very powerful tool in C++, albeit sometimes
 * cumbersome to obtain.

 * This class aims to make it simple and easy to use.
 *
 * @note
 * Both deduced and defined static virtual tables are supported.

 * Moreover, the `poly` class template also works with unmanaged objects.
 *
 * @tparam Concept Concept descriptor.
 * @tparam Len Size of the storage reserved for the small buffer optimization.
 */
template<typename Concept, std::size_t Len>
class poly: private Concept::template type<poly_base<poly<Concept, Len>>> {
    /*! @brief A poly base is allowed to snoop into a poly object. */
    friend struct poly_base<poly>;

    using vtable_type = typename poly_vtable<Concept, Len>::type;

public:
    /*! @brief Concept type. */
    using concept_type = typename Concept::template type<poly_base<poly>>;

    /*! @brief Default constructor. */
    poly() ENTT_NOEXCEPT
        : storage{},
          vtable{}
    {}

    /**
     * @brief Constructs a poly by directly initializing the new object.
     * @tparam Type Type of object to use to initialize the poly.
     * @tparam Args Types of arguments to use to construct the new instance.
     * @param args Parameters to use to construct the instance.
     */
    template<typename Type, typename... Args>
    explicit poly(std::in_place_type_t<Type>, Args &&... args)
        : storage{std::in_place_type<Type>, std::forward<Args>(args)...},
          vtable{poly_vtable<Concept, Len>::template instance<std::remove_const_t<std::remove_reference_t<Type>>>()}
    {}

    /**
     * @brief Constructs a poly that holds an unmanaged object.
     * @tparam Type Type of object to use to initialize the poly.
     * @param value An instance of an object to use to initialize the poly.
     */
    template<typename Type>
    poly(std::reference_wrapper<Type> value)
        : poly{std::in_place_type<Type &>, value.get()}
    {}

    /**
     * @brief Constructs a poly from a given value.
     * @tparam Type Type of object to use to initialize the poly.
     * @param value An instance of an object to use to initialize the poly.
     */
    template<typename Type, typename = std::enable_if_t<!std::is_same_v<std::remove_cv_t<std::remove_reference_t<Type>>, poly>>>
    poly(Type &&value) ENTT_NOEXCEPT
        : poly{std::in_place_type<std::remove_cv_t<std::remove_reference_t<Type>>>, std::forward<Type>(value)}
    {}

    /**
     * @brief Copy constructor.
     * @param other The instance to copy from.
     */
    poly(const poly &other) = default;

    /**
     * @brief Move constructor.
     * @param other The instance to move from.
     */
    poly(poly &&other) ENTT_NOEXCEPT
        : poly{}
    {
        swap(*this, other);
    }

    /**
     * @brief Assignment operator.
     * @param other The instance to assign from.
     * @return This poly object.
     */
    poly & operator=(poly other) {
        swap(other, *this);
        return *this;
    }

    /**
     * @brief Returns the type of the contained object.
     * @return The type of the contained object, if any.
     */
    [[nodiscard]] type_info type() const ENTT_NOEXCEPT {
        return storage.type();
    }

    /**
     * @brief Returns an opaque pointer to the contained instance.
     * @return An opaque pointer the contained instance, if any.
     */
    [[nodiscard]] const void * data() const ENTT_NOEXCEPT {
        return storage.data();
    }

    /*! @copydoc data */
    [[nodiscard]] void * data() ENTT_NOEXCEPT {
        return storage.data();
    }

    /**
     * @brief Replaces the contained object by creating a new instance directly.
     * @tparam Type Type of object to use to initialize the poly.
     * @tparam Args Types of arguments to use to construct the new instance.
     * @param args Parameters to use to construct the instance.
     */
    template<typename Type, typename... Args>
    void emplace(Args &&... args) {
        storage.template emplace<Type>(std::forward<Args>(args)...);
        vtable = poly_vtable<Concept, Len>::template instance<Type>();
    }

    /*! @brief Destroys contained object */
    void reset() {
        *this = poly{};
    }

    /**
     * @brief Returns false if a poly is empty, true otherwise.
     * @return False if the poly is empty, true otherwise.
     */
    [[nodiscard]] explicit operator bool() const ENTT_NOEXCEPT {
        return !(vtable == nullptr);
    }

    /**
     * @brief Returns a pointer to the underlying concept.
     * @return A pointer to the underlying concept.
     */
    [[nodiscard]] concept_type * operator->() ENTT_NOEXCEPT {
        return this;
    }

    /*! @copydoc operator-> */
    [[nodiscard]] const concept_type * operator->() const ENTT_NOEXCEPT {
        return this;
    }

    /**
     * @brief Swaps two poly objects.
     * @param lhs A valid poly object.
     * @param rhs A valid poly object.
     */
    friend void swap(poly &lhs, poly &rhs) {
        using std::swap;
        swap(lhs.storage, rhs.storage);
        swap(lhs.vtable, rhs.vtable);
    }

    /**
     * @brief Aliasing constructor.
     * @return A poly that shares a reference to an unmanaged object.
     */
    [[nodiscard]] poly as_ref() ENTT_NOEXCEPT {
        poly ref = std::as_const(*this).as_ref();
        ref.storage = storage.as_ref();
        return ref;
    }

    /*! @copydoc as_ref */
    [[nodiscard]] poly as_ref() const ENTT_NOEXCEPT {
        poly ref{};
        ref.storage = storage.as_ref();
        ref.vtable = vtable;
        return ref;
    }

private:
    basic_any<Len> storage;
    const vtable_type *vtable;
};

}

#endif
<commit_msg>poly: ::emplace support for reference types<commit_after>#ifndef ENTT_POLY_POLY_HPP
#define ENTT_POLY_POLY_HPP

#include <cstddef>
#include <functional>
#include <tuple>
#include <type_traits>
#include <utility>
#include "../config/config.h"
#include "../core/any.hpp"
#include "../core/type_info.hpp"
#include "../core/type_traits.hpp"
#include "fwd.hpp"

namespace entt {

/*! @brief Inspector class used to infer the type of the virtual table. */
struct poly_inspector {
    /**
     * @brief Generic conversion operator (definition only).
     * @tparam Type Type to which conversion is requested.
     */
    template <class Type>
    operator Type &&() const;

    /**
     * @brief Dummy invocation function (definition only).
     * @tparam Member Index of the function to invoke.
     * @tparam Args Types of arguments to pass to the function.
     * @param args The arguments to pass to the function.
     * @return A poly inspector convertible to any type.
     */
    template<auto Member, typename... Args>
    poly_inspector invoke(Args &&... args) const;

    /*! @copydoc invoke */
    template<auto Member, typename... Args>
    poly_inspector invoke(Args &&... args);
};

/**
 * @brief Static virtual table factory.
 * @tparam Concept Concept descriptor.
 * @tparam Len Size of the storage reserved for the small buffer optimization.
 */
template<typename Concept, std::size_t Len>
class poly_vtable {
    using inspector = typename Concept::template type<poly_inspector>;

    template<typename Ret, typename... Args>
    static auto vtable_entry(Ret(*)(inspector &, Args...)) -> Ret(*)(basic_any<Len> &, Args...);

    template<typename Ret, typename... Args>
    static auto vtable_entry(Ret(*)(const inspector &, Args...)) -> Ret(*)(const basic_any<Len> &, Args...);

    template<typename Ret, typename... Args>
    static auto vtable_entry(Ret(*)(Args...)) -> Ret(*)(const basic_any<Len> &, Args...);

    template<typename Ret, typename... Args>
    static auto vtable_entry(Ret(inspector:: *)(Args...)) -> Ret(*)(basic_any<Len> &, Args...);

    template<typename Ret, typename... Args>
    static auto vtable_entry(Ret(inspector:: *)(Args...) const) -> Ret(*)(const basic_any<Len> &, Args...);

    template<auto... Candidate>
    static auto make_vtable(value_list<Candidate...>)
    -> std::tuple<decltype(vtable_entry(Candidate))...>;

    template<typename... Func>
    [[nodiscard]] static constexpr auto make_vtable(type_list<Func...>)  {
        if constexpr(sizeof...(Func) == 0) {
            return decltype(make_vtable(typename Concept::template impl<inspector>{})){};
        } else if constexpr((std::is_function_v<Func> && ...)) {
            return decltype(std::make_tuple(vtable_entry(std::declval<Func inspector:: *>())...)){};
        }
    }

    template<typename Type, auto Candidate, typename Ret, typename Any, typename... Args>
    static void fill_vtable_entry(Ret(* &entry)(Any &, Args...)) {
        if constexpr(std::is_invocable_r_v<Ret, decltype(Candidate), Args...>) {
            entry = +[](Any &, Args... args) -> Ret {
                return std::invoke(Candidate, std::forward<Args>(args)...);
            };
        } else {
            entry = +[](Any &instance, Args... args) -> Ret {
                return static_cast<Ret>(std::invoke(Candidate, any_cast<constness_as_t<Type, Any> &>(instance), std::forward<Args>(args)...));
            };
        }
    }

    template<typename Type, auto... Index>
    [[nodiscard]] static auto fill_vtable(std::index_sequence<Index...>) {
        type impl{};
        (fill_vtable_entry<Type, value_list_element_v<Index, typename Concept::template impl<Type>>>(std::get<Index>(impl)), ...);
        return impl;
    }

public:
    /*! @brief Virtual table type. */
    using type = decltype(make_vtable(Concept{}));

    /**
     * @brief Returns a static virtual table for a specific concept and type.
     * @tparam Type The type for which to generate the virtual table.
     * @return A static virtual table for the given concept and type.
     */
    template<typename Type>
    [[nodiscard]] static const auto * instance() {
        static_assert(std::is_same_v<Type, std::decay_t<Type>>, "Type differs from its decayed form");
        static const auto vtable = fill_vtable<Type>(std::make_index_sequence<Concept::template impl<Type>::size>{});
        return &vtable;
    }
};

/**
 * @brief Poly base class used to inject functionalities into concepts.
 * @tparam Poly The outermost poly class.
 */
template<typename Poly>
struct poly_base {
    /**
     * @brief Invokes a function from the static virtual table.
     * @tparam Member Index of the function to invoke.
     * @tparam Args Types of arguments to pass to the function.
     * @param self A reference to the poly object that made the call.
     * @param args The arguments to pass to the function.
     * @return The return value of the invoked function, if any.
     */
    template<auto Member, typename... Args>
    [[nodiscard]] decltype(auto) invoke(const poly_base &self, Args &&... args) const {
        const auto &poly = static_cast<const Poly &>(self);
        return std::get<Member>(*poly.vtable)(poly.storage, std::forward<Args>(args)...);
    }

    /*! @copydoc invoke */
    template<auto Member, typename... Args>
    [[nodiscard]] decltype(auto) invoke(poly_base &self, Args &&... args) {
        auto &poly = static_cast<Poly &>(self);
        return std::get<Member>(*poly.vtable)(poly.storage, std::forward<Args>(args)...);
    }
};

/**
 * @brief Shortcut for calling `poly_base<Type>::invoke`.
 * @tparam Member Index of the function to invoke.
 * @tparam Poly A fully defined poly object.
 * @tparam Args Types of arguments to pass to the function.
 * @param self A reference to the poly object that made the call.
 * @param args The arguments to pass to the function.
 * @return The return value of the invoked function, if any.
 */
template<auto Member, typename Poly, typename... Args>
decltype(auto) poly_call(Poly &&self, Args &&... args) {
    return std::forward<Poly>(self).template invoke<Member>(self, std::forward<Args>(args)...);
}

/**
 * @brief Static polymorphism made simple and within everyone's reach.
 *
 * Static polymorphism is a very powerful tool in C++, albeit sometimes
 * cumbersome to obtain.

 * This class aims to make it simple and easy to use.
 *
 * @note
 * Both deduced and defined static virtual tables are supported.

 * Moreover, the `poly` class template also works with unmanaged objects.
 *
 * @tparam Concept Concept descriptor.
 * @tparam Len Size of the storage reserved for the small buffer optimization.
 */
template<typename Concept, std::size_t Len>
class poly: private Concept::template type<poly_base<poly<Concept, Len>>> {
    /*! @brief A poly base is allowed to snoop into a poly object. */
    friend struct poly_base<poly>;

    using vtable_type = typename poly_vtable<Concept, Len>::type;

public:
    /*! @brief Concept type. */
    using concept_type = typename Concept::template type<poly_base<poly>>;

    /*! @brief Default constructor. */
    poly() ENTT_NOEXCEPT
        : storage{},
          vtable{}
    {}

    /**
     * @brief Constructs a poly by directly initializing the new object.
     * @tparam Type Type of object to use to initialize the poly.
     * @tparam Args Types of arguments to use to construct the new instance.
     * @param args Parameters to use to construct the instance.
     */
    template<typename Type, typename... Args>
    explicit poly(std::in_place_type_t<Type>, Args &&... args)
        : storage{std::in_place_type<Type>, std::forward<Args>(args)...},
          vtable{poly_vtable<Concept, Len>::template instance<std::remove_const_t<std::remove_reference_t<Type>>>()}
    {}

    /**
     * @brief Constructs a poly that holds an unmanaged object.
     * @tparam Type Type of object to use to initialize the poly.
     * @param value An instance of an object to use to initialize the poly.
     */
    template<typename Type>
    poly(std::reference_wrapper<Type> value)
        : poly{std::in_place_type<Type &>, value.get()}
    {}

    /**
     * @brief Constructs a poly from a given value.
     * @tparam Type Type of object to use to initialize the poly.
     * @param value An instance of an object to use to initialize the poly.
     */
    template<typename Type, typename = std::enable_if_t<!std::is_same_v<std::remove_cv_t<std::remove_reference_t<Type>>, poly>>>
    poly(Type &&value) ENTT_NOEXCEPT
        : poly{std::in_place_type<std::remove_cv_t<std::remove_reference_t<Type>>>, std::forward<Type>(value)}
    {}

    /**
     * @brief Copy constructor.
     * @param other The instance to copy from.
     */
    poly(const poly &other) = default;

    /**
     * @brief Move constructor.
     * @param other The instance to move from.
     */
    poly(poly &&other) ENTT_NOEXCEPT
        : poly{}
    {
        swap(*this, other);
    }

    /**
     * @brief Assignment operator.
     * @param other The instance to assign from.
     * @return This poly object.
     */
    poly & operator=(poly other) {
        swap(other, *this);
        return *this;
    }

    /**
     * @brief Returns the type of the contained object.
     * @return The type of the contained object, if any.
     */
    [[nodiscard]] type_info type() const ENTT_NOEXCEPT {
        return storage.type();
    }

    /**
     * @brief Returns an opaque pointer to the contained instance.
     * @return An opaque pointer the contained instance, if any.
     */
    [[nodiscard]] const void * data() const ENTT_NOEXCEPT {
        return storage.data();
    }

    /*! @copydoc data */
    [[nodiscard]] void * data() ENTT_NOEXCEPT {
        return storage.data();
    }

    /**
     * @brief Replaces the contained object by creating a new instance directly.
     * @tparam Type Type of object to use to initialize the poly.
     * @tparam Args Types of arguments to use to construct the new instance.
     * @param args Parameters to use to construct the instance.
     */
    template<typename Type, typename... Args>
    void emplace(Args &&... args) {
        *this = poly{std::in_place_type<Type>, std::forward<Args>(args)...};
    }

    /*! @brief Destroys contained object */
    void reset() {
        *this = poly{};
    }

    /**
     * @brief Returns false if a poly is empty, true otherwise.
     * @return False if the poly is empty, true otherwise.
     */
    [[nodiscard]] explicit operator bool() const ENTT_NOEXCEPT {
        return !(vtable == nullptr);
    }

    /**
     * @brief Returns a pointer to the underlying concept.
     * @return A pointer to the underlying concept.
     */
    [[nodiscard]] concept_type * operator->() ENTT_NOEXCEPT {
        return this;
    }

    /*! @copydoc operator-> */
    [[nodiscard]] const concept_type * operator->() const ENTT_NOEXCEPT {
        return this;
    }

    /**
     * @brief Swaps two poly objects.
     * @param lhs A valid poly object.
     * @param rhs A valid poly object.
     */
    friend void swap(poly &lhs, poly &rhs) {
        using std::swap;
        swap(lhs.storage, rhs.storage);
        swap(lhs.vtable, rhs.vtable);
    }

    /**
     * @brief Aliasing constructor.
     * @return A poly that shares a reference to an unmanaged object.
     */
    [[nodiscard]] poly as_ref() ENTT_NOEXCEPT {
        poly ref = std::as_const(*this).as_ref();
        ref.storage = storage.as_ref();
        return ref;
    }

    /*! @copydoc as_ref */
    [[nodiscard]] poly as_ref() const ENTT_NOEXCEPT {
        poly ref{};
        ref.storage = storage.as_ref();
        ref.vtable = vtable;
        return ref;
    }

private:
    basic_any<Len> storage;
    const vtable_type *vtable;
};

}

#endif
<|endoftext|>


<commit_before>/*
 * MRustC - Rust Compiler
 * - By John Hodge (Mutabah/thePowersGang)
 *
 * expand/include.cpp
 * - include!/include_str!/include_bytes! support
 */
#include <synext_macro.hpp>
#include <synext.hpp>   // for Expand_BareExpr
#include <parse/common.hpp>
#include <parse/parseerror.hpp> // for GET_CHECK_TOK
#include <parse/ttstream.hpp>
#include <parse/lex.hpp>    // Lexer (new files)
#include <ast/expr.hpp>

namespace {

    ::std::string get_string(const Span& sp, TokenStream& lex, const ::AST::Crate& crate, AST::Module& mod)
    {
        auto n = Parse_ExprVal(lex);
        ASSERT_BUG(sp, n, "No expression returned");
        Expand_BareExpr(crate, mod, n);

        auto* string_np = dynamic_cast<AST::ExprNode_String*>(&*n);
        if( !string_np ) {
            ERROR(sp, E0000, "include! requires a string literal - got " << *n);
        }
        return mv$( string_np->m_value );
    }

    ::std::string get_path_relative_to(const ::std::string& base_path, ::std::string path)
    {
        if( path[0] == '/' ) {
            return path;
        }
        else if( base_path.size() == 0 ) {
            return path;
        }
        else if( base_path[base_path.size()-1] == '/' ) {
            return base_path + path;
        }
        else {

            auto slash = base_path.find_last_of('/');
            if( slash == ::std::string::npos )
            {
                return path;
            }
            else
            {
                slash += 1;
                ::std::string   rv;
                rv.reserve( slash + path.size() );
                rv.append( base_path.begin(), base_path.begin() + slash );
                rv.append( path.begin(), path.end() );
                return rv;
            }
        }
    }
};

class CIncludeExpander:
    public ExpandProcMacro
{
    ::std::unique_ptr<TokenStream> expand(const Span& sp, const AST::Crate& crate, const ::std::string& ident, const TokenTree& tt, AST::Module& mod) override
    {
        if( ident != "" )
            ERROR(sp, E0000, "include! doesn't take an ident");

        Token   tok;
        auto lex = TTStream(tt);

        auto path = get_string(sp, lex, crate, mod);
        GET_CHECK_TOK(tok, lex, TOK_EOF);

        ::std::string file_path = get_path_relative_to(mod.m_file_info.path, mv$(path));

        return box$( Lexer(file_path) );
    }
};

// TODO: include_str! and include_bytes!

STATIC_MACRO("include", CIncludeExpander);

<commit_msg>Expand - Handle windows paths in `include!`<commit_after>/*
 * MRustC - Rust Compiler
 * - By John Hodge (Mutabah/thePowersGang)
 *
 * expand/include.cpp
 * - include!/include_str!/include_bytes! support
 */
#include <synext_macro.hpp>
#include <synext.hpp>   // for Expand_BareExpr
#include <parse/common.hpp>
#include <parse/parseerror.hpp> // for GET_CHECK_TOK
#include <parse/ttstream.hpp>
#include <parse/lex.hpp>    // Lexer (new files)
#include <ast/expr.hpp>

namespace {

    ::std::string get_string(const Span& sp, TokenStream& lex, const ::AST::Crate& crate, AST::Module& mod)
    {
        auto n = Parse_ExprVal(lex);
        ASSERT_BUG(sp, n, "No expression returned");
        Expand_BareExpr(crate, mod, n);

        auto* string_np = dynamic_cast<AST::ExprNode_String*>(&*n);
        if( !string_np ) {
            ERROR(sp, E0000, "include! requires a string literal - got " << *n);
        }
        return mv$( string_np->m_value );
    }

    ::std::string get_path_relative_to(const ::std::string& base_path, ::std::string path)
    {
        DEBUG(base_path << ", " << path);
        if( path[0] == '/' || path[0] == '\\' ) {
            return path;
        }
        else if( base_path.size() == 0 ) {
            return path;
        }
        else if( base_path.back() == '/' || base_path.back() == '\\' ) {
            return base_path + path;
        }
        else {

            auto slash = ::std::min( base_path.find_last_of('/'), base_path.find_last_of('\\') );
            if( slash == ::std::string::npos )
            {
                return path;
            }
            else
            {
                slash += 1;
                ::std::string   rv;
                rv.reserve( slash + path.size() );
                rv.append( base_path.begin(), base_path.begin() + slash );
                rv.append( path.begin(), path.end() );
                return rv;
            }
        }
    }
};

class CIncludeExpander:
    public ExpandProcMacro
{
    ::std::unique_ptr<TokenStream> expand(const Span& sp, const AST::Crate& crate, const ::std::string& ident, const TokenTree& tt, AST::Module& mod) override
    {
        if( ident != "" )
            ERROR(sp, E0000, "include! doesn't take an ident");

        Token   tok;
        auto lex = TTStream(tt);

        auto path = get_string(sp, lex, crate, mod);
        GET_CHECK_TOK(tok, lex, TOK_EOF);

        ::std::string file_path = get_path_relative_to(mod.m_file_info.path, mv$(path));

        try {
            return box$( Lexer(file_path) );
        }
        catch(::std::runtime_error& e)
        {
            ERROR(sp, E0000, e.what());
        }
    }
};

// TODO: include_str! and include_bytes!

STATIC_MACRO("include", CIncludeExpander);

<|endoftext|>


<commit_before>/////////////////////////////////////////////////////////////////////////////
// BSD 3-Clause License
//
// Copyright (c) 2020, The Regents of the University of California
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
//   list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
//   this list of conditions and the following disclaimer in the documentation
//   and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder nor the names of its
//   contributors may be used to endorse or promote products derived from
//   this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
///////////////////////////////////////////////////////////////////////////////

#include "fin/Finale.h"

#include "DensityFill.h"

namespace fin {

////////////////////////////////////////////////////////////////

Finale::Finale() : db_(nullptr), debug_(false)
{
}

void Finale::init(odb::dbDatabase* db, Logger* logger)
{
  db_ = db;
  logger_ = logger;
}

void Finale::setDebug()
{
  debug_ = true;
}

void Finale::densityFill(const char* rules_filename, const odb::Rect& fill_area)
{
  DensityFill filler(db_, logger_, debug_);
  filler.fill(rules_filename, fill_area);
}

}  // namespace fin
<commit_msg>fin: coverity fixes<commit_after>/////////////////////////////////////////////////////////////////////////////
// BSD 3-Clause License
//
// Copyright (c) 2020, The Regents of the University of California
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
//   list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
//   this list of conditions and the following disclaimer in the documentation
//   and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder nor the names of its
//   contributors may be used to endorse or promote products derived from
//   this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
///////////////////////////////////////////////////////////////////////////////

#include "DensityFill.h"
#include "fin/Finale.h"

namespace fin {

////////////////////////////////////////////////////////////////

Finale::Finale() : db_(nullptr), logger_(nullptr), debug_(false)
{
}

void Finale::init(odb::dbDatabase* db, Logger* logger)
{
  db_ = db;
  logger_ = logger;
}

void Finale::setDebug()
{
  debug_ = true;
}

void Finale::densityFill(const char* rules_filename, const odb::Rect& fill_area)
{
  DensityFill filler(db_, logger_, debug_);
  filler.fill(rules_filename, fill_area);
}

}  // namespace fin
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <vector>

#include <kangaru/kangaru.hpp>

/**
 * This example explains moderate use of kangaru and it's components.
 * It covers providing instances to the container, self-injection
 */

using std::string;
using std::cout;
using std::endl;
using std::move;

struct WoodStack {
	int planks;
};

struct Product {
	Product(WoodStack& stack) {
		stack.planks--;
	}

	string name;
};

// This is our wood stack service definition
struct WoodStackService : kgr::SingleService<WoodStack> {};

// This is our product service definition
struct ProductService : kgr::Service<Product, kgr::Dependency<WoodStackService>> {};

struct Carpenter {
	Carpenter(kgr::Container& _container, WoodStack& _stack) : container{_container}, stack{_stack} {}

	// We are using ServiceType, which in this case is an alias to unique_ptr<Product>.
	void makeProduct(string name) {
		if (stack.planks > 0) {
			cout << "Another " << name << " made, but only " << stack.planks << " planks left!" << endl;

			auto product = container.service<ProductService>();
			product.name = name;

			products.emplace_back(move(product));
		} else {
			cout << "No planks left, no product made." << endl;
		}
	}

private:
	std::vector<Product> products;
	kgr::Container& container;
	WoodStack& stack;
};

// This is our carpenter service definition
struct CarpenterService : kgr::Service<Carpenter, kgr::Dependency<kgr::ContainerService, WoodStackService>> {};

int main()
{
	kgr::Container container;

	// We made the stack ourself and set the number of planks to 2
	WoodStack stack{2};

	// We are providing our stack instance to the container.
	container.instance<WoodStackService>(std::move(stack));

	// It has the Container and the WoodStack injected.
	auto gerald = container.service<CarpenterService>();

	// Will print: Another computer desk made, but only 1 planks left!
	gerald.makeProduct("computer desk");

	// Will print: Another chair made, but only 0 planks left!
	gerald.makeProduct("chair");

	// Will print: No planks left, no product made.
	// As a result, product3 is not made.
	gerald.makeProduct("table");
}
<commit_msg>Using emplace instead of instanciate<commit_after>#include <iostream>
#include <string>
#include <vector>

#include <kangaru/kangaru.hpp>

/**
 * This example explains moderate use of kangaru and it's components.
 * It covers providing instances to the container, self-injection
 */

using std::string;
using std::cout;
using std::endl;
using std::move;

struct WoodStack {
	int planks;
};

struct Product {
	Product(WoodStack& stack) {
		stack.planks--;
	}

	string name;
};

// This is our wood stack service definition
struct WoodStackService : kgr::SingleService<WoodStack> {};

// This is our product service definition
struct ProductService : kgr::Service<Product, kgr::Dependency<WoodStackService>> {};

struct Carpenter {
	Carpenter(kgr::Container& _container, WoodStack& _stack) : container{_container}, stack{_stack} {}

	// We are using ServiceType, which in this case is an alias to unique_ptr<Product>.
	void makeProduct(string name) {
		if (stack.planks > 0) {
			cout << "Another " << name << " made, but only " << stack.planks << " planks left!" << endl;

			auto product = container.service<ProductService>();
			product.name = name;

			products.emplace_back(move(product));
		} else {
			cout << "No planks left, no product made." << endl;
		}
	}

private:
	std::vector<Product> products;
	kgr::Container& container;
	WoodStack& stack;
};

// This is our carpenter service definition
struct CarpenterService : kgr::Service<Carpenter, kgr::Dependency<kgr::ContainerService, WoodStackService>> {};

int main()
{
	kgr::Container container;

	// We made the stack ourself and set the number of planks to 2
	container.emplace<WoodStackService>(2);

	// It has the Container and the WoodStack injected.
	auto gerald = container.service<CarpenterService>();

	// Will print: Another computer desk made, but only 1 planks left!
	gerald.makeProduct("computer desk");

	// Will print: Another chair made, but only 0 planks left!
	gerald.makeProduct("chair");

	// Will print: No planks left, no product made.
	// As a result, product3 is not made.
	gerald.makeProduct("table");
}
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <memory>

#include "kangaru.hpp"

/**
 * This example explains moderate use of kangaru and it's components.
 * It covers providing instances to the container, self-injection
 */

using namespace std;
using namespace kgr;

struct WoodStack {
	int planks;
};

struct Product {
	Product(WoodStack* stack) {
		stack->planks--;
	}

	string name;
};

// This is our wood stack service definitions
struct WoodStackService : Type<WoodStack*>, Single {
	WoodStackService(shared_ptr<WoodStack> instance) : _instance{move(instance)} {}

	static WoodStackService construct() {
		return make_shared<WoodStack>();
	}

	ServiceType forward() {
		return _instance.get();
	}

private:
	shared_ptr<WoodStack> _instance;
};

// This is our product service definitions
struct ProductService : Type<unique_ptr<Product>> {
	ProductService(unique_ptr<Product> instance) : _instance{move(instance)} {}

	static ProductService construct(WoodStackService& stack) {
		return unique_ptr<Product>(new Product{stack.forward()});
	}

	ServiceType forward() {
		return move(_instance);
	}

private:
	unique_ptr<Product> _instance;
};

struct Carpenter {
	Carpenter(Container& _container, WoodStack* _stack) : container{&_container}, stack{_stack} {}

	// We are using ServiceType, which in this case is an alias to unique_ptr<Product>.
	// Since the pointer type can be changed, using only unique_ptr here may be wrong.
	ProductService::ServiceType makeProduct(string name) {
		if (stack->planks > 0) {
			cout << "Another " << name << " made, but only " << stack->planks << " planks left!" << endl;

			auto product = container->service<ProductService>();
			product->name = name;

			return product;
		}

		cout << "No planks left, no product made." << endl;
		return nullptr;
	}

private:
	Container* container;
	WoodStack* stack;
};

// This is our carpenter service definitions
struct CarpenterService : Type<Carpenter> {
	CarpenterService(Carpenter instance) : _instance{move(instance)} {}

	static CarpenterService construct(ContainerService container, WoodStackService& stack) {
		return Carpenter{container.forward(), stack.forward()};
	}

	ServiceType forward() {
		return move(_instance);
	}

private:
	Carpenter _instance;
};

int main()
{
	auto container = make_container();

	// We made the stack ourself and set the number of planks to 2
	auto stack = make_shared<WoodStack>();

	// We are providing our stack instance to the container.
	container.instance(WoodStackService{stack});

	stack->planks = 2;

	// It has the Container and the WoodStack injected.
	auto gerald = container.service<CarpenterService>();

	// Will print: Another computer desk made, but only 1 planks left!
	auto product1 = gerald.makeProduct("computer desk");

	// Will print: Another chair made, but only 0 planks left!
	auto product2 = gerald.makeProduct("chair");

	// Will print: No planks left, no product made.
	// As a result, product3 is null.
	auto product3 = gerald.makeProduct("table");

	if (!product3) {
		cout << "There's definitely no product made!" << endl;
	}

	return 0;
}
<commit_msg>removed Type<commit_after>#include <iostream>
#include <string>
#include <memory>

#include "kangaru.hpp"

/**
 * This example explains moderate use of kangaru and it's components.
 * It covers providing instances to the container, self-injection
 */

using namespace std;
using namespace kgr;

struct WoodStack {
	int planks;
};

struct Product {
	Product(WoodStack* stack) {
		stack->planks--;
	}

	string name;
};

// This is our wood stack service definitions
struct WoodStackService : Single {
	WoodStackService(shared_ptr<WoodStack> instance) : _instance{move(instance)} {}

	static WoodStackService construct() {
		return make_shared<WoodStack>();
	}

	WoodStack* forward() {
		return _instance.get();
	}

private:
	shared_ptr<WoodStack> _instance;
};

// This is our product service definitions
struct ProductService {
	ProductService(unique_ptr<Product> instance) : _instance{move(instance)} {}

	static ProductService construct(WoodStackService& stack) {
		return unique_ptr<Product>(new Product{stack.forward()});
	}

	unique_ptr<Product> forward() {
		return move(_instance);
	}

private:
	unique_ptr<Product> _instance;
};

struct Carpenter {
	Carpenter(Container& _container, WoodStack* _stack) : container{&_container}, stack{_stack} {}

	// We are using ServiceType, which in this case is an alias to unique_ptr<Product>.
	// Since the pointer type can be changed, using only unique_ptr here may be wrong.
	ServiceType<ProductService> makeProduct(string name) {
		if (stack->planks > 0) {
			cout << "Another " << name << " made, but only " << stack->planks << " planks left!" << endl;

			auto product = container->service<ProductService>();
			product->name = name;

			return product;
		}

		cout << "No planks left, no product made." << endl;
		return nullptr;
	}

private:
	Container* container;
	WoodStack* stack;
};

// This is our carpenter service definitions
struct CarpenterService {
	CarpenterService(Carpenter instance) : _instance{move(instance)} {}

	static CarpenterService construct(ContainerService container, WoodStackService& stack) {
		return Carpenter{container.forward(), stack.forward()};
	}

	Carpenter forward() {
		return move(_instance);
	}

private:
	Carpenter _instance;
};

int main()
{
	auto container = make_container();

	// We made the stack ourself and set the number of planks to 2
	auto stack = make_shared<WoodStack>();

	// We are providing our stack instance to the container.
	container.instance(WoodStackService{stack});

	stack->planks = 2;

	// It has the Container and the WoodStack injected.
	auto gerald = container.service<CarpenterService>();

	// Will print: Another computer desk made, but only 1 planks left!
	auto product1 = gerald.makeProduct("computer desk");

	// Will print: Another chair made, but only 0 planks left!
	auto product2 = gerald.makeProduct("chair");

	// Will print: No planks left, no product made.
	// As a result, product3 is null.
	auto product3 = gerald.makeProduct("table");

	if (!product3) {
		cout << "There's definitely no product made!" << endl;
	}

	return 0;
}
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_tools.hxx"
#include <tools/iparser.hxx>
#include <tools/geninfo.hxx>
#include "bootstrp/appdef.hxx"
#include <stdio.h>

/*****************************************************************************/
#ifdef UNX
int main( int argc, char *argv[] )
#else
int _cdecl main( int argc, char *argv[] )
#endif
/*****************************************************************************/
{
    if ( argc == 1 ) {
        fprintf( stdout, "\ni_server.exe v2.0 (c) 2000\n\n" );
        fprintf( stdout, "Syntax:  i_server -i accesspath [-l] [-d database] \n" );
        fprintf( stdout, "Example: - i_server -i vcl364/settings/now\n" );
        fprintf( stdout, "           returns value of settings \"now\" of version \"vcl364\"\n" );
        fprintf( stdout, "         - i_server -i vcl364/settings -l\n" );
        fprintf( stdout, "           returns a list of all settings of version \"vcl364\"\n" );
    }
    else {
        BOOL bError = FALSE;
        BOOL bList = FALSE;
        ByteString sInfo( "" );
        ByteString sDataBase( GetDefStandList());

        BOOL bGetNow = FALSE;

        int nCount = 1;
        while (( nCount < argc ) &&
            ( !bError ))
        {
            if ( ByteString( argv[nCount] ).ToUpperAscii() == "-I" ) {
                // requestet info path
                nCount++;
                if( nCount < argc ) {
                    sInfo = ByteString( argv[nCount] );
                    nCount++;
                }
                else bError = TRUE;
            }
            else if ( ByteString( argv[nCount] ).ToUpperAscii() == "-D" ) {
                // requestet info path
                nCount++;
                if( nCount < argc ) {
                    sDataBase = ByteString( argv[nCount] );
                    nCount++;
                }
                else bError = TRUE;
            }
            else if ( ByteString( argv[nCount] ).ToUpperAscii() == "-L" ) {
                // request list of childs
                nCount++;
                bList = TRUE;
            }
            else if ( ByteString( argv[nCount] ).ToUpperAscii() == "-N" ) {
                // request list of childs
                nCount++;
                bGetNow = TRUE;
            }
            else {
                bError = TRUE;
            }
        }

        if ( !bError ) {
            InformationParser aParser( REPLACE_VARIABLES );
            ByteString sStandList( sDataBase );
            String s = String( sStandList, gsl_getSystemTextEncoding());
            GenericInformationList *pList = aParser.Execute( s );
            if ( !pList )
                return 1;

            if ( sInfo.Len()) {
                GenericInformation *pInfo = pList->GetInfo( sInfo, TRUE );

                if ( pInfo ) {
                    ByteString sValue( pInfo->GetValue());
                    // show the info and its value
                    fprintf( stdout, "%s %s\n", pInfo->GetBuffer(), sValue.GetBuffer());
                    if ( bList ) {
                        GenericInformationList *pList = pInfo->GetSubList();
                        if ( pList ) {
                            // show whole list of childs and their values
                            for( ULONG i = 0; i < pList->Count(); i++ ) {
                                GenericInformation *pInfo = pList->GetObject( i );
                                ByteString sValue( pInfo->GetValue());
                                fprintf( stdout, "    %s %s\n", pInfo->GetBuffer(), sValue.GetBuffer());
                            }
                        }
                    }
                    return 0;
                }
                return 1;
            }
            else {
                // show whole list of childs and their values
                for( ULONG i = 0; i < pList->Count(); i++ ) {
                    GenericInformation *pInfo = pList->GetObject( i );
                    if ( bGetNow ) {
                        ByteString sPath( "settings/now" );
                        GenericInformation *pSubInfo = pInfo->GetSubInfo( sPath, TRUE );
                        if ( pSubInfo && pSubInfo->GetValue() == "_TRUE" )
                            fprintf( stdout, "%s\n", pInfo->GetBuffer());
                    }
                    else {
                        ByteString sValue( pInfo->GetValue());
                        fprintf( stdout, "    %s %s\n", pInfo->GetBuffer(), sValue.GetBuffer());
                    }
                }
                return 0;
            }
        }
        else
            fprintf( stderr, "%s: Fehler in der Kommandozeile!", argv[0] );
            // command line arror !!!
    }

    return 1;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Removed an uncompiled file<commit_after><|endoftext|>


<commit_before>/*
 * Copyright (C) 2014 Luke San Antonio
 * All rights reserved.
 */
#include "program.h"
#include <sstream>
#include <fstream>
#include "../../common/log.h"
namespace survive
{
  namespace gfx
  {
    namespace gl
    {
      std::string load_stream(std::istream&& stream) noexcept
      {
        std::string ret;
        while(!stream.eof() && stream.good())
        {
          ret.push_back(stream.get());
        }
        return ret;
      }

      void compile_shader(GLuint shade, std::string const& data)
      {
        int len = data.size();
        auto data_cstr = data.data();
        glShaderSource(shade, 1, &data_cstr, &len);

        glCompileShader(shade);

        GLint result = 0;
        glGetShaderiv(shade, GL_COMPILE_STATUS, &result);
        if(result == GL_FALSE)
        {
          // Compilation failed.
          constexpr size_t info_log_length = 2048;
          auto info_log = new char[info_log_length];

          glGetShaderInfoLog(shade, info_log_length - 1, NULL, info_log);

          info_log[info_log_length - 1] = '\0';
          log_e("Shader compilation failed (info log):\n%", info_log);

          delete[] info_log;
        }
      }

      Program Program::from_contents(std::string v, std::string f) noexcept
      {
        auto program = Program{};
        program.vshade = glCreateShader(GL_VERTEX_SHADER);
        program.fshade = glCreateShader(GL_FRAGMENT_SHADER);

        compile_shader(program.vshade, v);
        compile_shader(program.fshade, f);

        program.program = glCreateProgram();
        glAttachShader(program.program, program.vshade);
        glAttachShader(program.program, program.fshade);
        glLinkProgram(program.program);

        GLint result = GL_FALSE;
        glGetProgramiv(program.program, GL_LINK_STATUS, &result);
        if(result == GL_FALSE)
        {
          // Compilation failed.
          constexpr size_t info_log_length = 2048;
          auto info_log = new char[info_log_length];

          glGetProgramInfoLog(program.program, info_log_length - 1, NULL,
                              info_log);

          info_log[info_log_length - 1] = '\0';
          log_e("Program linking failed (info log):\n%", info_log);

          delete[] info_log;
        }

        return program;
      }

      Program Program::from_streams(std::istream&& v, std::istream&& f) noexcept
      {
        return Program::from_contents(load_stream(std::move(v)),
                                      load_stream(std::move(f)));
      }
      Program Program::from_files(std::string vs, std::string fs) noexcept
      {
        std::ifstream vsfile{vs};
        std::ifstream fsfile{fs};
        return Program::from_streams(std::move(vsfile), std::move(fsfile));
      }
      void Program::use() noexcept
      {
        glUseProgram(program);
      }
      GLint Program::get_uniform_location(std::string n) noexcept
      {
        return glGetUniformLocation(program, n.data());
      }
      Program::Program(Program&& p1) noexcept
                       : vshade(p1.vshade), fshade(p1.fshade),
                         program(p1.program)
      {
        p1.vshade = 0;
        p1.fshade = 0;
        p1.program = 0;
      }
      Program& Program::operator=(Program&& p1) noexcept
      {
        vshade = p1.vshade;
        fshade = p1.fshade;
        program = p1.program;

        p1.vshade = 0;
        p1.fshade = 0;
        p1.program = 0;

        return *this;
      }
      Program::~Program() noexcept
      {
  #ifndef SURVIVE_RELEASE_BUILD
        GLint current_program;
        glGetIntegerv(GL_CURRENT_PROGRAM, &current_program);
        if(static_cast<GLuint>(current_program) == program)
        {
          log_w("% (Shader program) destructed while in use;"
                "Removing binding", name);
          glUseProgram(0);
        }
  #endif

        if(program) glDeleteProgram(program);
        if(fshade) glDeleteProgram(fshade);
        if(vshade) glDeleteProgram(vshade);
      }
    }
  }
}
<commit_msg>Changed the warning string in the Program destructor.<commit_after>/*
 * Copyright (C) 2014 Luke San Antonio
 * All rights reserved.
 */
#include "program.h"
#include <sstream>
#include <fstream>
#include "../../common/log.h"
namespace survive
{
  namespace gfx
  {
    namespace gl
    {
      std::string load_stream(std::istream&& stream) noexcept
      {
        std::string ret;
        while(!stream.eof() && stream.good())
        {
          ret.push_back(stream.get());
        }
        return ret;
      }

      void compile_shader(GLuint shade, std::string const& data)
      {
        int len = data.size();
        auto data_cstr = data.data();
        glShaderSource(shade, 1, &data_cstr, &len);

        glCompileShader(shade);

        GLint result = 0;
        glGetShaderiv(shade, GL_COMPILE_STATUS, &result);
        if(result == GL_FALSE)
        {
          // Compilation failed.
          constexpr size_t info_log_length = 2048;
          auto info_log = new char[info_log_length];

          glGetShaderInfoLog(shade, info_log_length - 1, NULL, info_log);

          info_log[info_log_length - 1] = '\0';
          log_e("Shader compilation failed (info log):\n%", info_log);

          delete[] info_log;
        }
      }

      Program Program::from_contents(std::string v, std::string f) noexcept
      {
        auto program = Program{};
        program.vshade = glCreateShader(GL_VERTEX_SHADER);
        program.fshade = glCreateShader(GL_FRAGMENT_SHADER);

        compile_shader(program.vshade, v);
        compile_shader(program.fshade, f);

        program.program = glCreateProgram();
        glAttachShader(program.program, program.vshade);
        glAttachShader(program.program, program.fshade);
        glLinkProgram(program.program);

        GLint result = GL_FALSE;
        glGetProgramiv(program.program, GL_LINK_STATUS, &result);
        if(result == GL_FALSE)
        {
          // Compilation failed.
          constexpr size_t info_log_length = 2048;
          auto info_log = new char[info_log_length];

          glGetProgramInfoLog(program.program, info_log_length - 1, NULL,
                              info_log);

          info_log[info_log_length - 1] = '\0';
          log_e("Program linking failed (info log):\n%", info_log);

          delete[] info_log;
        }

        return program;
      }

      Program Program::from_streams(std::istream&& v, std::istream&& f) noexcept
      {
        return Program::from_contents(load_stream(std::move(v)),
                                      load_stream(std::move(f)));
      }
      Program Program::from_files(std::string vs, std::string fs) noexcept
      {
        std::ifstream vsfile{vs};
        std::ifstream fsfile{fs};
        return Program::from_streams(std::move(vsfile), std::move(fsfile));
      }
      void Program::use() noexcept
      {
        glUseProgram(program);
      }
      GLint Program::get_uniform_location(std::string n) noexcept
      {
        return glGetUniformLocation(program, n.data());
      }
      Program::Program(Program&& p1) noexcept
                       : vshade(p1.vshade), fshade(p1.fshade),
                         program(p1.program)
      {
        p1.vshade = 0;
        p1.fshade = 0;
        p1.program = 0;
      }
      Program& Program::operator=(Program&& p1) noexcept
      {
        vshade = p1.vshade;
        fshade = p1.fshade;
        program = p1.program;

        p1.vshade = 0;
        p1.fshade = 0;
        p1.program = 0;

        return *this;
      }
      Program::~Program() noexcept
      {
  #ifndef SURVIVE_RELEASE_BUILD
        GLint current_program;
        glGetIntegerv(GL_CURRENT_PROGRAM, &current_program);
        if(static_cast<GLuint>(current_program) == program)
        {
          log_w("'%' (Shader program) destructed while in use; "
                "Removing binding", name);
          glUseProgram(0);
        }
  #endif

        if(program) glDeleteProgram(program);
        if(fshade) glDeleteProgram(fshade);
        if(vshade) glDeleteProgram(vshade);
      }
    }
  }
}
<|endoftext|>


<commit_before>//------------------------------------------------------------------------------
//  CoreGameState.cc
//  (C) 2013-2015 Individual contributors, see AUTHORS file
//------------------------------------------------------------------------------
#include "stdneb.h"
#include "Coregamestate.h"
#include "graphicsfeatureunit.h"
#include "input/keyboard.h"
#include "coreproject/coregameapplication.h"

namespace Tools
{
__ImplementClass(Tools::CoreGameState, 'CMGS', BaseGameFeature::GameStateHandler);

using namespace BaseGameFeature;
using namespace GraphicsFeature;
using namespace Util;
using namespace Math;

//------------------------------------------------------------------------------
/**
*/
CoreGameState::CoreGameState()
{
	// empty
}

//------------------------------------------------------------------------------
/**
*/
CoreGameState::~CoreGameState()
{
	// empty
}

//------------------------------------------------------------------------------
/**
*/
void
CoreGameState::OnStateEnter( const Util::String& prevState )
{
	GameStateHandler::OnStateEnter(prevState);
	this->focusset = false;
	//const Ptr<UI::UiLayout>& layout = UI::UiFeatureUnit::Instance()->GetLayout("main_menu");
	//Ptr<UI::UiElement> element = layout->GetElement("updatetext");
	//return element->GetText();
}

//------------------------------------------------------------------------------
/**
*/
void
CoreGameState::OnStateLeave( const Util::String& nextState )
{
	GameStateHandler::OnStateLeave(nextState);
}

//------------------------------------------------------------------------------
/**
*/
Util::String
CoreGameState::OnFrame()
{
	//handle all user input
	if (Input::InputServer::HasInstance())
	{
		this->HandleInput();
	}
	return GameStateHandler::OnFrame();
}

//------------------------------------------------------------------------------
/**
*/
void
CoreGameState::OnLoadBefore()
{

}

//------------------------------------------------------------------------------
/**
*/
void
CoreGameState::OnLoadAfter()
{

}

void CoreGameState::OnNetworkStarted()
{

}

	//------------------------------------------------------------------------------
/**
*/
void
CoreGameState::HandleInput()
{
	const Ptr<Input::Keyboard>& kbd = Input::InputServer::Instance()->GetDefaultKeyboard();

	if (kbd->KeyPressed(Input::Key::H))
	{
		this->player = FactoryManager::Instance()->CreateEntityByTemplate("Player", "dummychar");
		EntityManager::Instance()->AttachEntity(this->player);
		FocusManager::Instance()->SetCameraFocusEntity(this->player, false);
		FocusManager::Instance()->SetInputFocusEntity(this->player, false);
	}
	if(kbd->KeyPressed(Input::Key::J))
	{
		if (player != NULL)
		{
			FocusManager::Instance()->SetCameraFocusEntity(this->player, false);
			FocusManager::Instance()->SetInputFocusEntity(this->player, false);
		}
	}

}
} // namespace Tools<commit_msg>Spawn fix<commit_after>//------------------------------------------------------------------------------
//  CoreGameState.cc
//  (C) 2013-2015 Individual contributors, see AUTHORS file
//------------------------------------------------------------------------------
#include "stdneb.h"
#include "Coregamestate.h"
#include "graphicsfeatureunit.h"
#include "input/keyboard.h"
#include "coreproject/coregameapplication.h"

namespace Tools
{
__ImplementClass(Tools::CoreGameState, 'CMGS', BaseGameFeature::GameStateHandler);

using namespace BaseGameFeature;
using namespace GraphicsFeature;
using namespace Util;
using namespace Math;

//------------------------------------------------------------------------------
/**
*/
CoreGameState::CoreGameState()
{
	// empty
}

//------------------------------------------------------------------------------
/**
*/
CoreGameState::~CoreGameState()
{
	// empty
}

//------------------------------------------------------------------------------
/**
*/
void
CoreGameState::OnStateEnter( const Util::String& prevState )
{
	GameStateHandler::OnStateEnter(prevState);
	this->focusset = false;
	//const Ptr<UI::UiLayout>& layout = UI::UiFeatureUnit::Instance()->GetLayout("main_menu");
	//Ptr<UI::UiElement> element = layout->GetElement("updatetext");
	//return element->GetText();
}

//------------------------------------------------------------------------------
/**
*/
void
CoreGameState::OnStateLeave( const Util::String& nextState )
{
	GameStateHandler::OnStateLeave(nextState);
}

//------------------------------------------------------------------------------
/**
*/
Util::String
CoreGameState::OnFrame()
{
	//handle all user input
	if (Input::InputServer::HasInstance())
	{
		this->HandleInput();
	}
	return GameStateHandler::OnFrame();
}

//------------------------------------------------------------------------------
/**
*/
void
CoreGameState::OnLoadBefore()
{

}

//------------------------------------------------------------------------------
/**
*/
void
CoreGameState::OnLoadAfter()
{

}

void CoreGameState::OnNetworkStarted()
{

}

	//------------------------------------------------------------------------------
/**
*/
void
CoreGameState::HandleInput()
{
	const Ptr<Input::Keyboard>& kbd = Input::InputServer::Instance()->GetDefaultKeyboard();

	if (kbd->KeyDown(Input::Key::H))
	{
		this->player = FactoryManager::Instance()->CreateEntityByTemplate("Player", "dummychar");
		EntityManager::Instance()->AttachEntity(this->player);
		FocusManager::Instance()->SetCameraFocusEntity(this->player, false);
		FocusManager::Instance()->SetInputFocusEntity(this->player, false);
	}
	if (kbd->KeyDown(Input::Key::J))
	{
		if (player != NULL)
		{
			FocusManager::Instance()->SetCameraFocusEntity(this->player, false);
			FocusManager::Instance()->SetInputFocusEntity(this->player, false);
		}
	}

}
} // namespace Tools<|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/views/tab_contents/native_tab_contents_view_aura.h"

#include "chrome/browser/tab_contents/web_drop_target_win.h"
#include "chrome/browser/ui/views/tab_contents/native_tab_contents_view_delegate.h"
#include "chrome/browser/ui/views/tab_contents/native_tab_contents_view_views.h"
#include "content/browser/renderer_host/render_widget_host_view_aura.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/browser/tab_contents/tab_contents_view.h"
#include "ui/aura/event.h"
#include "ui/aura/window.h"
#include "views/views_delegate.h"
#include "views/widget/widget.h"

////////////////////////////////////////////////////////////////////////////////
// NativeTabContentsViewAura, public:

NativeTabContentsViewAura::NativeTabContentsViewAura(
    internal::NativeTabContentsViewDelegate* delegate)
    : views::NativeWidgetAura(delegate->AsNativeWidgetDelegate()),
      delegate_(delegate) {
}

NativeTabContentsViewAura::~NativeTabContentsViewAura() {
}

TabContents* NativeTabContentsViewAura::GetTabContents() const {
  return delegate_->GetTabContents();
}

void NativeTabContentsViewAura::EndDragging() {
  delegate_->OnNativeTabContentsViewDraggingEnded();
  // TODO(beng):
  NOTIMPLEMENTED();
}

////////////////////////////////////////////////////////////////////////////////
// NativeTabContentsViewAura, NativeTabContentsView implementation:

void NativeTabContentsViewAura::InitNativeTabContentsView() {
  views::Widget::InitParams params(views::Widget::InitParams::TYPE_CONTROL);
  params.native_widget = this;
  params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
  params.parent = NULL;
  GetWidget()->Init(params);
}

void NativeTabContentsViewAura::Unparent() {
  // Note that we do not DCHECK on focus_manager_ as it may be NULL when used
  // with an external tab container.
  views::Widget::ReparentNativeView(GetNativeView(), NULL);
  // TODO(beng):
  NOTIMPLEMENTED();
}

RenderWidgetHostView* NativeTabContentsViewAura::CreateRenderWidgetHostView(
    RenderWidgetHost* render_widget_host) {
  RenderWidgetHostViewAura* view =
      new RenderWidgetHostViewAura(render_widget_host);
  view->Init();
  GetNativeView()->AddChild(view->GetNativeView());
  view->Show();
  return view;
}

gfx::NativeWindow NativeTabContentsViewAura::GetTopLevelNativeWindow() const {
  // TODO(beng):
  NOTIMPLEMENTED();
  return NULL;
}

void NativeTabContentsViewAura::SetPageTitle(const string16& title) {
  // TODO(beng):
  NOTIMPLEMENTED();
}

void NativeTabContentsViewAura::StartDragging(const WebDropData& drop_data,
                                             WebKit::WebDragOperationsMask ops,
                                             const SkBitmap& image,
                                             const gfx::Point& image_offset) {
  // TODO(beng):
  NOTIMPLEMENTED();
}

void NativeTabContentsViewAura::CancelDrag() {
  // TODO(beng):
  NOTIMPLEMENTED();
}

bool NativeTabContentsViewAura::IsDoingDrag() const {
  // TODO(beng):
  NOTIMPLEMENTED();
  return false;
}

void NativeTabContentsViewAura::SetDragCursor(
    WebKit::WebDragOperation operation) {
  // TODO(beng):
  NOTIMPLEMENTED();
}

views::NativeWidget* NativeTabContentsViewAura::AsNativeWidget() {
  return this;
}

////////////////////////////////////////////////////////////////////////////////
// NativeTabContentsViewAura, views::NativeWidgetAura overrides:

void NativeTabContentsViewAura::OnBoundsChanged(const gfx::Rect& old_bounds,
                                                const gfx::Rect& new_bounds) {
  delegate_->OnNativeTabContentsViewSized(new_bounds.size());
  views::NativeWidgetAura::OnBoundsChanged(old_bounds, new_bounds);
}

bool NativeTabContentsViewAura::OnMouseEvent(aura::MouseEvent* event) {
  if (!delegate_->IsShowingSadTab()) {
    switch (event->type()) {
      case ui::ET_MOUSE_EXITED:
        delegate_->OnNativeTabContentsViewMouseMove(false);
        break;
      case ui::ET_MOUSE_MOVED:
        delegate_->OnNativeTabContentsViewMouseMove(true);
        break;
      default:
        // TODO(oshima): mouse wheel
        break;
    }
  }
  // Pass all mouse event to renderer.
  return views::NativeWidgetAura::OnMouseEvent(event);
}

////////////////////////////////////////////////////////////////////////////////
// NativeTabContentsView, public:

// static
NativeTabContentsView* NativeTabContentsView::CreateNativeTabContentsView(
    internal::NativeTabContentsViewDelegate* delegate) {
  return new NativeTabContentsViewViews(delegate);
  // TODO(beng): switch over to this.
  // return new NativeTabContentsViewAura(delegate);
}
<commit_msg>Fix aura bustage. Was part of earlier CL but not included in CL for some reason.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/views/tab_contents/native_tab_contents_view_aura.h"

#include "chrome/browser/ui/views/tab_contents/native_tab_contents_view_delegate.h"
#include "chrome/browser/ui/views/tab_contents/native_tab_contents_view_views.h"
#include "content/browser/renderer_host/render_widget_host_view_aura.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/browser/tab_contents/tab_contents_view.h"
#include "ui/aura/event.h"
#include "ui/aura/window.h"
#include "views/views_delegate.h"
#include "views/widget/widget.h"

////////////////////////////////////////////////////////////////////////////////
// NativeTabContentsViewAura, public:

NativeTabContentsViewAura::NativeTabContentsViewAura(
    internal::NativeTabContentsViewDelegate* delegate)
    : views::NativeWidgetAura(delegate->AsNativeWidgetDelegate()),
      delegate_(delegate) {
}

NativeTabContentsViewAura::~NativeTabContentsViewAura() {
}

TabContents* NativeTabContentsViewAura::GetTabContents() const {
  return delegate_->GetTabContents();
}

void NativeTabContentsViewAura::EndDragging() {
  delegate_->OnNativeTabContentsViewDraggingEnded();
  // TODO(beng):
  NOTIMPLEMENTED();
}

////////////////////////////////////////////////////////////////////////////////
// NativeTabContentsViewAura, NativeTabContentsView implementation:

void NativeTabContentsViewAura::InitNativeTabContentsView() {
  views::Widget::InitParams params(views::Widget::InitParams::TYPE_CONTROL);
  params.native_widget = this;
  params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
  params.parent = NULL;
  GetWidget()->Init(params);
}

void NativeTabContentsViewAura::Unparent() {
  // Note that we do not DCHECK on focus_manager_ as it may be NULL when used
  // with an external tab container.
  views::Widget::ReparentNativeView(GetNativeView(), NULL);
  // TODO(beng):
  NOTIMPLEMENTED();
}

RenderWidgetHostView* NativeTabContentsViewAura::CreateRenderWidgetHostView(
    RenderWidgetHost* render_widget_host) {
  RenderWidgetHostViewAura* view =
      new RenderWidgetHostViewAura(render_widget_host);
  view->Init();
  GetNativeView()->AddChild(view->GetNativeView());
  view->Show();
  return view;
}

gfx::NativeWindow NativeTabContentsViewAura::GetTopLevelNativeWindow() const {
  // TODO(beng):
  NOTIMPLEMENTED();
  return NULL;
}

void NativeTabContentsViewAura::SetPageTitle(const string16& title) {
  // TODO(beng):
  NOTIMPLEMENTED();
}

void NativeTabContentsViewAura::StartDragging(const WebDropData& drop_data,
                                             WebKit::WebDragOperationsMask ops,
                                             const SkBitmap& image,
                                             const gfx::Point& image_offset) {
  // TODO(beng):
  NOTIMPLEMENTED();
}

void NativeTabContentsViewAura::CancelDrag() {
  // TODO(beng):
  NOTIMPLEMENTED();
}

bool NativeTabContentsViewAura::IsDoingDrag() const {
  // TODO(beng):
  NOTIMPLEMENTED();
  return false;
}

void NativeTabContentsViewAura::SetDragCursor(
    WebKit::WebDragOperation operation) {
  // TODO(beng):
  NOTIMPLEMENTED();
}

views::NativeWidget* NativeTabContentsViewAura::AsNativeWidget() {
  return this;
}

////////////////////////////////////////////////////////////////////////////////
// NativeTabContentsViewAura, views::NativeWidgetAura overrides:

void NativeTabContentsViewAura::OnBoundsChanged(const gfx::Rect& old_bounds,
                                                const gfx::Rect& new_bounds) {
  delegate_->OnNativeTabContentsViewSized(new_bounds.size());
  views::NativeWidgetAura::OnBoundsChanged(old_bounds, new_bounds);
}

bool NativeTabContentsViewAura::OnMouseEvent(aura::MouseEvent* event) {
  if (!delegate_->IsShowingSadTab()) {
    switch (event->type()) {
      case ui::ET_MOUSE_EXITED:
        delegate_->OnNativeTabContentsViewMouseMove(false);
        break;
      case ui::ET_MOUSE_MOVED:
        delegate_->OnNativeTabContentsViewMouseMove(true);
        break;
      default:
        // TODO(oshima): mouse wheel
        break;
    }
  }
  // Pass all mouse event to renderer.
  return views::NativeWidgetAura::OnMouseEvent(event);
}

////////////////////////////////////////////////////////////////////////////////
// NativeTabContentsView, public:

// static
NativeTabContentsView* NativeTabContentsView::CreateNativeTabContentsView(
    internal::NativeTabContentsViewDelegate* delegate) {
  return new NativeTabContentsViewViews(delegate);
  // TODO(beng): switch over to this.
  // return new NativeTabContentsViewAura(delegate);
}
<|endoftext|>