<commit_before>#include <iomanip>
#include "InteractiveInterpreter.h"
#include "InterpretedDefinition.h"
#include "Util.h"
#include "Globals.h"

InteractiveInterpreter::InteractiveInterpreter(Emmental& interpreter)
	: Interpreter(interpreter)
{
	GenerateCommands();
}

int InteractiveInterpreter::RunLoop()
{
	Interpreter.OutputStream << "Entering Interactive Mode" << std::endl;
	Interpreter.OutputStream << "Inputs not starting with '__' will be interpreted by Emmental." << std::endl;
	Interpreter.OutputStream << "Type __help for a list of commands, or __exit to exit." << std::endl;

	while (true)
	{
		Interpreter.OutputStream << std::endl;
		Interpreter.OutputStream << "> ";
		std::string input;
		std::getline(Interpreter.InputStream, input);
		Interpreter.OutputStream << std::endl;

		if (EnableCommands)
		{
			// Special command to exit the loop
			if (input.find("__exit") == 0)
				return EXIT_SUCCESS;

			if (ParseCommand(input))
				continue;
		}

		for (auto&& x : input)
		{
			SymbolT symbol = (SymbolT)x;
			Interpreter.Interpret(symbol);
		}

		if (Globals::DebugMode)
		{
			Util::DescribeMemory(Interpreter, Interpreter.OutputStream);
		}
	}
}

void InteractiveInterpreter::AddCommand(const InteractiveCommand& command) { Commands.push_back(command); }

void InteractiveInterpreter::GenerateCommands()
{
	// These commands are handled as special cases, they'll never be called normally.
	AddCommand(InteractiveCommand("exit", "Exits this program.", nullptr));
	AddCommand(InteractiveCommand("help", "Shows this list.", nullptr));

	// Normal commands here
	AddCommand(InteractiveCommand("disablecommands", "Disables all commands, interpreting all input as Emmental code.", [&](Emmental& interpreter, std::string)
	{
		Util::Colorize(Util::ConsoleColor::BrightYellow, interpreter.OutputStream);
		interpreter.OutputStream << "WARNING! ";
		Util::Colorize(Util::ConsoleColor::Default, interpreter.OutputStream);
		interpreter.OutputStream << "All commands will be disabled, including __exit. Do you want to continue? (Y/N)";

		std::string answer;
		std::getline(Interpreter.InputStream, answer);
		if (answer == "y" || answer == "Y")
		{
			EnableCommands = false;
			interpreter.OutputStream << "All commands disabled." << std::endl;
		}
		else
		{
			interpreter.OutputStream << "Operation cancelled. " << std::endl;
		}
	}));
	AddCommand(InteractiveCommand("reset", "Resets the interpreter back to its original state.", [](Emmental& interpreter, std::string)
	{
		interpreter.Reset();
		interpreter.OutputStream << "Interpreter reset." << std::endl;
	}));

	AddCommand(InteractiveCommand("clearstack", "Clears the stack.", [](Emmental& interpreter, std::string)
	{
		interpreter.ClearStack();
		interpreter.OutputStream << "Stack cleared." << std::endl;
	}));

	AddCommand(InteractiveCommand("clearqueue", "Clears the queue.", [](Emmental& interpreter, std::string)
	{
		interpreter.ClearQueue();
		interpreter.OutputStream << "Queue cleared." << std::endl;
	}));

	AddCommand(InteractiveCommand("resetdefs", "Resets all symbol definitions back to their original native definitions.", [](Emmental& interpreter, std::string)
	{
		interpreter.ResetDefinitions();
		interpreter.OutputStream << "Symbol definitions reset to original native definitions." << std::endl;
	}));

	AddCommand(InteractiveCommand("undef", "Undefines a symbol. Pass the symbol number as an argument.", [](Emmental& interpreter, std::string arg)
	{
		SymbolT symbol;

		try
		{
			symbol = std::stoi(arg);
		}
		catch (std::invalid_argument)
		{
			interpreter.OutputStream << "Invalid symbol number." << std::endl;
			return;
		}
		catch (std::out_of_range)
		{
			interpreter.OutputStream << "Symbol value out of range." << std::endl;
			return;
		}

		interpreter.Undefine(symbol);
		interpreter.OutputStream << "Undefined symbol ";
		Util::DescribeSymbol(symbol, interpreter.OutputStream);
		interpreter.OutputStream << "." << std::endl;

	}));

	AddCommand(InteractiveCommand("debug", "Toggles debug mode on/off", [](Emmental& interpreter, std::string)
	{
		Globals::DebugMode = !Globals::DebugMode;
		interpreter.OutputStream << "Debug mode is now " << (Globals::DebugMode ? "on" : "off") << "." << std::endl;
	}));

	AddCommand(InteractiveCommand("color", "Toggles Virtual Console coloring on/off", [](Emmental& interpreter, std::string)
	{
		Globals::UseVirtualConsole = !Globals::UseVirtualConsole;
		interpreter.OutputStream << "Virtual Console coloring is now " << (Globals::UseVirtualConsole ? "on" : "off") << "." << std::endl;
	}));

	AddCommand(InteractiveCommand("optimize", "Toggles program optimization on/off", [](Emmental& interpreter, std::string)
	{
		Globals::OptimizeProgram = !Globals::OptimizeProgram;
		interpreter.OutputStream << "Optimization is now " << (Globals::OptimizeProgram ? "on" : "off") << "." << std::endl;
	}));

	AddCommand(InteractiveCommand("memory", "Shows the current stack and queue", [](Emmental& interpreter, std::string)
	{
		Util::DescribeMemory(interpreter, interpreter.OutputStream);
		interpreter.OutputStream << std::endl;
	}));

	AddCommand(InteractiveCommand("pushraw",
		"Pushes its argument into the stack (interpreted as raw ASCII bytes).",
		[](Emmental& interpreter, std::string args)
	{
		for (auto& symbol : args)
		{
			interpreter.Push(symbol);
			Util::DescribeSymbol(symbol, interpreter.OutputStream);
			interpreter.OutputStream << ", ";
		}

		interpreter.OutputStream << std::endl;
		interpreter.OutputStream << "Pushed " << args.length() << " bytes into the stack." << std::endl;
		interpreter.OutputStream << std::endl;

		Util::DescribeMemory(interpreter, interpreter.OutputStream);
		interpreter.OutputStream << std::endl;

	}));

	AddCommand(InteractiveCommand("defs",
		"Without argument: Displays all current symbol definitions. With symbol number as argument: Displays all captured definitions for the symbol.",
		[](Emmental& interpreter, std::string arg)
	{
		if (arg.empty())
		{
			interpreter.OutputStream << "Current interpreter definitions: " << std::endl;
			Util::DescribeDefinitions(interpreter.CopyDefinitions(), interpreter.OutputStream);
			interpreter.OutputStream << std::endl;
		}
		else
		{
			SymbolT symbol;

			try
			{
				symbol = std::stoi(arg);
			}
			catch (std::invalid_argument)
			{
				interpreter.OutputStream << "Invalid symbol number." << std::endl;
				return;
			}
			catch (std::out_of_range)
			{
				interpreter.OutputStream << "Symbol value out of range." << std::endl;
				return;
			}

			Util::DescribeDefinition(symbol, interpreter.CopyDefinitions(), true, interpreter.OutputStream);
			interpreter.OutputStream << std::endl;
		}
	}));

	AddCommand(InteractiveCommand("info", "Display interpreter information.", [](Emmental& interpreter, std::string)
	{
		interpreter.OutputStream << "Gory Emmental Interpreter 1.0.0 by Davipb" << std::endl;

		Util::Colorize(Util::ConsoleColor::BrightGreen, interpreter.OutputStream);
		interpreter.OutputStream << "== Compile-Time Settings ==" << std::endl;
		Util::Colorize(Util::ConsoleColor::Default, interpreter.OutputStream);
		interpreter.OutputStream << "Symbol Type: " << typeid(SymbolT).name() << std::endl;
		interpreter.OutputStream << "Symbol Size: " << sizeof(SymbolT) << " byte(s)" << std::endl;
		interpreter.OutputStream << "Max Stack Size: " << EMMENTAL_MAX_STACK_SIZE << std::endl;
		interpreter.OutputStream << "Max Queue Size: " << EMMENTAL_MAX_QUEUE_SIZE << std::endl;
		interpreter.OutputStream << "Max Recursion Level: " << EMMENTAL_MAX_RECURSION_LEVEL << std::endl;

		Util::Colorize(Util::ConsoleColor::BrightGreen, interpreter.OutputStream);
		interpreter.OutputStream << "== Runtime Settings ==" << std::endl;
		Util::Colorize(Util::ConsoleColor::Default, interpreter.OutputStream);
		interpreter.OutputStream << "Debug Mode: " << (Globals::DebugMode ? "On" : "Off") << std::endl;
		interpreter.OutputStream << "Colors: " << (Globals::UseVirtualConsole ? "On" : "Off") << std::endl;
		interpreter.OutputStream << "Optimization: " << (Globals::OptimizeProgram ? "On" : "Off") << std::endl;

	}));
}

bool InteractiveInterpreter::ParseCommand(std::string input)
{
	if (input.find("__") != 0)
		return false;

	std::string command = input.substr(2, input.size() - 2);

	if (command.find("help") == 0)
	{
		Interpreter.OutputStream << "Commands are case-sensitive. Arguments come right after a command." << std::endl;
		Interpreter.OutputStream << std::endl;

		for (auto& x : Commands)
		{
			Util::Colorize(Util::ConsoleColor::BrightGreen, Interpreter.OutputStream);
			Interpreter.OutputStream << "__" << x.GetName() << ": ";
			Util::Colorize(Util::ConsoleColor::Default, Interpreter.OutputStream);
			Interpreter.OutputStream << x.GetDescription() << std::endl;
		}
		return true;
	}

	for (auto& x : Commands)
	{
		if (command.find(x.GetName()) == 0)
		{
			std::string argument = command.substr(x.GetName().size(), command.size() - x.GetName().size());
			// Trim initial space from argument to allow "__command arg" instead of just "__commandarg"
			if (argument.length() > 0 && argument[0] == ' ')
				argument = argument.substr(1, argument.length() - 1);

			x.Execute(Interpreter, argument);
			return true;
		}
	}

	Util::Colorize(Util::ConsoleColor::Red, Interpreter.OutputStream);
	Interpreter.OutputStream << "Unknown command. Use __help for a list of commands." << std::endl;
	Util::Colorize(Util::ConsoleColor::Default, Interpreter.OutputStream);

	return true;
}<commit_msg>Improve Interactivity command parsing<commit_after>#include <iomanip>
#include "InteractiveInterpreter.h"
#include "InterpretedDefinition.h"
#include "Util.h"
#include "Globals.h"

InteractiveInterpreter::InteractiveInterpreter(Emmental& interpreter)
	: Interpreter(interpreter)
{
	GenerateCommands();
}

int InteractiveInterpreter::RunLoop()
{
	Interpreter.OutputStream << "Entering Interactive Mode" << std::endl;
	Interpreter.OutputStream << "Inputs not starting with '__' will be interpreted by Emmental." << std::endl;
	Interpreter.OutputStream << "Type __help for a list of commands, or __exit to exit." << std::endl;

	while (true)
	{
		Interpreter.OutputStream << std::endl;
		Interpreter.OutputStream << "> ";
		std::string input;
		std::getline(Interpreter.InputStream, input);
		Interpreter.OutputStream << std::endl;

		if (EnableCommands)
		{
			// Special command to exit the loop
			if (input.find("__exit") == 0)
				return EXIT_SUCCESS;

			if (ParseCommand(input))
				continue;
		}

		for (auto&& x : input)
		{
			SymbolT symbol = (SymbolT)x;
			Interpreter.Interpret(symbol);
		}

		if (Globals::DebugMode)
		{
			Util::DescribeMemory(Interpreter, Interpreter.OutputStream);
		}
	}
}

void InteractiveInterpreter::AddCommand(const InteractiveCommand& command) { Commands.push_back(command); }

