<commit_before>#include <QApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <stdlib.h>
#include <QtGlobal>
#include <QtWidgets>
#ifndef Q_OS_DARWIN
#include <QtSingleApplication>
#endif

int main(int argc, char *argv[])
{
    #if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    #endif

    // Non Darwin platforms uses QSingleApplication to ensure only one running instance.
    #ifndef Q_OS_DARWIN
    QtSingleApplication app(argc, argv);
    if (app.sendMessage("")) {
        return 0;
    }
    #else
    QApplication app(argc, argv);
    #endif

    QString app_dir = app.applicationDirPath();
    QString main_qml = "/qml/Main.qml";
    QString path_prefix;
    QString url_prefix;

    if (QFileInfo::exists(":" + main_qml)) {
        // Embedded resources
        path_prefix = ":";
        url_prefix = "qrc://";
    } else if (QFileInfo::exists(app_dir + main_qml)) {
        // Try relative to executable
        path_prefix = app_dir;
        url_prefix = app_dir;
    } else {  //Assume qml/main.qml in cwd.
        app_dir = ".";
        path_prefix = ".";
        url_prefix = ".";
    }

    app.setWindowIcon(QIcon(path_prefix + "/images/windowicon.png"));

    QQmlApplicationEngine engine;
    engine.rootContext()->setContextProperty("appDir", app_dir);
    engine.rootContext()->setContextProperty("urlPrefix", url_prefix);
    engine.rootContext()->setContextProperty("appVersion", APP_VERSION);

    qputenv("PYTHONDONTWRITEBYTECODE", "1");

    engine.load(QUrl(url_prefix + main_qml));

    #ifndef Q_OS_DARWIN
    // Wake up the root window on a message from new instance.
    for (auto object : engine.rootObjects()) {
        if (QWindow *window = qobject_cast<QWindow*>(object)) {
            QObject::connect(&app, &QtSingleApplication::messageReceived, [window]() {
                window->show();
                window->raise();
                window->requestActivate();
            });
        }
    }
    #endif

    return app.exec();
}
<commit_msg>Fix missing global menu bar in Unity<commit_after>#include <QApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <stdlib.h>
#include <QtGlobal>
#include <QtWidgets>
#ifndef Q_OS_DARWIN
#include <QtSingleApplication>
#endif

int main(int argc, char *argv[])
{
    // Global menubar is broken for qt5 apps in Ubuntu Unity, see:
    // https://bugs.launchpad.net/ubuntu/+source/appmenu-qt5/+bug/1323853
    // This workaround enables a local menubar.
    qputenv("UBUNTU_MENUPROXY","0");

    #if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    #endif

    // Non Darwin platforms uses QSingleApplication to ensure only one running instance.
    #ifndef Q_OS_DARWIN
    QtSingleApplication app(argc, argv);
    if (app.sendMessage("")) {
        return 0;
    }
    #else
    QApplication app(argc, argv);
    #endif

    QString app_dir = app.applicationDirPath();
    QString main_qml = "/qml/Main.qml";
    QString path_prefix;
    QString url_prefix;

    if (QFileInfo::exists(":" + main_qml)) {
        // Embedded resources
        path_prefix = ":";
        url_prefix = "qrc://";
    } else if (QFileInfo::exists(app_dir + main_qml)) {
        // Try relative to executable
        path_prefix = app_dir;
        url_prefix = app_dir;
    } else {  //Assume qml/main.qml in cwd.
        app_dir = ".";
        path_prefix = ".";
        url_prefix = ".";
    }

    app.setWindowIcon(QIcon(path_prefix + "/images/windowicon.png"));

    QQmlApplicationEngine engine;
    engine.rootContext()->setContextProperty("appDir", app_dir);
    engine.rootContext()->setContextProperty("urlPrefix", url_prefix);
    engine.rootContext()->setContextProperty("appVersion", APP_VERSION);

    qputenv("PYTHONDONTWRITEBYTECODE", "1");

    engine.load(QUrl(url_prefix + main_qml));

    #ifndef Q_OS_DARWIN
    // Wake up the root window on a message from new instance.
    for (auto object : engine.rootObjects()) {
        if (QWindow *window = qobject_cast<QWindow*>(object)) {
            QObject::connect(&app, &QtSingleApplication::messageReceived, [window]() {
                window->show();
                window->raise();
                window->requestActivate();
            });
        }
    }
    #endif

    return app.exec();
}
<|endoftext|>


<commit_before>/*
	This file is part of cpp-ethereum.

	cpp-ethereum is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	cpp-ethereum 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 General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/** @file MixClient.cpp
 * @author Arkadiy Paronyan arkadiy@ethdev.com
 * @date 2015
 * Ethereum IDE client.
 */

#include "MixClient.h"
#include <vector>
#include <utility>
#include <libdevcore/Exceptions.h>
#include <libethcore/Params.h>
#include <libethcore/BasicAuthority.h>
#include <libethereum/CanonBlockChain.h>
#include <libethereum/Transaction.h>
#include <libethereum/Executive.h>
#include <libethereum/ExtVM.h>
#include <libethereum/BlockChain.h>
#include <libevm/VM.h>
#include "Exceptions.h"
using namespace std;
using namespace dev;
using namespace dev::eth;

