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

#include "StableHeaders.h"
#include "QtModule.h"
#include "OgreRenderingModule.h"

#include <QtUiTools>
#include <QFile>
#include <QHash>
#include <QMessageBox>

#include "LoginUI.h"

namespace RexLogic
{
    /////////////////////////////////////////
    // Login CLASS
    /////////////////////////////////////////

    Login::Login(Foundation::Framework *framework, RexLogicModule *rexLogicModule)
        : framework_(framework), rexLogicModule_(rexLogicModule)
    {
        InitUICanvas();
        InitLoginUI();
        InitLogoutUI();
    }

    Login::~Login(void)
    {
		if (qtModule_.get() && canvas_login_.get() && canvas_logout_.get())
        {
            qtModule_->DeleteCanvas(canvas_login_->GetID());
            qtModule_->DeleteCanvas(canvas_logout_->GetID());
        }
    }

	void Login::Show()
	{
		if (canvas_login_.get())
			canvas_login_->Show();
	}

	void Login::Hide()
	{
		if (canvas_login_.get())
			canvas_login_->Hide();
	}

	void Login::QuitApplication()
	{
		if (rexLogicModule_->GetServerConnection()->IsConnected())
			rexLogicModule_->LogoutAndDeleteWorld();
		framework_->Exit();
	}

    void Login::Connected()
    {
        canvas_login_->Hide();
        canvas_logout_->Show();
        AdjustWindowSize(canvas_login_->GetRenderWindowSize());

        if (qtModule_.get())
            qtModule_->SetShowControlBar(true);
    }

	void Login::Disconnect()
	{
        if (qtModule_.get())
            qtModule_->SetShowControlBar(false);

		if (rexLogicModule_->GetServerConnection()->IsConnected())
        {
			rexLogicModule_->LogoutAndDeleteWorld();
            canvas_logout_->Hide();
            canvas_login_->Show();
            AdjustWindowSize(canvas_logout_->GetRenderWindowSize());
        }
	}

    void Login::InitUICanvas()
    {
        // Get QtModule and create canvas
        qtModule_ = framework_->GetModuleManager()->GetModule<QtUI::QtModule>(Foundation::Module::MT_Gui).lock();
        if (!qtModule_.get())
            return;
        canvas_login_ = qtModule_->CreateCanvas(QtUI::UICanvas::Internal).lock();
        canvas_logout_ = qtModule_->CreateCanvas(QtUI::UICanvas::Internal).lock();
    }

    void Login::InitLoginUI()
    {
        tabWidget_ = new QTabWidget(0);
        tabWidget_->addTab((QWidget*)new WebUI(tabWidget_, this, framework_, rexLogicModule_), QString("Web Login"));
        tabWidget_->addTab((QWidget*)new NaaliUI(tabWidget_, this, framework_, rexLogicModule_), QString("Traditional Login"));

        QSize rendererWindowSize = canvas_login_->GetRenderWindowSize();
        tabWidget_->resize(rendererWindowSize.width(), rendererWindowSize.height());
		canvas_login_->SetSize(rendererWindowSize.width(), rendererWindowSize.height());
        canvas_login_->SetPosition(0, 0);
        canvas_login_->AddWidget(tabWidget_);
        canvas_login_->SetAlwaysOnTop(true);
        canvas_login_->SetStationary(true);
        canvas_login_->SetResizable(false);
		canvas_login_->Show();

        QObject::connect(canvas_login_.get(), SIGNAL( RenderWindowSizeChanged(const QSize&) ), this, SLOT( AdjustWindowSize(const QSize&) ));
    }

    void Login::InitLogoutUI()
    {
        QUiLoader loader;
        QFile uiFile("./data/ui/inworld_controls.ui");

        if ( uiFile.exists() )
        {
            // Load ui to widget from file and get buttons
            QWidget *inworldControls = loader.load(&uiFile);
            inworldControls->resize(150, 25);
            logout_button_ = inworldControls->findChild<QPushButton *>("pushButton_Logout");
            quit_button_ = inworldControls->findChild<QPushButton *>("pushButton_Quit");
            uiFile.close();

            // Create UICanvas
            QSize parentWindowSize = canvas_logout_->GetRenderWindowSize();
            canvas_logout_->SetPosition(parentWindowSize.width()-95, 0);
            canvas_logout_->SetSize(95, 25);
            canvas_logout_->SetResizable(false);
            canvas_logout_->SetStationary(true);
            canvas_logout_->SetAlwaysOnTop(true);

            // Connect signals
            QObject::connect(canvas_logout_.get(), SIGNAL( RenderWindowSizeChanged(const QSize&) ), this, SLOT( AdjustWindowSize(const QSize&) ));
            QObject::connect(logout_button_, SIGNAL( clicked() ), this, SLOT( Disconnect() ));
            QObject::connect(quit_button_, SIGNAL( clicked() ), this, SLOT( QuitApplication() ));

            // Add widget to canvas and hide it as long as we are inworld
            canvas_logout_->AddWidget(inworldControls);
            canvas_logout_->Hide();
        }
    }

	void Login::AdjustWindowSize(const QSize &newSize)
	{
        if ( !canvas_login_->IsHidden() )
        {
		    canvas_login_->SetSize(newSize.width(), newSize.height());
            canvas_login_->SetPosition(0,0);
            canvas_login_->BringToTop();
            canvas_login_->Redraw();
        }

        if ( !canvas_logout_->IsHidden() )
        {
            canvas_logout_->SetPosition(newSize.width()-95, 0);
            canvas_logout_->BringToTop();
            canvas_logout_->Redraw();
        }
	}

    /////////////////////////////////////////
    // ABSTRACT AbstractLoginUI CLASS
    /////////////////////////////////////////

	AbstractLoginUI::AbstractLoginUI(QWidget *parent, Login *controller, Foundation::Framework* framework, RexLogicModule *rexLogic)
		: QWidget(parent), controller_(controller), framework_(framework), rexLogicModule_(rexLogic), loginHandler_(0)
	{

	}

	void AbstractLoginUI::SetLayout()
	{
		this->setLayout(new QVBoxLayout());
		this->layout()->setMargin(0);
	}

	void AbstractLoginUI::Show()
	{
		this->show();
	}

	void AbstractLoginUI::Hide()
	{
		this->Hide();
	}

	void AbstractLoginUI::LoginDone(bool success)
	{
        // Do something if needed, canvas hides/shows are already handled
	}

    /////////////////////////////////////////
    // NaaliUI CLASS
    /////////////////////////////////////////

	NaaliUI::NaaliUI(QWidget *parent, Login *controller, Foundation::Framework* framework, RexLogicModule *rexLogic)
		: AbstractLoginUI(parent, controller, framework, rexLogic)
	{
		SetLayout();
		SetLoginHandler();
		InitWidget();
		ReadConfig();
		ShowSelectedMode();
	}

	NaaliUI::~NaaliUI()
	{
		delete loginHandler_;
	}

	void NaaliUI::SetLoginHandler()
	{
		loginHandler_ = new OpenSimLoginHandler(framework_, rexLogicModule_);
		QObject::connect(loginHandler_, SIGNAL( LoginDone(bool) ), this, SLOT( LoginDone(bool) ));
	}

	void NaaliUI::InitWidget()
	{
		QUiLoader loader;
        QFile uiFile("./data/ui/login_new.ui");
		internalWidget_ = loader.load(&uiFile, this);
		uiFile.close();

		radioButton_openSim_ = findChild<QRadioButton *>("radioButton_OpenSim");
		radioButton_realXtend_ = findChild<QRadioButton *>("radioButton_realXtend");
		pushButton_connect_ = findChild<QPushButton *>("pushButton_Connect");
		pushButton_close_ = findChild<QPushButton *>("pushButton_Close");
		label_authAddress_ = findChild<QLabel *>("label_AuthenticationServer");
		lineEdit_authAddress_ = findChild<QLineEdit *>("lineEdit_AuthenticationAddress");
		lineEdit_worldAddress_ = findChild<QLineEdit *>("lineEdit_WorldAddress");
		lineEdit_username_ = findChild<QLineEdit *>("lineEdit_Username");
		lineEdit_password_ = findChild<QLineEdit *>("lineEdit_Password");

		QObject::connect(radioButton_openSim_, SIGNAL( clicked() ), this, SLOT( ShowSelectedMode() ));
		QObject::connect(radioButton_realXtend_, SIGNAL( clicked() ), this, SLOT( ShowSelectedMode() ));
		QObject::connect(pushButton_connect_, SIGNAL( clicked() ), this, SLOT( ParseInputAndConnect() ));
		QObject::connect(pushButton_close_, SIGNAL( clicked() ), controller_, SLOT( QuitApplication() ));
		QObject::connect(this, SIGNAL( ConnectOpenSim(QMap<QString, QString>) ), loginHandler_, SLOT( ProcessOpenSimLogin(QMap<QString, QString>) ));
		QObject::connect(this, SIGNAL( ConnectRealXtend(QMap<QString, QString>) ), loginHandler_, SLOT( ProcessRealXtendLogin(QMap<QString, QString>) ));

		this->layout()->addWidget(internalWidget_);
	}

	void NaaliUI::ReadConfig()
	{
		// Recover the connection settings that were used in previous login
		// from the xml configuration file.
		QString value, configKey;
		QString configGroup("Login");

		configKey = QString("username");
		opensim_username_ = QString(framework_->GetDefaultConfigPtr()->GetSetting<std::string>(configGroup.toStdString(), configKey.toStdString()).c_str());
		lineEdit_username_->setText(opensim_username_);

		configKey = QString("auth_name");
		realXtend_username_ = QString(framework_->GetDefaultConfigPtr()->GetSetting<std::string>(configGroup.toStdString(), configKey.toStdString()).c_str());

	    configKey = QString("rex_server");
		realXtend_server_ = QString(framework_->GetDefaultConfigPtr()->GetSetting<std::string>(configGroup.toStdString(), configKey.toStdString()).c_str());

		configKey = QString("server");
		value = QString(framework_->GetDefaultConfigPtr()->GetSetting<std::string>(configGroup.toStdString(), configKey.toStdString()).c_str());
		lineEdit_worldAddress_->setText(value);
		opensim_server_ = value;

		configKey = QString("auth_server");
		value = QString(framework_->GetDefaultConfigPtr()->GetSetting<std::string>(configGroup.toStdString(), configKey.toStdString()).c_str());
		lineEdit_authAddress_->setText(value);
		realXtend_authserver_ = value;
	}

	void NaaliUI::ShowSelectedMode()
	{
		bool hide = false;
		if (radioButton_openSim_->isChecked() == true)
		{
			hide = false;
			if (lineEdit_username_->text() == realXtend_username_)
			    lineEdit_username_->setText(opensim_username_);
            if (lineEdit_worldAddress_->text() == realXtend_server_)
			    lineEdit_worldAddress_->setText(opensim_server_);
		}
		else if (radioButton_realXtend_->isChecked() == true)
		{
			hide = true;
			if (lineEdit_username_->text() == opensim_username_)
			    lineEdit_username_->setText(realXtend_username_);
            if (lineEdit_worldAddress_->text() == opensim_server_)
			    lineEdit_worldAddress_->setText(realXtend_server_);
		}
		label_authAddress_->setVisible(hide);
		lineEdit_authAddress_->setVisible(hide);
        lineEdit_password_->clear();
	}