void InteractiveInterpreter::GenerateCommands()
{
	// These commands are handled as special cases, they'll never be called normally.
	AddCommand(InteractiveCommand("exit", "Exits this program.", nullptr));
	AddCommand(InteractiveCommand("help", "Shows this list.", nullptr));

	// Normal commands here
	AddCommand(InteractiveCommand("disablecommands", "Disables all commands, interpreting all input as Emmental code.", [&](Emmental& interpreter, std::string)
	{
		Util::Colorize(Util::ConsoleColor::BrightYellow, interpreter.OutputStream);
		interpreter.OutputStream << "WARNING! ";
		Util::Colorize(Util::ConsoleColor::Default, interpreter.OutputStream);
		interpreter.OutputStream << "All commands will be disabled, including __exit. Do you want to continue? (Y/N)";

		std::string answer;
		std::getline(Interpreter.InputStream, answer);
		if (answer == "y" || answer == "Y")
		{
			EnableCommands = false;
			interpreter.OutputStream << "All commands disabled." << std::endl;
		}
		else
		{
			interpreter.OutputStream << "Operation cancelled. " << std::endl;
		}
	}));
	AddCommand(InteractiveCommand("reset", "Resets the interpreter back to its original state.", [](Emmental& interpreter, std::string)
	{
		interpreter.Reset();
		interpreter.OutputStream << "Interpreter reset." << std::endl;
	}));

	AddCommand(InteractiveCommand("clearstack", "Clears the stack.", [](Emmental& interpreter, std::string)
	{
		interpreter.ClearStack();
		interpreter.OutputStream << "Stack cleared." << std::endl;
	}));

	AddCommand(InteractiveCommand("clearqueue", "Clears the queue.", [](Emmental& interpreter, std::string)
	{
		interpreter.ClearQueue();
		interpreter.OutputStream << "Queue cleared." << std::endl;
	}));

	AddCommand(InteractiveCommand("resetdefs", "Resets all symbol definitions back to their original native definitions.", [](Emmental& interpreter, std::string)
	{
		interpreter.ResetDefinitions();
		interpreter.OutputStream << "Symbol definitions reset to original native definitions." << std::endl;
	}));

	AddCommand(InteractiveCommand("undef", "Undefines a symbol. Pass the symbol number as an argument.", [](Emmental& interpreter, std::string arg)
	{
		SymbolT symbol;

		try
		{
			symbol = std::stoi(arg);
		}
		catch (std::invalid_argument)
		{
			interpreter.OutputStream << "Invalid symbol number." << std::endl;
			return;
		}
		catch (std::out_of_range)
		{
			interpreter.OutputStream << "Symbol value out of range." << std::endl;
			return;
		}

		interpreter.Undefine(symbol);
		interpreter.OutputStream << "Undefined symbol ";
		Util::DescribeSymbol(symbol, interpreter.OutputStream);
		interpreter.OutputStream << "." << std::endl;

	}));

	AddCommand(InteractiveCommand("debug", "Toggles debug mode on/off", [](Emmental& interpreter, std::string)
	{
		Globals::DebugMode = !Globals::DebugMode;
		interpreter.OutputStream << "Debug mode is now " << (Globals::DebugMode ? "on" : "off") << "." << std::endl;
	}));

	AddCommand(InteractiveCommand("color", "Toggles Virtual Console coloring on/off", [](Emmental& interpreter, std::string)
	{
		Globals::UseVirtualConsole = !Globals::UseVirtualConsole;
		interpreter.OutputStream << "Virtual Console coloring is now " << (Globals::UseVirtualConsole ? "on" : "off") << "." << std::endl;
	}));

	AddCommand(InteractiveCommand("optimize", "Toggles program optimization on/off", [](Emmental& interpreter, std::string)
	{
		Globals::OptimizeProgram = !Globals::OptimizeProgram;
		interpreter.OutputStream << "Optimization is now " << (Globals::OptimizeProgram ? "on" : "off") << "." << std::endl;
	}));

	AddCommand(InteractiveCommand("memory", "Shows the current stack and queue", [](Emmental& interpreter, std::string)
	{
		Util::DescribeMemory(interpreter, interpreter.OutputStream);
		interpreter.OutputStream << std::endl;
	}));

	AddCommand(InteractiveCommand("pushraw",
		"Pushes its argument into the stack (interpreted as raw ASCII bytes).",
		[](Emmental& interpreter, std::string args)
	{
		for (auto& symbol : args)
		{
			interpreter.Push(symbol);
			Util::DescribeSymbol(symbol, interpreter.OutputStream);
			interpreter.OutputStream << ", ";
		}

		interpreter.OutputStream << std::endl;
		interpreter.OutputStream << "Pushed " << args.length() << " bytes into the stack." << std::endl;
		interpreter.OutputStream << std::endl;

		Util::DescribeMemory(interpreter, interpreter.OutputStream);
		interpreter.OutputStream << std::endl;

	}));

	AddCommand(InteractiveCommand("defs",
		"Without argument: Displays all current symbol definitions. With symbol number as argument: Displays all captured definitions for the symbol.",
		[](Emmental& interpreter, std::string arg)
	{
		if (arg.empty())
		{
			interpreter.OutputStream << "Current interpreter definitions: " << std::endl;
			Util::DescribeDefinitions(interpreter.CopyDefinitions(), interpreter.OutputStream);
			interpreter.OutputStream << std::endl;
		}
		else
		{
			SymbolT symbol;

			try
			{
				symbol = std::stoi(arg);
			}
			catch (std::invalid_argument)
			{
				interpreter.OutputStream << "Invalid symbol number." << std::endl;
				return;
			}
			catch (std::out_of_range)
			{
				interpreter.OutputStream << "Symbol value out of range." << std::endl;
				return;
			}

			Util::DescribeDefinition(symbol, interpreter.CopyDefinitions(), true, interpreter.OutputStream);
			interpreter.OutputStream << std::endl;
		}
	}));

	AddCommand(InteractiveCommand("info", "Display interpreter information.", [](Emmental& interpreter, std::string)
	{
		interpreter.OutputStream << "Gory Emmental Interpreter 1.0.0 by Davipb" << std::endl;

		Util::Colorize(Util::ConsoleColor::BrightGreen, interpreter.OutputStream);
		interpreter.OutputStream << "== Compile-Time Settings ==" << std::endl;
		Util::Colorize(Util::ConsoleColor::Default, interpreter.OutputStream);
		interpreter.OutputStream << "Symbol Type: " << typeid(SymbolT).name() << std::endl;
		interpreter.OutputStream << "Symbol Size: " << sizeof(SymbolT) << " byte(s)" << std::endl;
		interpreter.OutputStream << "Max Stack Size: " << EMMENTAL_MAX_STACK_SIZE << std::endl;
		interpreter.OutputStream << "Max Queue Size: " << EMMENTAL_MAX_QUEUE_SIZE << std::endl;
		interpreter.OutputStream << "Max Recursion Level: " << EMMENTAL_MAX_RECURSION_LEVEL << std::endl;

		Util::Colorize(Util::ConsoleColor::BrightGreen, interpreter.OutputStream);
		interpreter.OutputStream << "== Runtime Settings ==" << std::endl;
		Util::Colorize(Util::ConsoleColor::Default, interpreter.OutputStream);
		interpreter.OutputStream << "Debug Mode: " << (Globals::DebugMode ? "On" : "Off") << std::endl;
		interpreter.OutputStream << "Colors: " << (Globals::UseVirtualConsole ? "On" : "Off") << std::endl;
		interpreter.OutputStream << "Optimization: " << (Globals::OptimizeProgram ? "On" : "Off") << std::endl;

	}));
}

bool InteractiveInterpreter::ParseCommand(std::string input)
{
	if (input.find("__") != 0)
		return false;

	std::string command = input.substr(2, input.size() - 2);

	if (command.find("help") == 0)
	{
		Interpreter.OutputStream << "Commands are case-sensitive. Arguments come right after a command." << std::endl;
		Interpreter.OutputStream << std::endl;

		for (auto& x : Commands)
		{
			Util::Colorize(Util::ConsoleColor::BrightGreen, Interpreter.OutputStream);
			Interpreter.OutputStream << "__" << x.GetName() << ": ";
			Util::Colorize(Util::ConsoleColor::Default, Interpreter.OutputStream);
			Interpreter.OutputStream << x.GetDescription() << std::endl;
		}
		return true;
	}

	std::string commandName = command;
	std::string argument;
	auto spaceLocation = commandName.find(' ');
	if (spaceLocation != commandName.length())
	{
		commandName = command.substr(0, spaceLocation);
		argument = command.substr(spaceLocation + 1, command.length() - spaceLocation - 1);
	}

	for (auto& x : Commands)
	{
		if (x.GetName() == commandName)
		{
			x.Execute(Interpreter, argument);
			return true;
		}
	}

	Util::Colorize(Util::ConsoleColor::Red, Interpreter.OutputStream);
	Interpreter.OutputStream << "Unknown command '" << commandName << "'. Use __help for a list of commands." << std::endl;
	Util::Colorize(Util::ConsoleColor::Default, Interpreter.OutputStream);

	return true;
}<|endoftext|>


<commit_before>// Copyright (c) 2011-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "buyiopdialog.h"

#include "addressbookpage.h"

#include <chrono>
#include <thread>

#include <QDesktopServices>
#include <QGridLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QLineEdit>
#include <QNetworkRequest>
#include <QObject>
#include <QSizePolicy>
#include <QUrl>
#include <iostream>

BuyIoPDialog::BuyIoPDialog(const PlatformStyle* _platformStyle, QWidget* parent) : QDialog(parent), platformStyle(_platformStyle), model(0)
{
    slotblock = false;

    QVBoxLayout* layout = new QVBoxLayout(this);

    // ADRESS SELECTION
    adressLineEdit = new QLineEdit(this);
    adressLineEdit->setPlaceholderText(tr("choose adress or paste your own"));
    selectAdress = new QPushButton(tr("choose"));

    mailEdit = new QLineEdit(this);
    mailEdit->setPlaceholderText(tr("your email adress"));

    QLabel* adressInfoLabel = new QLabel(tr("exchange service provided by indacoin.com"));
    adressInfoLabel->setObjectName("buy_adressInfo");

    QWidget* addressWidget = new QWidget(this);
    QVBoxLayout* topLayout = new QVBoxLayout(addressWidget);
    QHBoxLayout* adressLayout = new QHBoxLayout();
    QHBoxLayout* mailLayout = new QHBoxLayout();

    adressLayout->setContentsMargins(3, 0, 3, 0);
    adressLayout->setSpacing(3);
    adressLayout->addWidget(adressLineEdit);
    adressLayout->addWidget(selectAdress);
    mailLayout->addWidget(mailEdit);

    topLayout->addLayout(adressLayout);
    topLayout->addSpacing(20);
    topLayout->addLayout(mailLayout);
    topLayout->addSpacing(5);
    topLayout->addWidget(adressInfoLabel);

    layout->addWidget(addressWidget);

    layout->addSpacing(30);

    // AMOUNT SELECTION
    amountInfoLabel = new QLabel();
    QLabel* amountVaryInfoLabel = new QLabel(tr("the amount may vary"));
    amountInfoLabel->setObjectName("buy_amountInfo");
    amountVaryInfoLabel->setObjectName("buy_amountVaryInfo");

    amountIOP = new QLabel();
    amountIOP->setMaximumWidth(350);
    amountIOP->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
    amountIOP->setObjectName("buy_amountIOP");

    IOPLabel = new QLabel("IOP");
    IOPLabel->setObjectName("buy_IOPLabel");
    //IOPLabel->setMaximumWidth(500);

    currency = new QComboBox(this);
    currency->addItem("USD");
    currency->addItem("EUR");
    currency->addItem("RUB");
    currency->setObjectName("buy_currency");
    //currency->setMaximumWidth(500);

    paySpinBox = new QDoubleSpinBox();
    paySpinBox->setObjectName("pay_spinbox");
    paySpinBox->setRange(50, 50000);
    paySpinBox->setDecimals(2);
    paySpinBox->setSingleStep(1);
    paySpinBox->setValue(MIN_PRICE[currency->currentIndex()]);
    //paySpinBox->setMaximumWidth(350);
    paySpinBox->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);

    buyButton = new QPushButton(tr("buy"));
    buyButton->setObjectName("buyButton");
    buyButton->setEnabled(false);

    QWidget* bottomWidget = new QWidget(this);
    QGridLayout* bottomLayout = new QGridLayout(bottomWidget);

    QWidget* buttonWidget = new QWidget(bottomWidget);
    QHBoxLayout* buttonLayout = new QHBoxLayout(buttonWidget);

    buttonLayout->addWidget(buyButton);

    QWidget* payAmount = new QWidget(bottomWidget);
    QGridLayout* payLayout = new QGridLayout(payAmount);
    payLayout->setHorizontalSpacing(10);
    payLayout->setVerticalSpacing(5);
    payLayout->setRowMinimumHeight(2,10);
    payLayout->setColumnMinimumWidth(0,100);

    payLayout->addWidget(paySpinBox,0,0);
    payLayout->addWidget(currency,0,1);
    payLayout->addWidget(amountInfoLabel,1,0,1,2);

    payLayout->addWidget(amountIOP,3,0);
    payLayout->addWidget(IOPLabel,3,1);
    payLayout->addWidget(amountVaryInfoLabel,4,0,2,1);

    bottomLayout->addWidget(payAmount, 0, 0, Qt::AlignLeft);
    bottomLayout->addWidget(buttonWidget, 0, 1, Qt::AlignBottom | Qt::AlignRight);

    layout->addWidget(bottomWidget);

    amountInfoLabel->setText(tr("minimum exchange value: ").append(QString::number(MIN_PRICE[currency->currentIndex()])).append(" ").append(CURRENCY[currency->currentIndex()]));

    QFrame* lineb1 = new QFrame(this);
    lineb1->setObjectName(QStringLiteral("lineb1"));
    lineb1->setFrameShape(QFrame::HLine);
    lineb1->setFrameShadow(QFrame::Sunken);
    layout->addWidget(lineb1);

    layout->addSpacing(20);

    //network management
    iopPriceNAM = new QNetworkAccessManager();

    //SLOTS
    connect(currency, SIGNAL(currentIndexChanged(int)), this, SLOT(physicalUpdated(int)));
    connect(adressLineEdit, SIGNAL(textChanged(const QString&)), this, SLOT(adressChanged(const QString&)));
    connect(selectAdress, SIGNAL(clicked()), this, SLOT(chooseAdress()));
    connect(paySpinBox, SIGNAL(valueChanged(double)), this, SLOT(physicalUpdated(double)));
    connect(iopPriceNAM, SIGNAL(finished(QNetworkReply*)), this, SLOT(gotIoPPrice(QNetworkReply*)));
    connect(buyButton, SIGNAL(clicked()), this, SLOT(sendBuyRequest()));

    updateIoPPrice(paySpinBox->value());
}