namespace dev
{
namespace mix
{

u256 const c_mixGenesisDifficulty = 131072; //TODO: make it lower for Mix somehow

namespace
{
}

MixBlockChain::MixBlockChain(std::string const& _path, h256 _stateRoot):
	FullBlockChain<NoProof>(createGenesisBlock(_stateRoot), std::unordered_map<Address, Account>(), _path, WithExisting::Kill)
{
}

bytes MixBlockChain::createGenesisBlock(h256 _stateRoot)
{
	RLPStream block(3);
	block.appendList(13)
			<< h256() << EmptyListSHA3 << h160() << _stateRoot << EmptyTrie << EmptyTrie
			<< LogBloom() << c_mixGenesisDifficulty << 0 << c_genesisGasLimit << 0 << (unsigned)0
			<< std::string();
	block.appendRaw(RLPEmptyList);
	block.appendRaw(RLPEmptyList);
	return block.out();
}

MixClient::MixClient(std::string const& _dbPath):
	m_dbPath(_dbPath)
{
	resetState(std::unordered_map<Address, Account>());
}

MixClient::~MixClient()
{
}

void MixClient::resetState(std::unordered_map<Address, Account> const& _accounts,  Secret const& _miner)
{
	WriteGuard l(x_state);
	Guard fl(x_filtersWatches);

	m_filters.clear();
	for (auto& i: m_specialFilters)
		i.second.clear();
	m_watches.clear();

	m_stateDB = OverlayDB();
	SecureTrieDB<Address, MemoryDB> accountState(&m_stateDB);
	accountState.init();

	dev::eth::commit(_accounts, accountState);
	h256 stateRoot = accountState.root();
	m_bc.reset();
	m_bc.reset(new MixBlockChain(m_dbPath, stateRoot));
	State s(m_stateDB, BaseState::PreExisting, KeyPair(_miner).address());
	s.sync(bc());
	m_state = s;
	m_startState = m_state;
	WriteGuard lx(x_executions);
	m_executions.clear();
}

Transaction MixClient::replaceGas(Transaction const& _t, u256 const& _gas, Secret const& _secret)
{
	Transaction ret;
	if (_secret)
	{
		if (_t.isCreation())
			ret = Transaction(_t.value(), _t.gasPrice(), _gas, _t.data(), _t.nonce(), _secret);
		else
			ret = Transaction(_t.value(), _t.gasPrice(), _gas, _t.receiveAddress(), _t.data(), _t.nonce(), _secret);
	}
	else
	{
		if (_t.isCreation())
			ret = Transaction(_t.value(), _t.gasPrice(), _gas, _t.data(), _t.nonce());
		else
			ret = Transaction(_t.value(), _t.gasPrice(), _gas, _t.receiveAddress(), _t.data(), _t.nonce());
		ret.forceSender(_t.safeSender());
	}
	return ret;
}

void MixClient::executeTransaction(Transaction const& _t, State& _state, bool _call, bool _gasAuto, Secret const& _secret)
{
	Transaction t = _gasAuto ? replaceGas(_t, m_state.gasLimitRemaining()) : _t;
	// do debugging run first
	LastHashes lastHashes(256);
	lastHashes[0] = bc().numberHash(bc().number());
	for (unsigned i = 1; i < 256; ++i)
		lastHashes[i] = lastHashes[i - 1] ? bc().details(lastHashes[i - 1]).parent : h256();

	State execState = _state;
	execState.addBalance(t.sender(), t.gas() * t.gasPrice()); //give it enough balance for gas estimation
	eth::ExecutionResult er;
	Executive execution(execState, lastHashes, 0);
	execution.setResultRecipient(er);
	execution.initialize(t);
	execution.execute();
	std::vector<MachineState> machineStates;
	std::vector<unsigned> levels;
	std::vector<MachineCode> codes;
	std::map<bytes const*, unsigned> codeIndexes;
	std::vector<bytes> data;
	std::map<bytesConstRef const*, unsigned> dataIndexes;
	bytes const* lastCode = nullptr;
	bytesConstRef const* lastData = nullptr;
	unsigned codeIndex = 0;
	unsigned dataIndex = 0;
	auto onOp = [&](uint64_t steps, Instruction inst, bigint newMemSize, bigint gasCost, bigint gas, void* voidVM, void const* voidExt)
	{
		VM& vm = *static_cast<VM*>(voidVM);
		ExtVM const& ext = *static_cast<ExtVM const*>(voidExt);
		if (lastCode == nullptr || lastCode != &ext.code)
		{
			auto const& iter = codeIndexes.find(&ext.code);
			if (iter != codeIndexes.end())
				codeIndex = iter->second;
			else
			{
				codeIndex = codes.size();
				codes.push_back(MachineCode({ext.myAddress, ext.code}));
				codeIndexes[&ext.code] = codeIndex;
			}
			lastCode = &ext.code;
		}

		if (lastData == nullptr || lastData != &ext.data)
		{
			auto const& iter = dataIndexes.find(&ext.data);
			if (iter != dataIndexes.end())
				dataIndex = iter->second;
			else
			{
				dataIndex = data.size();
				data.push_back(ext.data.toBytes());
				dataIndexes[&ext.data] = dataIndex;
			}
			lastData = &ext.data;
		}

		if (levels.size() < ext.depth)
			levels.push_back(machineStates.size() - 1);
		else
			levels.resize(ext.depth);

		machineStates.push_back(MachineState{
									steps,
									vm.curPC(),
									inst,
									newMemSize,
									static_cast<u256>(gas),
									vm.stack(),
									vm.memory(),
									gasCost,
									ext.state().storage(ext.myAddress),
									std::move(levels),
									codeIndex,
									dataIndex
								});
	};

	execution.go(onOp);
	execution.finalize();

	switch (er.excepted)
	{
	case TransactionException::None:
		break;
	case TransactionException::NotEnoughCash:
		BOOST_THROW_EXCEPTION(Exception() << errinfo_comment("Insufficient balance for contract deployment"));
	case TransactionException::OutOfGasIntrinsic:
	case TransactionException::OutOfGasBase:
	case TransactionException::OutOfGas:
		BOOST_THROW_EXCEPTION(OutOfGas() << errinfo_comment("Not enough gas"));
	case TransactionException::BlockGasLimitReached:
		BOOST_THROW_EXCEPTION(OutOfGas() << errinfo_comment("Block gas limit reached"));
	case TransactionException::BadJumpDestination:
		BOOST_THROW_EXCEPTION(OutOfGas() << errinfo_comment("Solidity exception (bad jump)"));
	case TransactionException::OutOfStack:
		BOOST_THROW_EXCEPTION(Exception() << errinfo_comment("Out of stack"));
	case TransactionException::StackUnderflow:
		BOOST_THROW_EXCEPTION(Exception() << errinfo_comment("Stack underflow"));
		//these should not happen in mix
	case TransactionException::Unknown:
	case TransactionException::BadInstruction:
	case TransactionException::InvalidSignature:
	case TransactionException::InvalidNonce:
	case TransactionException::InvalidFormat:
	case TransactionException::BadRLP:
		BOOST_THROW_EXCEPTION(Exception() << errinfo_comment("Internal execution error"));
	}

	ExecutionResult d;
	d.inputParameters = t.data();
	d.result = er;
	d.machineStates = machineStates;
	d.executionCode = std::move(codes);
	d.transactionData = std::move(data);
	d.address = _t.receiveAddress();
	d.sender = _t.sender();
	d.value = _t.value();
	d.gasUsed = er.gasUsed + er.gasRefunded + c_callStipend;
	if (_t.isCreation())
		d.contractAddress = right160(sha3(rlpList(_t.sender(), _t.nonce())));
	if (!_call)
		d.transactionIndex = m_state.pending().size();
	d.executonIndex = m_executions.size();

	// execute on a state
	if (!_call)
	{
		t = _gasAuto ? replaceGas(_t, d.gasUsed, _secret) : _t;
		er = _state.execute(lastHashes, t);
		if (t.isCreation() && _state.code(d.contractAddress).empty())
			BOOST_THROW_EXCEPTION(OutOfGas() << errinfo_comment("Not enough gas for contract deployment"));
		d.gasUsed = er.gasUsed + er.gasRefunded + er.gasForDeposit + c_callStipend;
		LocalisedLogEntries logs;
		TransactionReceipt const& tr = _state.receipt(_state.pending().size() - 1);

		//auto trHash = _state.pending().at(_state.pending().size() - 1).sha3();
		LogEntries le = tr.log();
		if (le.size())
			for (unsigned j = 0; j < le.size(); ++j)
				logs.insert(logs.begin(), LocalisedLogEntry(le[j]));
		d.logs =  logs;
	}
	WriteGuard l(x_executions);
	m_executions.emplace_back(std::move(d));
}

void MixClient::mine()
{
	WriteGuard l(x_state);
	m_state.commitToMine(bc());

	NoProof::BlockHeader h(m_state.info());
	RLPStream header;
	h.streamRLP(header);
	m_state.sealBlock(header.out());
	bc().import(m_state.blockData(), m_state.db(), ImportRequirements::Default & ~ImportRequirements::ValidSeal);
	m_state.sync(bc());
	m_startState = m_state;
}

ExecutionResult MixClient::lastExecution() const
{
	ReadGuard l(x_executions);
	return m_executions.empty() ? ExecutionResult() : m_executions.back();
}

ExecutionResult MixClient::execution(unsigned _index) const
{
	ReadGuard l(x_executions);
	return m_executions.at(_index);
}

State MixClient::asOf(h256 const& _block) const
{
	ReadGuard l(x_state);
	State ret(m_stateDB);
	ret.populateFromChain(bc(), _block);
	return ret;
}

pair<h256, Address> MixClient::submitTransaction(eth::TransactionSkeleton const& _ts, Secret const& _secret, bool _gasAuto)
{
	WriteGuard l(x_state);
	TransactionSkeleton ts = _ts;
	ts.from = toAddress(_secret);
	ts.nonce = m_state.transactionsFrom(ts.from);
	eth::Transaction t(ts, _secret);
	executeTransaction(t, m_state, false, _gasAuto, _secret);
	return make_pair(t.sha3(), toAddress(ts.from, ts.nonce));
}

dev::eth::ExecutionResult MixClient::call(Address const& _from, u256 _value, Address _dest, bytes const& _data, u256 _gas, u256 _gasPrice, BlockNumber _blockNumber, bool _gasAuto, FudgeFactor _ff)
{
	(void)_blockNumber;
	State temp = asOf(eth::PendingBlock);
	u256 n = temp.transactionsFrom(_from);
	Transaction t(_value, _gasPrice, _gas, _dest, _data, n);
	t.forceSender(_from);
	if (_ff == FudgeFactor::Lenient)
		temp.addBalance(_from, (u256)(t.gasRequired() * t.gasPrice() + t.value()));
	WriteGuard lw(x_state); //TODO: lock is required only for last execution state
	executeTransaction(t, temp, true, _gasAuto);
	return lastExecution().result;
}

dev::eth::ExecutionResult MixClient::call(Address const& _from, u256 _value, Address _dest, bytes const& _data, u256 _gas, u256 _gasPrice, BlockNumber _blockNumber, eth::FudgeFactor _ff)
{
	return call(_from, _value, _dest, _data, _gas, _gasPrice, _blockNumber, false, _ff);
}

dev::eth::ExecutionResult MixClient::create(Address const& _from, u256 _value, bytes const& _data, u256 _gas, u256 _gasPrice, BlockNumber _blockNumber, eth::FudgeFactor _ff)
{
	(void)_blockNumber;
	u256 n;
	State temp;
	{
		ReadGuard lr(x_state);
		temp = asOf(eth::PendingBlock);
		n = temp.transactionsFrom(_from);
	}
	Transaction t(_value, _gasPrice, _gas, _data, n);
	t.forceSender(_from);
	if (_ff == FudgeFactor::Lenient)
		temp.addBalance(_from, (u256)(t.gasRequired() * t.gasPrice() + t.value()));
	WriteGuard lw(x_state); //TODO: lock is required only for last execution state
	executeTransaction(t, temp, true, false);
	return lastExecution().result;
}

eth::BlockInfo MixClient::blockInfo() const
{
	ReadGuard l(x_state);
	return BlockInfo(bc().block());
}

void MixClient::setAddress(Address _us)
{
	WriteGuard l(x_state);
	m_state.setAddress(_us);
}

void MixClient::startMining()
{
	//no-op
}

void MixClient::stopMining()
{
	//no-op
}

bool MixClient::isMining() const
{
	return false;
}

uint64_t MixClient::hashrate() const
{
	return 0;
}

eth::WorkingProgress MixClient::miningProgress() const
{
	return eth::WorkingProgress();
}

}
}
<commit_msg>started tests refactoring<commit_after>/*
	This file is part of cpp-ethereum.

	cpp-ethereum is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	cpp-ethereum 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 General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/** @file MixClient.cpp
 * @author Arkadiy Paronyan arkadiy@ethdev.com
 * @date 2015
 * Ethereum IDE client.
 */

#include "MixClient.h"
#include <vector>
#include <utility>
#include <libdevcore/Exceptions.h>
#include <libethcore/Params.h>
#include <libethcore/BasicAuthority.h>
#include <libethereum/CanonBlockChain.h>
#include <libethereum/Transaction.h>
#include <libethereum/Executive.h>
#include <libethereum/ExtVM.h>
#include <libethereum/BlockChain.h>
#include <libevm/VM.h>
#include "Exceptions.h"
using namespace std;
using namespace dev;
using namespace dev::eth;