	void NaaliUI::ParseInputAndConnect()
	{
		if ( !lineEdit_worldAddress_->text().isEmpty() &&
			 !lineEdit_username_->text().isEmpty() &&
			 !lineEdit_password_->text().isEmpty() )
		{
			QMap<QString, QString> map;
			map["WorldAddress"] = lineEdit_worldAddress_->text();
			map["Username"] = lineEdit_username_->text();
			map["Password"] = lineEdit_password_->text();
			if (radioButton_openSim_->isChecked() == true)
			{
				emit( ConnectOpenSim(map) );
			}
			else if (radioButton_realXtend_->isChecked() == true &&
					 !lineEdit_authAddress_->text().isEmpty() )
			{
				map["AuthenticationAddress"] = lineEdit_authAddress_->text();
				emit( ConnectRealXtend(map) );
			}
		}
	}

    /////////////////////////////////////////
    // WebUI CLASS
    /////////////////////////////////////////

	WebUI::WebUI(QWidget *parent, Login *controller, Foundation::Framework *framework, RexLogicModule *rexLogic)
		: AbstractLoginUI(parent, controller, framework, rexLogic)
	{
		SetLayout();
		SetLoginHandler();
		InitWidget();
	}

	WebUI::~WebUI()
	{
		delete loginHandler_;
	}

	void WebUI::SetLoginHandler()
	{
		loginHandler_ = new TaigaLoginHandler(framework_, rexLogicModule_);
		QObject::connect(loginHandler_, SIGNAL( LoginDone(bool) ), this, SLOT( LoginDone(bool) ));
	}

	void WebUI::InitWidget()
	{
		QFile confFile("./data/default_login.ini");
		if (!confFile.open(QIODevice::ReadOnly | QIODevice::Text))
			return;
		QString url(confFile.readLine());
		confFile.close();
		webLogin_ = new RexWebLogin(this, url);
		QObject::connect(webLogin_, SIGNAL( WebLoginInfoRecieved(QWebFrame *) ), loginHandler_, SLOT( ProcessWebLogin(QWebFrame *) ));
		this->layout()->addWidget(webLogin_);
	}

}<commit_msg>Removed not needed OgreRenderingModule include<commit_after>// For conditions of distribution and use, see copyright notice in license.txt

#include "StableHeaders.h"
#include "QtModule.h"
#include "RexLogicModule.h"

#include <QtUiTools>
#include <QFile>
#include <QHash>
#include <QMessageBox>

#include "LoginUI.h"

namespace RexLogic
{
    /////////////////////////////////////////
    // Login CLASS
    /////////////////////////////////////////

    Login::Login(Foundation::Framework *framework, RexLogicModule *rexLogicModule)
        : framework_(framework), rexLogicModule_(rexLogicModule)
    {
        InitUICanvas();
        InitLoginUI();
        InitLogoutUI();
    }

    Login::~Login(void)
    {
		if (qtModule_.get() && canvas_login_.get() && canvas_logout_.get())
        {
            qtModule_->DeleteCanvas(canvas_login_->GetID());
            qtModule_->DeleteCanvas(canvas_logout_->GetID());
        }
    }

	void Login::Show()
	{
		if (canvas_login_.get())
			canvas_login_->Show();
	}

	void Login::Hide()
	{
		if (canvas_login_.get())
			canvas_login_->Hide();
	}

	void Login::QuitApplication()
	{
		if (rexLogicModule_->GetServerConnection()->IsConnected())
			rexLogicModule_->LogoutAndDeleteWorld();
		framework_->Exit();
	}

    void Login::Connected()
    {
        canvas_login_->Hide();
        canvas_logout_->Show();
        AdjustWindowSize(canvas_login_->GetRenderWindowSize());

        if (qtModule_.get())
            qtModule_->SetShowControlBar(true);
    }

	void Login::Disconnect()
	{
        if (qtModule_.get())
            qtModule_->SetShowControlBar(false);

		if (rexLogicModule_->GetServerConnection()->IsConnected())
        {
			rexLogicModule_->LogoutAndDeleteWorld();
            canvas_logout_->Hide();
            canvas_login_->Show();
            AdjustWindowSize(canvas_logout_->GetRenderWindowSize());
        }
	}

    void Login::InitUICanvas()
    {
        // Get QtModule and create canvas
        qtModule_ = framework_->GetModuleManager()->GetModule<QtUI::QtModule>(Foundation::Module::MT_Gui).lock();
        if (!qtModule_.get())
            return;
        canvas_login_ = qtModule_->CreateCanvas(QtUI::UICanvas::Internal).lock();
        canvas_logout_ = qtModule_->CreateCanvas(QtUI::UICanvas::Internal).lock();
    }

    void Login::InitLoginUI()
    {
        tabWidget_ = new QTabWidget(0);
        tabWidget_->addTab((QWidget*)new WebUI(tabWidget_, this, framework_, rexLogicModule_), QString("Web Login"));
        tabWidget_->addTab((QWidget*)new NaaliUI(tabWidget_, this, framework_, rexLogicModule_), QString("Traditional Login"));

        QSize rendererWindowSize = canvas_login_->GetRenderWindowSize();
        tabWidget_->resize(rendererWindowSize.width(), rendererWindowSize.height());
		canvas_login_->SetSize(rendererWindowSize.width(), rendererWindowSize.height());
        canvas_login_->SetPosition(0, 0);
        canvas_login_->AddWidget(tabWidget_);
        canvas_login_->SetAlwaysOnTop(true);
        canvas_login_->SetStationary(true);
        canvas_login_->SetResizable(false);
		canvas_login_->Show();

        QObject::connect(canvas_login_.get(), SIGNAL( RenderWindowSizeChanged(const QSize&) ), this, SLOT( AdjustWindowSize(const QSize&) ));
    }

    void Login::InitLogoutUI()
    {
        QUiLoader loader;
        QFile uiFile("./data/ui/inworld_controls.ui");

        if ( uiFile.exists() )
        {
            // Load ui to widget from file and get buttons
            QWidget *inworldControls = loader.load(&uiFile);
            inworldControls->resize(150, 25);
            logout_button_ = inworldControls->findChild<QPushButton *>("pushButton_Logout");
            quit_button_ = inworldControls->findChild<QPushButton *>("pushButton_Quit");
            uiFile.close();

            // Create UICanvas
            QSize parentWindowSize = canvas_logout_->GetRenderWindowSize();
            canvas_logout_->SetPosition(parentWindowSize.width()-95, 0);
            canvas_logout_->SetSize(95, 25);
            canvas_logout_->SetResizable(false);
            canvas_logout_->SetStationary(true);
            canvas_logout_->SetAlwaysOnTop(true);

            // Connect signals
            QObject::connect(canvas_logout_.get(), SIGNAL( RenderWindowSizeChanged(const QSize&) ), this, SLOT( AdjustWindowSize(const QSize&) ));
            QObject::connect(logout_button_, SIGNAL( clicked() ), this, SLOT( Disconnect() ));
            QObject::connect(quit_button_, SIGNAL( clicked() ), this, SLOT( QuitApplication() ));

            // Add widget to canvas and hide it as long as we are inworld
            canvas_logout_->AddWidget(inworldControls);
            canvas_logout_->Hide();
        }
    }

	void Login::AdjustWindowSize(const QSize &newSize)
	{
        if ( !canvas_login_->IsHidden() )
        {
		    canvas_login_->SetSize(newSize.width(), newSize.height());
            canvas_login_->SetPosition(0,0);
            canvas_login_->BringToTop();
            canvas_login_->Redraw();
        }

        if ( !canvas_logout_->IsHidden() )
        {
            canvas_logout_->SetPosition(newSize.width()-95, 0);
            canvas_logout_->BringToTop();
            canvas_logout_->Redraw();
        }
	}

    /////////////////////////////////////////
    // ABSTRACT AbstractLoginUI CLASS
    /////////////////////////////////////////

	AbstractLoginUI::AbstractLoginUI(QWidget *parent, Login *controller, Foundation::Framework* framework, RexLogicModule *rexLogic)
		: QWidget(parent), controller_(controller), framework_(framework), rexLogicModule_(rexLogic), loginHandler_(0)
	{

	}

	void AbstractLoginUI::SetLayout()
	{
		this->setLayout(new QVBoxLayout());
		this->layout()->setMargin(0);
	}

	void AbstractLoginUI::Show()
	{
		this->show();
	}

	void AbstractLoginUI::Hide()
	{
		this->Hide();
	}

	void AbstractLoginUI::LoginDone(bool success)
	{
        // Do something if needed, canvas hides/shows are already handled
	}

    /////////////////////////////////////////
    // NaaliUI CLASS
    /////////////////////////////////////////

	NaaliUI::NaaliUI(QWidget *parent, Login *controller, Foundation::Framework* framework, RexLogicModule *rexLogic)
		: AbstractLoginUI(parent, controller, framework, rexLogic)
	{
		SetLayout();
		SetLoginHandler();
		InitWidget();
		ReadConfig();
		ShowSelectedMode();
	}

	NaaliUI::~NaaliUI()
	{
		delete loginHandler_;
	}

	void NaaliUI::SetLoginHandler()
	{
		loginHandler_ = new OpenSimLoginHandler(framework_, rexLogicModule_);
		QObject::connect(loginHandler_, SIGNAL( LoginDone(bool) ), this, SLOT( LoginDone(bool) ));
	}

	void NaaliUI::InitWidget()
	{
		QUiLoader loader;
        QFile uiFile("./data/ui/login_new.ui");
		internalWidget_ = loader.load(&uiFile, this);
		uiFile.close();

		radioButton_openSim_ = findChild<QRadioButton *>("radioButton_OpenSim");
		radioButton_realXtend_ = findChild<QRadioButton *>("radioButton_realXtend");
		pushButton_connect_ = findChild<QPushButton *>("pushButton_Connect");
		pushButton_close_ = findChild<QPushButton *>("pushButton_Close");
		label_authAddress_ = findChild<QLabel *>("label_AuthenticationServer");
		lineEdit_authAddress_ = findChild<QLineEdit *>("lineEdit_AuthenticationAddress");
		lineEdit_worldAddress_ = findChild<QLineEdit *>("lineEdit_WorldAddress");
		lineEdit_username_ = findChild<QLineEdit *>("lineEdit_Username");
		lineEdit_password_ = findChild<QLineEdit *>("lineEdit_Password");

		QObject::connect(radioButton_openSim_, SIGNAL( clicked() ), this, SLOT( ShowSelectedMode() ));
		QObject::connect(radioButton_realXtend_, SIGNAL( clicked() ), this, SLOT( ShowSelectedMode() ));
		QObject::connect(pushButton_connect_, SIGNAL( clicked() ), this, SLOT( ParseInputAndConnect() ));
		QObject::connect(pushButton_close_, SIGNAL( clicked() ), controller_, SLOT( QuitApplication() ));
		QObject::connect(this, SIGNAL( ConnectOpenSim(QMap<QString, QString>) ), loginHandler_, SLOT( ProcessOpenSimLogin(QMap<QString, QString>) ));
		QObject::connect(this, SIGNAL( ConnectRealXtend(QMap<QString, QString>) ), loginHandler_, SLOT( ProcessRealXtendLogin(QMap<QString, QString>) ));

		this->layout()->addWidget(internalWidget_);
	}