void BuyIoPDialog::setModel(WalletModel* _model)
{
    this->model = _model;
}

void BuyIoPDialog::adressChanged(const QString& txt)
{
    if (adressLineEdit->text().isEmpty() || model->validateAddress(adressLineEdit->text())) {
        buyButton->setEnabled(true);
        adressLineEdit->setStyleSheet("");
        //std::cout << "buybutton enabled" << std::endl;
    } else {
        buyButton->setEnabled(false);
        //adressLineEdit->setValid(false);
        adressLineEdit->setStyleSheet("background: rgb(155,0,0);");

        //std::cout << "buybutton enabled" << std::endl;
    }
}

void BuyIoPDialog::chooseAdress()
{
    if (model) {
        AddressBookPage dlg(platformStyle, AddressBookPage::ForSelection, AddressBookPage::ReceivingTab, this);
        dlg.setModel(model->getAddressTableModel());
        if (dlg.exec()) {
            adressLineEdit->setText(dlg.getReturnValue());
        }
    }
}

void BuyIoPDialog::physicalUpdated(int i)
{
    BuyIoPDialog::physicalUpdated(paySpinBox->value());
}

void BuyIoPDialog::physicalUpdated(double i)
{

    amountInfoLabel->setText(tr("minimum exchange value: ").append(QString::number(MIN_PRICE[currency->currentIndex()])).append(" ").append(CURRENCY[currency->currentIndex()]));

    if (i > MIN_PRICE[currency->currentIndex()] && i < MAX_PRICE[currency->currentIndex()])
        updateIoPPrice(i);
    else {
        paySpinBox->setRange(MIN_PRICE[currency->currentIndex()], MAX_PRICE[currency->currentIndex()]);
        /* if (i <= MIN_PRICE[currency->currentIndex()])
            paySpinBox->setValue(MIN_PRICE[currency->currentIndex()]);
        if (i >= MAX_PRICE[currency->currentIndex()])
            paySpinBox->setValue(MAX_PRICE[currency->currentIndex()]); */
    }
}

void BuyIoPDialog::updateIoPPrice(double amount)
{
    responsed = false;
    QNetworkRequest request(QUrl(QString(GET_PRICE).append(CURRENCY[currency->currentIndex()]).append(SEPERATOR).append(IOP_CURRENCY).append(SEPERATOR).append(QString::number(amount).append(SEPERATOR))));
    //std::cout << "iop price: " << request.url().toString().toStdString() << std::endl;
    iopPriceNAM->get(request);
}

void BuyIoPDialog::sendBuyRequest()
{
    QString adress = QString(BUY_URL).append(PARTNER_NAME).append(CUR_FROM).append(CURRENCY[currency->currentIndex()]).append(CUR_TO).append(IOP_CURRENCY).append(AMOUNT).append(QString::number(paySpinBox->value()).append(ADDRESS).append(adressLineEdit->text()).append(USER_ID).append(mailEdit->text().replace('@',"%40",Qt::CaseInsensitive)));
    //std::cout << "buy url: " << adress.toStdString() << std::endl;

    QDesktopServices::openUrl(QUrl(adress, QUrl::TolerantMode));
}

void BuyIoPDialog::gotIoPPrice(QNetworkReply* reply)
{
    if (reply->error()) {
        std::cout << "ERROR! " << reply->errorString().toStdString() << std::endl; //Error handling
        responsed = true;
        return;
    }
    QString answer = reply->readAll();
    bool successfullParsed;
    iopPrice = answer.toDouble(&successfullParsed);
    //std::cout << "GOT PRICE: " << answer.toStdString() << std::endl;
    amountIOP->setText(QString::number(iopPrice));
    responsed = true;
    return;
}

BuyIoPDialog::~BuyIoPDialog()
{
}
<commit_msg>matching number seperators<commit_after>// Copyright (c) 2011-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "buyiopdialog.h"

#include "addressbookpage.h"

#include <chrono>
#include <thread>

#include <QDesktopServices>
#include <QGridLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QLineEdit>
#include <QLocale>
#include <QNetworkRequest>
#include <QObject>
#include <QSizePolicy>
#include <QUrl>
#include <iostream>

BuyIoPDialog::BuyIoPDialog(const PlatformStyle* _platformStyle, QWidget* parent) : QDialog(parent), platformStyle(_platformStyle), model(0)
{
    slotblock = false;

    QVBoxLayout* layout = new QVBoxLayout(this);

    // ADRESS SELECTION
    adressLineEdit = new QLineEdit(this);
    adressLineEdit->setPlaceholderText(tr("choose adress or paste your own"));
    selectAdress = new QPushButton(tr("choose"));

    mailEdit = new QLineEdit(this);
    mailEdit->setPlaceholderText(tr("your email adress"));

    QLabel* adressInfoLabel = new QLabel(tr("exchange service provided by indacoin.com"));
    adressInfoLabel->setObjectName("buy_adressInfo");

    QWidget* addressWidget = new QWidget(this);
    QVBoxLayout* topLayout = new QVBoxLayout(addressWidget);
    QHBoxLayout* adressLayout = new QHBoxLayout();
    QHBoxLayout* mailLayout = new QHBoxLayout();

    adressLayout->setContentsMargins(3, 0, 3, 0);
    adressLayout->setSpacing(3);
    adressLayout->addWidget(adressLineEdit);
    adressLayout->addWidget(selectAdress);
    mailLayout->addWidget(mailEdit);

    topLayout->addLayout(adressLayout);
    topLayout->addSpacing(20);
    topLayout->addLayout(mailLayout);
    topLayout->addSpacing(5);
    topLayout->addWidget(adressInfoLabel);

    layout->addWidget(addressWidget);

    layout->addSpacing(30);

    // AMOUNT SELECTION
    amountInfoLabel = new QLabel();
    QLabel* amountVaryInfoLabel = new QLabel(tr("the amount may vary"));
    amountInfoLabel->setObjectName("buy_amountInfo");
    amountVaryInfoLabel->setObjectName("buy_amountVaryInfo");

    amountIOP = new QLabel();
    amountIOP->setMaximumWidth(350);
    amountIOP->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
    amountIOP->setObjectName("buy_amountIOP");

    IOPLabel = new QLabel("IOP");
    IOPLabel->setObjectName("buy_IOPLabel");
    //IOPLabel->setMaximumWidth(500);

    currency = new QComboBox(this);
    currency->addItem("USD");
    currency->addItem("EUR");
    currency->addItem("RUB");
    currency->setObjectName("buy_currency");
    //currency->setMaximumWidth(500);

    paySpinBox = new QDoubleSpinBox();
    paySpinBox->setObjectName("pay_spinbox");
    paySpinBox->setRange(50, 50000);
    paySpinBox->setDecimals(2);
    paySpinBox->setSingleStep(1);
    paySpinBox->setLocale(QLocale::Language::English);
    paySpinBox->setValue(MIN_PRICE[currency->currentIndex()]);
    //paySpinBox->setMaximumWidth(350);
    paySpinBox->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);

    buyButton = new QPushButton(tr("buy"));
    buyButton->setObjectName("buyButton");
    buyButton->setEnabled(false);

    QWidget* bottomWidget = new QWidget(this);
    QGridLayout* bottomLayout = new QGridLayout(bottomWidget);

    QWidget* buttonWidget = new QWidget(bottomWidget);
    QHBoxLayout* buttonLayout = new QHBoxLayout(buttonWidget);

    buttonLayout->addWidget(buyButton);

    QWidget* payAmount = new QWidget(bottomWidget);
    QGridLayout* payLayout = new QGridLayout(payAmount);
    payLayout->setHorizontalSpacing(10);
    payLayout->setVerticalSpacing(5);
    payLayout->setRowMinimumHeight(2,10);
    payLayout->setColumnMinimumWidth(0,100);

    payLayout->addWidget(paySpinBox,0,0);
    payLayout->addWidget(currency,0,1);
    payLayout->addWidget(amountInfoLabel,1,0,1,2);

    payLayout->addWidget(amountIOP,3,0);
    payLayout->addWidget(IOPLabel,3,1);
    payLayout->addWidget(amountVaryInfoLabel,4,0,2,1);

    bottomLayout->addWidget(payAmount, 0, 0, Qt::AlignLeft);
    bottomLayout->addWidget(buttonWidget, 0, 1, Qt::AlignBottom | Qt::AlignRight);

    layout->addWidget(bottomWidget);

    amountInfoLabel->setText(tr("minimum exchange value: ").append(QString::number(MIN_PRICE[currency->currentIndex()])).append(" ").append(CURRENCY[currency->currentIndex()]));

    QFrame* lineb1 = new QFrame(this);
    lineb1->setObjectName(QStringLiteral("lineb1"));
    lineb1->setFrameShape(QFrame::HLine);
    lineb1->setFrameShadow(QFrame::Sunken);
    layout->addWidget(lineb1);

    layout->addSpacing(20);

    //network management
    iopPriceNAM = new QNetworkAccessManager();

    //SLOTS
    connect(currency, SIGNAL(currentIndexChanged(int)), this, SLOT(physicalUpdated(int)));
    connect(adressLineEdit, SIGNAL(textChanged(const QString&)), this, SLOT(adressChanged(const QString&)));
    connect(selectAdress, SIGNAL(clicked()), this, SLOT(chooseAdress()));
    connect(paySpinBox, SIGNAL(valueChanged(double)), this, SLOT(physicalUpdated(double)));
    connect(iopPriceNAM, SIGNAL(finished(QNetworkReply*)), this, SLOT(gotIoPPrice(QNetworkReply*)));
    connect(buyButton, SIGNAL(clicked()), this, SLOT(sendBuyRequest()));

    updateIoPPrice(paySpinBox->value());
}

void BuyIoPDialog::setModel(WalletModel* _model)
{
    this->model = _model;
}

void BuyIoPDialog::adressChanged(const QString& txt)
{
    if (adressLineEdit->text().isEmpty() || model->validateAddress(adressLineEdit->text())) {
        buyButton->setEnabled(true);
        adressLineEdit->setStyleSheet("");
        //std::cout << "buybutton enabled" << std::endl;
    } else {
        buyButton->setEnabled(false);
        //adressLineEdit->setValid(false);
        adressLineEdit->setStyleSheet("background: rgb(155,0,0);");

        //std::cout << "buybutton enabled" << std::endl;
    }
}