namespace dev
{
namespace mix
{

u256 const c_mixGenesisDifficulty = 131072; //TODO: make it lower for Mix somehow

namespace
{
}

MixBlockChain::MixBlockChain(std::string const& _path, h256 _stateRoot):
	FullBlockChain<NoProof>(createGenesisBlock(_stateRoot), std::unordered_map<Address, Account>(), _path, WithExisting::Kill)
{
}

bytes MixBlockChain::createGenesisBlock(h256 _stateRoot)
{
	RLPStream block(3);
	block.appendList(13)
			<< h256() << EmptyListSHA3 << h160() << _stateRoot << EmptyTrie << EmptyTrie
			<< LogBloom() << c_mixGenesisDifficulty << 0 << c_genesisGasLimit << 0 << (unsigned)0
			<< std::string();
	block.appendRaw(RLPEmptyList);
	block.appendRaw(RLPEmptyList);
	return block.out();
}

MixClient::MixClient(std::string const& _dbPath):
	m_dbPath(_dbPath)
{
	resetState(std::unordered_map<Address, Account>());
}

MixClient::~MixClient()
{
}

void MixClient::resetState(std::unordered_map<Address, Account> const& _accounts,  Secret const& _miner)
{
	WriteGuard l(x_state);
	Guard fl(x_filtersWatches);

	m_filters.clear();
	for (auto& i: m_specialFilters)
		i.second.clear();
	m_watches.clear();

	m_stateDB = OverlayDB();
	SecureTrieDB<Address, MemoryDB> accountState(&m_stateDB);
	accountState.init();

	dev::eth::commit(_accounts, accountState);
	h256 stateRoot = accountState.root();
	m_bc.reset();
	m_bc.reset(new MixBlockChain(m_dbPath, stateRoot));
	State s(m_stateDB, BaseState::PreExisting, KeyPair(_miner).address());
	s.sync(bc());
	m_state = s;
	m_startState = m_state;
	WriteGuard lx(x_executions);
	m_executions.clear();
}

Transaction MixClient::replaceGas(Transaction const& _t, u256 const& _gas, Secret const& _secret)
{
	Transaction ret;
	if (_secret)
	{
		if (_t.isCreation())
			ret = Transaction(_t.value(), _t.gasPrice(), _gas, _t.data(), _t.nonce(), _secret);
		else
			ret = Transaction(_t.value(), _t.gasPrice(), _gas, _t.receiveAddress(), _t.data(), _t.nonce(), _secret);
	}
	else
	{
		if (_t.isCreation())
			ret = Transaction(_t.value(), _t.gasPrice(), _gas, _t.data(), _t.nonce());
		else
			ret = Transaction(_t.value(), _t.gasPrice(), _gas, _t.receiveAddress(), _t.data(), _t.nonce());
		ret.forceSender(_t.safeSender());
	}
	return ret;
}

void MixClient::executeTransaction(Transaction const& _t, State& _state, bool _call, bool _gasAuto, Secret const& _secret)
{
	Transaction t = _gasAuto ? replaceGas(_t, m_state.gasLimitRemaining()) : _t;
	// do debugging run first
	LastHashes lastHashes(256);
	lastHashes[0] = bc().numberHash(bc().number());
	for (unsigned i = 1; i < 256; ++i)
		lastHashes[i] = lastHashes[i - 1] ? bc().details(lastHashes[i - 1]).parent : h256();

	State execState = _state;
	execState.addBalance(t.sender(), t.gas() * t.gasPrice()); //give it enough balance for gas estimation
	eth::ExecutionResult er;
	Executive execution(execState, lastHashes, 0);
	execution.setResultRecipient(er);
	execution.initialize(t);
	execution.execute();
	std::vector<MachineState> machineStates;
	std::vector<unsigned> levels;
	std::vector<MachineCode> codes;
	std::map<bytes const*, unsigned> codeIndexes;
	std::vector<bytes> data;
	std::map<bytesConstRef const*, unsigned> dataIndexes;
	bytes const* lastCode = nullptr;
	bytesConstRef const* lastData = nullptr;
	unsigned codeIndex = 0;
	unsigned dataIndex = 0;
	auto onOp = [&](uint64_t steps, Instruction inst, bigint newMemSize, bigint gasCost, bigint gas, void* voidVM, void const* voidExt)
	{
		VM& vm = *static_cast<VM*>(voidVM);
		ExtVM const& ext = *static_cast<ExtVM const*>(voidExt);
		if (lastCode == nullptr || lastCode != &ext.code)
		{
			auto const& iter = codeIndexes.find(&ext.code);
			if (iter != codeIndexes.end())
				codeIndex = iter->second;
			else
			{
				codeIndex = codes.size();
				codes.push_back(MachineCode({ext.myAddress, ext.code}));
				codeIndexes[&ext.code] = codeIndex;
			}
			lastCode = &ext.code;
		}

		if (lastData == nullptr || lastData != &ext.data)
		{
			auto const& iter = dataIndexes.find(&ext.data);
			if (iter != dataIndexes.end())
				dataIndex = iter->second;
			else
			{
				dataIndex = data.size();
				data.push_back(ext.data.toBytes());
				dataIndexes[&ext.data] = dataIndex;
			}
			lastData = &ext.data;
		}

		if (levels.size() < ext.depth)
			levels.push_back(machineStates.size() - 1);
		else
			levels.resize(ext.depth);

		machineStates.push_back(MachineState{
									steps,
									vm.curPC(),
									inst,
									newMemSize,
									static_cast<u256>(gas),
									vm.stack(),
									vm.memory(),
									gasCost,
									ext.state().storage(ext.myAddress),
									std::move(levels),
									codeIndex,
									dataIndex
								});
	};

	execution.go(onOp);
	execution.finalize();

	switch (er.excepted)
	{
	case TransactionException::None:
		break;
	case TransactionException::NotEnoughCash:
		BOOST_THROW_EXCEPTION(Exception() << errinfo_comment("Insufficient balance for contract deployment"));
	case TransactionException::OutOfGasIntrinsic:
	case TransactionException::OutOfGasBase:
	case TransactionException::OutOfGas:
		BOOST_THROW_EXCEPTION(OutOfGas() << errinfo_comment("Not enough gas"));
	case TransactionException::BlockGasLimitReached:
		BOOST_THROW_EXCEPTION(OutOfGas() << errinfo_comment("Block gas limit reached"));
	case TransactionException::BadJumpDestination:
		BOOST_THROW_EXCEPTION(OutOfGas() << errinfo_comment("Solidity exception (bad jump)"));
	case TransactionException::OutOfStack:
		BOOST_THROW_EXCEPTION(Exception() << errinfo_comment("Out of stack"));
	case TransactionException::StackUnderflow:
		BOOST_THROW_EXCEPTION(Exception() << errinfo_comment("Stack underflow"));
		//these should not happen in mix
	case TransactionException::Unknown:
	case TransactionException::BadInstruction:
	case TransactionException::InvalidSignature:
	case TransactionException::InvalidNonce:
	case TransactionException::InvalidFormat:
	case TransactionException::BadRLP:
		BOOST_THROW_EXCEPTION(Exception() << errinfo_comment("Internal execution error"));
	}

	ExecutionResult d;
	d.inputParameters = t.data();
	d.result = er;
	d.machineStates = machineStates;
	d.executionCode = std::move(codes);
	d.transactionData = std::move(data);
	d.address = _t.receiveAddress();
	d.sender = _t.sender();
	d.value = _t.value();
	d.gasUsed = er.gasUsed + er.gasRefunded + c_callStipend;
	if (_t.isCreation())
		d.contractAddress = right160(sha3(rlpList(_t.sender(), _t.nonce())));
	if (!_call)
		d.transactionIndex = m_state.pending().size();
	d.executonIndex = m_executions.size();

	// execute on a state
	if (!_call)
	{
		t = _gasAuto ? replaceGas(_t, d.gasUsed, _secret) : _t;
		er = _state.execute(lastHashes, t);
		if (t.isCreation() && _state.code(d.contractAddress).empty())
			BOOST_THROW_EXCEPTION(OutOfGas() << errinfo_comment("Not enough gas for contract deployment"));
		d.gasUsed = er.gasUsed + er.gasRefunded + er.gasForDeposit + c_callStipend;
		LocalisedLogEntries logs;
		TransactionReceipt const& tr = _state.receipt(_state.pending().size() - 1);

		//auto trHash = _state.pending().at(_state.pending().size() - 1).sha3();
		LogEntries le = tr.log();
		if (le.size())
			for (unsigned j = 0; j < le.size(); ++j)
				logs.insert(logs.begin(), LocalisedLogEntry(le[j]));
		d.logs =  logs;
	}
	WriteGuard l(x_executions);
	m_executions.emplace_back(std::move(d));
}

void MixClient::mine()
{
	WriteGuard l(x_state);
	m_state.commitToMine(bc());

	NoProof::BlockHeader h(m_state.info());
	RLPStream header;
	h.streamRLP(header);
	m_state.sealBlock(header.out());
	bc().import(m_state.blockData(), m_state.db(), ImportRequirements::Everything & ~ImportRequirements::ValidSeal);
	m_state.sync(bc());
	m_startState = m_state;
}

ExecutionResult MixClient::lastExecution() const
{
	ReadGuard l(x_executions);
	return m_executions.empty() ? ExecutionResult() : m_executions.back();
}

ExecutionResult MixClient::execution(unsigned _index) const
{
	ReadGuard l(x_executions);
	return m_executions.at(_index);
}

State MixClient::asOf(h256 const& _block) const
{
	ReadGuard l(x_state);
	State ret(m_stateDB);
	ret.populateFromChain(bc(), _block);
	return ret;
}

pair<h256, Address> MixClient::submitTransaction(eth::TransactionSkeleton const& _ts, Secret const& _secret, bool _gasAuto)
{
	WriteGuard l(x_state);
	TransactionSkeleton ts = _ts;
	ts.from = toAddress(_secret);
	ts.nonce = m_state.transactionsFrom(ts.from);
	eth::Transaction t(ts, _secret);
	executeTransaction(t, m_state, false, _gasAuto, _secret);
	return make_pair(t.sha3(), toAddress(ts.from, ts.nonce));
}

dev::eth::ExecutionResult MixClient::call(Address const& _from, u256 _value, Address _dest, bytes const& _data, u256 _gas, u256 _gasPrice, BlockNumber _blockNumber, bool _gasAuto, FudgeFactor _ff)
{
	(void)_blockNumber;
	State temp = asOf(eth::PendingBlock);
	u256 n = temp.transactionsFrom(_from);
	Transaction t(_value, _gasPrice, _gas, _dest, _data, n);
	t.forceSender(_from);
	if (_ff == FudgeFactor::Lenient)
		temp.addBalance(_from, (u256)(t.gasRequired() * t.gasPrice() + t.value()));
	WriteGuard lw(x_state); //TODO: lock is required only for last execution state
	executeTransaction(t, temp, true, _gasAuto);
	return lastExecution().result;
}

dev::eth::ExecutionResult MixClient::call(Address const& _from, u256 _value, Address _dest, bytes const& _data, u256 _gas, u256 _gasPrice, BlockNumber _blockNumber, eth::FudgeFactor _ff)
{
	return call(_from, _value, _dest, _data, _gas, _gasPrice, _blockNumber, false, _ff);
}

dev::eth::ExecutionResult MixClient::create(Address const& _from, u256 _value, bytes const& _data, u256 _gas, u256 _gasPrice, BlockNumber _blockNumber, eth::FudgeFactor _ff)
{
	(void)_blockNumber;
	u256 n;
	State temp;
	{
		ReadGuard lr(x_state);
		temp = asOf(eth::PendingBlock);
		n = temp.transactionsFrom(_from);
	}
	Transaction t(_value, _gasPrice, _gas, _data, n);
	t.forceSender(_from);
	if (_ff == FudgeFactor::Lenient)
		temp.addBalance(_from, (u256)(t.gasRequired() * t.gasPrice() + t.value()));
	WriteGuard lw(x_state); //TODO: lock is required only for last execution state
	executeTransaction(t, temp, true, false);
	return lastExecution().result;
}

eth::BlockInfo MixClient::blockInfo() const
{
	ReadGuard l(x_state);
	return BlockInfo(bc().block());
}

void MixClient::setAddress(Address _us)
{
	WriteGuard l(x_state);
	m_state.setAddress(_us);
}

void MixClient::startMining()
{
	//no-op
}

void MixClient::stopMining()
{
	//no-op
}

bool MixClient::isMining() const
{
	return false;
}

uint64_t MixClient::hashrate() const
{
	return 0;
}

eth::WorkingProgress MixClient::miningProgress() const
{
	return eth::WorkingProgress();
}

}
}
<|endoftext|>


<commit_before>#include "ODocument.h"
#include "ui_awindow.h"
#include <QFile>
#include <QTextStream>
#include <QDebug>
#include <QLayout>

aWindow::aWindow(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::aWindow)
{
    ui->setupUi(this);
    QFile aFile("Widget_Manual2.1.txt");
    if(!aFile.open(QFile::ReadOnly | QFile::Text))
       //QDebug() << "Can not open";
    QTextStream WidM(&aFile);
 //   ui->textBrowser->append(WidM.readline());

    QHBoxLayout *layout = new QHBoxLayout;
       layout->addWidget(ui->textBrowser);
       setLayout(layout);

}

aWindow::~aWindow()
{
    delete ui;
}

void aWindow::on_actionNew_Window_triggered()
{
    aDialog = new QDialog(this);
    aDialog->setModal(false);
    aDialog->show();
}
<commit_msg>Delete ODocument.cpp<commit_after><|endoftext|>


<commit_before>/*
Copyright 2014-2015 Adam Grandquist

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.
 */
/**
 * @author Adam Grandquist
 * @copyright Apache
 */

#include "ReQL-expr.hpp"

#include "ReQL.hpp"

#include <limits>