	void NaaliUI::ReadConfig()
	{
		// Recover the connection settings that were used in previous login
		// from the xml configuration file.
		QString value, configKey;
		QString configGroup("Login");

		configKey = QString("username");
		opensim_username_ = QString(framework_->GetDefaultConfigPtr()->GetSetting<std::string>(configGroup.toStdString(), configKey.toStdString()).c_str());
		lineEdit_username_->setText(opensim_username_);

		configKey = QString("auth_name");
		realXtend_username_ = QString(framework_->GetDefaultConfigPtr()->GetSetting<std::string>(configGroup.toStdString(), configKey.toStdString()).c_str());

	    configKey = QString("rex_server");
		realXtend_server_ = QString(framework_->GetDefaultConfigPtr()->GetSetting<std::string>(configGroup.toStdString(), configKey.toStdString()).c_str());

		configKey = QString("server");
		value = QString(framework_->GetDefaultConfigPtr()->GetSetting<std::string>(configGroup.toStdString(), configKey.toStdString()).c_str());
		lineEdit_worldAddress_->setText(value);
		opensim_server_ = value;

		configKey = QString("auth_server");
		value = QString(framework_->GetDefaultConfigPtr()->GetSetting<std::string>(configGroup.toStdString(), configKey.toStdString()).c_str());
		lineEdit_authAddress_->setText(value);
		realXtend_authserver_ = value;
	}

	void NaaliUI::ShowSelectedMode()
	{
		bool hide = false;
		if (radioButton_openSim_->isChecked() == true)
		{
			hide = false;
			if (lineEdit_username_->text() == realXtend_username_)
			    lineEdit_username_->setText(opensim_username_);
            if (lineEdit_worldAddress_->text() == realXtend_server_)
			    lineEdit_worldAddress_->setText(opensim_server_);
		}
		else if (radioButton_realXtend_->isChecked() == true)
		{
			hide = true;
			if (lineEdit_username_->text() == opensim_username_)
			    lineEdit_username_->setText(realXtend_username_);
            if (lineEdit_worldAddress_->text() == opensim_server_)
			    lineEdit_worldAddress_->setText(realXtend_server_);
		}
		label_authAddress_->setVisible(hide);
		lineEdit_authAddress_->setVisible(hide);
        lineEdit_password_->clear();
	}

	void NaaliUI::ParseInputAndConnect()
	{
		if ( !lineEdit_worldAddress_->text().isEmpty() &&
			 !lineEdit_username_->text().isEmpty() &&
			 !lineEdit_password_->text().isEmpty() )
		{
			QMap<QString, QString> map;
			map["WorldAddress"] = lineEdit_worldAddress_->text();
			map["Username"] = lineEdit_username_->text();
			map["Password"] = lineEdit_password_->text();
			if (radioButton_openSim_->isChecked() == true)
			{
				emit( ConnectOpenSim(map) );
			}
			else if (radioButton_realXtend_->isChecked() == true &&
					 !lineEdit_authAddress_->text().isEmpty() )
			{
				map["AuthenticationAddress"] = lineEdit_authAddress_->text();
				emit( ConnectRealXtend(map) );
			}
		}
	}

    /////////////////////////////////////////
    // WebUI CLASS
    /////////////////////////////////////////

	WebUI::WebUI(QWidget *parent, Login *controller, Foundation::Framework *framework, RexLogicModule *rexLogic)
		: AbstractLoginUI(parent, controller, framework, rexLogic)
	{
		SetLayout();
		SetLoginHandler();
		InitWidget();
	}

	WebUI::~WebUI()
	{
		delete loginHandler_;
	}

	void WebUI::SetLoginHandler()
	{
		loginHandler_ = new TaigaLoginHandler(framework_, rexLogicModule_);
		QObject::connect(loginHandler_, SIGNAL( LoginDone(bool) ), this, SLOT( LoginDone(bool) ));
	}

	void WebUI::InitWidget()
	{
		QFile confFile("./data/default_login.ini");
		if (!confFile.open(QIODevice::ReadOnly | QIODevice::Text))
			return;
		QString url(confFile.readLine());
		confFile.close();
		webLogin_ = new RexWebLogin(this, url);
		QObject::connect(webLogin_, SIGNAL( WebLoginInfoRecieved(QWebFrame *) ), loginHandler_, SLOT( ProcessWebLogin(QWebFrame *) ));
		this->layout()->addWidget(webLogin_);
	}

}<|endoftext|>


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

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

//MITK
#include "mitkTestingMacros.h"
#include "mitkRenderingTestHelper.h"

//VTK
#include <vtkRegressionTestImage.h>
#include <mitkTransferFunctionProperty.h>
#include <mitkTransferFunction.h>

int mitkImageVtkMapper2DTransferFunctionTest(int argc, char* argv[])
{
    // load all arguments into a datastorage, take last argument as reference rendering
    // setup a renderwindow of fixed size X*Y
    // render the datastorage
    // compare rendering to reference image
    MITK_TEST_BEGIN("mitkImageVtkMapper2DTransferFunctionTest")

    // enough parameters?
    if ( argc < 2 )
    {
        MITK_TEST_OUTPUT( << "Usage: " << std::string(*argv) << " [file1 file2 ...] outputfile" )
                MITK_TEST_OUTPUT( << "Will render a central axial slice of all given files into outputfile" )
                exit( EXIT_SUCCESS );
    }
    mitkRenderingTestHelper renderingHelper(640, 480, argc, argv);

    //define an arbitrary colortransferfunction
    vtkSmartPointer<vtkColorTransferFunction> colorTransferFunction = vtkSmartPointer<vtkColorTransferFunction>::New();
    colorTransferFunction->SetColorSpaceToRGB();
    colorTransferFunction->AddRGBPoint(0.0, 1, 0, 0); //black = red
    colorTransferFunction->AddRGBPoint(127.5, 0, 1, 0); //grey = green
    colorTransferFunction->AddRGBPoint(255.0, 0, 0, 1); //white = blue
    mitk::TransferFunction::Pointer transferFucntion = mitk::TransferFunction::New();
    transferFucntion->SetColorTransferFunction( colorTransferFunction );

    //set the property for the image
    renderingHelper.SetImageProperty("Image Rendering.Transfer Function", mitk::TransferFunctionProperty::New(transferFucntion));

    renderingHelper.Render();

    //use this to generate a reference screenshot or save the file:
    bool generateReferenceScreenshot = false;
    if(generateReferenceScreenshot)
    {
        renderingHelper.SaveAsPNG("/home/kilgus/Pictures/RenderingTestData/output.png");
    }

    //### Usage of vtkRegressionTestImage:
    //vtkRegressionTestImage( vtkRenderWindow )
    //Set a vtkRenderWindow containing the desired scene.
    //vtkRegressionTestImage automatically searches in argc and argv[]
    //for a path a valid image with -V. If the test failed with the
    //first image (foo.png) check if there are images of the form
    //foo_N.png (where N=1,2,3...) and compare against them.
    renderingHelper.PrepareRender();
    int retVal = vtkRegressionTestImage( renderingHelper.GetVtkRenderWindow() );

    //retVal meanings: (see VTK/Rendering/vtkTesting.h)
    //0 = test failed
    //1 = test passed
    //2 = test not run
    //3 = something with vtkInteraction
    MITK_TEST_CONDITION( retVal == 1, "VTK test result positive" );

    MITK_TEST_END();
}
<commit_msg>COMP: doubling tolerance threshold for issues on windows.<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

//MITK
#include "mitkTestingMacros.h"
#include "mitkRenderingTestHelper.h"

//VTK
#include <vtkRegressionTestImage.h>
#include <mitkTransferFunctionProperty.h>
#include <mitkTransferFunction.h>

int mitkImageVtkMapper2DTransferFunctionTest(int argc, char* argv[])
{
    // load all arguments into a datastorage, take last argument as reference rendering
    // setup a renderwindow of fixed size X*Y
    // render the datastorage
    // compare rendering to reference image
    MITK_TEST_BEGIN("mitkImageVtkMapper2DTransferFunctionTest")

    // enough parameters?
    if ( argc < 2 )
    {
        MITK_TEST_OUTPUT( << "Usage: " << std::string(*argv) << " [file1 file2 ...] outputfile" )
                MITK_TEST_OUTPUT( << "Will render a central axial slice of all given files into outputfile" )
                exit( EXIT_SUCCESS );
    }
    mitkRenderingTestHelper renderingHelper(640, 480, argc, argv);

    //define an arbitrary colortransferfunction
    vtkSmartPointer<vtkColorTransferFunction> colorTransferFunction = vtkSmartPointer<vtkColorTransferFunction>::New();
    colorTransferFunction->SetColorSpaceToRGB();
    colorTransferFunction->AddRGBPoint(0.0, 1, 0, 0); //black = red
    colorTransferFunction->AddRGBPoint(127.5, 0, 1, 0); //grey = green
    colorTransferFunction->AddRGBPoint(255.0, 0, 0, 1); //white = blue
    mitk::TransferFunction::Pointer transferFucntion = mitk::TransferFunction::New();
    transferFucntion->SetColorTransferFunction( colorTransferFunction );

    //set the property for the image
    renderingHelper.SetImageProperty("Image Rendering.Transfer Function", mitk::TransferFunctionProperty::New(transferFucntion));

    renderingHelper.Render();

    //use this to generate a reference screenshot or save the file:
    bool generateReferenceScreenshot = false;
    if(generateReferenceScreenshot)
    {
        renderingHelper.SaveAsPNG("/home/kilgus/Pictures/RenderingTestData/output.png");
    }

    renderingHelper.PrepareRender();
    //### Usage of vtkRegressionTestImage:
    //vtkRegressionTestImage( vtkRenderWindow )
    //Set a vtkRenderWindow containing the desired scene.
    //vtkRegressionTestImage automatically searches in argc and argv[]
    //for a path a valid image with -V. If the test failed with the
    //first image (foo.png) check if there are images of the form
    //foo_N.png (where N=1,2,3...) and compare against them.
    //Default tolerance for rendering tests is 10 (set by VTK).
    //For this case, small artifacts in Windows occur and boundaries of the fonts,
    //thus we double the default tolerance threshold and set it to 20.
    int retVal = vtkTesting::Test(argc, argv, renderingHelper.GetVtkRenderWindow(), 20 );

    //retVal meanings: (see VTK/Rendering/vtkTesting.h)
    //0 = test failed
    //1 = test passed
    //2 = test not run
    //3 = something with vtkInteraction
    MITK_TEST_CONDITION( retVal == 1, "VTK test result positive" );

    MITK_TEST_END();
}
<|endoftext|>