void BuyIoPDialog::chooseAdress()
{
    if (model) {
        AddressBookPage dlg(platformStyle, AddressBookPage::ForSelection, AddressBookPage::ReceivingTab, this);
        dlg.setModel(model->getAddressTableModel());
        if (dlg.exec()) {
            adressLineEdit->setText(dlg.getReturnValue());
        }
    }
}

void BuyIoPDialog::physicalUpdated(int i)
{
    BuyIoPDialog::physicalUpdated(paySpinBox->value());
}

void BuyIoPDialog::physicalUpdated(double i)
{

    amountInfoLabel->setText(tr("minimum exchange value: ").append(QString::number(MIN_PRICE[currency->currentIndex()])).append(" ").append(CURRENCY[currency->currentIndex()]));

    if (i > MIN_PRICE[currency->currentIndex()] && i < MAX_PRICE[currency->currentIndex()])
        updateIoPPrice(i);
    else {
        paySpinBox->setRange(MIN_PRICE[currency->currentIndex()], MAX_PRICE[currency->currentIndex()]);
        /* if (i <= MIN_PRICE[currency->currentIndex()])
            paySpinBox->setValue(MIN_PRICE[currency->currentIndex()]);
        if (i >= MAX_PRICE[currency->currentIndex()])
            paySpinBox->setValue(MAX_PRICE[currency->currentIndex()]); */
    }
}

void BuyIoPDialog::updateIoPPrice(double amount)
{
    responsed = false;
    QNetworkRequest request(QUrl(QString(GET_PRICE).append(CURRENCY[currency->currentIndex()]).append(SEPERATOR).append(IOP_CURRENCY).append(SEPERATOR).append(QString::number(amount).append(SEPERATOR))));
    //std::cout << "iop price: " << request.url().toString().toStdString() << std::endl;
    iopPriceNAM->get(request);
}

void BuyIoPDialog::sendBuyRequest()
{
    QString adress = QString(BUY_URL).append(PARTNER_NAME).append(CUR_FROM).append(CURRENCY[currency->currentIndex()]).append(CUR_TO).append(IOP_CURRENCY).append(AMOUNT).append(QString::number(paySpinBox->value()).append(ADDRESS).append(adressLineEdit->text()).append(USER_ID).append(mailEdit->text().replace('@',"%40",Qt::CaseInsensitive)));
    //std::cout << "buy url: " << adress.toStdString() << std::endl;

    QDesktopServices::openUrl(QUrl(adress, QUrl::TolerantMode));
}

void BuyIoPDialog::gotIoPPrice(QNetworkReply* reply)
{
    if (reply->error()) {
        std::cout << "ERROR! " << reply->errorString().toStdString() << std::endl; //Error handling
        responsed = true;
        return;
    }
    QString answer = reply->readAll();
    bool successfullParsed;
    iopPrice = answer.toDouble(&successfullParsed);
    //std::cout << "GOT PRICE: " << answer.toStdString() << std::endl;
    amountIOP->setText(QString::number(iopPrice));
    responsed = true;
    return;
}

BuyIoPDialog::~BuyIoPDialog()
{
}
<|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
//
// ---------------------------------------------------------------------------
//
// A portion of this file was generated by the CEF translator tool.  When
// making changes by hand only do so within the body of existing function
// implementations. See the translator.README.txt file in the tools directory
// for more information.
//

#include "libcef_dll/cpptoc/client_cpptoc.h"
#include "libcef_dll/cpptoc/life_span_handler_cpptoc.h"
#include "libcef_dll/ctocpp/browser_ctocpp.h"

// MEMBER FUNCTIONS - Body may be edited by hand.

int CEF_CALLBACK life_span_handler_on_before_popup(
    struct _cef_life_span_handler_t* self, cef_browser_t* parentBrowser,
    const struct _cef_popup_features_t* popupFeatures,
    cef_window_info_t* windowInfo, const cef_string_t* url,
    struct _cef_client_t** client, struct _cef_browser_settings_t* settings)
{
  DCHECK(self);
  DCHECK(parentBrowser);
  DCHECK(popupFeatures);
  DCHECK(windowInfo);
  DCHECK(url);
  DCHECK(client);
  DCHECK(settings);
  if (!self || !parentBrowser || !popupFeatures || !windowInfo || !url ||
      !client || !settings)
    return 0;

  CefWindowInfo wndInfo;
  CefBrowserSettings browserSettings;
  CefPopupFeatures features;

  // Take ownership of the values.
  wndInfo.AttachTo(*windowInfo);
  browserSettings.AttachTo(*settings);

  // Reference the existing values instead of copying.
  features.Set(*popupFeatures, false);

  // |newHandler| will start off pointing to the current handler.
  CefRefPtr<CefClient> clientPtr;
  if (*client)
    clientPtr = CefClientCppToC::Unwrap(*client);
  CefClient* origClient = clientPtr.get();

  // |parentBrowser| will be NULL if this is a top-level browser window.
  CefRefPtr<CefBrowser> browserPtr(CefBrowserCToCpp::Wrap(parentBrowser));

  bool rv = CefLifeSpanHandlerCppToC::Get(self)->OnBeforePopup(
      browserPtr, features, wndInfo, CefString(url), clientPtr,
      browserSettings);

  if (clientPtr.get()) {
    if (clientPtr.get() != origClient) {
      // The handler has been changed.
      *client = CefClientCppToC::Wrap(clientPtr);
    }
  } else {
    *client = NULL;
  }

  // Return the values to the structures.
  wndInfo.DetachTo(*windowInfo);
  browserSettings.DetachTo(*settings);

  return rv;
}

void CEF_CALLBACK life_span_handler_on_after_created(
    struct _cef_life_span_handler_t* self, cef_browser_t* browser)
{
  DCHECK(self);
  DCHECK(browser);
  if (!self || !browser)
    return;

  CefLifeSpanHandlerCppToC::Get(self)->OnAfterCreated(
      CefBrowserCToCpp::Wrap(browser));
}

void CEF_CALLBACK life_span_handler_on_before_close(
    struct _cef_life_span_handler_t* self, cef_browser_t* browser)
{
  DCHECK(self);
  DCHECK(browser);
  if (!self || !browser)
    return;

  CefLifeSpanHandlerCppToC::Get(self)->OnBeforeClose(
      CefBrowserCToCpp::Wrap(browser));
}

// CONSTRUCTOR - Do not edit by hand.

CefLifeSpanHandlerCppToC::CefLifeSpanHandlerCppToC(CefLifeSpanHandler* cls)
    : CefCppToC<CefLifeSpanHandlerCppToC, CefLifeSpanHandler,
        cef_life_span_handler_t>(cls)
{
  struct_.struct_.on_before_popup = life_span_handler_on_before_popup;
  struct_.struct_.on_after_created = life_span_handler_on_after_created;
  struct_.struct_.on_before_close = life_span_handler_on_before_close;
}

#ifndef NDEBUG
template<> long CefCppToC<CefLifeSpanHandlerCppToC, CefLifeSpanHandler,
    cef_life_span_handler_t>::DebugObjCt = 0;
#endif