namespace ReQL {

Expr::Expr() : p_query(ReQL_Datum()) {}

Expr::Expr(const ReQL_AST_Function &f, const std::vector<Query> &args, const std::map<std::string, Query> &kwargs) : p_func(f) {
  std::size_t args_size = args.size();

  if (args_size > std::numeric_limits<std::uint32_t>::max()) {
    return;
  }

  std::size_t kwargs_size = kwargs.size();

  if (kwargs_size > std::numeric_limits<std::uint32_t>::max()) {
    return;
  }

  ReQL_Term query(static_cast<std::uint32_t>(args_size), static_cast<std::uint32_t>(kwargs_size));

  for (auto it=args.cbegin(); it!=args.cend(); ++it) {
    p_array.insert(p_array.end(), *it);
    query.add_arg(it->p_query);
  }

  for (auto it=kwargs.cbegin(); it!=kwargs.cend(); ++it) {
    Expr key(it->first);
    p_object.insert(p_object.end(), {key, it->second});
    query.add_kwarg(key.p_query, it->second.p_query);
  }

  query.finalize(p_func);

  p_query = std::move(query);
}

Expr::Expr(const std::string &val) : p_query(std::move(ReQL_String(val))) {}

Expr::Expr(const double &val) : p_query(std::move(ReQL_Datum(val))) {}

Expr::Expr(const bool &val) : p_query(std::move(ReQL_Datum(val))) {}

Expr::Expr(const std::vector<Query> &val) {
  std::size_t size = val.size();

  if (size > std::numeric_limits<std::uint32_t>::max()) {
    return;
  }

  ReQL_Array query(static_cast<std::uint32_t>(size));

  for (auto it=val.cbegin(); it!=val.cend(); ++it) {
    p_array.insert(p_array.end(), *it);
    query.add_elem(it->p_query);
  }

  p_query = std::move(query);
}

Expr::Expr(const std::map<std::string, Query> &val) {
  std::size_t size = val.size();

  if (size > std::numeric_limits<std::uint32_t>::max()) {
    return;
  }

  ReQL_Object query(static_cast<std::uint32_t>(size));

  for (auto it=val.cbegin(); it!=val.cend(); ++it) {
    Expr key(it->first);
    p_object.insert(p_object.end(), {key, it->second});
    query.add_key(key.p_query, it->second.p_query);
  }

  p_query = std::move(query);
}

bool Expr::operator<(const Expr &other) const {
  return p_query < other.p_query;
}

Expr::Expr(const Expr &other) : p_array(other.p_array), p_func(other.p_func), p_object(other.p_object) {
  copy(other);
}

Expr::Expr(Expr &&other) {
  p_array = std::move(other.p_array);
  p_func = std::move(other.p_func);
  p_object = std::move(other.p_object);
  p_query = std::move(other.p_query);
}

Expr &Expr::operator=(const Expr &other) {
  if (this != &other) {
    p_array = other.p_array;
    p_func = other.p_func;
    p_object = other.p_object;

    copy(other);
  }

  return *this;
}

void
Expr::copy(const Expr &other) {
  switch (other.p_query.type()) {
    case REQL_R_ARRAY: {
      ReQL_Array query(static_cast<std::uint32_t>(p_array.size()));

      for (auto it=p_array.cbegin(); it!=p_array.cend(); ++it) {
        query.add_elem(it->p_query);
      }

      p_query = std::move(query);
      break;
    }
    case REQL_R_BOOL: {
      p_query = std::move(ReQL_Datum(reql_to_bool(other.p_query.data()) ? true : false));
      break;
    }
    case REQL_R_NULL: {
      p_query = std::move(ReQL_Datum());
      break;
    }
    case REQL_R_NUM: {
      p_query = std::move(ReQL_Datum(reql_to_number(other.p_query.data())));
      break;
    }
    case REQL_R_OBJECT: {
      ReQL_Object query(static_cast<std::uint32_t>(p_object.size()));

      for (auto it=p_object.cbegin(); it!=p_object.cend(); ++it) {
        query.add_key(it->first.p_query, it->second.p_query);
      }

      p_query = std::move(query);
      break;
    }
    case REQL_R_STR: {
      std::string str((char*)reql_string_buf(other.p_query.data()), static_cast<std::size_t>(reql_size(other.p_query.data())));
      p_query = std::move(ReQL_String(str));
      break;
    }
    case REQL_R_JSON: throw;
    case REQL_R_REQL: {
      ReQL_Term query(static_cast<std::uint32_t>(p_array.size()), static_cast<std::uint32_t>(p_object.size()));

      for (auto it=p_array.cbegin(); it!=p_array.cend(); ++it) {
        query.add_arg(it->p_query);
      }

      for (auto it=p_object.cbegin(); it!=p_object.cend(); ++it) {
        query.add_kwarg(it->first.p_query, it->second.p_query);
      }

      query.finalize(p_func);

      p_query = std::move(query);
      break;
    }
  }
}

Expr &Expr::operator=(Expr &&other) {
  if (this != &other) {
    p_array = std::move(other.p_array);
    p_func = std::move(other.p_func);
    p_object = std::move(other.p_object);
    p_query = std::move(other.p_query);
  }

  return *this;
}

}
<commit_msg>Reorder property initialization.<commit_after>/*
Copyright 2014-2015 Adam Grandquist

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.
 */
/**
 * @author Adam Grandquist
 * @copyright Apache
 */

#include "ReQL-expr.hpp"

#include "ReQL.hpp"

#include <limits>

namespace ReQL {

Expr::Expr() : p_query(ReQL_Datum()) {}

Expr::Expr(const ReQL_AST_Function &f, const std::vector<Query> &args, const std::map<std::string, Query> &kwargs) : p_func(f) {
  std::size_t args_size = args.size();

  if (args_size > std::numeric_limits<std::uint32_t>::max()) {
    return;
  }

  std::size_t kwargs_size = kwargs.size();

  if (kwargs_size > std::numeric_limits<std::uint32_t>::max()) {
    return;
  }

  ReQL_Term query(static_cast<std::uint32_t>(args_size), static_cast<std::uint32_t>(kwargs_size));

  for (auto it=args.cbegin(); it!=args.cend(); ++it) {
    p_array.insert(p_array.end(), *it);
    query.add_arg(it->p_query);
  }

  for (auto it=kwargs.cbegin(); it!=kwargs.cend(); ++it) {
    Expr key(it->first);
    p_object.insert(p_object.end(), {key, it->second});
    query.add_kwarg(key.p_query, it->second.p_query);
  }

  query.finalize(p_func);

  p_query = std::move(query);
}

Expr::Expr(const std::string &val) : p_query(std::move(ReQL_String(val))) {}

Expr::Expr(const double &val) : p_query(std::move(ReQL_Datum(val))) {}

Expr::Expr(const bool &val) : p_query(std::move(ReQL_Datum(val))) {}

Expr::Expr(const std::vector<Query> &val) {
  std::size_t size = val.size();

  if (size > std::numeric_limits<std::uint32_t>::max()) {
    return;
  }

  ReQL_Array query(static_cast<std::uint32_t>(size));

  for (auto it=val.cbegin(); it!=val.cend(); ++it) {
    p_array.insert(p_array.end(), *it);
    query.add_elem(it->p_query);
  }

  p_query = std::move(query);
}

Expr::Expr(const std::map<std::string, Query> &val) {
  std::size_t size = val.size();

  if (size > std::numeric_limits<std::uint32_t>::max()) {
    return;
  }

  ReQL_Object query(static_cast<std::uint32_t>(size));

  for (auto it=val.cbegin(); it!=val.cend(); ++it) {
    Expr key(it->first);
    p_object.insert(p_object.end(), {key, it->second});
    query.add_key(key.p_query, it->second.p_query);
  }

  p_query = std::move(query);
}

bool Expr::operator<(const Expr &other) const {
  return p_query < other.p_query;
}

Expr::Expr(const Expr &other) : p_func(other.p_func), p_array(other.p_array), p_object(other.p_object) {
  copy(other);
}

Expr::Expr(Expr &&other) {
  p_array = std::move(other.p_array);
  p_func = std::move(other.p_func);
  p_object = std::move(other.p_object);
  p_query = std::move(other.p_query);
}

Expr &Expr::operator=(const Expr &other) {
  if (this != &other) {
    p_array = other.p_array;
    p_func = other.p_func;
    p_object = other.p_object;

    copy(other);
  }

  return *this;
}

void
Expr::copy(const Expr &other) {
  switch (other.p_query.type()) {
    case REQL_R_ARRAY: {
      ReQL_Array query(static_cast<std::uint32_t>(p_array.size()));

      for (auto it=p_array.cbegin(); it!=p_array.cend(); ++it) {
        query.add_elem(it->p_query);
      }

      p_query = std::move(query);
      break;
    }
    case REQL_R_BOOL: {
      p_query = std::move(ReQL_Datum(reql_to_bool(other.p_query.data()) ? true : false));
      break;
    }
    case REQL_R_NULL: {
      p_query = std::move(ReQL_Datum());
      break;
    }
    case REQL_R_NUM: {
      p_query = std::move(ReQL_Datum(reql_to_number(other.p_query.data())));
      break;
    }
    case REQL_R_OBJECT: {
      ReQL_Object query(static_cast<std::uint32_t>(p_object.size()));

      for (auto it=p_object.cbegin(); it!=p_object.cend(); ++it) {
        query.add_key(it->first.p_query, it->second.p_query);
      }

      p_query = std::move(query);
      break;
    }
    case REQL_R_STR: {
      std::string str((char*)reql_string_buf(other.p_query.data()), static_cast<std::size_t>(reql_size(other.p_query.data())));
      p_query = std::move(ReQL_String(str));
      break;
    }
    case REQL_R_JSON: throw;
    case REQL_R_REQL: {
      ReQL_Term query(static_cast<std::uint32_t>(p_array.size()), static_cast<std::uint32_t>(p_object.size()));

      for (auto it=p_array.cbegin(); it!=p_array.cend(); ++it) {
        query.add_arg(it->p_query);
      }

      for (auto it=p_object.cbegin(); it!=p_object.cend(); ++it) {
        query.add_kwarg(it->first.p_query, it->second.p_query);
      }

      query.finalize(p_func);

      p_query = std::move(query);
      break;
    }
  }
}

Expr &Expr::operator=(Expr &&other) {
  if (this != &other) {
    p_array = std::move(other.p_array);
    p_func = std::move(other.p_func);
    p_object = std::move(other.p_object);
    p_query = std::move(other.p_query);
  }

  return *this;
}

}
<|endoftext|>


<commit_before>#include <algorithm>
#include <iostream>
#include <vector>
#include <cstdlib>

#include <windows.h>
#include <Psapi.h>

std::ostream& dout = std::cout; // debug output stream

struct PriorityClass {
    int baseprio;
    const char* name;
    DWORD symbol;
};

static const PriorityClass PRIORITYCLASSES[] = {
    {4, "IDLE", IDLE_PRIORITY_CLASS},
    {6, "BELOWNORMAL", BELOW_NORMAL_PRIORITY_CLASS},
    {8, "NORMAL", NORMAL_PRIORITY_CLASS},
    {10, "ABOVENORMAL", ABOVE_NORMAL_PRIORITY_CLASS},
    {13, "HIGH", HIGH_PRIORITY_CLASS},
    {24, "REALTIME", REALTIME_PRIORITY_CLASS},
};

const std::size_t PRIORITYCLASSES_LENGTH =
    sizeof(PRIORITYCLASSES)/sizeof(PriorityClass);

const PriorityClass* PRIORITYCLASSES_END =
    PRIORITYCLASSES + PRIORITYCLASSES_LENGTH;

const PriorityClass* get_priorityclass(const char* name)
{
    const PriorityClass *it = PRIORITYCLASSES;
    for (; it < PRIORITYCLASSES_END; ++it)
        if (!strcmp(name, it->name)) return it;

    return it;
}

const PriorityClass* get_priorityclass(DWORD symbol)
{
    const PriorityClass *it = PRIORITYCLASSES;
    for (; it < PRIORITYCLASSES_END; ++it)
        if (symbol == it->symbol) return it;

    return it;
}

const PriorityClass* incdec_priorityclass(
    const PriorityClass* current_class,
    int incdec_by
)
{
    const PriorityClass* new_class = current_class + incdec_by;

    if (new_class < PRIORITYCLASSES) return PRIORITYCLASSES;
    else if (new_class >= PRIORITYCLASSES_END) return PRIORITYCLASSES_END - 1;
    else
        return new_class;
}