<commit_before>#include <iostream>

#include "dstar_lite/dstar.h"

int main(int argc, char **argv) {
  // Check that there are 3 arguments, aka argc == 4.
  if (argc != 4) {
    std::cerr << "Terminating. Incorrect number of arguments."
              << "Expected 3." << std::endl;
    return EXIT_FAILURE;
  }

  // Parse grid.
  std::string flat_grid = argv[3];

  // Construct a grid.
  const uint grid_size = (uint)std::sqrt(flat_grid.size());
  std::vector<std::vector<int>>
      occupancy_grid (grid_size, vector<int>(grid_size));

  // Parse input
  // Retrieve start position
  const uint start = std::atoi(argv[1]);
  std::array<uint, 2> start_indices;
  start_indices[0] = std::floor(start / grid_size); //x index
  start_indices[1] = start - start_indices[0] * grid_size; //y index

  // Retrieve goal position
  const uint goal = std::atoi(argv[2]);
  std::array<uint, 2> goal_indices;
  goal_indices[0] = std::floor(goal / grid_size); //x index
  goal_indices[1] = goal - goal_indices[0] * grid_size; //y index

  // Reshape input to a grid with x, y coordinates
  for (uint i = 0, j = 0, k = 0; k < flat_grid.size(); k++) {
    j = k % grid_size;

    // Check that we are not out of bounds.
    if ( i < grid_size && j < grid_size) {
      const int a = (int)flat_grid.at(k) - 48;
      occupancy_grid[i][j] = a;
    } else {
      std::cerr << "Index out of bounds, check that"
                   " input grid is squared." << std::endl;
      return EXIT_FAILURE;
    }

    if (j == (grid_size - 1)) {
      i++;
    }
  }

  Dstar* dstar = new Dstar();
  dstar->init(start_indices[0], start_indices[1], goal_indices[0], goal_indices[1]);
  for (uint i = 0; i < occupancy_grid.size(); i++) {
    for (uint j = 0; j < occupancy_grid.at(i).size(); j++) {
      std::cout << "Occ grid vals: " << occupancy_grid[i][j] << '\n';
      if (occupancy_grid.at(i).at(j) == 1) {
        dstar->updateCell(i+1, j+1, -1);
      }
    }
  }

  if (!dstar->replan()) {
    std::cerr << "No found path to goal" << std::endl;
    return EXIT_FAILURE;
  }

  list<state> path = dstar->getPath();
  for(const state& waypoint: path) {
    std::cout << "Waypoint: "
              << waypoint.x << ", "
              << waypoint.y << std::endl;
  }

  return EXIT_SUCCESS;
}
<commit_msg>Inverse occupancy_grid values<commit_after>#include <iostream>

#include "dstar_lite/dstar.h"

int main(int argc, char **argv) {
  // Check that there are 3 arguments, aka argc == 4.
  if (argc != 4) {
    std::cerr << "Terminating. Incorrect number of arguments."
              << "Expected 3." << std::endl;
    return EXIT_FAILURE;
  }

  // Parse grid.
  std::string flat_grid = argv[3];

  // Construct a grid.
  const uint grid_size = (uint)std::sqrt(flat_grid.size());
  std::vector<std::vector<int>>
      occupancy_grid (grid_size, vector<int>(grid_size));

  // Parse input
  // Retrieve start position
  const uint start = std::atoi(argv[1]);
  std::array<uint, 2> start_indices;
  start_indices[0] = std::floor(start / grid_size); //x index
  start_indices[1] = start - start_indices[0] * grid_size; //y index

  // Retrieve goal position
  const uint goal = std::atoi(argv[2]);
  std::array<uint, 2> goal_indices;
  goal_indices[0] = std::floor(goal / grid_size); //x index
  goal_indices[1] = goal - goal_indices[0] * grid_size; //y index

  // Reshape input to a grid with x, y coordinates
  for (uint i = 0, j = 0, k = 0; k < flat_grid.size(); k++) {
    j = k % grid_size;

    // Check that we are not out of bounds.
    if ( i < grid_size && j < grid_size) {
      const int a = 1 - ((int)flat_grid.at(k) - 48);
      occupancy_grid[i][j] = a;
    } else {
      std::cerr << "Index out of bounds, check that"
                   " input grid is squared." << std::endl;
      return EXIT_FAILURE;
    }

    if (j == (grid_size - 1)) {
      i++;
    }
  }

  Dstar* dstar = new Dstar();
  dstar->init(start_indices[0], start_indices[1], goal_indices[0], goal_indices[1]);
  for (uint i = 0; i < occupancy_grid.size(); i++) {
    for (uint j = 0; j < occupancy_grid.at(i).size(); j++) {
      std::cout << "Occ grid vals: " << occupancy_grid[i][j] << '\n';
      if (occupancy_grid.at(i).at(j) == 1) {
        dstar->updateCell(i+1, j+1, -1);
      }
    }
  }

  if (!dstar->replan()) {
    std::cerr << "No found path to goal" << std::endl;
    return EXIT_FAILURE;
  }

  list<state> path = dstar->getPath();
  for(const state& waypoint: path) {
    std::cout << "Waypoint: "
              << waypoint.x << ", "
              << waypoint.y << std::endl;
  }

  return EXIT_SUCCESS;
}
<|endoftext|>


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

#ifndef _TOKSTACK_HXX
#define _TOKSTACK_HXX

#ifndef _INC_STRING
#include <string.h>
#endif

#ifndef _DEBUG_HXX //autogen
#include <tools/debug.hxx>
#endif

#ifndef SC_COMPILER_HXX
#include "compiler.hxx"
#endif

typedef OpCode DefTokenId;
// in PRODUCT version: ambiguity between OpCode (being USHORT) and UINT16
// Unfortunately a typedef is just a dumb alias and not a real type ...
//typedef UINT16 TokenId;
struct TokenId
{
        UINT16          nId;

                        TokenId() : nId( 0 ) {}
                        TokenId( UINT16 n ) : nId( n ) {}
                        TokenId( const TokenId& r ) : nId( r.nId ) {}
    inline  TokenId&    operator =( const TokenId& r ) { nId = r.nId; return *this; }
    inline  TokenId&    operator =( UINT16 n ) { nId = n; return *this; }
    inline              operator UINT16&() { return nId; }
    inline              operator const UINT16&() const { return nId; }
    inline  BOOL        operator <( UINT16 n ) const { return nId < n; }
    inline  BOOL        operator >( UINT16 n ) const { return nId > n; }
    inline  BOOL        operator <=( UINT16 n ) const { return nId <= n; }
    inline  BOOL        operator >=( UINT16 n ) const { return nId >= n; }
    inline  BOOL        operator ==( UINT16 n ) const { return nId == n; }
    inline  BOOL        operator !=( UINT16 n ) const { return nId != n; }
};

//------------------------------------------------------------------------
struct ComplRefData;
class TokenStack;
class ScToken;

enum E_TYPE
{
    T_Id,       // Id-Folge
    T_Str,      // String
    T_D,        // Double
    T_RefC,     // Cell Reference
    T_RefA,     // Area Reference
    T_RN,       // Range Name
    T_Ext,      // irgendwas Unbekanntes mit Funktionsnamen
    T_Nlf,      // token for natural language formula
    T_Matrix,   // token for inline arrays
    T_Error     // fuer Abfrage im Fehlerfall
};

class TokenPool
{
    // !ACHTUNG!: externe Id-Basis ist 1, interne 0!
    // Ausgabe Id = 0 -> Fehlerfall
    private:
        String**                    ppP_Str;    // Pool fuer Strings
        UINT16                      nP_Str;     // ...mit Groesse
        UINT16                      nP_StrAkt;  // ...und Schreibmarke

        double*                     pP_Dbl;     // Pool fuer Doubles
        UINT16                      nP_Dbl;
        UINT16                      nP_DblAkt;

        SingleRefData**             ppP_RefTr;  // Pool fuer Referenzen
        UINT16                      nP_RefTr;
        UINT16                      nP_RefTrAkt;

        UINT16*                     pP_Id;      // Pool fuer Id-Folgen
        UINT16                      nP_Id;
        UINT16                      nP_IdAkt;
        UINT16                      nP_IdLast;  // letzter Folgen-Beginn

        struct  EXTCONT
        {
            DefTokenId              eId;
            String                  aText;
                                    EXTCONT( const DefTokenId e, const String& r ) :
                                        eId( e ), aText( r ){}
        };
        EXTCONT**                   ppP_Ext;
        UINT16                      nP_Ext;
        UINT16                      nP_ExtAkt;

        struct  NLFCONT
        {
            SingleRefData           aRef;
                                    NLFCONT( const SingleRefData& r ) : aRef( r )   {}
        };
        NLFCONT**                   ppP_Nlf;
        UINT16                      nP_Nlf;
        UINT16                      nP_NlfAkt;

        ScMatrix**                  ppP_Matrix;     // Pool fuer Matricies
        UINT16                      nP_Matrix;
        UINT16                      nP_MatrixAkt;

        UINT16*                     pElement;   // Array mit Indizes fuer Elemente
        E_TYPE*                     pType;      // ...mit Typ-Info
        UINT16*                     pSize;      // ...mit Laengenangabe (Anz. UINT16)
        UINT16                      nElement;
        UINT16                      nElementAkt;

        static const UINT16         nScTokenOff;// Offset fuer SC-Token
#ifdef DBG_UTIL
        UINT16                      nRek;       // Rekursionszaehler
#endif
        ScTokenArray*               pScToken;   // Tokenbastler

        void                        GrowString( void );
        void                        GrowDouble( void );
        void                        GrowTripel( void );
        void                        GrowId( void );
        void                        GrowElement( void );
        void                        GrowExt( void );
        void                        GrowNlf( void );
        void                        GrowMatrix( void );
        void                        GetElement( const UINT16 nId );
        void                        GetElementRek( const UINT16 nId );
    public:
                                    TokenPool( void );
                                    ~TokenPool();
        inline TokenPool&           operator <<( const TokenId nId );
        inline TokenPool&           operator <<( const DefTokenId eId );
        inline TokenPool&           operator <<( TokenStack& rStack );
        void                        operator >>( TokenId& rId );
        inline void                 operator >>( TokenStack& rStack );
        inline const TokenId        Store( void );
        const TokenId               Store( const double& rDouble );

                                    // nur fuer Range-Names
        const TokenId               Store( const UINT16 nIndex );
        inline const TokenId        Store( const INT16 nWert );
        const TokenId               Store( const String& rString );
        const TokenId               Store( const SingleRefData& rTr );
        const TokenId               Store( const ComplRefData& rTr );

        const TokenId               Store( const DefTokenId eId, const String& rName );
                                        // 4 externals (e.g. AddIns, Makros...)
        const TokenId               StoreNlf( const SingleRefData& rTr );
        const TokenId               StoreMatrix( SCSIZE nC, SCSIZE nR );