<commit_msg>Remove the url check from life_span_handler_on_before_popup because the URL will be NULL when clicking a link with target="_blank" (issue #247).<commit_after>// Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
//
// ---------------------------------------------------------------------------
//
// A portion of this file was generated by the CEF translator tool.  When
// making changes by hand only do so within the body of existing function
// implementations. See the translator.README.txt file in the tools directory
// for more information.
//

#include "libcef_dll/cpptoc/client_cpptoc.h"
#include "libcef_dll/cpptoc/life_span_handler_cpptoc.h"
#include "libcef_dll/ctocpp/browser_ctocpp.h"

// MEMBER FUNCTIONS - Body may be edited by hand.

int CEF_CALLBACK life_span_handler_on_before_popup(
    struct _cef_life_span_handler_t* self, cef_browser_t* parentBrowser,
    const struct _cef_popup_features_t* popupFeatures,
    cef_window_info_t* windowInfo, const cef_string_t* url,
    struct _cef_client_t** client, struct _cef_browser_settings_t* settings)
{
  DCHECK(self);
  DCHECK(parentBrowser);
  DCHECK(popupFeatures);
  DCHECK(windowInfo);
  DCHECK(client);
  DCHECK(settings);
  if (!self || !parentBrowser || !popupFeatures || !windowInfo || !client ||
      !settings)
    return 0;

  CefWindowInfo wndInfo;
  CefBrowserSettings browserSettings;
  CefPopupFeatures features;

  // Take ownership of the values.
  wndInfo.AttachTo(*windowInfo);
  browserSettings.AttachTo(*settings);

  // Reference the existing values instead of copying.
  features.Set(*popupFeatures, false);

  // |newHandler| will start off pointing to the current handler.
  CefRefPtr<CefClient> clientPtr;
  if (*client)
    clientPtr = CefClientCppToC::Unwrap(*client);
  CefClient* origClient = clientPtr.get();

  // |parentBrowser| will be NULL if this is a top-level browser window.
  CefRefPtr<CefBrowser> browserPtr(CefBrowserCToCpp::Wrap(parentBrowser));

  bool rv = CefLifeSpanHandlerCppToC::Get(self)->OnBeforePopup(
      browserPtr, features, wndInfo, CefString(url), clientPtr,
      browserSettings);

  if (clientPtr.get()) {
    if (clientPtr.get() != origClient) {
      // The handler has been changed.
      *client = CefClientCppToC::Wrap(clientPtr);
    }
  } else {
    *client = NULL;
  }

  // Return the values to the structures.
  wndInfo.DetachTo(*windowInfo);
  browserSettings.DetachTo(*settings);

  return rv;
}

void CEF_CALLBACK life_span_handler_on_after_created(
    struct _cef_life_span_handler_t* self, cef_browser_t* browser)
{
  DCHECK(self);
  DCHECK(browser);
  if (!self || !browser)
    return;

  CefLifeSpanHandlerCppToC::Get(self)->OnAfterCreated(
      CefBrowserCToCpp::Wrap(browser));
}

void CEF_CALLBACK life_span_handler_on_before_close(
    struct _cef_life_span_handler_t* self, cef_browser_t* browser)
{
  DCHECK(self);
  DCHECK(browser);
  if (!self || !browser)
    return;

  CefLifeSpanHandlerCppToC::Get(self)->OnBeforeClose(
      CefBrowserCToCpp::Wrap(browser));
}

// CONSTRUCTOR - Do not edit by hand.

CefLifeSpanHandlerCppToC::CefLifeSpanHandlerCppToC(CefLifeSpanHandler* cls)
    : CefCppToC<CefLifeSpanHandlerCppToC, CefLifeSpanHandler,
        cef_life_span_handler_t>(cls)
{
  struct_.struct_.on_before_popup = life_span_handler_on_before_popup;
  struct_.struct_.on_after_created = life_span_handler_on_after_created;
  struct_.struct_.on_before_close = life_span_handler_on_before_close;
}

#ifndef NDEBUG
template<> long CefCppToC<CefLifeSpanHandlerCppToC, CefLifeSpanHandler,
    cef_life_span_handler_t>::DebugObjCt = 0;
#endif

<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    TestMultiBlock.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

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

=========================================================================*/
// This example demonstrates how hierarchical box (uniform rectilinear)
// AMR datasets can be processed using the new vtkHierarchicalBoxDataSet class.
//
// The command line arguments are:
// -I        => run in interactive mode; unless this is used, the program will
//              not allow interaction and exit
// -D <path> => path to the data; the data should be in <path>/Data/

#include "vtkCellDataToPointData.h"
#include "vtkContourFilter.h"
#include "vtkDebugLeaks.h"
#include "vtkHierarchicalDataExtractDataSets.h"
#include "vtkHierarchicalDataSetGeometryFilter.h"
#include "vtkMultiBlockPLOT3DReader.h"
#include "vtkOutlineCornerFilter.h"
#include "vtkPolyDataMapper.h"
#include "vtkProperty.h"
#include "vtkRegressionTestImage.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkShrinkPolyData.h"
#include "vtkTestUtilities.h"

int TestMultiBlock(int argc, char* argv[])
{
  // Disable for testing
  vtkDebugLeaks::PromptUserOff();

  // Standard rendering classes
  vtkRenderer *ren = vtkRenderer::New();
  vtkRenderWindow *renWin = vtkRenderWindow::New();
  renWin->AddRenderer(ren);
  vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New();
  iren->SetRenderWindow(renWin);

  char* xyzname =
    vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/mbwavelet_ascii.xyz");
  char* qname =
    vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/mbwavelet_ascii.q");

  vtkMultiBlockPLOT3DReader* reader = vtkMultiBlockPLOT3DReader::New();
  reader->SetXYZFileName(xyzname);
  reader->SetQFileName(qname);
  reader->SetMultiGrid(1);
  reader->SetBinaryFile(0);
  delete[] xyzname;
  delete[] qname;

  // geometry filter
  vtkHierarchicalDataSetGeometryFilter* geom =
    vtkHierarchicalDataSetGeometryFilter::New();
  geom->SetInputConnection(0, reader->GetOutputPort(0));

  vtkShrinkPolyData* shrink = vtkShrinkPolyData::New();
  shrink->SetShrinkFactor(0.2);
  shrink->SetInputConnection(0, geom->GetOutputPort(0));

  // Rendering objects
  vtkPolyDataMapper* shMapper = vtkPolyDataMapper::New();
  shMapper->SetInputConnection(0, shrink->GetOutputPort(0));
  vtkActor* shActor = vtkActor::New();
  shActor->SetMapper(shMapper);
  shActor->GetProperty()->SetColor(0, 0, 1);
  ren->AddActor(shActor);

  // corner outline
  vtkOutlineCornerFilter* ocf = vtkOutlineCornerFilter::New();
  ocf->SetInputConnection(0, reader->GetOutputPort(0));

  // geometry filter
  vtkHierarchicalDataSetGeometryFilter* geom2 =
    vtkHierarchicalDataSetGeometryFilter::New();
  geom2->SetInputConnection(0, ocf->GetOutputPort(0));

  // Rendering objects
  vtkPolyDataMapper* ocMapper = vtkPolyDataMapper::New();
  ocMapper->SetInputConnection(0, geom2->GetOutputPort(0));
  vtkActor* ocActor = vtkActor::New();
  ocActor->SetMapper(ocMapper);
  ocActor->GetProperty()->SetColor(1, 0, 0);
  ren->AddActor(ocActor);

  // extract a block
  vtkHierarchicalDataExtractDataSets* eds =
    vtkHierarchicalDataExtractDataSets::New();
  eds->SetInputConnection(0, reader->GetOutputPort(0));
  eds->AddDataSet(0, 1);

  // contour
  vtkContourFilter* contour = vtkContourFilter::New();
  contour->SetInputConnection(0, eds->GetOutputPort(0));
  contour->SetValue(0, 149);

  // geometry filter
  vtkHierarchicalDataSetGeometryFilter* geom3 =
    vtkHierarchicalDataSetGeometryFilter::New();
  geom3->SetInputConnection(0, contour->GetOutputPort(0));

  // Rendering objects
  vtkPolyDataMapper* contMapper = vtkPolyDataMapper::New();
  contMapper->SetInputConnection(0, geom3->GetOutputPort(0));
  vtkActor* contActor = vtkActor::New();
  contActor->SetMapper(contMapper);
  contActor->GetProperty()->SetColor(1, 0, 0);
  ren->AddActor(contActor);

  // Standard testing code.
  eds->Delete();
  ocf->Delete();
  geom2->Delete();
  ocMapper->Delete();
  ocActor->Delete();
  contour->Delete();
  geom3->Delete();
  contMapper->Delete();
  contActor->Delete();
  ren->SetBackground(1,1,1);
  renWin->SetSize(300,300);
  renWin->Render();
  int retVal = vtkRegressionTestImage( renWin );
  if ( retVal == vtkRegressionTester::DO_INTERACTOR)
    {
    iren->Start();
    }

  // Cleanup
  geom->Delete();
  shMapper->Delete();
  shActor->Delete();
  ren->Delete();
  renWin->Delete();
  iren->Delete();
  reader->Delete();
  shrink->Delete();

  return !retVal;
}
<commit_msg>ENH: Changed camera position to avoid small polygones (failure on some opengl drivers)<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    TestMultiBlock.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

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

=========================================================================*/
// This example demonstrates how hierarchical box (uniform rectilinear)
// AMR datasets can be processed using the new vtkHierarchicalBoxDataSet class.
//
// The command line arguments are:
// -I        => run in interactive mode; unless this is used, the program will
//              not allow interaction and exit
// -D <path> => path to the data; the data should be in <path>/Data/

#include "vtkCamera.h"
#include "vtkCellDataToPointData.h"
#include "vtkContourFilter.h"
#include "vtkDebugLeaks.h"
#include "vtkHierarchicalDataExtractDataSets.h"
#include "vtkHierarchicalDataSetGeometryFilter.h"
#include "vtkMultiBlockPLOT3DReader.h"
#include "vtkOutlineCornerFilter.h"
#include "vtkPolyDataMapper.h"
#include "vtkProperty.h"
#include "vtkRegressionTestImage.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkShrinkPolyData.h"
#include "vtkTestUtilities.h"

int TestMultiBlock(int argc, char* argv[])
{
  // Disable for testing
  vtkDebugLeaks::PromptUserOff();

  // Standard rendering classes
  vtkRenderer *ren = vtkRenderer::New();
  vtkCamera* cam = ren->GetActiveCamera();
  cam->SetPosition(-5.1828, 5.89733, 8.97969);
  cam->SetFocalPoint(14.6491, -2.08677, -8.92362);
  cam->SetViewUp(0.210794, 0.95813, -0.193784);

  vtkRenderWindow *renWin = vtkRenderWindow::New();
  renWin->AddRenderer(ren);
  vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New();
  iren->SetRenderWindow(renWin);

  char* xyzname =
    vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/mbwavelet_ascii.xyz");
  char* qname =
    vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/mbwavelet_ascii.q");

  vtkMultiBlockPLOT3DReader* reader = vtkMultiBlockPLOT3DReader::New();
  reader->SetXYZFileName(xyzname);
  reader->SetQFileName(qname);
  reader->SetMultiGrid(1);
  reader->SetBinaryFile(0);
  delete[] xyzname;
  delete[] qname;

  // geometry filter
  vtkHierarchicalDataSetGeometryFilter* geom =
    vtkHierarchicalDataSetGeometryFilter::New();
  geom->SetInputConnection(0, reader->GetOutputPort(0));

  vtkShrinkPolyData* shrink = vtkShrinkPolyData::New();
  shrink->SetShrinkFactor(0.2);
  shrink->SetInputConnection(0, geom->GetOutputPort(0));

  // Rendering objects
  vtkPolyDataMapper* shMapper = vtkPolyDataMapper::New();
  shMapper->SetInputConnection(0, shrink->GetOutputPort(0));
  vtkActor* shActor = vtkActor::New();
  shActor->SetMapper(shMapper);
  shActor->GetProperty()->SetColor(0, 0, 1);
  ren->AddActor(shActor);

  // corner outline
  vtkOutlineCornerFilter* ocf = vtkOutlineCornerFilter::New();
  ocf->SetInputConnection(0, reader->GetOutputPort(0));

  // geometry filter
  vtkHierarchicalDataSetGeometryFilter* geom2 =
    vtkHierarchicalDataSetGeometryFilter::New();
  geom2->SetInputConnection(0, ocf->GetOutputPort(0));

  // Rendering objects
  vtkPolyDataMapper* ocMapper = vtkPolyDataMapper::New();
  ocMapper->SetInputConnection(0, geom2->GetOutputPort(0));
  vtkActor* ocActor = vtkActor::New();
  ocActor->SetMapper(ocMapper);
  ocActor->GetProperty()->SetColor(1, 0, 0);
  ren->AddActor(ocActor);

  // extract a block
  vtkHierarchicalDataExtractDataSets* eds =
    vtkHierarchicalDataExtractDataSets::New();
  eds->SetInputConnection(0, reader->GetOutputPort(0));
  eds->AddDataSet(0, 1);

  // contour
  vtkContourFilter* contour = vtkContourFilter::New();
  contour->SetInputConnection(0, eds->GetOutputPort(0));
  contour->SetValue(0, 149);

  // geometry filter
  vtkHierarchicalDataSetGeometryFilter* geom3 =
    vtkHierarchicalDataSetGeometryFilter::New();
  geom3->SetInputConnection(0, contour->GetOutputPort(0));

  // Rendering objects
  vtkPolyDataMapper* contMapper = vtkPolyDataMapper::New();
  contMapper->SetInputConnection(0, geom3->GetOutputPort(0));
  vtkActor* contActor = vtkActor::New();
  contActor->SetMapper(contMapper);
  contActor->GetProperty()->SetColor(1, 0, 0);
  ren->AddActor(contActor);

  // Standard testing code.
  eds->Delete();
  ocf->Delete();
  geom2->Delete();
  ocMapper->Delete();
  ocActor->Delete();
  contour->Delete();
  geom3->Delete();
  contMapper->Delete();
  contActor->Delete();
  ren->SetBackground(1,1,1);
  renWin->SetSize(300,300);
  renWin->Render();
  int retVal = vtkRegressionTestImage( renWin );
  if ( retVal == vtkRegressionTester::DO_INTERACTOR)
    {
    iren->Start();
    }

  // Cleanup
  geom->Delete();
  shMapper->Delete();
  shActor->Delete();
  ren->Delete();
  renWin->Delete();
  iren->Delete();
  reader->Delete();
  shrink->Delete();

  return !retVal;
}
<|endoftext|>


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

#include "src/envoy/http/authn/http_filter.h"
#include "authentication/v1alpha1/policy.pb.h"
#include "common/http/utility.h"
#include "envoy/config/filter/http/authn/v2alpha1/config.pb.h"
#include "src/envoy/http/authn/origin_authenticator.h"
#include "src/envoy/http/authn/peer_authenticator.h"
#include "src/envoy/utils/authn.h"
#include "src/envoy/utils/utils.h"

using istio::authn::Payload;
using istio::envoy::config::filter::http::authn::v2alpha1::FilterConfig;

namespace iaapi = istio::authentication::v1alpha1;

namespace Envoy {
namespace Http {
namespace Istio {
namespace AuthN {

AuthenticationFilter::AuthenticationFilter(const FilterConfig& filter_config)
    : filter_config_(filter_config) {}

AuthenticationFilter::~AuthenticationFilter() {}

void AuthenticationFilter::onDestroy() {
  ENVOY_LOG(debug, "Called AuthenticationFilter : {}", __func__);
}

FilterHeadersStatus AuthenticationFilter::decodeHeaders(HeaderMap& headers,
                                                        bool) {
  ENVOY_LOG(debug, "Called AuthenticationFilter : {}", __func__);
  state_ = State::PROCESSING;

  filter_context_.reset(new Istio::AuthN::FilterContext(
      &headers, decoder_callbacks_->connection(), filter_config_));

  Payload payload;

  if (!createPeerAuthenticator(filter_context_.get())->run(&payload)) {
    rejectRequest("Peer authentication failed.");
    return FilterHeadersStatus::StopIteration;
  }

  bool success =
      createOriginAuthenticator(filter_context_.get())->run(&payload);

  // After Istio authn, the JWT headers consumed by Istio authn should be
  // removed.
  // TODO: remove internal headers used to pass data between filters
  // https://github.com/istio/istio/issues/4689
  for (auto const iter : filter_config_.jwt_output_payload_locations()) {
    filter_context_->headers()->remove(LowerCaseString(iter.second));
  }

  if (!success) {
    rejectRequest("Origin authentication failed.");
    return FilterHeadersStatus::StopIteration;
  }

  // Put authentication result to headers.
  if (filter_context_ != nullptr) {
    Utils::Authentication::SaveResultToHeader(
        filter_context_->authenticationResult(), filter_context_->headers());
  }

  return FilterHeadersStatus::Continue;
}

FilterDataStatus AuthenticationFilter::decodeData(Buffer::Instance&, bool) {
  ENVOY_LOG(debug, "Called AuthenticationFilter : {}", __func__);
  ENVOY_LOG(debug,
            "Called AuthenticationFilter : {} FilterDataStatus::Continue;",
            __FUNCTION__);
  if (state_ == State::PROCESSING) {
    return FilterDataStatus::StopIterationAndWatermark;
  }
  return FilterDataStatus::Continue;
}

FilterTrailersStatus AuthenticationFilter::decodeTrailers(HeaderMap&) {
  ENVOY_LOG(debug, "Called AuthenticationFilter : {}", __func__);
  if (state_ == State::PROCESSING) {
    return FilterTrailersStatus::StopIteration;
  }
  return FilterTrailersStatus::Continue;
}

void AuthenticationFilter::setDecoderFilterCallbacks(
    StreamDecoderFilterCallbacks& callbacks) {
  ENVOY_LOG(debug, "Called AuthenticationFilter : {}", __func__);
  decoder_callbacks_ = &callbacks;
}

void AuthenticationFilter::rejectRequest(const std::string& message) {
  if (state_ != State::PROCESSING) {
    ENVOY_LOG(error, "State {} is not PROCESSING.", state_);
    return;
  }
  state_ = State::REJECTED;
  Utility::sendLocalReply(*decoder_callbacks_, false, Http::Code::Unauthorized,
                          message);
}

std::unique_ptr<Istio::AuthN::AuthenticatorBase>
AuthenticationFilter::createPeerAuthenticator(
    Istio::AuthN::FilterContext* filter_context) {
  return std::make_unique<Istio::AuthN::PeerAuthenticator>(
      filter_context, filter_config_.policy());
}

std::unique_ptr<Istio::AuthN::AuthenticatorBase>
AuthenticationFilter::createOriginAuthenticator(
    Istio::AuthN::FilterContext* filter_context) {
  return std::make_unique<Istio::AuthN::OriginAuthenticator>(
      filter_context, filter_config_.policy());
}

}  // namespace AuthN
}  // namespace Istio
}  // namespace Http
}  // namespace Envoy
<commit_msg>Fix a bug that Istio authn filter blocks downstream filters (#1465)<commit_after>/* Copyright 2018 Istio Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "src/envoy/http/authn/http_filter.h"
#include "authentication/v1alpha1/policy.pb.h"
#include "common/http/utility.h"
#include "envoy/config/filter/http/authn/v2alpha1/config.pb.h"
#include "src/envoy/http/authn/origin_authenticator.h"
#include "src/envoy/http/authn/peer_authenticator.h"
#include "src/envoy/utils/authn.h"
#include "src/envoy/utils/utils.h"

using istio::authn::Payload;
using istio::envoy::config::filter::http::authn::v2alpha1::FilterConfig;

namespace iaapi = istio::authentication::v1alpha1;

namespace Envoy {
namespace Http {
namespace Istio {
namespace AuthN {

AuthenticationFilter::AuthenticationFilter(const FilterConfig& filter_config)
    : filter_config_(filter_config) {}

AuthenticationFilter::~AuthenticationFilter() {}

void AuthenticationFilter::onDestroy() {
  ENVOY_LOG(debug, "Called AuthenticationFilter : {}", __func__);
}

FilterHeadersStatus AuthenticationFilter::decodeHeaders(HeaderMap& headers,
                                                        bool) {
  ENVOY_LOG(debug, "Called AuthenticationFilter : {}", __func__);
  state_ = State::PROCESSING;

  filter_context_.reset(new Istio::AuthN::FilterContext(
      &headers, decoder_callbacks_->connection(), filter_config_));

  Payload payload;

  if (!createPeerAuthenticator(filter_context_.get())->run(&payload)) {
    rejectRequest("Peer authentication failed.");
    return FilterHeadersStatus::StopIteration;
  }

  bool success =
      createOriginAuthenticator(filter_context_.get())->run(&payload);

  // After Istio authn, the JWT headers consumed by Istio authn should be
  // removed.
  // TODO: remove internal headers used to pass data between filters
  // https://github.com/istio/istio/issues/4689
  for (auto const iter : filter_config_.jwt_output_payload_locations()) {
    filter_context_->headers()->remove(LowerCaseString(iter.second));
  }

  if (!success) {
    rejectRequest("Origin authentication failed.");
    return FilterHeadersStatus::StopIteration;
  }

  // Put authentication result to headers.
  if (filter_context_ != nullptr) {
    Utils::Authentication::SaveResultToHeader(
        filter_context_->authenticationResult(), filter_context_->headers());
  }
  state_ = State::COMPLETE;
  return FilterHeadersStatus::Continue;
}

FilterDataStatus AuthenticationFilter::decodeData(Buffer::Instance&, bool) {
  ENVOY_LOG(debug, "Called AuthenticationFilter : {}", __func__);
  ENVOY_LOG(debug,
            "Called AuthenticationFilter : {} FilterDataStatus::Continue;",
            __FUNCTION__);
  if (state_ == State::PROCESSING) {
    return FilterDataStatus::StopIterationAndWatermark;
  }
  return FilterDataStatus::Continue;
}

FilterTrailersStatus AuthenticationFilter::decodeTrailers(HeaderMap&) {
  ENVOY_LOG(debug, "Called AuthenticationFilter : {}", __func__);
  if (state_ == State::PROCESSING) {
    return FilterTrailersStatus::StopIteration;
  }
  return FilterTrailersStatus::Continue;
}

void AuthenticationFilter::setDecoderFilterCallbacks(
    StreamDecoderFilterCallbacks& callbacks) {
  ENVOY_LOG(debug, "Called AuthenticationFilter : {}", __func__);
  decoder_callbacks_ = &callbacks;
}

void AuthenticationFilter::rejectRequest(const std::string& message) {
  if (state_ != State::PROCESSING) {
    ENVOY_LOG(error, "State {} is not PROCESSING.", state_);
    return;
  }
  state_ = State::REJECTED;
  Utility::sendLocalReply(*decoder_callbacks_, false, Http::Code::Unauthorized,
                          message);
}

std::unique_ptr<Istio::AuthN::AuthenticatorBase>
AuthenticationFilter::createPeerAuthenticator(
    Istio::AuthN::FilterContext* filter_context) {
  return std::make_unique<Istio::AuthN::PeerAuthenticator>(
      filter_context, filter_config_.policy());
}

std::unique_ptr<Istio::AuthN::AuthenticatorBase>
AuthenticationFilter::createOriginAuthenticator(
    Istio::AuthN::FilterContext* filter_context) {
  return std::make_unique<Istio::AuthN::OriginAuthenticator>(
      filter_context, filter_config_.policy());
}

}  // namespace AuthN
}  // namespace Istio
}  // namespace Http
}  // namespace Envoy
<|endoftext|>


<commit_before>/**
 *  @file
 *  @copyright defined in eos/LICENSE.txt
 */
#pragma once
#include <eosio/chain/exceptions.hpp>
#include <eosio/chain/types.hpp>
#include <eosio/chain/symbol.hpp>

namespace eosio { namespace chain {

/**

asset includes amount and currency symbol

asset::from_string takes a string of the form "10.0000 CUR" and constructs an asset
with amount = 10 and symbol(4,"CUR")

*/

struct asset
{
   static constexpr int64_t max_amount = (1LL << 62) - 1;

   explicit asset(share_type a = 0, symbol id = symbol(CORE_SYMBOL)) :amount(a), sym(id) {
      EOS_ASSERT( is_amount_within_range(), asset_type_exception, "magnitude of asset amount must be less than 2^62" );
      EOS_ASSERT( sym.valid(), asset_type_exception, "invalid symbol" );
   }

   bool is_amount_within_range()const { return -max_amount <= amount && amount <= max_amount; }
   bool is_valid()const               { return is_amount_within_range() && sym.valid(); }

   double to_real()const { return static_cast<double>(amount) / precision(); }

   uint8_t     decimals()const;
   string      symbol_name()const;
   int64_t     precision()const;
   const symbol& get_symbol() const { return sym; }

   static asset from_string(const string& from);
   string       to_string()const;

   asset& operator += (const asset& o)
   {
      FC_ASSERT(get_symbol() == o.get_symbol());
      amount += o.amount;
      return *this;
   }

   asset& operator -= (const asset& o)
   {
      FC_ASSERT(get_symbol() == o.get_symbol());
      amount -= o.amount;
      return *this;
   }
   asset operator -()const { return asset(-amount, get_symbol()); }

   friend bool operator == (const asset& a, const asset& b)
   {
      return std::tie(a.get_symbol(), a.amount) == std::tie(b.get_symbol(), b.amount);
   }
   friend bool operator < (const asset& a, const asset& b)
   {
      FC_ASSERT(a.get_symbol() == b.get_symbol());
      return std::tie(a.amount,a.get_symbol()) < std::tie(b.amount,b.get_symbol());
   }
   friend bool operator <= (const asset& a, const asset& b) { return (a == b) || (a < b); }
   friend bool operator != (const asset& a, const asset& b) { return !(a == b); }
   friend bool operator > (const asset& a, const asset& b)  { return !(a <= b); }
   friend bool operator >= (const asset& a, const asset& b) { return !(a < b);  }

   friend asset operator - (const asset& a, const asset& b) {
      FC_ASSERT(a.get_symbol() == b.get_symbol());
      return asset(a.amount - b.amount, a.get_symbol());
   }

   friend asset operator + (const asset& a, const asset& b) {
      FC_ASSERT(a.get_symbol() == b.get_symbol());
      return asset(a.amount + b.amount, a.get_symbol());
   }

   friend std::ostream& operator << (std::ostream& out, const asset& a) { return out << a.to_string(); }

   friend struct fc::reflector<asset>;

   void reflector_verify()const {
      EOS_ASSERT( is_amount_within_range(), asset_type_exception, "magnitude of asset amount must be less than 2^62" );
      EOS_ASSERT( sym.valid(), asset_type_exception, "invalid symbol" );
   }

private:
   share_type amount;
   symbol     sym;

};

struct extended_asset  {
  extended_asset(){}
  extended_asset( asset a, name n ):quantity(a),contract(n){}
  asset quantity;
  name contract;
};

bool  operator <  (const asset& a, const asset& b);
bool  operator <= (const asset& a, const asset& b);

}} // namespace eosio::chain

namespace fc {
inline void to_variant(const eosio::chain::asset& var, fc::variant& vo) { vo = var.to_string(); }
inline void from_variant(const fc::variant& var, eosio::chain::asset& vo) {
   vo = eosio::chain::asset::from_string(var.get_string());
}
}

FC_REFLECT(eosio::chain::asset, (amount)(sym))
FC_REFLECT(eosio::chain::extended_asset, (quantity)(contract) )
<commit_msg>Add get_amount()<commit_after>/**
 *  @file
 *  @copyright defined in eos/LICENSE.txt
 */
#pragma once
#include <eosio/chain/exceptions.hpp>
#include <eosio/chain/types.hpp>
#include <eosio/chain/symbol.hpp>

namespace eosio { namespace chain {

/**

asset includes amount and currency symbol

asset::from_string takes a string of the form "10.0000 CUR" and constructs an asset
with amount = 10 and symbol(4,"CUR")

*/

struct asset
{
   static constexpr int64_t max_amount = (1LL << 62) - 1;

   explicit asset(share_type a = 0, symbol id = symbol(CORE_SYMBOL)) :amount(a), sym(id) {
      EOS_ASSERT( is_amount_within_range(), asset_type_exception, "magnitude of asset amount must be less than 2^62" );
      EOS_ASSERT( sym.valid(), asset_type_exception, "invalid symbol" );
   }

   bool is_amount_within_range()const { return -max_amount <= amount && amount <= max_amount; }
   bool is_valid()const               { return is_amount_within_range() && sym.valid(); }

   double to_real()const { return static_cast<double>(amount) / precision(); }

   uint8_t     decimals()const;
   string      symbol_name()const;
   int64_t     precision()const;
   const symbol& get_symbol() const { return sym; }
   share_type get_amount()const { return amount; }

   static asset from_string(const string& from);
   string       to_string()const;

   asset& operator += (const asset& o)
   {
      FC_ASSERT(get_symbol() == o.get_symbol());
      amount += o.amount;
      return *this;
   }

   asset& operator -= (const asset& o)
   {
      FC_ASSERT(get_symbol() == o.get_symbol());
      amount -= o.amount;
      return *this;
   }
   asset operator -()const { return asset(-amount, get_symbol()); }

   friend bool operator == (const asset& a, const asset& b)
   {
      return std::tie(a.get_symbol(), a.amount) == std::tie(b.get_symbol(), b.amount);
   }
   friend bool operator < (const asset& a, const asset& b)
   {
      FC_ASSERT(a.get_symbol() == b.get_symbol());
      return std::tie(a.amount,a.get_symbol()) < std::tie(b.amount,b.get_symbol());
   }
   friend bool operator <= (const asset& a, const asset& b) { return (a == b) || (a < b); }
   friend bool operator != (const asset& a, const asset& b) { return !(a == b); }
   friend bool operator > (const asset& a, const asset& b)  { return !(a <= b); }
   friend bool operator >= (const asset& a, const asset& b) { return !(a < b);  }

   friend asset operator - (const asset& a, const asset& b) {
      FC_ASSERT(a.get_symbol() == b.get_symbol());
      return asset(a.amount - b.amount, a.get_symbol());
   }

   friend asset operator + (const asset& a, const asset& b) {
      FC_ASSERT(a.get_symbol() == b.get_symbol());
      return asset(a.amount + b.amount, a.get_symbol());
   }

   friend std::ostream& operator << (std::ostream& out, const asset& a) { return out << a.to_string(); }

   friend struct fc::reflector<asset>;

   void reflector_verify()const {
      EOS_ASSERT( is_amount_within_range(), asset_type_exception, "magnitude of asset amount must be less than 2^62" );
      EOS_ASSERT( sym.valid(), asset_type_exception, "invalid symbol" );
   }

private:
   share_type amount;
   symbol     sym;

};

struct extended_asset  {
  extended_asset(){}
  extended_asset( asset a, name n ):quantity(a),contract(n){}
  asset quantity;
  name contract;
};

bool  operator <  (const asset& a, const asset& b);
bool  operator <= (const asset& a, const asset& b);

}} // namespace eosio::chain

namespace fc {
inline void to_variant(const eosio::chain::asset& var, fc::variant& vo) { vo = var.to_string(); }
inline void from_variant(const fc::variant& var, eosio::chain::asset& vo) {
   vo = eosio::chain::asset::from_string(var.get_string());
}
}

FC_REFLECT(eosio::chain::asset, (amount)(sym))
FC_REFLECT(eosio::chain::extended_asset, (quantity)(contract) )
<|endoftext|>


<commit_before>// Copyright (c) 2011-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "navcoinunits.h"

#include "primitives/transaction.h"
#include "util.h"

#include <math.h>

#include <QStringList>
#include <QSettings>

NavCoinUnits::NavCoinUnits(QObject *parent):
        QAbstractListModel(parent),
        unitlist(availableUnits())
{
}

QList<NavCoinUnits::Unit> NavCoinUnits::availableUnits()
{
    QList<NavCoinUnits::Unit> unitlist;
    unitlist.append(NAV);
//    unitlist.append(mNAV);
//    unitlist.append(uNAV);
    unitlist.append(BTC);
    unitlist.append(EUR);
    unitlist.append(USD);
    return unitlist;
}

bool NavCoinUnits::valid(int unit)
{
    switch(unit)
    {
    case NAV:
//    case mNAV:
//    case uNAV:
    case BTC:
    case EUR:
    case USD:
        return true;
    default:
        return false;
    }
}

QString NavCoinUnits::name(int unit)
{
    switch(unit)
    {
    case NAV: return QString("NAV");
//    case mNAV: return QString("mNAV");
//    case uNAV: return QString::fromUtf8("μNAV");
    case BTC: return QString::fromUtf8("BTC");
    case EUR: return QString::fromUtf8("EUR");
    case USD: return QString::fromUtf8("USD");
    default: return QString("???");
    }
}

QString NavCoinUnits::description(int unit)
{
    switch(unit)
    {
    case NAV: return QString("NavCoins");
//    case mNAV: return QString("Milli-NavCoins (1 / 1" THIN_SP_UTF8 "000)");
//    case uNAV: return QString("Micro-NavCoins (1 / 1" THIN_SP_UTF8 "000" THIN_SP_UTF8 "000)");
    case BTC: return QString("BTC");
    case EUR: return QString("Euro");
    case USD: return QString("US Dolar");
    default: return QString("???");
    }
}

qint64 NavCoinUnits::factor(int unit)
{

    QSettings settings;

    switch(unit)
    {
    case NAV:  return 100000000;
//    case mNAV: return 100000;
//    case uNAV: return 100;
    case BTC:  return settings.value("btcFactor", 0).toFloat();
    case EUR:  return settings.value("eurFactor", 0).toFloat();
    case USD:  return settings.value("usdFactor", 0).toFloat();
    default:   return 100000000;
    }
}

int NavCoinUnits::decimals(int unit)
{
    switch(unit)
    {
    case NAV: return 8;
//    case mNAV: return 5;
//    case uNAV: return 2;
    case BTC: return 8;
    case EUR: return 6;
    case USD: return 6;
    default: return 0;
    }
}

QString NavCoinUnits::format(int unit, const CAmount& nIn, bool fPlus, SeparatorStyle separators)
{
    // Note: not using straight sprintf here because we do NOT want
    // localized number formatting.
    if(!valid(unit))
        return QString(); // Refuse to format invalid unit
    qint64 n = (qint64)nIn;
    qint64 coin = factor(unit);
    int num_decimals = decimals(unit);
    qint64 n_abs = (n > 0 ? n : -n);
    double quotient;
    qint64 remainder;

    double q;
    double r = modf((double)n_abs / (double)coin, &q);
    quotient = q;
    remainder = r * (double)pow(10,num_decimals);

    QString quotient_str = QString::number((qint64)quotient);
    QString remainder_str = QString::number(remainder).rightJustified(num_decimals, '0');

    // Use SI-style thin space separators as these are locale independent and can't be
    // confused with the decimal marker.
    QChar thin_sp(THIN_SP_CP);
    int q_size = quotient_str.size();
    if (separators == separatorAlways || (separators == separatorStandard && q_size > 4))
        for (int i = 3; i < q_size; i += 3)
            quotient_str.insert(q_size - i, thin_sp);

    if (n < 0)
        quotient_str.insert(0, '-');
    else if (fPlus && n > 0)
        quotient_str.insert(0, '+');

    return quotient_str + QString(".") + remainder_str;
}

// NOTE: Using formatWithUnit in an HTML context risks wrapping
// quantities at the thousands separator. More subtly, it also results
// in a standard space rather than a thin space, due to a bug in Qt's
// XML whitespace canonicalisation
//
// Please take care to use formatHtmlWithUnit instead, when
// appropriate.

QString NavCoinUnits::formatWithUnit(int unit, const CAmount& amount, bool plussign, SeparatorStyle separators)
{
    return format(unit, amount, plussign, separators) + QString(" ") + name(unit);
}

QString NavCoinUnits::formatHtmlWithUnit(int unit, const CAmount& amount, bool plussign, SeparatorStyle separators)
{
    QString str(formatWithUnit(unit, amount, plussign, separators));
    str.replace(QChar(THIN_SP_CP), QString(THIN_SP_HTML));
    return QString("%1").arg(str);
}

bool NavCoinUnits::parse(int unit, const QString &value, CAmount *val_out)
{
    if(!valid(unit) || value.isEmpty())
        return false; // Refuse to parse invalid unit or empty string
    int num_decimals = decimals(unit);

    // Ignore spaces and thin spaces when parsing
    QStringList parts = removeSpaces(value).split(".");

    if(parts.size() > 2)
    {
        return false; // More than one dot
    }
    QString whole = parts[0];
    QString decimals;

    if(parts.size() > 1)
    {
        decimals = parts[1];
    }
    if(decimals.size() > num_decimals)
    {
        return false; // Exceeds max precision
    }
    bool ok = false;
    QString str = whole + decimals.leftJustified(num_decimals, '0');

    if(str.size() > 18)
    {
        return false; // Longer numbers will exceed 63 bits
    }
    CAmount retvalue(str.toLongLong(&ok));
    if(val_out)
    {
        *val_out = retvalue;
    }
    return ok;
}

QString NavCoinUnits::getAmountColumnTitle(int unit)
{
    QString amountTitle = QObject::tr("Amount");
    if (NavCoinUnits::valid(unit))
    {
        amountTitle += " ("+NavCoinUnits::name(unit) + ")";
    }
    return amountTitle;
}

int NavCoinUnits::rowCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent);
    return unitlist.size();
}