DWORD cerr_last_error()
{
    DWORD lastError = GetLastError();
    LPVOID lpMsgBuf;

    FormatMessage(
        FORMAT_MESSAGE_ALLOCATE_BUFFER |
        FORMAT_MESSAGE_FROM_SYSTEM |
        FORMAT_MESSAGE_IGNORE_INSERTS, // The formatting options, and how to interpret the lpSource parameter OMG I FRICKEN HATE MICROSOFT WHY IS THIS SO COMPLICATED
        NULL, // The location of the message definition
        lastError, // The message identifier for the requested message
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // The language identifier for the requested message
        (LPTSTR) &lpMsgBuf, // A pointer to a buffer that receives the null-terminated string that specifies the formatted message
        0, NULL
    );

    std::cerr<<"Error "<<lastError<<": "<<static_cast<LPCTSTR>(lpMsgBuf);

    LocalFree(lpMsgBuf);

    return lastError;
}

std::vector<DWORD> get_all_pids()
{
    const std::size_t PID_ARRAY_SIZE = 1024;

    std::vector<DWORD> processIds(PID_ARRAY_SIZE);
    DWORD bytesReturned;
    DWORD maxArraySize = PID_ARRAY_SIZE;

    if (!EnumProcesses(&processIds[0], maxArraySize*sizeof(DWORD), &bytesReturned))
        return std::vector<DWORD>();

    // if we don't have enough space, exponentially increase the PID buffer
    while(bytesReturned == maxArraySize*sizeof(DWORD))
    {
        maxArraySize <<= 1;
        dout<<"Size for PID Array was insufficient. Retrying with "<<
            maxArraySize * sizeof(DWORD)<<" bytes \n";

        // reallocate with appropriate size
        processIds.reserve(maxArraySize);

        if (!EnumProcesses(&processIds[0], maxArraySize*sizeof(DWORD), &bytesReturned))
            return std::vector<DWORD>();
    }

    // reset to correct size
    processIds.resize(bytesReturned/sizeof(DWORD));

    //dout<<"Enumerating processes succeeded. Number of processes: "<<
    //    bytesReturned/sizeof(DWORD)<<'\n';

    return processIds;
}

template <typename MapType>
typename MapType::const_iterator
find_value(const MapType& m, const typename MapType::mapped_type& value)
{
    auto it = m.begin();
    for (; it != m.end(); ++it)
        if (it->second == value)
            return it;

    return it;
}

struct ProgramOptions
{
    bool show_help = false;
    bool show_version = false;

    enum class ReniceWhat {
        pid,
        exe_all
    } what;

    enum class ReniceHow {
        set,
        increase,
        decrease
    } how;

    std::string whatstring;
    std::string priostring;
};

inline char get_switch(const char* arg)
{
    if (arg[0] != '-' && arg[0] != '/')
        return 0;

    return tolower(arg[1]);
}

bool read_args(ProgramOptions& po, int argc, char *argv[])
{
    po.what = ProgramOptions::ReniceWhat::pid;
    po.how = ProgramOptions::ReniceHow::set;

    unsigned positional = 0;
    for (int currArg = 1; currArg < argc ; ++currArg)
    {
        if (get_switch(argv[currArg]) == 'h')
        {
            po.show_help = true;
            return true; // stop parsing after help flag
        }

        if (get_switch(argv[currArg]) == 'v')
        {
            po.show_version = true;
            return true; // stop parsing after version flag
        }

        if (get_switch(argv[currArg]) == 'i')
        {
            po.how = ProgramOptions::ReniceHow::increase;
            continue;
        }

        if (get_switch(argv[currArg]) == 'd')
        {
            po.how = ProgramOptions::ReniceHow::decrease;
            continue;
        }

        if (get_switch(argv[currArg]) == 'p')
        {
            po.what = ProgramOptions::ReniceWhat::pid;
            continue;
        }

        if (get_switch(argv[currArg]) == 'e')
        {
            po.what = ProgramOptions::ReniceWhat::exe_all;
            continue;
        }

        // first argument is the priority
        if (positional == 0)
        {
            po.priostring = argv[currArg];
            ++positional;
            continue;
        }

        // second argument is the target
        if (positional == 1)
        {
            po.whatstring = argv[currArg];
            ++positional;
            continue;
        }
    }

    // if we didn't get at least two positional arguments, it's not enough
    if (positional < 2)
    {
        std::cerr<<"Not enough input arguments given.\n";
        return false;
    }

    return true;
}

std::string get_process_module_name(DWORD pid)
{
    HANDLE process = OpenProcess(
        PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, // The access to the process object.
        false, // If this value is TRUE, processes created by this process will inherit the handle.
        pid // The identifier of the local process to be opened.
    );
    if(process == NULL)
        return std::string();

    const std::size_t BASENAME_MAX = 512;
    char lpBaseName[BASENAME_MAX];

    std::size_t len = GetModuleBaseName(process,NULL, lpBaseName, BASENAME_MAX);
    if (!len)
    {
        std::cerr<<"Failed to retrieve executable name for process "
            <<pid<<". ";
        cerr_last_error();
        return std::string();
    }

    // dout<<"Executable name of process "<<pid<<" is. "<<lpBaseName<<'\n';

    return lpBaseName;
}

void renice_one(
    DWORD pid,
    DWORD prio
)
{
    // get a handle to the process
    HANDLE process = OpenProcess(
        PROCESS_SET_INFORMATION, // The access to the process object.
        false, // If this value is TRUE, processes created by this process will inherit the handle.
        pid // The identifier of the local process to be opened.
    );
    if(process == NULL)
    {
        std::cerr<<"Failed to open process "<<pid<<". ";
        cerr_last_error();
        return;
    }

    if (!SetPriorityClass(process, prio))
    {
        std::cerr<<"Failed to set priority class for process "<<pid<<". ";
        cerr_last_error();
    }

    std::cout<<"Setting process "<<pid<<" to priority class "<<
        get_priorityclass(prio)->name<<".\n";

before_exit:
    CloseHandle(process);
}

void incremental_renice_one(
    DWORD pid,
    int incdec_by
)
{
    // get a handle to the process
    HANDLE process = OpenProcess(
        PROCESS_SET_INFORMATION | PROCESS_QUERY_LIMITED_INFORMATION, // The access to the process object.
        false, // If this value is TRUE, processes created by this process will inherit the handle.
        pid // The identifier of the local process to be opened.
    );
    if(process == NULL)
    {
        std::cerr<<"Failed to open process "<<pid<<". ";
        cerr_last_error();
        return;
    }

    DWORD prio = GetPriorityClass(process);
    if (prio == 0)
    {
        std::cerr<<"Failed to retrieve priority class for process "<<pid<<". ";
        cerr_last_error();
        CloseHandle(process);
        return;
    }

    auto pp = get_priorityclass(prio);
    if (pp == PRIORITYCLASSES_END)
    {
        std::cerr<<"Unknown priority class returned for process "<<pid<<". ";
        CloseHandle(process);
        return;
    }

    pp = incdec_priorityclass(pp, incdec_by);
    prio = pp->symbol;

    if (!SetPriorityClass(process, prio))
    {
        std::cerr<<"Failed to set priority class for process "<<pid<<". ";
        cerr_last_error();
    }

    std::cout<<"Setting process "<<pid<<" to priority class "<<
        get_priorityclass(prio)->name<<".\n";

    CloseHandle(process);
}

void display_help()
{}

#define PROGRAM_VERSION "0.1"

void display_version()
{
    std::cout<<"winrenice version "<<PROGRAM_VERSION<<" by Alexander Korsunsky\n";
}

int main(int argc, char *argv[])
{
    ProgramOptions po;

    if (!read_args(po, argc, argv))
    {
        display_help();
        return EXIT_FAILURE;
    }

    if (po.show_help)
    {
        display_help();
        return EXIT_SUCCESS;
    }
    else if(po.show_version)
    {
        display_version();
        return EXIT_SUCCESS;
    }

    // get all PID'S
    std::vector<DWORD> all_pids = get_all_pids();
    if (all_pids.empty())
        return cerr_last_error();

    // vector for the target PID's
    std::vector<DWORD> target_pids;

    switch(po.what)
    {
        case ProgramOptions::ReniceWhat::pid:
        {
            const char *nptr = po.whatstring.c_str();
            char *endptr;
            DWORD pid = strtoul(nptr, &endptr, 10);
            if (endptr == nptr)
            {
                std::cerr<<"Process ID must be numerical. "
                    "Add /E or /A switch to look up a process by its executable name.";
                return EXIT_FAILURE;
            }

            if (all_pids.end() == std::find(all_pids.begin(), all_pids.end(), pid))
            {
                std::cerr<<"Process with ID "<<pid<<" does not exist.\n";
                return EXIT_FAILURE;
            }

            target_pids.push_back(pid);
            break;
        }
        case ProgramOptions::ReniceWhat::exe_all:
        {
            for(DWORD pid: all_pids)
                if (get_process_module_name(pid) == po.whatstring)
                    target_pids.push_back(pid);

            break;
        }
    }

    // set numerical priority depending on command line arguments
    switch(po.how)
    {
        case ProgramOptions::ReniceHow::set:
        {
            // capitalize
            std::string priostring_capitalized = po.priostring;
            for (char& c: priostring_capitalized)
                c = toupper(c);

            // find priority class
            auto p = get_priorityclass(priostring_capitalized.c_str());
            if (p == PRIORITYCLASSES_END)
            {
                std::cerr<<"Unknown priority class "<<po.priostring<<".\n";
                return EXIT_FAILURE;
            }

            for(DWORD pid: target_pids)
                renice_one(pid, p->symbol);

            break;
        }
        case ProgramOptions::ReniceHow::increase:
        case ProgramOptions::ReniceHow::decrease:
        {
            const char *nptr = po.priostring.c_str();
            char *endptr;
            int prio_incdec = strtoul(nptr, &endptr, 10);
            if (endptr == nptr)
            {
                std::cerr<<"Priority for increasing or decreasing must be numerical.";
                return EXIT_FAILURE;
            }

            if(po.how == ProgramOptions::ReniceHow::decrease)
                prio_incdec = -prio_incdec;

            for(DWORD pid: target_pids)
                incremental_renice_one(pid, prio_incdec);

            break;
        }
    }

    return EXIT_SUCCESS;
}
<commit_msg>Rewrite argument parsing<commit_after>#include <algorithm>
#include <iostream>
#include <vector>
#include <cstdlib>

#include <windows.h>
#include <Psapi.h>

std::ostream& dout = std::cout; // debug output stream

struct PriorityClass {
    int baseprio;
    const char* name;
    DWORD symbol;
};

static const PriorityClass PRIORITYCLASSES[] = {
    {4, "IDLE", IDLE_PRIORITY_CLASS},
    {6, "BELOWNORMAL", BELOW_NORMAL_PRIORITY_CLASS},
    {8, "NORMAL", NORMAL_PRIORITY_CLASS},
    {10, "ABOVENORMAL", ABOVE_NORMAL_PRIORITY_CLASS},
    {13, "HIGH", HIGH_PRIORITY_CLASS},
    {24, "REALTIME", REALTIME_PRIORITY_CLASS},
};

const std::size_t PRIORITYCLASSES_LENGTH =
    sizeof(PRIORITYCLASSES)/sizeof(PriorityClass);

const PriorityClass* PRIORITYCLASSES_END =
    PRIORITYCLASSES + PRIORITYCLASSES_LENGTH;