        inline const TokenId        LastId( void ) const;
        inline const ScTokenArray*  operator []( const TokenId nId );
        void                        Reset( void );
        inline E_TYPE               GetType( const TokenId& nId ) const;
        inline const SingleRefData* GetSRD( const TokenId& nId ) const;
        BOOL                        IsSingleOp( const TokenId& nId, const DefTokenId eId ) const;
        const String*               GetExternal( const TokenId& nId ) const;
        const String*               GetString( const TokenId& nId ) const;
        ScMatrix*                   GetMatrix( unsigned int n ) const;
};

class TokenStack
    // Stack fuer Token-Ids: Id 0 sollte reserviert bleiben als
    //  fehlerhafte Id, da z.B. Get() im Fehlerfall 0 liefert
{
    private:
        TokenId*                    pStack;     // Stack als Array
        UINT16                      nPos;       // Schreibmarke
        UINT16                      nSize;      // Erster Index ausserhalb des Stacks
    public:
                                    TokenStack( UINT16 nNewSize = 1024 );
                                    ~TokenStack();
        inline TokenStack&          operator <<( const TokenId nNewId );
        inline void                 operator >>( TokenId &rId );

        inline void                 Reset( void );

        inline bool                 HasMoreTokens() const { return nPos > 0; }
        inline const TokenId        Get( void );
};

inline const TokenId TokenStack::Get( void )
{
    DBG_ASSERT( nPos > 0,
        "*TokenStack::Get(): Leer ist leer, ist leer, ist leer, ist..." );

    TokenId nRet;

    if( nPos == 0 )
        nRet = 0;
    else
    {
        nPos--;
        nRet = pStack[ nPos ];
    }

    return nRet;
}

inline TokenStack &TokenStack::operator <<( const TokenId nNewId )
{// Element auf Stack
    DBG_ASSERT( nPos < nSize, "*TokenStack::<<(): Stackueberlauf" );
    if( nPos < nSize )
    {
        pStack[ nPos ] = nNewId;
        nPos++;
    }

    return *this;
}

inline void TokenStack::operator >>( TokenId& rId )
{// Element von Stack
    DBG_ASSERT( nPos > 0,
        "*TokenStack::>>(): Leer ist leer, ist leer, ist leer, ..." );
    if( nPos > 0 )
    {
        nPos--;
        rId = pStack[ nPos ];
    }
}

inline void TokenStack::Reset( void )
{
    nPos = 0;
}

inline TokenPool& TokenPool::operator <<( const TokenId nId )
{
    // POST: nId's werden hintereinander im Pool unter einer neuen Id
    //       abgelegt. Vorgang wird mit >> oder Store() abgeschlossen
    // nId -> ( UINT16 ) nId - 1;
    DBG_ASSERT( ( UINT16 ) nId < nScTokenOff,
        "-TokenPool::operator <<: TokenId im DefToken-Bereich!" );

    if( nP_IdAkt >= nP_Id )
        GrowId();

    pP_Id[ nP_IdAkt ] = ( ( UINT16 ) nId ) - 1;
    nP_IdAkt++;

    return *this;
}

inline TokenPool& TokenPool::operator <<( const DefTokenId eId )
{
    DBG_ASSERT( ( UINT32 ) eId + nScTokenOff < 0xFFFF,
        "-TokenPool::operator<<: enmum zu gross!" );

    if( nP_IdAkt >= nP_Id )
        GrowId();

    pP_Id[ nP_IdAkt ] = ( ( UINT16 ) eId ) + nScTokenOff;
    nP_IdAkt++;

    return *this;
}

inline TokenPool& TokenPool::operator <<( TokenStack& rStack )
{
    if( nP_IdAkt >= nP_Id )
        GrowId();

    pP_Id[ nP_IdAkt ] = ( ( UINT16 ) rStack.Get() ) - 1;
    nP_IdAkt++;

    return *this;
}

inline void TokenPool::operator >>( TokenStack& rStack )
{
    TokenId nId;
    *this >> nId;
    rStack << nId;
}

inline const TokenId TokenPool::Store( void )
{
    TokenId nId;
    *this >> nId;
    return nId;
}

inline const TokenId TokenPool::Store( const INT16 nWert )
{
    return Store( ( double ) nWert );
}

inline const TokenId TokenPool::LastId( void ) const
{
    return ( TokenId ) nElementAkt; // stimmt, da Ausgabe mit Offset 1!
}

const inline ScTokenArray* TokenPool::operator []( const TokenId nId )
{
    pScToken->Clear();

    if( nId )
    {//...nur wenn nId > 0!
#ifdef DBG_UTIL
        nRek = 0;
#endif
        GetElement( ( UINT16 ) nId - 1 );
    }

    return pScToken;
}

inline E_TYPE TokenPool::GetType( const TokenId& rId ) const
{
    E_TYPE nRet;

    UINT16 nId = (UINT16) rId - 1;

    if( nId < nElementAkt )
        nRet = pType[ nId ] ;
    else
        nRet = T_Error;

    return nRet;
}

inline const SingleRefData* TokenPool::GetSRD( const TokenId& rId ) const
{
    SingleRefData* pRet;

    UINT16 nId = (UINT16) rId - 1;

    if( nId < nElementAkt && pType[ nId ] == T_RefC )
        pRet = ppP_RefTr[ pElement[ nId ] ];
    else
        pRet = NULL;

    return pRet;
}

#endif

<commit_msg>INTEGRATION: CWS odff (1.12.90); FILE MERGED 2008/01/10 14:40:27 dr 1.12.90.1: import/export error codes<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: tokstack.hxx,v $
 *
 *  $Revision: 1.13 $
 *
 *  last change: $Author: kz $ $Date: 2008-03-06 15:49:21 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _TOKSTACK_HXX
#define _TOKSTACK_HXX

#ifndef _INC_STRING
#include <string.h>
#endif

#ifndef _DEBUG_HXX //autogen
#include <tools/debug.hxx>
#endif

#ifndef SC_COMPILER_HXX
#include "compiler.hxx"
#endif

typedef OpCode DefTokenId;
// in PRODUCT version: ambiguity between OpCode (being USHORT) and UINT16
// Unfortunately a typedef is just a dumb alias and not a real type ...
//typedef UINT16 TokenId;
struct TokenId
{
        UINT16          nId;

                        TokenId() : nId( 0 ) {}
                        TokenId( UINT16 n ) : nId( n ) {}
                        TokenId( const TokenId& r ) : nId( r.nId ) {}
    inline  TokenId&    operator =( const TokenId& r ) { nId = r.nId; return *this; }
    inline  TokenId&    operator =( UINT16 n ) { nId = n; return *this; }
    inline              operator UINT16&() { return nId; }
    inline              operator const UINT16&() const { return nId; }
    inline  BOOL        operator <( UINT16 n ) const { return nId < n; }
    inline  BOOL        operator >( UINT16 n ) const { return nId > n; }
    inline  BOOL        operator <=( UINT16 n ) const { return nId <= n; }
    inline  BOOL        operator >=( UINT16 n ) const { return nId >= n; }
    inline  BOOL        operator ==( UINT16 n ) const { return nId == n; }
    inline  BOOL        operator !=( UINT16 n ) const { return nId != n; }
};

//------------------------------------------------------------------------
struct ComplRefData;
class TokenStack;
class ScToken;

enum E_TYPE
{
    T_Id,       // Id-Folge
    T_Str,      // String
    T_D,        // Double
    T_Err,      // Error code
    T_RefC,     // Cell Reference
    T_RefA,     // Area Reference
    T_RN,       // Range Name
    T_Ext,      // irgendwas Unbekanntes mit Funktionsnamen
    T_Nlf,      // token for natural language formula
    T_Matrix,   // token for inline arrays
    T_Error     // fuer Abfrage im Fehlerfall
};

class TokenPool
{
    // !ACHTUNG!: externe Id-Basis ist 1, interne 0!
    // Ausgabe Id = 0 -> Fehlerfall
    private:
        String**                    ppP_Str;    // Pool fuer Strings
        UINT16                      nP_Str;     // ...mit Groesse
        UINT16                      nP_StrAkt;  // ...und Schreibmarke

        double*                     pP_Dbl;     // Pool fuer Doubles
        UINT16                      nP_Dbl;
        UINT16                      nP_DblAkt;

        USHORT*                     pP_Err;     // Pool for error codes
        UINT16                      nP_Err;
        UINT16                      nP_ErrAkt;

        SingleRefData**             ppP_RefTr;  // Pool fuer Referenzen
        UINT16                      nP_RefTr;
        UINT16                      nP_RefTrAkt;

        UINT16*                     pP_Id;      // Pool fuer Id-Folgen
        UINT16                      nP_Id;
        UINT16                      nP_IdAkt;
        UINT16                      nP_IdLast;  // letzter Folgen-Beginn

        struct  EXTCONT
        {
            DefTokenId              eId;
            String                  aText;
                                    EXTCONT( const DefTokenId e, const String& r ) :
                                        eId( e ), aText( r ){}
        };
        EXTCONT**                   ppP_Ext;
        UINT16                      nP_Ext;
        UINT16                      nP_ExtAkt;

        struct  NLFCONT
        {
            SingleRefData           aRef;
                                    NLFCONT( const SingleRefData& r ) : aRef( r )   {}
        };
        NLFCONT**                   ppP_Nlf;
        UINT16                      nP_Nlf;
        UINT16                      nP_NlfAkt;

        ScMatrix**                  ppP_Matrix;     // Pool fuer Matricies
        UINT16                      nP_Matrix;
        UINT16                      nP_MatrixAkt;

        UINT16*                     pElement;   // Array mit Indizes fuer Elemente
        E_TYPE*                     pType;      // ...mit Typ-Info
        UINT16*                     pSize;      // ...mit Laengenangabe (Anz. UINT16)
        UINT16                      nElement;
        UINT16                      nElementAkt;

        static const UINT16         nScTokenOff;// Offset fuer SC-Token
#ifdef DBG_UTIL
        UINT16                      nRek;       // Rekursionszaehler
#endif
        ScTokenArray*               pScToken;   // Tokenbastler

        void                        GrowString( void );
        void                        GrowDouble( void );
        void                        GrowError( void );
        void                        GrowTripel( void );
        void                        GrowId( void );
        void                        GrowElement( void );
        void                        GrowExt( void );
        void                        GrowNlf( void );
        void                        GrowMatrix( void );
        void                        GetElement( const UINT16 nId );
        void                        GetElementRek( const UINT16 nId );
    public:
                                    TokenPool( void );
                                    ~TokenPool();
        inline TokenPool&           operator <<( const TokenId nId );
        inline TokenPool&           operator <<( const DefTokenId eId );
        inline TokenPool&           operator <<( TokenStack& rStack );
        void                        operator >>( TokenId& rId );
        inline void                 operator >>( TokenStack& rStack );
        inline const TokenId        Store( void );
        const TokenId               Store( const double& rDouble );
        const TokenId               StoreError( USHORT nError );