QVariant NavCoinUnits::data(const QModelIndex &index, int role) const
{
    int row = index.row();
    if(row >= 0 && row < unitlist.size())
    {
        Unit unit = unitlist.at(row);
        switch(role)
        {
        case Qt::EditRole:
        case Qt::DisplayRole:
            return QVariant(name(unit));
        case Qt::ToolTipRole:
            return QVariant(description(unit));
        case UnitRole:
            return QVariant(static_cast<int>(unit));
        }
    }
    return QVariant();
}

CAmount NavCoinUnits::maxMoney()
{
    return MAX_MONEY;
}
<commit_msg>gui: fixes amount precision<commit_after>// Copyright (c) 2011-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "navcoinunits.h"

#include "primitives/transaction.h"
#include "util.h"

#include <math.h>

#include <QStringList>
#include <QSettings>

#include <sstream>
#include <string>
#include <iomanip>

NavCoinUnits::NavCoinUnits(QObject *parent):
        QAbstractListModel(parent),
        unitlist(availableUnits())
{
}

QList<NavCoinUnits::Unit> NavCoinUnits::availableUnits()
{
    QList<NavCoinUnits::Unit> unitlist;
    unitlist.append(NAV);
//    unitlist.append(mNAV);
//    unitlist.append(uNAV);
    unitlist.append(BTC);
    unitlist.append(EUR);
    unitlist.append(USD);
    return unitlist;
}