const PriorityClass* get_priorityclass(const char* name)
{
    const PriorityClass *it = PRIORITYCLASSES;
    for (; it < PRIORITYCLASSES_END; ++it)
        if (!strcmp(name, it->name)) return it;

    return it;
}

const PriorityClass* get_priorityclass(DWORD symbol)
{
    const PriorityClass *it = PRIORITYCLASSES;
    for (; it < PRIORITYCLASSES_END; ++it)
        if (symbol == it->symbol) return it;

    return it;
}

const PriorityClass* incdec_priorityclass(
    const PriorityClass* current_class,
    int incdec_by
)
{
    const PriorityClass* new_class = current_class + incdec_by;

    if (new_class < PRIORITYCLASSES) return PRIORITYCLASSES;
    else if (new_class >= PRIORITYCLASSES_END) return PRIORITYCLASSES_END - 1;
    else
        return new_class;
}

DWORD cerr_last_error()
{
    DWORD lastError = GetLastError();
    LPVOID lpMsgBuf;

    FormatMessage(
        FORMAT_MESSAGE_ALLOCATE_BUFFER |
        FORMAT_MESSAGE_FROM_SYSTEM |
        FORMAT_MESSAGE_IGNORE_INSERTS, // The formatting options, and how to interpret the lpSource parameter OMG I FRICKEN HATE MICROSOFT WHY IS THIS SO COMPLICATED
        NULL, // The location of the message definition
        lastError, // The message identifier for the requested message
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // The language identifier for the requested message
        (LPTSTR) &lpMsgBuf, // A pointer to a buffer that receives the null-terminated string that specifies the formatted message
        0, NULL
    );

    std::cerr<<"Error "<<lastError<<": "<<static_cast<LPCTSTR>(lpMsgBuf);

    LocalFree(lpMsgBuf);

    return lastError;
}

std::vector<DWORD> get_all_pids()
{
    const std::size_t PID_ARRAY_SIZE = 1024;

    std::vector<DWORD> processIds(PID_ARRAY_SIZE);
    DWORD bytesReturned;
    DWORD maxArraySize = PID_ARRAY_SIZE;

    if (!EnumProcesses(&processIds[0], maxArraySize*sizeof(DWORD), &bytesReturned))
        return std::vector<DWORD>();

    // if we don't have enough space, exponentially increase the PID buffer
    while(bytesReturned == maxArraySize*sizeof(DWORD))
    {
        maxArraySize <<= 1;
        dout<<"Size for PID Array was insufficient. Retrying with "<<
            maxArraySize * sizeof(DWORD)<<" bytes \n";

        // reallocate with appropriate size
        processIds.reserve(maxArraySize);

        if (!EnumProcesses(&processIds[0], maxArraySize*sizeof(DWORD), &bytesReturned))
            return std::vector<DWORD>();
    }

    // reset to correct size
    processIds.resize(bytesReturned/sizeof(DWORD));

    //dout<<"Enumerating processes succeeded. Number of processes: "<<
    //    bytesReturned/sizeof(DWORD)<<'\n';

    return processIds;
}

template <typename MapType>
typename MapType::const_iterator
find_value(const MapType& m, const typename MapType::mapped_type& value)
{
    auto it = m.begin();
    for (; it != m.end(); ++it)
        if (it->second == value)
            return it;

    return it;
}

struct ProgramOptions
{
    bool show_help = false;
    bool show_version = false;

    enum class ReniceWhat {
        pid,
        exe_all
    } what;

    DWORD target_pid;
    std::string target_str;

    enum class ReniceHow {
        set,
        increase,
        decrease
    } how;

    union {
        DWORD set;
        int incdec;
    } priority;
};

inline char get_switch(const char* arg)
{
    if (arg[0] != '-' && arg[0] != '/')
        return 0;

    return tolower(arg[1]);
}

bool read_args(ProgramOptions& po, int argc, char *argv[])
{
    po.what = ProgramOptions::ReniceWhat::pid;
    po.how = ProgramOptions::ReniceHow::set;

    std::string priostring;
    std::string whatstring;

    unsigned positional = 0;
    for (int currArg = 1; currArg < argc ; ++currArg)
    {
        if (get_switch(argv[currArg]) == 'h')
        {
            po.show_help = true;
            return true; // stop parsing after help flag
        }

        if (get_switch(argv[currArg]) == 'v')
        {
            po.show_version = true;
            return true; // stop parsing after version flag
        }

        if (get_switch(argv[currArg]) == 'i')
        {
            po.how = ProgramOptions::ReniceHow::increase;
            continue;
        }

        if (get_switch(argv[currArg]) == 'd')
        {
            po.how = ProgramOptions::ReniceHow::decrease;
            continue;
        }

        if (get_switch(argv[currArg]) == 'p')
        {
            po.what = ProgramOptions::ReniceWhat::pid;
            continue;
        }

        if (get_switch(argv[currArg]) == 'e')
        {
            po.what = ProgramOptions::ReniceWhat::exe_all;
            continue;
        }

        // anything else is not accepted
        if (get_switch(argv[currArg]))
        {
            std::cerr<<"Unknown option \""<<argv[currArg]<<"\"\n";
            return false;
        }

        // first argument is the priority
        if (positional == 0)
        {
            priostring = argv[currArg];
            ++positional;
            continue;
        }

        // second argument is the target
        if (positional == 1)
        {
            whatstring = argv[currArg];
            ++positional;
            continue;
        }
    }

    // if we didn't get two positional arguments, it's not correct
    if (positional < 2)
    {
        std::cerr<<"Not enough input arguments given.\n";
        return false;
    }
    else if( positional > 2)
    {
        std::cerr<<"Too many input arguments given.\n";
        return false;
    }

    // interpret the "how" argument depending on input arguments
    switch (po.how)
    {
        case ProgramOptions::ReniceHow::set:
        {
            // capitalize
            std::string priostring_capitalized = priostring;
            for (char& c: priostring_capitalized)
                c = toupper(c);

            // find priority class
            auto p = get_priorityclass(priostring_capitalized.c_str());
            if (p == PRIORITYCLASSES_END)
            {
                std::cerr<<"Unknown priority class "<<priostring<<".\n";
                return false;
            }

            po.priority.set = p->symbol;
            break;
        }
        case ProgramOptions::ReniceHow::increase:
        case ProgramOptions::ReniceHow::decrease:
        {
            const char *nptr = priostring.c_str();
            char *endptr;
            po.priority.incdec = strtoul(nptr, &endptr, 10);
            if (endptr == nptr)
            {
                std::cerr<<"Priority for increasing or decreasing must be numerical.";
                return false;
            }

            if(po.how == ProgramOptions::ReniceHow::decrease)
                po.priority.incdec = -po.priority.incdec;
        }
    }

    // interpret the "what" argument depending on input arguments
    switch(po.what)
    {
        case ProgramOptions::ReniceWhat::pid:
        {
            const char *nptr = whatstring.c_str();
            char *endptr;
            po.target_pid = strtoul(nptr, &endptr, 10);
            if (endptr == nptr)
            {
                std::cerr<<"Process ID must be numerical. "
                    "Add /E or /A switch to look up a process by its executable name.";
                return false;
            }

            break;
        }
        case ProgramOptions::ReniceWhat::exe_all:
        {
            po.target_str = whatstring;
            std::cout<<"after\n";
            break;
        }
    }

    return true;
}

std::string get_process_module_name(DWORD pid)
{
    HANDLE process = OpenProcess(
        PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, // The access to the process object.
        false, // If this value is TRUE, processes created by this process will inherit the handle.
        pid // The identifier of the local process to be opened.
    );
    if(process == NULL)
        return std::string();

    const std::size_t BASENAME_MAX = 512;
    char lpBaseName[BASENAME_MAX];

    std::size_t len = GetModuleBaseName(process,NULL, lpBaseName, BASENAME_MAX);
    if (!len)
    {
        std::cerr<<"Failed to retrieve executable name for process "
            <<pid<<". ";
        cerr_last_error();
        return std::string();
    }

    // dout<<"Executable name of process "<<pid<<" is. "<<lpBaseName<<'\n';

    return lpBaseName;
}

void renice_one(
    DWORD pid,
    DWORD prio
)
{
    // get a handle to the process
    HANDLE process = OpenProcess(
        PROCESS_SET_INFORMATION, // The access to the process object.
        false, // If this value is TRUE, processes created by this process will inherit the handle.
        pid // The identifier of the local process to be opened.
    );
    if(process == NULL)
    {
        std::cerr<<"Failed to open process "<<pid<<". ";
        cerr_last_error();
        return;
    }

    if (!SetPriorityClass(process, prio))
    {
        std::cerr<<"Failed to set priority class for process "<<pid<<". ";
        cerr_last_error();
    }

    std::cout<<"Setting process "<<pid<<" to priority class "<<
        get_priorityclass(prio)->name<<".\n";

before_exit:
    CloseHandle(process);
}

void incremental_renice_one(
    DWORD pid,
    int incdec_by
)
{
    // get a handle to the process
    HANDLE process = OpenProcess(
        PROCESS_SET_INFORMATION | PROCESS_QUERY_LIMITED_INFORMATION, // The access to the process object.
        false, // If this value is TRUE, processes created by this process will inherit the handle.
        pid // The identifier of the local process to be opened.
    );
    if(process == NULL)
    {
        std::cerr<<"Failed to open process "<<pid<<". ";
        cerr_last_error();
        return;
    }

    DWORD prio = GetPriorityClass(process);
    if (prio == 0)
    {
        std::cerr<<"Failed to retrieve priority class for process "<<pid<<". ";
        cerr_last_error();
        CloseHandle(process);
        return;
    }

    auto pp = get_priorityclass(prio);
    if (pp == PRIORITYCLASSES_END)
    {
        std::cerr<<"Unknown priority class returned for process "<<pid<<". ";
        CloseHandle(process);
        return;
    }

    pp = incdec_priorityclass(pp, incdec_by);
    prio = pp->symbol;

    if (!SetPriorityClass(process, prio))
    {
        std::cerr<<"Failed to set priority class for process "<<pid<<". ";
        cerr_last_error();
    }

    std::cout<<"Setting process "<<pid<<" to priority class "<<
        get_priorityclass(prio)->name<<".\n";

    CloseHandle(process);
}

void display_help()
{}

#define PROGRAM_VERSION "0.1"

void display_version()
{
    std::cout<<"winrenice version "<<PROGRAM_VERSION<<" by Alexander Korsunsky\n";
}