                                    // nur fuer Range-Names
        const TokenId               Store( const UINT16 nIndex );
        inline const TokenId        Store( const INT16 nWert );
        const TokenId               Store( const String& rString );
        const TokenId               Store( const SingleRefData& rTr );
        const TokenId               Store( const ComplRefData& rTr );

        const TokenId               Store( const DefTokenId eId, const String& rName );
                                        // 4 externals (e.g. AddIns, Makros...)
        const TokenId               StoreNlf( const SingleRefData& rTr );
        const TokenId               StoreMatrix( SCSIZE nC, SCSIZE nR );

        inline const TokenId        LastId( void ) const;
        inline const ScTokenArray*  operator []( const TokenId nId );
        void                        Reset( void );
        inline E_TYPE               GetType( const TokenId& nId ) const;
        inline const SingleRefData* GetSRD( const TokenId& nId ) const;
        BOOL                        IsSingleOp( const TokenId& nId, const DefTokenId eId ) const;
        const String*               GetExternal( const TokenId& nId ) const;
        const String*               GetString( const TokenId& nId ) const;
        ScMatrix*                   GetMatrix( unsigned int n ) const;
};

class TokenStack
    // Stack fuer Token-Ids: Id 0 sollte reserviert bleiben als
    //  fehlerhafte Id, da z.B. Get() im Fehlerfall 0 liefert
{
    private:
        TokenId*                    pStack;     // Stack als Array
        UINT16                      nPos;       // Schreibmarke
        UINT16                      nSize;      // Erster Index ausserhalb des Stacks
    public:
                                    TokenStack( UINT16 nNewSize = 1024 );
                                    ~TokenStack();
        inline TokenStack&          operator <<( const TokenId nNewId );
        inline void                 operator >>( TokenId &rId );

        inline void                 Reset( void );

        inline bool                 HasMoreTokens() const { return nPos > 0; }
        inline const TokenId        Get( void );
};

inline const TokenId TokenStack::Get( void )
{
    DBG_ASSERT( nPos > 0,
        "*TokenStack::Get(): Leer ist leer, ist leer, ist leer, ist..." );

    TokenId nRet;

    if( nPos == 0 )
        nRet = 0;
    else
    {
        nPos--;
        nRet = pStack[ nPos ];
    }

    return nRet;
}

inline TokenStack &TokenStack::operator <<( const TokenId nNewId )
{// Element auf Stack
    DBG_ASSERT( nPos < nSize, "*TokenStack::<<(): Stackueberlauf" );
    if( nPos < nSize )
    {
        pStack[ nPos ] = nNewId;
        nPos++;
    }

    return *this;
}

inline void TokenStack::operator >>( TokenId& rId )
{// Element von Stack
    DBG_ASSERT( nPos > 0,
        "*TokenStack::>>(): Leer ist leer, ist leer, ist leer, ..." );
    if( nPos > 0 )
    {
        nPos--;
        rId = pStack[ nPos ];
    }
}

inline void TokenStack::Reset( void )
{
    nPos = 0;
}

inline TokenPool& TokenPool::operator <<( const TokenId nId )
{
    // POST: nId's werden hintereinander im Pool unter einer neuen Id
    //       abgelegt. Vorgang wird mit >> oder Store() abgeschlossen
    // nId -> ( UINT16 ) nId - 1;
    DBG_ASSERT( ( UINT16 ) nId < nScTokenOff,
        "-TokenPool::operator <<: TokenId im DefToken-Bereich!" );

    if( nP_IdAkt >= nP_Id )
        GrowId();

    pP_Id[ nP_IdAkt ] = ( ( UINT16 ) nId ) - 1;
    nP_IdAkt++;

    return *this;
}

inline TokenPool& TokenPool::operator <<( const DefTokenId eId )
{
    DBG_ASSERT( ( UINT32 ) eId + nScTokenOff < 0xFFFF,
        "-TokenPool::operator<<: enmum zu gross!" );

    if( nP_IdAkt >= nP_Id )
        GrowId();

    pP_Id[ nP_IdAkt ] = ( ( UINT16 ) eId ) + nScTokenOff;
    nP_IdAkt++;

    return *this;
}

inline TokenPool& TokenPool::operator <<( TokenStack& rStack )
{
    if( nP_IdAkt >= nP_Id )
        GrowId();

    pP_Id[ nP_IdAkt ] = ( ( UINT16 ) rStack.Get() ) - 1;
    nP_IdAkt++;

    return *this;
}

inline void TokenPool::operator >>( TokenStack& rStack )
{
    TokenId nId;
    *this >> nId;
    rStack << nId;
}

inline const TokenId TokenPool::Store( void )
{
    TokenId nId;
    *this >> nId;
    return nId;
}

inline const TokenId TokenPool::Store( const INT16 nWert )
{
    return Store( ( double ) nWert );
}

inline const TokenId TokenPool::LastId( void ) const
{
    return ( TokenId ) nElementAkt; // stimmt, da Ausgabe mit Offset 1!
}

const inline ScTokenArray* TokenPool::operator []( const TokenId nId )
{
    pScToken->Clear();

    if( nId )
    {//...nur wenn nId > 0!
#ifdef DBG_UTIL
        nRek = 0;
#endif
        GetElement( ( UINT16 ) nId - 1 );
    }

    return pScToken;
}

inline E_TYPE TokenPool::GetType( const TokenId& rId ) const
{
    E_TYPE nRet;

    UINT16 nId = (UINT16) rId - 1;

    if( nId < nElementAkt )
        nRet = pType[ nId ] ;
    else
        nRet = T_Error;

    return nRet;
}

inline const SingleRefData* TokenPool::GetSRD( const TokenId& rId ) const
{
    SingleRefData* pRet;

    UINT16 nId = (UINT16) rId - 1;

    if( nId < nElementAkt && pType[ nId ] == T_RefC )
        pRet = ppP_RefTr[ pElement[ nId ] ];
    else
        pRet = NULL;

    return pRet;
}

#endif

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: xmlannoi.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2004-07-13 07:47:42 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef SC_XMLANNOI_HXX
#define SC_XMLANNOI_HXX

#ifndef _XMLOFF_XMLICTXT_HXX
#include <xmloff/xmlictxt.hxx>
#endif
#ifndef _XMLOFF_XMLIMP_HXX
#include <xmloff/xmlimp.hxx>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif

class ScXMLImport;
class ScXMLTableRowCellContext;

class ScXMLAnnotationContext : public SvXMLImportContext
{
    rtl::OUStringBuffer sOUText;
    rtl::OUStringBuffer sAuthorBuffer;
    rtl::OUStringBuffer sCreateDateBuffer;
    rtl::OUStringBuffer sCreateDateStringBuffer;
    sal_Int32       nParagraphCount;
    sal_Bool        bDisplay : 1;
    sal_Bool        bHasTextP : 1;
    ScXMLTableRowCellContext*   pCellContext;

    const ScXMLImport& GetScImport() const { return (const ScXMLImport&)GetImport(); }
    ScXMLImport& GetScImport() { return (ScXMLImport&)GetImport(); }

public:

    ScXMLAnnotationContext( ScXMLImport& rImport, USHORT nPrfx,
                        const ::rtl::OUString& rLName,
                        const ::com::sun::star::uno::Reference<
                                        ::com::sun::star::xml::sax::XAttributeList>& xAttrList,
                        ScXMLTableRowCellContext* pCellContext);

    virtual ~ScXMLAnnotationContext();

    virtual SvXMLImportContext *CreateChildContext( USHORT nPrefix,
                                     const ::rtl::OUString& rLocalName,
                                     const ::com::sun::star::uno::Reference<
                                          ::com::sun::star::xml::sax::XAttributeList>& xAttrList );

    virtual void Characters( const ::rtl::OUString& rChars );

    virtual void EndElement();
};

#endif

<commit_msg>INTEGRATION: CWS dr12 (1.4.306); FILE MERGED 2004/08/09 13:44:36 sab 1.4.306.3: #i21253#; make old notes work 2004/07/27 01:44:10 sab 1.4.306.2: RESYNC: (1.4-1.5); FILE MERGED 2004/07/23 20:58:26 sab 1.4.306.1: #i21253#; add formatted notes<commit_after>/*************************************************************************
 *
 *  $RCSfile: xmlannoi.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: hr $ $Date: 2004-09-08 13:50:33 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef SC_XMLANNOI_HXX
#define SC_XMLANNOI_HXX

#ifndef _XMLOFF_XMLICTXT_HXX
#include <xmloff/xmlictxt.hxx>
#endif
#ifndef _XMLOFF_XMLIMP_HXX
#include <xmloff/xmlimp.hxx>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#ifndef _COM_SUN_STAR_DRAWING_XSHAPE_HPP_
#include <com/sun/star/drawing/XShape.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_XSHAPES_HPP_
#include <com/sun/star/drawing/XShapes.hpp>
#endif

class ScXMLImport;
class ScXMLTableRowCellContext;

class ScXMLAnnotationContext : public SvXMLImportContext
{
    rtl::OUStringBuffer sOUText;
    rtl::OUStringBuffer sAuthorBuffer;
    rtl::OUStringBuffer sCreateDateBuffer;
    rtl::OUStringBuffer sCreateDateStringBuffer;
    sal_Int32       nParagraphCount;
    sal_Bool        bDisplay;
    sal_Bool        bHasTextP;
    sal_Bool        bHasPos;
    ScXMLTableRowCellContext*   pCellContext;
    SvXMLImportContext*         pShapeContext;
    com::sun::star::uno::Reference< com::sun::star::drawing::XShape > xShape;
    com::sun::star::uno::Reference< com::sun::star::drawing::XShapes > xShapes;

    const ScXMLImport& GetScImport() const { return (const ScXMLImport&)GetImport(); }
    ScXMLImport& GetScImport() { return (ScXMLImport&)GetImport(); }

public:

    ScXMLAnnotationContext( ScXMLImport& rImport, USHORT nPrfx,
                        const ::rtl::OUString& rLName,
                        const ::com::sun::star::uno::Reference<
                                        ::com::sun::star::xml::sax::XAttributeList>& xAttrList,
                        ScXMLTableRowCellContext* pCellContext);

    virtual ~ScXMLAnnotationContext();

    virtual SvXMLImportContext *CreateChildContext( USHORT nPrefix,
                                     const ::rtl::OUString& rLocalName,
                                     const ::com::sun::star::uno::Reference<
                                          ::com::sun::star::xml::sax::XAttributeList>& xAttrList );

    virtual void StartElement(const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList);

    virtual void Characters( const ::rtl::OUString& rChars );

    virtual void EndElement();

    void SetShape(const com::sun::star::uno::Reference< com::sun::star::drawing::XShape >& xTempShape,
        const com::sun::star::uno::Reference< com::sun::star::drawing::XShapes >& xTempShapes) { xShape.set(xTempShape); xShapes.set(xTempShapes); }
};

#endif

<|endoftext|>