bool NavCoinUnits::valid(int unit)
{
    switch(unit)
    {
    case NAV:
//    case mNAV:
//    case uNAV:
    case BTC:
    case EUR:
    case USD:
        return true;
    default:
        return false;
    }
}

QString NavCoinUnits::name(int unit)
{
    switch(unit)
    {
    case NAV: return QString("NAV");
//    case mNAV: return QString("mNAV");
//    case uNAV: return QString::fromUtf8("μNAV");
    case BTC: return QString::fromUtf8("BTC");
    case EUR: return QString::fromUtf8("EUR");
    case USD: return QString::fromUtf8("USD");
    default: return QString("???");
    }
}

QString NavCoinUnits::description(int unit)
{
    switch(unit)
    {
    case NAV: return QString("NavCoins");
//    case mNAV: return QString("Milli-NavCoins (1 / 1" THIN_SP_UTF8 "000)");
//    case uNAV: return QString("Micro-NavCoins (1 / 1" THIN_SP_UTF8 "000" THIN_SP_UTF8 "000)");
    case BTC: return QString("BTC");
    case EUR: return QString("Euro");
    case USD: return QString("US Dolar");
    default: return QString("???");
    }
}

qint64 NavCoinUnits::factor(int unit)
{

    QSettings settings;

    switch(unit)
    {
    case NAV:  return 100000000;
//    case mNAV: return 100000;
//    case uNAV: return 100;
    case BTC:  return settings.value("btcFactor", 0).toFloat();
    case EUR:  return settings.value("eurFactor", 0).toFloat();
    case USD:  return settings.value("usdFactor", 0).toFloat();
    default:   return 100000000;
    }
}

int NavCoinUnits::decimals(int unit)
{
    switch(unit)
    {
    case NAV: return 8;
//    case mNAV: return 5;
//    case uNAV: return 2;
    case BTC: return 8;
    case EUR: return 6;
    case USD: return 6;
    default: return 0;
    }
}

QString NavCoinUnits::format(int unit, const CAmount& nIn, bool fPlus, SeparatorStyle separators)
{
    // Note: not using straight sprintf here because we do NOT want
    // localized number formatting.
    if(!valid(unit))
        return QString(); // Refuse to format invalid unit
    qint64 n = (qint64)nIn;
    qint64 coin = factor(unit);
    int num_decimals = decimals(unit);
    qint64 n_abs = (n > 0 ? n : -n);
    double quotient;
    qint64 remainder;

    quotient = n_abs / coin;

    std::ostringstream out;
    out << std::setprecision(num_decimals) << std::fixed
        << std::showpoint << (double)n_abs / (double)coin;
    std::istringstream in(out.str());
    std::string wholePart;
    std::getline(in, wholePart, '.');
    in >> remainder;

    QString quotient_str = QString::number((qint64)quotient);
    QString remainder_str = QString::number(remainder).rightJustified(num_decimals, '0');

    // Use SI-style thin space separators as these are locale independent and can't be
    // confused with the decimal marker.
    QChar thin_sp(THIN_SP_CP);
    int q_size = quotient_str.size();
    if (separators == separatorAlways || (separators == separatorStandard && q_size > 4))
        for (int i = 3; i < q_size; i += 3)
            quotient_str.insert(q_size - i, thin_sp);

    if (n < 0)
        quotient_str.insert(0, '-');
    else if (fPlus && n > 0)
        quotient_str.insert(0, '+');

    return quotient_str + QString(".") + remainder_str;
}