int main(int argc, char *argv[])
{
    ProgramOptions po;

    if (!read_args(po, argc, argv))
    {
        display_help();
        return EXIT_FAILURE;
    }

    if (po.show_help)
    {
        display_help();
        return EXIT_SUCCESS;
    }
    else if(po.show_version)
    {
        display_version();
        return EXIT_SUCCESS;
    }

    // get all PID'S
    std::vector<DWORD> all_pids = get_all_pids();
    if (all_pids.empty())
        return cerr_last_error();

    // vector for the target PID's
    std::vector<DWORD> target_pids;

    switch(po.what)
    {
        case ProgramOptions::ReniceWhat::pid:
        {
            if (all_pids.end() ==
                std::find(all_pids.begin(), all_pids.end(), po.target_pid)
            )
            {
                std::cerr<<"Process with ID "<<po.target_pid<<" does not exist.\n";
                return EXIT_FAILURE;
            }

            target_pids.push_back(po.target_pid);
            break;
        }
        case ProgramOptions::ReniceWhat::exe_all:
        {
            for(DWORD pid: all_pids)
                if (get_process_module_name(pid) == po.target_str)
                    target_pids.push_back(pid);

            break;
        }
    }

    // set numerical priority depending on command line arguments
    switch(po.how)
    {
        case ProgramOptions::ReniceHow::set:
        {
            for(DWORD pid: target_pids)
                renice_one(pid, po.priority.set);

            break;
        }
        case ProgramOptions::ReniceHow::increase:
        case ProgramOptions::ReniceHow::decrease:
        {
            for(DWORD pid: target_pids)
                incremental_renice_one(pid, po.priority.incdec);

            break;
        }
    }

    return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>#ifndef WRAP_ITER_HPP__
#define WRAP_ITER_HPP__

#include <iterator>

namespace iter {
    template <typename Iterator>
    class wrap_iter {
        private:
            Iterator iter;
            typename std::iterator_traits<Iterator>::difference_type step;

        public:
            //using difference_type = typename std::iterator_traits<Iterator>::difference_type;
            wrap_iter(const Iterator & iter,
                    typename std::iterator_traits<Iterator>::difference_type step) :
                iter(iter),
                step(step)
            { }

            wrap_iter & operator++() {
                std::advance(iter,step);
                return *this;
            }

            bool operator!=(const wrap_iter & rhs) const {
                return this->iter != rhs.iter;
            }

            auto operator*() const -> decltype(*iter)
            {
                return *iter;
            }
    };

    template <typename Iterator>
    wrap_iter<Iterator> make_wrap_iter(const Iterator & iter,
            typename std::iterator_traits<Iterator>::difference_type step) {
        return wrap_iter<Iterator>(iter,step);
    }

}
namespace std {
template <typename Iterator>
    struct iterator_traits<iter::wrap_iter<Iterator>> {
        using difference_type = typename iterator_traits<Iterator>::difference_type;
        using iterator_category = typename iterator_traits<Iterator>::iterator_category;
        //should add the rest later for a more usable class
    };
}
#endif //WRAP_ITER_HPP__
<commit_msg>removes wrap_iter, nothing uses it anymore<commit_after><|endoftext|>


<commit_before><commit_msg>*** empty log message ***<commit_after><|endoftext|>


<commit_before>#include <Graphics.h>

namespace nme
{

// --- GraphicsPath ------------------------------------------

int gCommandDataSize[256];
bool sCommandDataInit = false;

GraphicsPath::GraphicsPath() : winding(wrOddEven)
{
   if (!sCommandDataInit)
   {
      sCommandDataInit = true;
      for(int i=0;i<256;i++)
      {
         switch(i)
         {
            case pcBeginAt:
            case pcMoveTo:
            case pcLineTo:
               gCommandDataSize[i] = 1;
               break;
            case pcCurveTo:
               gCommandDataSize[i] = 2;
               break;
            case pcCubicTo:
               gCommandDataSize[i] = 3;
               break;
            default:
               gCommandDataSize[i] = 0;
         }
      }
   }
}

void GraphicsPath::initPosition(const UserPoint &inPoint)
{
   commands.push_back(pcBeginAt);
   data.push_back(inPoint.x);
   data.push_back(inPoint.y);
}

void GraphicsPath::clear()
{
   commands.resize(0);
   data.resize(0);
}

void GraphicsPath::curveTo(float controlX, float controlY, float anchorX, float anchorY)
{
   commands.push_back(pcCurveTo);
   data.push_back(controlX);
   data.push_back(controlY);
   data.push_back(anchorX);
   data.push_back(anchorY);
}

void GraphicsPath::cubicTo(float cx0, float cy0, float cx1, float cy1, float anchorX, float anchorY)
{
   commands.push_back(pcCubicTo);
   data.push_back(cx0);
   data.push_back(cy0);
   data.push_back(cx1);
   data.push_back(cy1);
   data.push_back(anchorX);
   data.push_back(anchorY);
}

void GraphicsPath::arcTo(float controlX, float controlY, float anchorX, float anchorY)
{
   commands.push_back(pcArcTo);
   data.push_back(controlX);
   data.push_back(controlY);
   data.push_back(anchorX);
   data.push_back(anchorY);
}

void GraphicsPath::elementBlendMode(int inMode)
{
   switch(inMode)
   {
      case bmAdd:
         commands.push_back(pcBlendModeAdd);
         break;
      case bmMultiply:
         commands.push_back(pcBlendModeMultiply);
         break;
      case bmScreen:
         commands.push_back(pcBlendModeScreen);
         break;
   }
}

void GraphicsPath::lineTo(float x, float y)
{
   commands.push_back(pcLineTo);
   data.push_back(x);
   data.push_back(y);
}

void GraphicsPath::moveTo(float x, float y)
{
   commands.push_back(pcMoveTo);
   data.push_back(x);
   data.push_back(y);
}

void GraphicsPath::wideLineTo(float x, float y)
{
   commands.push_back(pcLineTo);
   data.push_back(x);
   data.push_back(y);
}

void GraphicsPath::wideMoveTo(float x, float y)
{
   commands.push_back(pcMoveTo);
   data.push_back(x);
   data.push_back(y);
}

void GraphicsPath::tile(float x, float y, const Rect &inTileRect,float *inTrans,float *inRGBA)
{
   data.push_back(x);
   data.push_back(y);
   data.push_back(inTileRect.x);
   data.push_back(inTileRect.y);
   data.push_back(inTileRect.w);
   data.push_back(inTileRect.h);
   if (inTrans)
   {
      data.push_back(inTrans[0]);
      data.push_back(inTrans[1]);
      data.push_back(inTrans[2]);
      data.push_back(inTrans[3]);
   }
   if (inRGBA)
   {
      data.push_back(inRGBA[0]);
      data.push_back(inRGBA[1]);
      data.push_back(inRGBA[2]);
      data.push_back(inRGBA[3]);
   }
}

void GraphicsPath::reserveTiles(int inN, bool inFullImage, bool inTrans2x2, bool inHasColour, bool isFixed)
{
   commands.reserve( commands.size() + inN );
   int points = inFullImage ? 1 : 3;
   if (inTrans2x2)
      points += 2;
   if (inHasColour)
      points += 2;
   if (isFixed)
      points++;
   data.reserve( data.size() + inN*points*2 );
}

void GraphicsPath::closeLine(int inCommand0, int inData0)
{
   float *point = &data[inData0];
   float *move = 0;
   for(int c=inCommand0; c<commands.size(); c++)
   {
      switch(commands[c])
      {
         case pcWideMoveTo:
            point+=2;
         case pcBeginAt:
         case pcMoveTo:
            move = point;
            break;

         case pcCubicTo:
            point+=1;
            // Fall through...
         case pcWideLineTo:
         case pcCurveTo:
            point+=2;
            // Fall through...
         case pcLineTo:
            if (move && move[0]==point[0] && move[1]==point[1])
            {
               // Closed loop detected - no need to close.
               move = 0;
            }
            break;
      }
      point+=2;
   }
   if (move)
      lineTo(move[0], move[1]);
}

void GraphicsPath::drawPoints(QuickVec<float> inXYs, QuickVec<int> inRGBAs)
{
   int n = inXYs.size()/2;
   int d0 = data.size();

   if (inRGBAs.size()==n)
   {
       commands.push_back(pcPointsXYRGBA);
       data.resize(d0 + n*3);
       memcpy(&data[d0], &inXYs[0], n*2*sizeof(float));
       d0+=n*2;
       memcpy(&data[d0], &inRGBAs[0], n*sizeof(int));
   }
   else
   {
       commands.push_back(pcPointsXY);
       data.resize(d0 + n*2);
       memcpy(&data[d0], &inXYs[0], n*sizeof(float));
   }
}

// -- GraphicsTrianglePath ---------------------------------------------------------

GraphicsTrianglePath::GraphicsTrianglePath( const QuickVec<float> &inXYs,
            const QuickVec<int> &inIndices,
            const QuickVec<float> &inUVT, int inCull,
            const QuickVec<int> &inColours,
            int inBlendMode)
{
   UserPoint *v = (UserPoint *) &inXYs[0];
    uint32 *c = (uint32 *) &inColours[0];
    if(inColours.empty()) c=0;

   int v_count = inXYs.size()/2;
   int uv_parts = inUVT.size()==v_count*2 ? 2 : inUVT.size()==v_count*3 ? 3 : 0;
   const float *uvt = &inUVT[0];

   mBlendMode = inBlendMode;

   if (inIndices.empty())
   {
      int t_count = v_count/3;
      if (inCull==tcNone)
      {
         mVertices.resize(3*t_count);
         memcpy(&mVertices[0],v,3*t_count*sizeof(UserPoint));

         int vCount = t_count * 3;
         if (uv_parts)
         {
            mUVT.resize(uv_parts*vCount);
            memcpy(&mUVT[0],&inUVT[0],uv_parts*sizeof(UserPoint));
         }
         if(c)
         {
            for(int j=0;j<vCount;j++)
            {
               uint32 co0 = *c++;
               mColours.push_back( (co0 & 0xff00ff00) | ((co0 & 0xFF) << 16) | ((co0 >> 16) & 0xFF) );
            }
         }
      }
      else
      {
         for(int i=0;i<t_count;i++)
         {
            UserPoint p0 = *v++;
            UserPoint p1 = *v++;
            UserPoint p2 = *v++;
            if ( inCull==tcNone || (p1-p0).Cross(p2-p0)*inCull > 0)
            {
               mTriangleCount++;
               mVertices.push_back(p0);
               mVertices.push_back(p1);
               mVertices.push_back(p2);
               for(int i=0;i<uv_parts*3;i++)
                  mUVT.push_back( *uvt++ );

               if(c)
               {
                  for(int j=0;j<3;j++)
                  {
                     uint32 co0 = *c++;
                     mColours.push_back( (co0 & 0xff00ff00) | ((co0 & 0xFF) << 16) | ((co0 >> 16) & 0xFF) );
                  }
               }
            }
            else
            {
               uvt += uv_parts;
               if (c)
                  c+= 3;
            }
         }
      }

   }
   else
   {
      const int *idx = &inIndices[0];
      int t_count = inIndices.size()/3;
      for(int i=0;i<t_count;i++)
      {
         int i0 = *idx++;
         int i1 = *idx++;
         int i2 = *idx++;
         if (i0>=0 && i1>=0 && i2>=0 && i0<v_count && i1<v_count && i2<v_count)
         {
            UserPoint p0 = v[i0];
            UserPoint p1 = v[i1];
            UserPoint p2 = v[i2];
            if ( (p1-p0).Cross(p2-p0)*inCull >= 0)
            {
               mVertices.push_back(p0);
               mVertices.push_back(p1);
               mVertices.push_back(p2);
               if(c)
               {
                  uint32 co0 = c[i0];
                  uint32 co1 = c[i1];
                  uint32 co2 = c[i2];
                  co0 = ((co0 >> 24) & 0xFF) << 24 | (co0 & 0xFF) << 16 | ((co0 >> 8) & 0xFF) << 8 | ((co0 >> 16) & 0xFF);
                  co1 = ((co1 >> 24) & 0xFF) << 24 | (co1 & 0xFF) << 16 | ((co1 >> 8) & 0xFF) << 8 | ((co1 >> 16) & 0xFF);
                  co2 = ((co2 >> 24) & 0xFF) << 24 | (co2 & 0xFF) << 16 | ((co2 >> 8) & 0xFF) << 8 | ((co2 >> 16) & 0xFF);
                  mColours.push_back(co0);
                  mColours.push_back(co1);
                  mColours.push_back(co2);
               }
               if (uv_parts)
               {
                  const float *f = uvt + uv_parts*i0;
                  for(int i=0;i<uv_parts;i++) mUVT.push_back( *f++ );
                  f = uvt + uv_parts*i1;
                  for(int i=0;i<uv_parts;i++) mUVT.push_back( *f++ );
                  f = uvt + uv_parts*i2;
                  for(int i=0;i<uv_parts;i++) mUVT.push_back( *f++ );
               }
            }
         }
      }
   }

   mTriangleCount = mVertices.size()/3;
   mType = uv_parts==2 ? vtVertexUV : uv_parts==3? vtVertexUVT : vtVertex;
}

} // end namespace nme

<commit_msg>Skip correct number of points when looking for end of cubic<commit_after>#include <Graphics.h>

namespace nme
{

// --- GraphicsPath ------------------------------------------

int gCommandDataSize[256];
bool sCommandDataInit = false;

GraphicsPath::GraphicsPath() : winding(wrOddEven)
{
   if (!sCommandDataInit)
   {
      sCommandDataInit = true;
      for(int i=0;i<256;i++)
      {
         switch(i)
         {
            case pcBeginAt:
            case pcMoveTo:
            case pcLineTo:
               gCommandDataSize[i] = 1;
               break;
            case pcCurveTo:
               gCommandDataSize[i] = 2;
               break;
            case pcCubicTo:
               gCommandDataSize[i] = 3;
               break;
            default:
               gCommandDataSize[i] = 0;
         }
      }
   }
}

void GraphicsPath::initPosition(const UserPoint &inPoint)
{
   commands.push_back(pcBeginAt);
   data.push_back(inPoint.x);
   data.push_back(inPoint.y);
}

void GraphicsPath::clear()
{
   commands.resize(0);
   data.resize(0);
}

void GraphicsPath::curveTo(float controlX, float controlY, float anchorX, float anchorY)
{
   commands.push_back(pcCurveTo);
   data.push_back(controlX);
   data.push_back(controlY);
   data.push_back(anchorX);
   data.push_back(anchorY);
}

void GraphicsPath::cubicTo(float cx0, float cy0, float cx1, float cy1, float anchorX, float anchorY)
{
   commands.push_back(pcCubicTo);
   data.push_back(cx0);
   data.push_back(cy0);
   data.push_back(cx1);
   data.push_back(cy1);
   data.push_back(anchorX);
   data.push_back(anchorY);
}

void GraphicsPath::arcTo(float controlX, float controlY, float anchorX, float anchorY)
{
   commands.push_back(pcArcTo);
   data.push_back(controlX);
   data.push_back(controlY);
   data.push_back(anchorX);
   data.push_back(anchorY);
}

void GraphicsPath::elementBlendMode(int inMode)
{
   switch(inMode)
   {
      case bmAdd:
         commands.push_back(pcBlendModeAdd);
         break;
      case bmMultiply:
         commands.push_back(pcBlendModeMultiply);
         break;
      case bmScreen:
         commands.push_back(pcBlendModeScreen);
         break;
   }
}

void GraphicsPath::lineTo(float x, float y)
{
   commands.push_back(pcLineTo);
   data.push_back(x);
   data.push_back(y);
}

void GraphicsPath::moveTo(float x, float y)
{
   commands.push_back(pcMoveTo);
   data.push_back(x);
   data.push_back(y);
}

void GraphicsPath::wideLineTo(float x, float y)
{
   commands.push_back(pcLineTo);
   data.push_back(x);
   data.push_back(y);
}

void GraphicsPath::wideMoveTo(float x, float y)
{
   commands.push_back(pcMoveTo);
   data.push_back(x);
   data.push_back(y);
}

void GraphicsPath::tile(float x, float y, const Rect &inTileRect,float *inTrans,float *inRGBA)
{
   data.push_back(x);
   data.push_back(y);
   data.push_back(inTileRect.x);
   data.push_back(inTileRect.y);
   data.push_back(inTileRect.w);
   data.push_back(inTileRect.h);
   if (inTrans)
   {
      data.push_back(inTrans[0]);
      data.push_back(inTrans[1]);
      data.push_back(inTrans[2]);
      data.push_back(inTrans[3]);
   }
   if (inRGBA)
   {
      data.push_back(inRGBA[0]);
      data.push_back(inRGBA[1]);
      data.push_back(inRGBA[2]);
      data.push_back(inRGBA[3]);
   }
}

void GraphicsPath::reserveTiles(int inN, bool inFullImage, bool inTrans2x2, bool inHasColour, bool isFixed)
{
   commands.reserve( commands.size() + inN );
   int points = inFullImage ? 1 : 3;
   if (inTrans2x2)
      points += 2;
   if (inHasColour)
      points += 2;
   if (isFixed)
      points++;
   data.reserve( data.size() + inN*points*2 );
}

void GraphicsPath::closeLine(int inCommand0, int inData0)
{
   float *point = &data[inData0];
   float *move = 0;
   for(int c=inCommand0; c<commands.size(); c++)
   {
      switch(commands[c])
      {
         case pcWideMoveTo:
            point+=2;
         case pcBeginAt:
         case pcMoveTo:
            move = point;
            break;

         case pcCubicTo:
            point+=2;
            // Fall through...
         case pcWideLineTo:
         case pcCurveTo:
            point+=2;
            // Fall through...
         case pcLineTo:
            if (move && move[0]==point[0] && move[1]==point[1])
            {
               // Closed loop detected - no need to close.
               move = 0;
            }
            break;
      }
      point+=2;
   }
   if (move)
      lineTo(move[0], move[1]);
}

void GraphicsPath::drawPoints(QuickVec<float> inXYs, QuickVec<int> inRGBAs)
{
   int n = inXYs.size()/2;
   int d0 = data.size();

   if (inRGBAs.size()==n)
   {
       commands.push_back(pcPointsXYRGBA);
       data.resize(d0 + n*3);
       memcpy(&data[d0], &inXYs[0], n*2*sizeof(float));
       d0+=n*2;
       memcpy(&data[d0], &inRGBAs[0], n*sizeof(int));
   }
   else
   {
       commands.push_back(pcPointsXY);
       data.resize(d0 + n*2);
       memcpy(&data[d0], &inXYs[0], n*sizeof(float));
   }
}

// -- GraphicsTrianglePath ---------------------------------------------------------

GraphicsTrianglePath::GraphicsTrianglePath( const QuickVec<float> &inXYs,
            const QuickVec<int> &inIndices,
            const QuickVec<float> &inUVT, int inCull,
            const QuickVec<int> &inColours,
            int inBlendMode)
{
   UserPoint *v = (UserPoint *) &inXYs[0];
    uint32 *c = (uint32 *) &inColours[0];
    if(inColours.empty()) c=0;

   int v_count = inXYs.size()/2;
   int uv_parts = inUVT.size()==v_count*2 ? 2 : inUVT.size()==v_count*3 ? 3 : 0;
   const float *uvt = &inUVT[0];

   mBlendMode = inBlendMode;

   if (inIndices.empty())
   {
      int t_count = v_count/3;
      if (inCull==tcNone)
      {
         mVertices.resize(3*t_count);
         memcpy(&mVertices[0],v,3*t_count*sizeof(UserPoint));

         int vCount = t_count * 3;
         if (uv_parts)
         {
            mUVT.resize(uv_parts*vCount);
            memcpy(&mUVT[0],&inUVT[0],uv_parts*sizeof(UserPoint));
         }
         if(c)
         {
            for(int j=0;j<vCount;j++)
            {
               uint32 co0 = *c++;
               mColours.push_back( (co0 & 0xff00ff00) | ((co0 & 0xFF) << 16) | ((co0 >> 16) & 0xFF) );
            }
         }
      }
      else
      {
         for(int i=0;i<t_count;i++)
         {
            UserPoint p0 = *v++;
            UserPoint p1 = *v++;
            UserPoint p2 = *v++;
            if ( inCull==tcNone || (p1-p0).Cross(p2-p0)*inCull > 0)
            {
               mTriangleCount++;
               mVertices.push_back(p0);
               mVertices.push_back(p1);
               mVertices.push_back(p2);
               for(int i=0;i<uv_parts*3;i++)
                  mUVT.push_back( *uvt++ );

               if(c)
               {
                  for(int j=0;j<3;j++)
                  {
                     uint32 co0 = *c++;
                     mColours.push_back( (co0 & 0xff00ff00) | ((co0 & 0xFF) << 16) | ((co0 >> 16) & 0xFF) );
                  }
               }
            }
            else
            {
               uvt += uv_parts;
               if (c)
                  c+= 3;
            }
         }
      }

   }
   else
   {
      const int *idx = &inIndices[0];
      int t_count = inIndices.size()/3;
      for(int i=0;i<t_count;i++)
      {
         int i0 = *idx++;
         int i1 = *idx++;
         int i2 = *idx++;
         if (i0>=0 && i1>=0 && i2>=0 && i0<v_count && i1<v_count && i2<v_count)
         {
            UserPoint p0 = v[i0];
            UserPoint p1 = v[i1];
            UserPoint p2 = v[i2];
            if ( (p1-p0).Cross(p2-p0)*inCull >= 0)
            {
               mVertices.push_back(p0);
               mVertices.push_back(p1);
               mVertices.push_back(p2);
               if(c)
               {
                  uint32 co0 = c[i0];
                  uint32 co1 = c[i1];
                  uint32 co2 = c[i2];
                  co0 = ((co0 >> 24) & 0xFF) << 24 | (co0 & 0xFF) << 16 | ((co0 >> 8) & 0xFF) << 8 | ((co0 >> 16) & 0xFF);
                  co1 = ((co1 >> 24) & 0xFF) << 24 | (co1 & 0xFF) << 16 | ((co1 >> 8) & 0xFF) << 8 | ((co1 >> 16) & 0xFF);
                  co2 = ((co2 >> 24) & 0xFF) << 24 | (co2 & 0xFF) << 16 | ((co2 >> 8) & 0xFF) << 8 | ((co2 >> 16) & 0xFF);
                  mColours.push_back(co0);
                  mColours.push_back(co1);
                  mColours.push_back(co2);
               }
               if (uv_parts)
               {
                  const float *f = uvt + uv_parts*i0;
                  for(int i=0;i<uv_parts;i++) mUVT.push_back( *f++ );
                  f = uvt + uv_parts*i1;
                  for(int i=0;i<uv_parts;i++) mUVT.push_back( *f++ );
                  f = uvt + uv_parts*i2;
                  for(int i=0;i<uv_parts;i++) mUVT.push_back( *f++ );
               }
            }
         }
      }
   }

   mTriangleCount = mVertices.size()/3;
   mType = uv_parts==2 ? vtVertexUV : uv_parts==3? vtVertexUVT : vtVertex;
}

} // end namespace nme

<|endoftext|>