<commit_before>#ifndef DUNE_STUFF_FUNCTION_CHECKERBOARD_HH
#define DUNE_STUFF_FUNCTION_CHECKERBOARD_HH

#include <vector>

#include <dune/common/exceptions.hh>
#include <dune/common/static_assert.hh>
#include <dune/stuff/common/parameter/tree.hh>
#include <dune/stuff/common/color.hh>

#include "interface.hh"

namespace Dune {
namespace Stuff {

// forward, to allow for specialization
template< class DomainFieldImp, int domainDim,
          class RangeFieldImp, int rangeDim >
class FunctionCheckerboard;

template< class DomainFieldImp, int domainDim, class RangeFieldImp >
class FunctionCheckerboard< DomainFieldImp, domainDim, RangeFieldImp, 1 >
  : public FunctionInterface< DomainFieldImp, domainDim, RangeFieldImp, 1 >
{
public:
  typedef FunctionCheckerboard< DomainFieldImp, domainDim, RangeFieldImp, 1 > ThisType;
  typedef FunctionInterface< DomainFieldImp, domainDim, RangeFieldImp, 1 >    BaseType;

  typedef typename BaseType::DomainFieldType  DomainFieldType;
  static const int                            dimDomain = BaseType::dimDomain;
  typedef typename BaseType::DomainType       DomainType;
  typedef typename BaseType::RangeFieldType   RangeFieldType;
  static const int                            dimRange = BaseType::dimRange;
  typedef typename BaseType::RangeType        RangeType;

  static const std::string id()
  {
    return BaseType::id() + ".checkerboard";
  }

  FunctionCheckerboard(const DomainType _lowerLeft,
                       const DomainType _upperRight,
                       const std::vector< size_t > _numElements,
                       const std::vector< RangeFieldType > _values,
                       const std::string _name = id())
    : lowerLeft_(_lowerLeft)
    , upperRight_(_upperRight)
    , numElements_(_numElements)
    , values_(_values)
    , name_(_name)
  {
    // checks
    dune_static_assert((dimDomain > 0), "Really?");
    dune_static_assert((dimDomain <= 3), "Not implemented!");
    dune_static_assert((dimRange > 0), "Really?");
    // get total number of subdomains
    size_t totalSubdomains = 1;
    for (int dd = 0; dd < dimDomain; ++dd) {
      totalSubdomains *= numElements_[dd];
    }
    if (values_.size() < totalSubdomains)
      DUNE_THROW(Dune::InvalidStateException,
                 "\n" << Dune::Stuff::Common::colorStringRed("ERROR:")
                 << " please provide at least as many '_values' as subdomains given by '_numElements'!");
  } // FunctionCheckerboard(...)

  static Dune::ParameterTree createSampleDescription(const std::string subName = "")
  {
    Dune::ParameterTree description;
    description["lowerLeft"] = "[0.0; 0.0; 0.0]";
    description["upperRight"] = "[1.0; 1.0; 1.0]";
    description["numElements"] = "[2; 2; 2]";
    description["values"] = "[1.0; 2.0; 3.0; 4.0; 5.0; 6.0; 7.0; 8.0]";
    description["name"] = id();
    if (subName.empty())
      return description;
    else {
      Dune::Stuff::Common::ExtendedParameterTree extendedDescription;
      extendedDescription.add(description, subName);
      return extendedDescription;
    }
  } // ... createSampleDescription(...)

  static ThisType* create(const DSC::ExtendedParameterTree description)
  {
    // get data
    const std::vector< DomainFieldType > lowerLefts = description.getVector("lowerLeft", DomainFieldType(0), dimDomain);
    const std::vector< DomainFieldType > upperRights = description.getVector("upperRight",
                                                                             DomainFieldType(1),
                                                                             dimDomain);
    const std::vector< size_t > numElements = description.getVector("numElements", size_t(1), dimDomain);
    size_t subdomains = 1;
    for (size_t ii = 0; ii < numElements.size(); ++ii)
      subdomains *= numElements[ii];
    const std::vector< RangeFieldType > values = description.getVector("values", RangeFieldType(1), subdomains);
    // convert and leave the checks to the constructor
    DomainType lowerLeft;
    DomainType upperRight;
    for (int dd = 0; dd < dimDomain; ++dd) {
      lowerLeft[dd] = lowerLefts[dd];
      upperRight[dd] = upperRights[dd];
    }
    // create and return
    return new ThisType(lowerLeft, upperRight, numElements, values);
  } // ... create(...)

  const DomainType& lowerLeft() const
  {
    return lowerLeft_;
  }

  const DomainType& upperRight() const
  {
    return upperRight_;
  }

  const std::vector< size_t >& numElements() const
  {
    return numElements_;
  }

  const std::vector< RangeFieldType >& values() const
  {
    return values_;
  }

  virtual std::string name() const
  {
    return name_;
  }

  virtual int order() const
  {
    return 0;
  }

  virtual void evaluate(const DomainType& x, RangeType& ret) const
  {
    // decide on the subdomain the point x belongs to
    std::vector< size_t > whichPartition;
    for (int d = 0; d < dimDomain; ++d)
    {
      whichPartition.push_back(std::floor(numElements_[d]*((x[d] - lowerLeft_[d])/(upperRight_[d] - lowerLeft_[d]))));
    }
    size_t subdomain = 0;
    if (dimDomain == 1)
      subdomain = whichPartition[0];
    else if (dimDomain == 2)
      subdomain = whichPartition[0] + whichPartition[1]*numElements_[0];
    else // has to be 3, see checks in constructor
      subdomain = whichPartition[0]
                  + whichPartition[1]*numElements_[0]
                  + whichPartition[2]*numElements_[1]*numElements_[0];
    // return the component that belongs to the subdomain of x
    ret = values_[subdomain];
  } // virtual void evaluate(const DomainType& x, RangeType& ret) const

private:
  DomainType lowerLeft_;
  DomainType upperRight_;
  std::vector< size_t > numElements_;
  std::vector< RangeFieldType > values_;
  std::string name_;
}; // class FunctionCheckerboard

} // namespace Stuff
} // namespace Dune

#endif // DUNE_STUFF_FUNCTION_CHECKERBOARD_HH
<commit_msg>[function.checkerboard] fixed possible overflow<commit_after>#ifndef DUNE_STUFF_FUNCTION_CHECKERBOARD_HH
#define DUNE_STUFF_FUNCTION_CHECKERBOARD_HH

#include <vector>

#include <dune/common/exceptions.hh>
#include <dune/common/static_assert.hh>
#include <dune/stuff/common/parameter/tree.hh>
#include <dune/stuff/common/color.hh>

#include "interface.hh"

namespace Dune {
namespace Stuff {

// forward, to allow for specialization
template< class DomainFieldImp, int domainDim,
          class RangeFieldImp, int rangeDim >
class FunctionCheckerboard;

template< class DomainFieldImp, int domainDim, class RangeFieldImp >
class FunctionCheckerboard< DomainFieldImp, domainDim, RangeFieldImp, 1 >
  : public FunctionInterface< DomainFieldImp, domainDim, RangeFieldImp, 1 >
{
public:
  typedef FunctionCheckerboard< DomainFieldImp, domainDim, RangeFieldImp, 1 > ThisType;
  typedef FunctionInterface< DomainFieldImp, domainDim, RangeFieldImp, 1 >    BaseType;

  typedef typename BaseType::DomainFieldType  DomainFieldType;
  static const int                            dimDomain = BaseType::dimDomain;
  typedef typename BaseType::DomainType       DomainType;
  typedef typename BaseType::RangeFieldType   RangeFieldType;
  static const int                            dimRange = BaseType::dimRange;
  typedef typename BaseType::RangeType        RangeType;

  static const std::string id()
  {
    return BaseType::id() + ".checkerboard";
  }

  FunctionCheckerboard(const DomainType _lowerLeft,
                       const DomainType _upperRight,
                       const std::vector< size_t > _numElements,
                       const std::vector< RangeFieldType > _values,
                       const std::string _name = id())
    : lowerLeft_(_lowerLeft)
    , upperRight_(_upperRight)
    , numElements_(_numElements)
    , values_(_values)
    , name_(_name)
  {
    // checks
    dune_static_assert((dimDomain > 0), "Really?");
    dune_static_assert((dimDomain <= 3), "Not implemented!");
    dune_static_assert((dimRange > 0), "Really?");
    // get total number of subdomains
    size_t totalSubdomains = 1;
    for (int dd = 0; dd < dimDomain; ++dd) {
      totalSubdomains *= numElements_[dd];
    }
    if (values_.size() < totalSubdomains)
      DUNE_THROW(Dune::InvalidStateException,
                 "\n" << Dune::Stuff::Common::colorStringRed("ERROR:")
                 << " please provide at least as many '_values' as subdomains given by '_numElements'!");
  } // FunctionCheckerboard(...)

  static Dune::ParameterTree createSampleDescription(const std::string subName = "")
  {
    Dune::ParameterTree description;
    description["lowerLeft"] = "[0.0; 0.0; 0.0]";
    description["upperRight"] = "[1.0; 1.0; 1.0]";
    description["numElements"] = "[2; 2; 2]";
    description["values"] = "[1.0; 2.0; 3.0; 4.0; 5.0; 6.0; 7.0; 8.0]";
    description["name"] = id();
    if (subName.empty())
      return description;
    else {
      Dune::Stuff::Common::ExtendedParameterTree extendedDescription;
      extendedDescription.add(description, subName);
      return extendedDescription;
    }
  } // ... createSampleDescription(...)

  static ThisType* create(const DSC::ExtendedParameterTree description)
  {
    // get data
    const std::vector< DomainFieldType > lowerLefts = description.getVector("lowerLeft", DomainFieldType(0), dimDomain);
    const std::vector< DomainFieldType > upperRights = description.getVector("upperRight",
                                                                             DomainFieldType(1),
                                                                             dimDomain);
    const std::vector< size_t > numElements = description.getVector("numElements", size_t(1), dimDomain);
    size_t subdomains = 1;
    for (size_t ii = 0; ii < numElements.size(); ++ii)
      subdomains *= numElements[ii];
    const std::vector< RangeFieldType > values = description.getVector("values", RangeFieldType(1), subdomains);
    // convert and leave the checks to the constructor
    DomainType lowerLeft;
    DomainType upperRight;
    for (int dd = 0; dd < dimDomain; ++dd) {
      lowerLeft[dd] = lowerLefts[dd];
      upperRight[dd] = upperRights[dd];
    }
    // create and return
    return new ThisType(lowerLeft, upperRight, numElements, values);
  } // ... create(...)

  const DomainType& lowerLeft() const
  {
    return lowerLeft_;
  }

  const DomainType& upperRight() const
  {
    return upperRight_;
  }

  const std::vector< size_t >& numElements() const
  {
    return numElements_;
  }

  const std::vector< RangeFieldType >& values() const
  {
    return values_;
  }

  virtual std::string name() const
  {
    return name_;
  }

  virtual int order() const
  {
    return 0;
  }

  /**
   *  \todo put this stuff in an expression, that is expanded at compile time (dimension dependent)
   */
  virtual void evaluate(const DomainType& x, RangeType& ret) const
  {
    // decide on the subdomain the point x belongs to
    std::vector< size_t > whichPartition;
    for (int d = 0; d < dimDomain; ++d)
    {
      // for points that are on upperRight_[d], this selects one partition too much
      // so we need to cap this
      whichPartition.push_back(std::min(size_t(std::floor(numElements_[d]*((x[d] - lowerLeft_[d])/(upperRight_[d] - lowerLeft_[d])))),
                                        numElements_[d] - 1));
    }
    size_t subdomain = 0;
    if (dimDomain == 1)
      subdomain = whichPartition[0];
    else if (dimDomain == 2)
      subdomain = whichPartition[0] + whichPartition[1]*numElements_[0];
    else // has to be 3, see checks in constructor
      subdomain = whichPartition[0]
                  + whichPartition[1]*numElements_[0]
                  + whichPartition[2]*numElements_[1]*numElements_[0];
    // return the component that belongs to the subdomain of x
    ret = values_[subdomain];
  } // virtual void evaluate(const DomainType& x, RangeType& ret) const

private:
  DomainType lowerLeft_;
  DomainType upperRight_;
  std::vector< size_t > numElements_;
  std::vector< RangeFieldType > values_;
  std::string name_;
}; // class FunctionCheckerboard

} // namespace Stuff
} // namespace Dune