// NOTE: Using formatWithUnit in an HTML context risks wrapping
// quantities at the thousands separator. More subtly, it also results
// in a standard space rather than a thin space, due to a bug in Qt's
// XML whitespace canonicalisation
//
// Please take care to use formatHtmlWithUnit instead, when
// appropriate.

QString NavCoinUnits::formatWithUnit(int unit, const CAmount& amount, bool plussign, SeparatorStyle separators)
{
    return format(unit, amount, plussign, separators) + QString(" ") + name(unit);
}

QString NavCoinUnits::formatHtmlWithUnit(int unit, const CAmount& amount, bool plussign, SeparatorStyle separators)
{
    QString str(formatWithUnit(unit, amount, plussign, separators));
    str.replace(QChar(THIN_SP_CP), QString(THIN_SP_HTML));
    return QString("%1").arg(str);
}

bool NavCoinUnits::parse(int unit, const QString &value, CAmount *val_out)
{
    if(!valid(unit) || value.isEmpty())
        return false; // Refuse to parse invalid unit or empty string
    int num_decimals = decimals(unit);

    // Ignore spaces and thin spaces when parsing
    QStringList parts = removeSpaces(value).split(".");

    if(parts.size() > 2)
    {
        return false; // More than one dot
    }
    QString whole = parts[0];
    QString decimals;

    if(parts.size() > 1)
    {
        decimals = parts[1];
    }
    if(decimals.size() > num_decimals)
    {
        return false; // Exceeds max precision
    }
    bool ok = false;
    QString str = whole + decimals.leftJustified(num_decimals, '0');

    if(str.size() > 18)
    {
        return false; // Longer numbers will exceed 63 bits
    }
    CAmount retvalue(str.toLongLong(&ok));
    if(val_out)
    {
        *val_out = retvalue;
    }
    return ok;
}

QString NavCoinUnits::getAmountColumnTitle(int unit)
{
    QString amountTitle = QObject::tr("Amount");
    if (NavCoinUnits::valid(unit))
    {
        amountTitle += " ("+NavCoinUnits::name(unit) + ")";
    }
    return amountTitle;
}

int NavCoinUnits::rowCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent);
    return unitlist.size();
}

QVariant NavCoinUnits::data(const QModelIndex &index, int role) const
{
    int row = index.row();
    if(row >= 0 && row < unitlist.size())
    {
        Unit unit = unitlist.at(row);
        switch(role)
        {
        case Qt::EditRole:
        case Qt::DisplayRole:
            return QVariant(name(unit));
        case Qt::ToolTipRole:
            return QVariant(description(unit));
        case UnitRole:
            return QVariant(static_cast<int>(unit));
        }
    }
    return QVariant();
}

CAmount NavCoinUnits::maxMoney()
{
    return MAX_MONEY;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: layerdefaultremover.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: ssmith $ $Date: 2002-11-11 13:18:02 $
 *
 *  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 CONFIGMGR_XML_LAYERDECORATOR_HXX
#define CONFIGMGR_XML_LAYERDECORATOR_HXX

#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif // _CPPUHELPER_IMPLBASE1_HXX_

#ifndef INCLUDED_VECTOR
#include <vector>
#define INCLUDED_VECTOR
#endif

#include <drafts/com/sun/star/configuration/backend/XLayerHandler.hpp>

// -----------------------------------------------------------------------------
namespace configmgr
{
    // -----------------------------------------------------------------------------
    namespace backend
    {
        // -----------------------------------------------------------------------------
        using rtl::OUString;
        namespace uno       = ::com::sun::star::uno;
        namespace lang      = ::com::sun::star::lang;
        namespace beans     = ::com::sun::star::beans;
        namespace container = ::com::sun::star::container;
        namespace backenduno    = ::drafts::com::sun::star::configuration::backend;

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

        class LayerDefaultRemover : public cppu::WeakImplHelper1<backenduno::XLayerHandler>
        {
        public:
            typedef uno::Reference< backenduno::XLayerHandler > ResultHandler;
            explicit
                LayerDefaultRemover(ResultHandler const & _xResultHandler);
            virtual ~LayerDefaultRemover();

            // XLayerHandler
        public:
            virtual void SAL_CALL
                startLayer(  )
                throw (backenduno::MalformedDataException, uno::RuntimeException);

            virtual void SAL_CALL
                endLayer(  )
                throw (backenduno::MalformedDataException, lang::IllegalAccessException, uno::RuntimeException);

            virtual void SAL_CALL
                overrideNode( const OUString& aName, sal_Int16 aAttributes )
                throw (backenduno::MalformedDataException, container::NoSuchElementException, lang::IllegalAccessException, lang::IllegalArgumentException, uno::RuntimeException);

            virtual void SAL_CALL
                addOrReplaceNode( const OUString& aName, sal_Int16 aAttributes )
                throw (backenduno::MalformedDataException, container::NoSuchElementException, lang::IllegalAccessException, lang::IllegalArgumentException, uno::RuntimeException);

            virtual void SAL_CALL
                addOrReplaceNodeFromTemplate( const OUString& aName, const backenduno::TemplateIdentifier& aTemplate, sal_Int16 aAttributes )
                throw (backenduno::MalformedDataException, container::NoSuchElementException, beans::IllegalTypeException, lang::IllegalAccessException, lang::IllegalArgumentException, uno::RuntimeException);

            virtual void SAL_CALL
                endNode(  )
                throw (backenduno::MalformedDataException, uno::RuntimeException);

            virtual void SAL_CALL
                dropNode( const OUString& aName )
                throw (backenduno::MalformedDataException, container::NoSuchElementException, lang::IllegalAccessException, lang::IllegalArgumentException, uno::RuntimeException);

            virtual void SAL_CALL
                overrideProperty( const OUString& aName, sal_Int16 aAttributes, const uno::Type& aType )
                throw (backenduno::MalformedDataException, beans::UnknownPropertyException, beans::IllegalTypeException, lang::IllegalAccessException, lang::IllegalArgumentException, uno::RuntimeException);

            virtual void SAL_CALL
                addProperty( const OUString& aName, sal_Int16 aAttributes, const uno::Type& aType )
                throw (backenduno::MalformedDataException, beans::PropertyExistException, beans::IllegalTypeException, lang::IllegalArgumentException, uno::RuntimeException);

            virtual void SAL_CALL
                addPropertyWithValue( const OUString& aName, sal_Int16 aAttributes, const uno::Any& aValue )
                throw (backenduno::MalformedDataException, beans::PropertyExistException, beans::IllegalTypeException, lang::IllegalArgumentException, uno::RuntimeException);

            virtual void SAL_CALL
                endProperty(  )
                throw (backenduno::MalformedDataException, uno::RuntimeException);

            virtual void SAL_CALL
                setPropertyValue( const uno::Any& aValue )
                throw (backenduno::MalformedDataException, beans::IllegalTypeException, lang::IllegalArgumentException, uno::RuntimeException);

            virtual void SAL_CALL
                setPropertyValueForLocale( const uno::Any& aValue, const OUString& aLocale )
                throw (backenduno::MalformedDataException, beans::IllegalTypeException, lang::IllegalArgumentException, uno::RuntimeException);

        private:
            void playBackNodeStack( bool bPlayProperty=false);
            void raiseMalformedDataException(sal_Char const * pMsg);
            inline bool hasPendingProperty();
            inline void clearPendingProperty();
        private:
            ResultHandler   m_xResultHandler;
            typedef std::vector<OUString> NodeStack;
            NodeStack m_aNodeStack;
            struct PropertyStruct
            {
                OUString Name;
                uno::Type Type;
            }m_aPropName;
        };
        // -----------------------------------------------------------------------------
    } // namespace xml
    // -----------------------------------------------------------------------------

} // namespace configmgr
#endif <commit_msg>INTEGRATION: CWS configapi01 (1.2.26); FILE MERGED 2003/04/15 10:25:28 jb 1.2.26.2: #i11893# backend\updatedata.cxx 2003/04/10 15:47:06 jb 1.2.26.1: #1077715# Move configuration backend API out of drafts; adjust to API changes<commit_after>/*************************************************************************
 *
 *  $RCSfile: layerdefaultremover.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2003-04-17 13:15:56 $
 *
 *  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 CONFIGMGR_XML_LAYERDECORATOR_HXX
#define CONFIGMGR_XML_LAYERDECORATOR_HXX

#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif // _CPPUHELPER_IMPLBASE1_HXX_

#ifndef INCLUDED_VECTOR
#include <vector>
#define INCLUDED_VECTOR
#endif

#include <com/sun/star/configuration/backend/XLayerHandler.hpp>

// -----------------------------------------------------------------------------
namespace configmgr
{
    // -----------------------------------------------------------------------------
    namespace backend
    {
        // -----------------------------------------------------------------------------
        using rtl::OUString;
        namespace uno       = ::com::sun::star::uno;
        namespace lang      = ::com::sun::star::lang;
        namespace backenduno    = ::com::sun::star::configuration::backend;

        using backenduno::MalformedDataException;
        // -----------------------------------------------------------------------------

        class LayerDefaultRemover : public cppu::WeakImplHelper1<backenduno::XLayerHandler>
        {
        public:
            typedef uno::Reference< backenduno::XLayerHandler > ResultHandler;
            explicit
                LayerDefaultRemover(ResultHandler const & _xResultHandler);
            virtual ~LayerDefaultRemover();

            // XLayerHandler
        public:
            virtual void SAL_CALL
                startLayer(  )
                    throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException);

            virtual void SAL_CALL
                endLayer(  )
                    throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException);

            virtual void SAL_CALL
                overrideNode( const OUString& aName, sal_Int16 aAttributes, sal_Bool bClear )
                    throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException);

            virtual void SAL_CALL
                addOrReplaceNode( const OUString& aName, sal_Int16 aAttributes )
                    throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException);

            virtual void SAL_CALL
                addOrReplaceNodeFromTemplate( const OUString& aName, const backenduno::TemplateIdentifier& aTemplate, sal_Int16 aAttributes )
                    throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException);

            virtual void SAL_CALL
                endNode(  )
                    throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException);

            virtual void SAL_CALL
                dropNode( const OUString& aName )
                    throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException);

            virtual void SAL_CALL
                overrideProperty( const OUString& aName, sal_Int16 aAttributes, const uno::Type& aType, sal_Bool bClear )
                    throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException);

            virtual void SAL_CALL
                addProperty( const OUString& aName, sal_Int16 aAttributes, const uno::Type& aType )
                    throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException);

            virtual void SAL_CALL
                addPropertyWithValue( const OUString& aName, sal_Int16 aAttributes, const uno::Any& aValue )
                    throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException);

            virtual void SAL_CALL
                endProperty(  )
                    throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException);

            virtual void SAL_CALL
                setPropertyValue( const uno::Any& aValue )
                    throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException);

            virtual void SAL_CALL
                setPropertyValueForLocale( const uno::Any& aValue, const OUString& aLocale )
                    throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException);

        private:
            void playBackNodeStack( bool bPlayProperty=false);
            void raiseMalformedDataException(sal_Char const * pMsg);
            inline bool hasPendingProperty();
            inline void clearPendingProperty();
        private:
            ResultHandler   m_xResultHandler;
            typedef std::vector<OUString> NodeStack;
            NodeStack m_aNodeStack;
            struct PropertyStruct
            {
                OUString Name;
                uno::Type Type;
            }m_aPropName;
        };
        // -----------------------------------------------------------------------------
    } // namespace xml
    // -----------------------------------------------------------------------------

} // namespace configmgr
#endif <|endoftext|>