#endif // DUNE_STUFF_FUNCTION_CHECKERBOARD_HH
<|endoftext|>


<commit_before>#include <archie/utils/fused/zip.h>
#include <archie/utils/test.h>

namespace fused = archie::utils::fused;

void canZipTwoTuples() {
  auto a = fused::make_tuple(1, 2u, '3');
  auto b = fused::make_tuple('4', 5.0, 6u);
  auto x = fused::zip(a, b);

  EXPECT_EQ(3u, fused::tuple_size<decltype(x)>::value);
  EXPECT_EQ(fused::make_tuple(1, '4'), fused::get<0>(x));
  EXPECT_EQ(fused::make_tuple(2u, 5.0), fused::get<1>(x));
  EXPECT_EQ(fused::make_tuple('3', 6u), fused::get<2>(x));
}

void canZipViewTwoTuples() {
  auto a = fused::make_tuple(1, 2u, '3');
  auto b = fused::make_tuple('4', 5.0, 6u);
  auto x = fused::zip_view(a, b);

  static_assert(fused::tuple_size<decltype(x)>::value == 3u, "");
  auto const& x0 = fused::get<0>(x);
  auto const& x1 = fused::get<1>(x);
  auto const& x2 = fused::get<2>(x);

  static_assert(
      std::is_same<decltype(x0), fused::tuple<int&, char&> const&>::value, "");
  static_assert(std::is_same<decltype(x1),
                             fused::tuple<unsigned&, double&> const&>::value,
                "");
  static_assert(
      std::is_same<decltype(x2), fused::tuple<char&, unsigned&> const&>::value,
      "");

  EXPECT_EQ(&fused::get<0>(a), &fused::get<0>(x0));
  EXPECT_EQ(&fused::get<1>(a), &fused::get<0>(x1));
  EXPECT_EQ(&fused::get<2>(a), &fused::get<0>(x2));

  EXPECT_EQ(&fused::get<0>(b), &fused::get<1>(x0));
  EXPECT_EQ(&fused::get<1>(b), &fused::get<1>(x1));
  EXPECT_EQ(&fused::get<2>(b), &fused::get<1>(x2));

  fused::get<0>(x1) = 7u;
  EXPECT_EQ(7u, fused::get<1>(a));
  fused::get<1>(x2) = 8u;
  EXPECT_EQ(8u, fused::get<2>(b));
}

void canZipViewTwoConstTuples() {
  auto const a = fused::make_tuple(1, 2u, '3');
  auto const b = fused::make_tuple('4', 5.0, 6u);
  auto x = fused::zip_view(a, b);

  static_assert(fused::tuple_size<decltype(x)>::value == 3u, "");
  auto x0 = fused::get<0>(x);
  auto x1 = fused::get<1>(x);
  auto x2 = fused::get<2>(x);

  EXPECT_EQ(&fused::get<0>(a), &fused::get<0>(x0));
  EXPECT_EQ(&fused::get<1>(a), &fused::get<0>(x1));
  EXPECT_EQ(&fused::get<2>(a), &fused::get<0>(x2));
  EXPECT_EQ(&fused::get<0>(b), &fused::get<1>(x0));
  EXPECT_EQ(&fused::get<1>(b), &fused::get<1>(x1));
  EXPECT_EQ(&fused::get<2>(b), &fused::get<1>(x2));
}

void canZipViewTwoTuplesWithConsts() {
  auto const c = 2u;
  auto const d = 5.0;
  auto a = fused::tuple<int, const unsigned, char>{1, c, '3'};

  static_assert(std::is_same<std::remove_reference_t<decltype(a)>,
                             fused::tuple<int, const unsigned, char>>::value,
                "");
  auto b = fused::make_tuple('4', d, 6u);
  static_assert(std::is_same<std::remove_reference_t<decltype(b)>,
                             fused::tuple<char, const double, unsigned>>::value,
                "");

  auto x = fused::zip_view(a, b);
  static_assert(fused::tuple_size<decltype(x)>::value == 3u, "");
  auto x0 = fused::get<0>(x);
  auto x1 = fused::get<1>(x);
  auto x2 = fused::get<2>(x);

  EXPECT_EQ(&fused::get<0>(a), &fused::get<0>(x0));
  EXPECT_EQ(&fused::get<1>(a), &fused::get<0>(x1));
  EXPECT_EQ(&fused::get<2>(a), &fused::get<0>(x2));
  EXPECT_EQ(&fused::get<0>(b), &fused::get<1>(x0));
  EXPECT_EQ(&fused::get<1>(b), &fused::get<1>(x1));
  EXPECT_EQ(&fused::get<2>(b), &fused::get<1>(x2));

  fused::get<0>(x0) = 7;
  fused::get<1>(x2) = 8u;

  EXPECT_EQ(7, fused::get<0>(a));
  EXPECT_EQ(8u, fused::get<2>(b));
}

int main() {
  canZipTwoTuples();
  canZipViewTwoTuples();
  canZipViewTwoConstTuples();
  canZipViewTwoTuplesWithConsts();
  return 0;
}
<commit_msg>fused::tuple type is an implementation detail of used tie function skip static assert<commit_after>#include <archie/utils/fused/zip.h>
#include <archie/utils/test.h>

namespace fused = archie::utils::fused;

void canZipTwoTuples() {
  auto a = fused::make_tuple(1, 2u, '3');
  auto b = fused::make_tuple('4', 5.0, 6u);
  auto x = fused::zip(a, b);

  EXPECT_EQ(3u, fused::tuple_size<decltype(x)>::value);
  EXPECT_EQ(fused::make_tuple(1, '4'), fused::get<0>(x));
  EXPECT_EQ(fused::make_tuple(2u, 5.0), fused::get<1>(x));
  EXPECT_EQ(fused::make_tuple('3', 6u), fused::get<2>(x));
}

void canZipViewTwoTuples() {
  auto a = fused::make_tuple(1, 2u, '3');
  auto b = fused::make_tuple('4', 5.0, 6u);
  auto x = fused::zip_view(a, b);

  static_assert(fused::tuple_size<decltype(x)>::value == 3u, "");
  auto const& x0 = fused::get<0>(x);
  auto const& x1 = fused::get<1>(x);
  auto const& x2 = fused::get<2>(x);

  static_assert(
      std::is_same<decltype(x0), fused::tuple<int&, char&> const&>::value, "");
  static_assert(std::is_same<decltype(x1),
                             fused::tuple<unsigned&, double&> const&>::value,
                "");
  static_assert(
      std::is_same<decltype(x2), fused::tuple<char&, unsigned&> const&>::value,
      "");

  EXPECT_EQ(&fused::get<0>(a), &fused::get<0>(x0));
  EXPECT_EQ(&fused::get<1>(a), &fused::get<0>(x1));
  EXPECT_EQ(&fused::get<2>(a), &fused::get<0>(x2));

  EXPECT_EQ(&fused::get<0>(b), &fused::get<1>(x0));
  EXPECT_EQ(&fused::get<1>(b), &fused::get<1>(x1));
  EXPECT_EQ(&fused::get<2>(b), &fused::get<1>(x2));

  fused::get<0>(x1) = 7u;
  EXPECT_EQ(7u, fused::get<1>(a));
  fused::get<1>(x2) = 8u;
  EXPECT_EQ(8u, fused::get<2>(b));
}

void canZipViewTwoConstTuples() {
  auto const a = fused::make_tuple(1, 2u, '3');
  auto const b = fused::make_tuple('4', 5.0, 6u);
  auto x = fused::zip_view(a, b);

  static_assert(fused::tuple_size<decltype(x)>::value == 3u, "");
  auto x0 = fused::get<0>(x);
  auto x1 = fused::get<1>(x);
  auto x2 = fused::get<2>(x);

  EXPECT_EQ(&fused::get<0>(a), &fused::get<0>(x0));
  EXPECT_EQ(&fused::get<1>(a), &fused::get<0>(x1));
  EXPECT_EQ(&fused::get<2>(a), &fused::get<0>(x2));
  EXPECT_EQ(&fused::get<0>(b), &fused::get<1>(x0));
  EXPECT_EQ(&fused::get<1>(b), &fused::get<1>(x1));
  EXPECT_EQ(&fused::get<2>(b), &fused::get<1>(x2));
}

void canZipViewTwoTuplesWithConsts() {
  auto const c = 2u;
  auto const d = 5.0;
  auto a = fused::tuple<int, const unsigned, char>{1, c, '3'};
  auto b = fused::make_tuple('4', d, 6u);

  auto x = fused::zip_view(a, b);
  static_assert(fused::tuple_size<decltype(x)>::value == 3u, "");
  auto x0 = fused::get<0>(x);
  auto x1 = fused::get<1>(x);
  auto x2 = fused::get<2>(x);

  EXPECT_EQ(&fused::get<0>(a), &fused::get<0>(x0));
  EXPECT_EQ(&fused::get<1>(a), &fused::get<0>(x1));
  EXPECT_EQ(&fused::get<2>(a), &fused::get<0>(x2));
  EXPECT_EQ(&fused::get<0>(b), &fused::get<1>(x0));
  EXPECT_EQ(&fused::get<1>(b), &fused::get<1>(x1));
  EXPECT_EQ(&fused::get<2>(b), &fused::get<1>(x2));

  fused::get<0>(x0) = 7;
  fused::get<1>(x2) = 8u;

  EXPECT_EQ(7, fused::get<0>(a));
  EXPECT_EQ(8u, fused::get<2>(b));
}

int main() {
  canZipTwoTuples();
  canZipViewTwoTuples();
  canZipViewTwoConstTuples();
  canZipViewTwoTuplesWithConsts();
  return 0;
}
<|endoftext|>