<commit_before>/*!
  \copyright (c) RDO-Team, 2012
  \file      function.h
  \author      (rdo@rk9.bmstu.ru)
  \date      14.12.2012
  \brief     -
  \indent    4T
*/

// ---------------------------------------------------------------------------- PCH
#include "simulator/compiler/parser/pch.h"
// ----------------------------------------------------------------------- INCLUDES
#include <boost/bind.hpp>
#include <boost/foreach.hpp>
#include <boost/range/algorithm/find_if.hpp>
// ----------------------------------------------------------------------- SYNOPSIS
#include "simulator/compiler/parser/src/function/function.h"
#include "simulator/compiler/parser/rdoparser.h"
// --------------------------------------------------------------------------------

OPEN_RDO_PARSER_NAMESPACE

Function::Function(CREF(LPTypeInfo) pReturnType, CREF(RDOParserSrcInfo) srcInfo)
	: RDOParserSrcInfo(srcInfo)
	, m_pReturnType(pReturnType)
{
	ASSERT(m_pReturnType);
}

Function::~Function()
{}

void Function::setCall(CREF(rdo::runtime::LPRDOCalc) pCalc)
{
	ASSERT(!m_pCallpCalc);
	ASSERT(pCalc);
	m_pCallpCalc = pCalc;
}

LPExpression Function::expression() const
{
	ASSERT(m_pCallpCalc);
	LPExpression pExpression = rdo::Factory<Expression>::create(
		rdo::Factory<TypeInfo>::create(m_pFunctionType, m_pFunctionType->src_info()),
		m_pCallpCalc,
		src_info()
	);
	ASSERT(pExpression);
	return pExpression;
}

void Function::pushContext()
{
	RDOParser::s_parser()->contextStack()->push(this);
}

void Function::popContext()
{
	RDOParser::s_parser()->contextStack()->pop_safe<Function>();
}

void Function::pushParamDefinitionContext()
{
	LPContextParamDefinition pContextParamDefinition = rdo::Factory<ContextParamDefinition>::create(
		boost::bind(&Function::onPushParam, this, _1)
	);
	ASSERT(pContextParamDefinition);
	RDOParser::s_parser()->contextStack()->push(pContextParamDefinition);
}

void Function::popParamDefinitionContext()
{
	RDOParser::s_parser()->contextStack()->pop_safe<ContextParamDefinition>();

	m_pFunctionType = generateType();
	ASSERT(m_pFunctionType);
}

void Function::onPushParam(CREF(LPRDOParam) pParam)
{
	ASSERT(pParam);
	LPRDOParam pParamPrev = findParam(pParam->name());
	if (pParamPrev)
	{
		RDOParser::s_parser()->error().push_only(pParam->src_info(), rdo::format(_T("  : %s"), pParam->name().c_str()));
		RDOParser::s_parser()->error().push_only(pParamPrev->src_info(), _T(".  "));
		RDOParser::s_parser()->error().push_done();
	}
	m_paramList.push_back(pParam);
}

LPRDOParam Function::findParam(CREF(tstring) paramName) const
{
	ParamList::const_iterator it = find(paramName);

	return it != m_paramList.end()
		? *it
		: LPRDOParam(NULL);
}

Function::ParamID Function::findParamID(CREF(tstring) paramName) const
{
	ParamList::const_iterator it = find(paramName);

	return it != m_paramList.end()
		? it - m_paramList.begin()
		: ParamID();
}

Function::ParamList::const_iterator Function::find(CREF(tstring) paramName) const
{
	return boost::range::find_if(m_paramList, compareName<RDOParam>(paramName));
}

LPFunctionType Function::generateType() const
{
	ASSERT(m_pReturnType);

	FunctionParamType::ParamList paramTypeList;
	BOOST_FOREACH(const LPRDOParam& pParam, m_paramList)
	{
		paramTypeList.push_back(pParam->getTypeInfo());
	}
	LPFunctionParamType pParamType = rdo::Factory<FunctionParamType>::create(paramTypeList, src_info());
	ASSERT(pParamType);

	return rdo::Factory<FunctionType>::create(m_pReturnType, pParamType, src_info());
}

void Function::pushFunctionBodyContext()
{
	ASSERT(!m_pContextMemory);
	m_pContextMemory = rdo::Factory<ContextMemory>::create();
	ASSERT(m_pContextMemory);
	RDOParser::s_parser()->contextStack()->push(m_pContextMemory);

	ContextMemory::push();
}

void Function::popFunctionBodyContext()
{
	ContextMemory::pop();
	RDOParser::s_parser()->contextStack()->pop_safe<ContextMemory>();
}

Context::FindResult Function::onFindContext(CREF(LPRDOValue) pValue) const
{
	ASSERT(pValue);

	LPRDOParam pParam = findParam(pValue->value().getIdentificator());
	if (pParam)
	{
		rdo::runtime::RDOType::TypeID typeID = pParam->getTypeInfo()->type()->typeID();
		if (typeID == rdo::runtime::RDOType::t_identificator || typeID == rdo::runtime::RDOType::t_unknow)
		{
			RDOParser::s_parser()->error().push_only(
				pValue->src_info(),
				rdo::format(_T("  '%s'  "), pValue->src_info().src_text().c_str())
			);
			RDOParser::s_parser()->error().push_only(pParam->getTypeInfo()->src_info(), _T(".  "));
			RDOParser::s_parser()->error().push_done();
		}
		ParamID paramID = findParamID(pValue->value().getIdentificator());
		ASSERT(paramID.is_initialized());
		LPExpression pExpression = rdo::Factory<Expression>::create(
			pParam->getTypeInfo(),
			rdo::Factory<rdo::runtime::RDOCalcFuncParam>::create(*paramID, pParam->src_info()),
			pValue->src_info()
		);
		ASSERT(pExpression);
		return Context::FindResult(const_cast<PTR(Function)>(this), pExpression, pValue, pParam);
	}

	return Context::FindResult();
}

CLOSE_RDO_PARSER_NAMESPACE
<commit_msg> - добавлена инициализация пустого списка параметров через void<commit_after>/*!
  \copyright (c) RDO-Team, 2012
  \file      function.h
  \author      (rdo@rk9.bmstu.ru)
  \date      14.12.2012
  \brief     -
  \indent    4T
*/

// ---------------------------------------------------------------------------- PCH
#include "simulator/compiler/parser/pch.h"
// ----------------------------------------------------------------------- INCLUDES
#include <boost/bind.hpp>
#include <boost/foreach.hpp>
#include <boost/range/algorithm/find_if.hpp>
// ----------------------------------------------------------------------- SYNOPSIS
#include "simulator/compiler/parser/src/function/function.h"
#include "simulator/compiler/parser/rdoparser.h"
// --------------------------------------------------------------------------------

OPEN_RDO_PARSER_NAMESPACE

Function::Function(CREF(LPTypeInfo) pReturnType, CREF(RDOParserSrcInfo) srcInfo)
	: RDOParserSrcInfo(srcInfo)
	, m_pReturnType(pReturnType)
{
	ASSERT(m_pReturnType);
}

Function::~Function()
{}

void Function::setCall(CREF(rdo::runtime::LPRDOCalc) pCalc)
{
	ASSERT(!m_pCallpCalc);
	ASSERT(pCalc);
	m_pCallpCalc = pCalc;
}

LPExpression Function::expression() const
{
	ASSERT(m_pCallpCalc);
	LPExpression pExpression = rdo::Factory<Expression>::create(
		rdo::Factory<TypeInfo>::create(m_pFunctionType, m_pFunctionType->src_info()),
		m_pCallpCalc,
		src_info()
	);
	ASSERT(pExpression);
	return pExpression;
}

void Function::pushContext()
{
	RDOParser::s_parser()->contextStack()->push(this);
}

void Function::popContext()
{
	RDOParser::s_parser()->contextStack()->pop_safe<Function>();
}

void Function::pushParamDefinitionContext()
{
	LPContextParamDefinition pContextParamDefinition = rdo::Factory<ContextParamDefinition>::create(
		boost::bind(&Function::onPushParam, this, _1)
	);
	ASSERT(pContextParamDefinition);
	RDOParser::s_parser()->contextStack()->push(pContextParamDefinition);
}

void Function::popParamDefinitionContext()
{
	RDOParser::s_parser()->contextStack()->pop_safe<ContextParamDefinition>();

	m_pFunctionType = generateType();
	ASSERT(m_pFunctionType);
}

void Function::onPushParam(CREF(LPRDOParam) pParam)
{
	ASSERT(pParam);
	LPRDOParam pParamPrev = findParam(pParam->name());
	if (pParamPrev)
	{
		RDOParser::s_parser()->error().push_only(pParam->src_info(), rdo::format(_T("  : %s"), pParam->name().c_str()));
		RDOParser::s_parser()->error().push_only(pParamPrev->src_info(), _T(".  "));
		RDOParser::s_parser()->error().push_done();
	}
	m_paramList.push_back(pParam);
}

LPRDOParam Function::findParam(CREF(tstring) paramName) const
{
	ParamList::const_iterator it = find(paramName);

	return it != m_paramList.end()
		? *it
		: LPRDOParam(NULL);
}

Function::ParamID Function::findParamID(CREF(tstring) paramName) const
{
	ParamList::const_iterator it = find(paramName);

	return it != m_paramList.end()
		? it - m_paramList.begin()
		: ParamID();
}

Function::ParamList::const_iterator Function::find(CREF(tstring) paramName) const
{
	return boost::range::find_if(m_paramList, compareName<RDOParam>(paramName));
}

LPFunctionType Function::generateType() const
{
	ASSERT(m_pReturnType);

	FunctionParamType::ParamList paramTypeList;
	BOOST_FOREACH(const LPRDOParam& pParam, m_paramList)
	{
		paramTypeList.push_back(pParam->getTypeInfo());
	}

	if (paramTypeList.empty())
	{
		paramTypeList.push_back(
			rdo::Factory<TypeInfo>::delegate<RDOType__void>(src_info())
		);
	}

	LPFunctionParamType pParamType = rdo::Factory<FunctionParamType>::create(paramTypeList, src_info());
	ASSERT(pParamType);

	return rdo::Factory<FunctionType>::create(m_pReturnType, pParamType, src_info());
}

void Function::pushFunctionBodyContext()
{
	ASSERT(!m_pContextMemory);
	m_pContextMemory = rdo::Factory<ContextMemory>::create();
	ASSERT(m_pContextMemory);
	RDOParser::s_parser()->contextStack()->push(m_pContextMemory);

	ContextMemory::push();
}

void Function::popFunctionBodyContext()
{
	ContextMemory::pop();
	RDOParser::s_parser()->contextStack()->pop_safe<ContextMemory>();
}

Context::FindResult Function::onFindContext(CREF(LPRDOValue) pValue) const
{
	ASSERT(pValue);

	LPRDOParam pParam = findParam(pValue->value().getIdentificator());
	if (pParam)
	{
		rdo::runtime::RDOType::TypeID typeID = pParam->getTypeInfo()->type()->typeID();
		if (typeID == rdo::runtime::RDOType::t_identificator || typeID == rdo::runtime::RDOType::t_unknow)
		{
			RDOParser::s_parser()->error().push_only(
				pValue->src_info(),
				rdo::format(_T("  '%s'  "), pValue->src_info().src_text().c_str())
			);
			RDOParser::s_parser()->error().push_only(pParam->getTypeInfo()->src_info(), _T(".  "));
			RDOParser::s_parser()->error().push_done();
		}
		ParamID paramID = findParamID(pValue->value().getIdentificator());
		ASSERT(paramID.is_initialized());
		LPExpression pExpression = rdo::Factory<Expression>::create(
			pParam->getTypeInfo(),
			rdo::Factory<rdo::runtime::RDOCalcFuncParam>::create(*paramID, pParam->src_info()),
			pValue->src_info()
		);
		ASSERT(pExpression);
		return Context::FindResult(const_cast<PTR(Function)>(this), pExpression, pValue, pParam);
	}

	return Context::FindResult();
}

CLOSE_RDO_PARSER_NAMESPACE
<|endoftext|>


<commit_before>#include "midiconnectionsmodel.h"

#include "iomidi.h"

#include <QtDebug>

bool operator==(const snd_seq_addr_t& lhs, const snd_seq_addr_t& rhs) {
    return lhs.client == rhs.client && lhs.port == rhs.port;
}

MidiConnectionsModel::MidiConnectionsModel(IOMidi* io) :
    QAbstractListModel(io),
    m_io(io)
{
    Q_CHECK_PTR(m_io);

    connect(
        m_io,
        &IOMidi::eventReceived,
        this,
        &MidiConnectionsModel::handleMidiEvent);

    connect(
        this,
        &MidiConnectionsModel::dataChanged,
        [=]() {
            emit connectedPortChanged(connectedPort());
            emit connectedChanged(connected());
            emit externallyManagedChanged(externallyManaged());
        }
    );

    m_addrs.append({0, 0}); // Row for disconnect choice

    // Loop from already connected clients and ports to populate the addresses list

    snd_seq_client_info_t *cinfo;
    snd_seq_client_info_alloca(&cinfo);

    snd_seq_port_info_t *pinfo;
    snd_seq_port_info_alloca(&pinfo);

    snd_seq_client_info_set_client(cinfo, -1);
    while (snd_seq_query_next_client(m_io->handle(), cinfo) >= 0) {
        if (!acceptClient(cinfo)) {
            continue;
        }

        snd_seq_port_info_set_client(pinfo, snd_seq_client_info_get_client(cinfo));
        snd_seq_port_info_set_port(pinfo, -1);
        while (snd_seq_query_next_port(m_io->handle(), pinfo) >= 0) {
            if (!acceptPort(pinfo)) {
                continue;
            }

            const snd_seq_addr_t* addr = snd_seq_port_info_get_addr(pinfo);
            Q_CHECK_PTR(addr);

            addAddress(addr);
        }
    }
}

int MidiConnectionsModel::rowCount(const QModelIndex &parent) const {
    return parent.isValid() ? 0 : m_addrs.count();
}

QVariant MidiConnectionsModel::data(const QModelIndex &index, int role) const {
    if (index.row() == 0) {
        if (role == Qt::DisplayRole) {
            return "Disconnect";
        }
    }

    if (role == Qt::DisplayRole) {
        return portName(index);
    }
    return QVariant();
}

QModelIndex MidiConnectionsModel::connectedPort() const {
    Q_ASSERT(m_addrs.count() > 0);

    QModelIndex ret = index(0);
    for (int r = 1 ; r < m_addrs.count() ; ++r) {
        switch (portConnection(m_addrs[r])) {
        case Direction::Disconnected:
            break;

        // Partially connected, done externally
        case Direction::From:
        case Direction::To:
            return QModelIndex();

        // If a second addr is connected both ways, done externally
        case Direction::BothWays:
            if (ret.row() != 0) {
                return QModelIndex();
            }
            ret = index(r);
            break;
        }
    }
    return ret;
}

bool MidiConnectionsModel::connected() const {
    for (int r = 0 ; r < m_addrs.count() ; ++r) {
        if (portConnection(m_addrs[r]) > Direction::Disconnected) {
            return true;
        }
    }
    return false;
}

bool MidiConnectionsModel::externallyManaged() const {
    return connected() && !connectedPort().isValid();
}

void MidiConnectionsModel::connectPort(const QModelIndex &idx) {
    Q_ASSERT(idx.isValid());

    disconnectAllPorts();

    if (idx.row() > 0) {
        connectPort(m_addrs[idx.row()]);
    }

    emit dataChanged(index(0), index(m_addrs.count()));
}

void MidiConnectionsModel::disconnectAllPorts() const {
    Q_CHECK_PTR(m_io);

    snd_seq_query_subscribe_t *subs;
    snd_seq_query_subscribe_alloca(&subs);
    const snd_seq_addr_t ownaddr = {m_io->clientId(), m_io->portId()};
    snd_seq_query_subscribe_set_root(subs, &ownaddr);

    snd_seq_addr_t addr;

    snd_seq_query_subscribe_set_index(subs, 0);
    snd_seq_query_subscribe_set_type(subs, SND_SEQ_QUERY_SUBS_READ);
    while (snd_seq_query_port_subscribers(m_io->handle(), subs) >= 0) {
        addr = *snd_seq_query_subscribe_get_addr(subs);
        if (snd_seq_disconnect_to(m_io->handle(), m_io->portId(), addr.client, addr.port)) {
            qWarning() << "Cannot disconnect to" << addr.client << addr.port;
        }
    }
    snd_seq_query_subscribe_set_index(subs, 0);
    snd_seq_query_subscribe_set_type(subs, SND_SEQ_QUERY_SUBS_WRITE);
    while (snd_seq_query_port_subscribers(m_io->handle(), subs) >= 0) {
        addr = *snd_seq_query_subscribe_get_addr(subs);
        if (snd_seq_disconnect_from(m_io->handle(), m_io->portId(), addr.client, addr.port)) {
            qWarning() << "Cannot disconnect from" << addr.client << addr.port;
        }
    }
}

void MidiConnectionsModel::connectPort(const snd_seq_addr_t &addr) {
    Q_CHECK_PTR(m_io);

    if (snd_seq_connect_from(m_io->handle(), m_io->portId(), addr.client, addr.port) < 0) {
        qWarning() << "Cannot connect from";
    }

    if (snd_seq_connect_to(m_io->handle(), m_io->portId(), addr.client, addr.port) < 0) {
        qWarning() << "Cannot connect to";
    }
}

void MidiConnectionsModel::handleMidiEvent(const snd_seq_event_t* ev) {
    Q_CHECK_PTR(m_io);
    Q_CHECK_PTR(ev);

    const snd_seq_addr_t ownaddr = {m_io->clientId(), m_io->portId()};

    switch (ev->type) {
    case SND_SEQ_EVENT_PORT_START:
        return addAddressIfAccepted(&ev->data.addr);
    case SND_SEQ_EVENT_PORT_EXIT:
        return removeAddressIfAccepted(&ev->data.addr);
    case SND_SEQ_EVENT_PORT_CHANGE:
        return notifyDataChangedForAddress(&ev->data.addr);
    case SND_SEQ_EVENT_PORT_SUBSCRIBED:
    case SND_SEQ_EVENT_PORT_UNSUBSCRIBED:
        if (ownaddr == ev->data.connect.sender || ownaddr == ev->data.connect.dest) {
            if (ownaddr == ev->data.connect.sender) {
                return notifyDataChangedForAddress(&ev->data.connect.dest);
            }
            if (ownaddr == ev->data.connect.dest) {
                return notifyDataChangedForAddress(&ev->data.connect.sender);
            }
        }
        return;
    case SND_SEQ_EVENT_CLIENT_START:
    case SND_SEQ_EVENT_CLIENT_EXIT:
        emit connectedPortChanged(connectedPort());
        return;
    default:
        return;
    }
}

void MidiConnectionsModel::addAddressIfAccepted(const snd_seq_addr_t *addr) {
    Q_CHECK_PTR(addr);

    if (acceptAddress(addr)) {
        addAddress(addr);
    }
}

void MidiConnectionsModel::removeAddressIfAccepted(const snd_seq_addr_t *addr) {
    Q_CHECK_PTR(addr);

    const int r = m_addrs.indexOf(*addr);
    if (r >= 0) {
        beginRemoveRows(QModelIndex(), r, r);
        m_addrs.removeAt(r);
        endRemoveRows();
    }
}

void MidiConnectionsModel::notifyDataChangedForAddress(const snd_seq_addr_t *addr) {
    Q_CHECK_PTR(addr);

    const int r = m_addrs.indexOf(*addr);
    if (r >= 0) {
        const QModelIndex idx = index(r);
        emit dataChanged(idx, idx);
    }
}

void MidiConnectionsModel::addAddress(const snd_seq_addr_t *addr) {
    Q_CHECK_PTR(addr);
    Q_ASSERT(!m_addrs.contains(*addr));

    beginInsertRows(QModelIndex(), m_addrs.count(), m_addrs.count());
    m_addrs.append(*addr);
    endInsertRows();
}

bool MidiConnectionsModel::acceptAddress(const snd_seq_addr_t *addr) const {
    Q_CHECK_PTR(addr);

    snd_seq_client_info_t *cinfo;
    snd_seq_client_info_alloca(&cinfo);
    if (snd_seq_get_any_client_info(m_io->handle(), addr->client, cinfo) < 0 ||
        !acceptClient(cinfo)) {
        return false;
    }

    snd_seq_port_info_t *pinfo;
    snd_seq_port_info_alloca(&pinfo);
    return snd_seq_get_any_port_info(m_io->handle(), addr->client, addr->port, pinfo) == 0 &&
           acceptPort(pinfo);
}

bool MidiConnectionsModel::acceptClient(const snd_seq_client_info_t *info) const {
    Q_CHECK_PTR(m_io);
    Q_CHECK_PTR(info);

    const int id = snd_seq_client_info_get_client(info);
    return id != m_io->clientId() && id != SND_SEQ_CLIENT_SYSTEM;
}

bool MidiConnectionsModel::acceptPort(const snd_seq_port_info_t *info) const {
    Q_CHECK_PTR(info);

    const unsigned int caps = snd_seq_port_info_get_capability(info);
    return !(caps & SND_SEQ_PORT_CAP_NO_EXPORT) &&
           caps & SND_SEQ_PORT_CAP_READ &&
           caps & SND_SEQ_PORT_CAP_WRITE;
}

QString MidiConnectionsModel::portName(const QModelIndex& index) const {
    Q_ASSERT(index.isValid());

    const snd_seq_addr_t &addr = m_addrs[index.row()];
    snd_seq_port_info_t *info;
    snd_seq_port_info_alloca(&info);
    const int res = snd_seq_get_any_port_info(m_io->handle(), addr.client, addr.port, info);
    Q_UNUSED(res);
    Q_ASSERT(res >= 0);
    return snd_seq_port_info_get_name(info);
}

MidiConnectionsModel::Directions MidiConnectionsModel::portConnection(const QModelIndex& index) const {
    Q_CHECK_PTR(m_io);
    Q_ASSERT(index.isValid());

    return portConnection(m_addrs[index.row()]);
}

MidiConnectionsModel::Directions MidiConnectionsModel::portConnection(const snd_seq_addr_t& addr) const {
    Q_CHECK_PTR(m_io);

    MidiConnectionsModel::Directions ret = Direction::Disconnected;

    const snd_seq_addr_t ownaddr = {m_io->clientId(), m_io->portId()};

    snd_seq_port_subscribe_t *subs;
    snd_seq_port_subscribe_alloca(&subs);

    snd_seq_port_subscribe_set_sender(subs, &ownaddr);
    snd_seq_port_subscribe_set_dest(subs, &addr);
    if (snd_seq_get_port_subscription(m_io->handle(), subs) == 0) {
        ret |= Direction::To;
    }

    snd_seq_port_subscribe_set_sender(subs, &addr);
    snd_seq_port_subscribe_set_dest(subs, &ownaddr);
    if (snd_seq_get_port_subscription(m_io->handle(), subs) == 0) {
        ret |= Direction::From;
    }

    return ret;
}
<commit_msg>Fix bad return value check<commit_after>#include "midiconnectionsmodel.h"

#include "iomidi.h"

#include <QtDebug>

bool operator==(const snd_seq_addr_t& lhs, const snd_seq_addr_t& rhs) {
    return lhs.client == rhs.client && lhs.port == rhs.port;
}

MidiConnectionsModel::MidiConnectionsModel(IOMidi* io) :
    QAbstractListModel(io),
    m_io(io)
{
    Q_CHECK_PTR(m_io);

    connect(
        m_io,
        &IOMidi::eventReceived,
        this,
        &MidiConnectionsModel::handleMidiEvent);

    connect(
        this,
        &MidiConnectionsModel::dataChanged,
        [=]() {
            emit connectedPortChanged(connectedPort());
            emit connectedChanged(connected());
            emit externallyManagedChanged(externallyManaged());
        }
    );

    m_addrs.append({0, 0}); // Row for disconnect choice

    // Loop from already connected clients and ports to populate the addresses list

    snd_seq_client_info_t *cinfo;
    snd_seq_client_info_alloca(&cinfo);

    snd_seq_port_info_t *pinfo;
    snd_seq_port_info_alloca(&pinfo);

    snd_seq_client_info_set_client(cinfo, -1);
    while (snd_seq_query_next_client(m_io->handle(), cinfo) >= 0) {
        if (!acceptClient(cinfo)) {
            continue;
        }

        snd_seq_port_info_set_client(pinfo, snd_seq_client_info_get_client(cinfo));
        snd_seq_port_info_set_port(pinfo, -1);
        while (snd_seq_query_next_port(m_io->handle(), pinfo) >= 0) {
            if (!acceptPort(pinfo)) {
                continue;
            }

            const snd_seq_addr_t* addr = snd_seq_port_info_get_addr(pinfo);
            Q_CHECK_PTR(addr);

            addAddress(addr);
        }
    }
}

int MidiConnectionsModel::rowCount(const QModelIndex &parent) const {
    return parent.isValid() ? 0 : m_addrs.count();
}

QVariant MidiConnectionsModel::data(const QModelIndex &index, int role) const {
    if (index.row() == 0) {
        if (role == Qt::DisplayRole) {
            return "Disconnect";
        }
    }

    if (role == Qt::DisplayRole) {
        return portName(index);
    }
    return QVariant();
}

QModelIndex MidiConnectionsModel::connectedPort() const {
    Q_ASSERT(m_addrs.count() > 0);

    QModelIndex ret = index(0);
    for (int r = 1 ; r < m_addrs.count() ; ++r) {
        switch (portConnection(m_addrs[r])) {
        case Direction::Disconnected:
            break;

        // Partially connected, done externally
        case Direction::From:
        case Direction::To:
            return QModelIndex();

        // If a second addr is connected both ways, done externally
        case Direction::BothWays:
            if (ret.row() != 0) {
                return QModelIndex();
            }
            ret = index(r);
            break;
        }
    }
    return ret;
}

bool MidiConnectionsModel::connected() const {
    for (int r = 0 ; r < m_addrs.count() ; ++r) {
        if (portConnection(m_addrs[r]) > Direction::Disconnected) {
            return true;
        }
    }
    return false;
}

bool MidiConnectionsModel::externallyManaged() const {
    return connected() && !connectedPort().isValid();
}

void MidiConnectionsModel::connectPort(const QModelIndex &idx) {
    Q_ASSERT(idx.isValid());

    disconnectAllPorts();

    if (idx.row() > 0) {
        connectPort(m_addrs[idx.row()]);
    }

    emit dataChanged(index(0), index(m_addrs.count()));
}

void MidiConnectionsModel::disconnectAllPorts() const {
    Q_CHECK_PTR(m_io);

    snd_seq_query_subscribe_t *subs;
    snd_seq_query_subscribe_alloca(&subs);
    const snd_seq_addr_t ownaddr = {m_io->clientId(), m_io->portId()};
    snd_seq_query_subscribe_set_root(subs, &ownaddr);

    snd_seq_addr_t addr;

    snd_seq_query_subscribe_set_index(subs, 0);
    snd_seq_query_subscribe_set_type(subs, SND_SEQ_QUERY_SUBS_READ);
    while (snd_seq_query_port_subscribers(m_io->handle(), subs) >= 0) {
        addr = *snd_seq_query_subscribe_get_addr(subs);
        if (snd_seq_disconnect_to(m_io->handle(), m_io->portId(), addr.client, addr.port) < 0) {
            qWarning() << "Cannot disconnect to" << addr.client << addr.port;
        }
    }
    snd_seq_query_subscribe_set_index(subs, 0);
    snd_seq_query_subscribe_set_type(subs, SND_SEQ_QUERY_SUBS_WRITE);
    while (snd_seq_query_port_subscribers(m_io->handle(), subs) >= 0) {
        addr = *snd_seq_query_subscribe_get_addr(subs);
        if (snd_seq_disconnect_from(m_io->handle(), m_io->portId(), addr.client, addr.port) < 0) {
            qWarning() << "Cannot disconnect from" << addr.client << addr.port;
        }
    }
}

void MidiConnectionsModel::connectPort(const snd_seq_addr_t &addr) {
    Q_CHECK_PTR(m_io);

    if (snd_seq_connect_from(m_io->handle(), m_io->portId(), addr.client, addr.port) < 0) {
        qWarning() << "Cannot connect from";
    }

    if (snd_seq_connect_to(m_io->handle(), m_io->portId(), addr.client, addr.port) < 0) {
        qWarning() << "Cannot connect to";
    }
}

void MidiConnectionsModel::handleMidiEvent(const snd_seq_event_t* ev) {
    Q_CHECK_PTR(m_io);
    Q_CHECK_PTR(ev);

    const snd_seq_addr_t ownaddr = {m_io->clientId(), m_io->portId()};

    switch (ev->type) {
    case SND_SEQ_EVENT_PORT_START:
        return addAddressIfAccepted(&ev->data.addr);
    case SND_SEQ_EVENT_PORT_EXIT:
        return removeAddressIfAccepted(&ev->data.addr);
    case SND_SEQ_EVENT_PORT_CHANGE:
        return notifyDataChangedForAddress(&ev->data.addr);
    case SND_SEQ_EVENT_PORT_SUBSCRIBED:
    case SND_SEQ_EVENT_PORT_UNSUBSCRIBED:
        if (ownaddr == ev->data.connect.sender || ownaddr == ev->data.connect.dest) {
            if (ownaddr == ev->data.connect.sender) {
                return notifyDataChangedForAddress(&ev->data.connect.dest);
            }
            if (ownaddr == ev->data.connect.dest) {
                return notifyDataChangedForAddress(&ev->data.connect.sender);
            }
        }
        return;
    case SND_SEQ_EVENT_CLIENT_START:
    case SND_SEQ_EVENT_CLIENT_EXIT:
        emit connectedPortChanged(connectedPort());
        return;
    default:
        return;
    }
}

void MidiConnectionsModel::addAddressIfAccepted(const snd_seq_addr_t *addr) {
    Q_CHECK_PTR(addr);

    if (acceptAddress(addr)) {
        addAddress(addr);
    }
}

void MidiConnectionsModel::removeAddressIfAccepted(const snd_seq_addr_t *addr) {
    Q_CHECK_PTR(addr);

    const int r = m_addrs.indexOf(*addr);
    if (r >= 0) {
        beginRemoveRows(QModelIndex(), r, r);
        m_addrs.removeAt(r);
        endRemoveRows();
    }
}

void MidiConnectionsModel::notifyDataChangedForAddress(const snd_seq_addr_t *addr) {
    Q_CHECK_PTR(addr);

    const int r = m_addrs.indexOf(*addr);
    if (r >= 0) {
        const QModelIndex idx = index(r);
        emit dataChanged(idx, idx);
    }
}

void MidiConnectionsModel::addAddress(const snd_seq_addr_t *addr) {
    Q_CHECK_PTR(addr);
    Q_ASSERT(!m_addrs.contains(*addr));

    beginInsertRows(QModelIndex(), m_addrs.count(), m_addrs.count());
    m_addrs.append(*addr);
    endInsertRows();
}

bool MidiConnectionsModel::acceptAddress(const snd_seq_addr_t *addr) const {
    Q_CHECK_PTR(addr);

    snd_seq_client_info_t *cinfo;
    snd_seq_client_info_alloca(&cinfo);
    if (snd_seq_get_any_client_info(m_io->handle(), addr->client, cinfo) < 0 ||
        !acceptClient(cinfo)) {
        return false;
    }

    snd_seq_port_info_t *pinfo;
    snd_seq_port_info_alloca(&pinfo);
    return snd_seq_get_any_port_info(m_io->handle(), addr->client, addr->port, pinfo) == 0 &&
           acceptPort(pinfo);
}

bool MidiConnectionsModel::acceptClient(const snd_seq_client_info_t *info) const {
    Q_CHECK_PTR(m_io);
    Q_CHECK_PTR(info);

    const int id = snd_seq_client_info_get_client(info);
    return id != m_io->clientId() && id != SND_SEQ_CLIENT_SYSTEM;
}

bool MidiConnectionsModel::acceptPort(const snd_seq_port_info_t *info) const {
    Q_CHECK_PTR(info);

    const unsigned int caps = snd_seq_port_info_get_capability(info);
    return !(caps & SND_SEQ_PORT_CAP_NO_EXPORT) &&
           caps & SND_SEQ_PORT_CAP_READ &&
           caps & SND_SEQ_PORT_CAP_WRITE;
}

QString MidiConnectionsModel::portName(const QModelIndex& index) const {
    Q_ASSERT(index.isValid());

    const snd_seq_addr_t &addr = m_addrs[index.row()];
    snd_seq_port_info_t *info;
    snd_seq_port_info_alloca(&info);
    const int res = snd_seq_get_any_port_info(m_io->handle(), addr.client, addr.port, info);
    Q_UNUSED(res);
    Q_ASSERT(res >= 0);
    return snd_seq_port_info_get_name(info);
}

MidiConnectionsModel::Directions MidiConnectionsModel::portConnection(const QModelIndex& index) const {
    Q_CHECK_PTR(m_io);
    Q_ASSERT(index.isValid());

    return portConnection(m_addrs[index.row()]);
}

MidiConnectionsModel::Directions MidiConnectionsModel::portConnection(const snd_seq_addr_t& addr) const {
    Q_CHECK_PTR(m_io);

    MidiConnectionsModel::Directions ret = Direction::Disconnected;

    const snd_seq_addr_t ownaddr = {m_io->clientId(), m_io->portId()};

    snd_seq_port_subscribe_t *subs;
    snd_seq_port_subscribe_alloca(&subs);

    snd_seq_port_subscribe_set_sender(subs, &ownaddr);
    snd_seq_port_subscribe_set_dest(subs, &addr);
    if (snd_seq_get_port_subscription(m_io->handle(), subs) == 0) {
        ret |= Direction::To;
    }

    snd_seq_port_subscribe_set_sender(subs, &addr);
    snd_seq_port_subscribe_set_dest(subs, &ownaddr);
    if (snd_seq_get_port_subscription(m_io->handle(), subs) == 0) {
        ret |= Direction::From;
    }

    return ret;
}
<|endoftext|>


<commit_before>#include "shader.h"
#include "glslUtility.h"

using namespace glslUtility;

ShaderProgram::ShaderProgram()
{
    program = 0;
    vs = 0;
    fs = 0;
    gs = 0;
}

ShaderProgram::~ShaderProgram()
{
    glDeleteProgram( program );
    glDeleteShader( vs );
    glDeleteShader( fs );
    glDeleteShader( gs );
}

int ShaderProgram::init(const char* vs_source, const char* fs_source, const char* gs_source )
{
    //load shader sources and compile
    shaders_t shaderSet = loadShaders( vs_source, fs_source, gs_source );
    vs = shaderSet.vertex;
    fs = shaderSet.fragment;
    gs = shaderSet.geometry;

    //create program
    program = glCreateProgram();

    //attach shader
    attachAndLinkProgram( program, shaderSet );

    return 0;
}

void ShaderProgram::use()
{
    glUseProgram( program );
}
void ShaderProgram::unuse()
{
    glUseProgram( 0 );
}

void ShaderProgram::setParameter( shaderAttrib type, void* param, char* name )
{
    switch( type )
    {
    case f1:
        glUniform1f( glGetUniformLocation( program, name ), *((float*)param) );
        break;
    case fv3:
        glUniform3fv( glGetUniformLocation( program, name ), 1, (float*)param );
        break;
    case fv4:
        glUniform4fv( glGetUniformLocation( program, name ), 1, (float*)param );
        break;
    case mat4:
        glUniformMatrix4fv( glGetUniformLocation( program, name ), 1, GL_FALSE, (float*)param );
        break;
    case mat3:
        glUniformMatrix3fv( glGetUniformLocation( program, name ), 1, GL_FALSE, (float*)param );
        break;
    }
}<commit_msg>clean bugs on loading shader files<commit_after>// Sparse Voxel Octree and Voxel Cone Tracing
//
// University of Pennsylvania CIS565 final project
// copyright (c) 2013 Cheng-Tso Lin

#include <gl/glew.h>
#include "shader.h"
#include "glslUtility.h"

using namespace glslUtility;

ShaderProgram::ShaderProgram()
{
    program = 0;
    vs = 0;
    fs = 0;
    gs = 0;
}

ShaderProgram::~ShaderProgram()
{
    glDeleteProgram( program );
    glDeleteShader( vs );
    glDeleteShader( fs );
    glDeleteShader( gs );
}

int ShaderProgram::init(const char* vs_source, const char* fs_source, const char* gs_source )
{
    //load shader sources and compile
    shaders_t shaderSet = loadShaders( vs_source, fs_source, gs_source );
    vs = shaderSet.vertex;
    fs = shaderSet.fragment;
    gs = shaderSet.geometry;

    //create program
    program = glCreateProgram();

    //attach shader
    attachAndLinkProgram( program, shaderSet );

    return 0;
}

void ShaderProgram::use()
{
    glUseProgram( program );
}
void ShaderProgram::unuse()
{
    glUseProgram( 0 );
}

void ShaderProgram::setParameter( shaderAttrib type, void* param, char* name )
{
    switch( type )
    {
    case f1:
        glUniform1f( glGetUniformLocation( program, name ), *((float*)param) );
        break;
    case fv3:
        glUniform3fv( glGetUniformLocation( program, name ), 1, (float*)param );
        break;
    case fv4:
        glUniform4fv( glGetUniformLocation( program, name ), 1, (float*)param );
        break;
    case mat4x4:
        glUniformMatrix4fv( glGetUniformLocation( program, name ), 1, GL_FALSE, (float*)param );
        break;
    case mat3x3:
        glUniformMatrix3fv( glGetUniformLocation( program, name ), 1, GL_FALSE, (float*)param );
        break;
    }
}<|endoftext|>


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

#include "osl/file.hxx"

#include "vendorbase.hxx"
#include "util.hxx"
#include "sunjre.hxx"

using namespace std;
using namespace rtl;
using namespace osl;

namespace jfw_plugin
{
rtl::Reference<VendorBase> createInstance(createInstance_func pFunc,
                                          vector<pair<OUString, OUString> > properties);

//##############################################################################

MalformedVersionException::MalformedVersionException()
{}
MalformedVersionException::MalformedVersionException(
    const MalformedVersionException & )
{}
MalformedVersionException::~MalformedVersionException()
{}
MalformedVersionException &
MalformedVersionException::operator =(
    const MalformedVersionException &)
{
    return *this;
}
//##############################################################################

VendorBase::VendorBase(): m_bAccessibility(false)
{
}

char const* const * VendorBase::getJavaExePaths(int* size)
{
    static char const * ar[] = {
#ifdef WNT
        "java.exe",
        "bin/java.exe"
#elif UNX
        "java",
        "bin/java"
#endif
    };
    *size = sizeof(ar) / sizeof(char*);
    return ar;
}

rtl::Reference<VendorBase> VendorBase::createInstance()
{
    VendorBase *pBase = new VendorBase();
    return rtl::Reference<VendorBase>(pBase);
}

bool VendorBase::initialize(vector<pair<OUString, OUString> > props)
{
    //get java.vendor, java.version, java.home,
    //javax.accessibility.assistive_technologies from system properties

    OUString sVendor;
    typedef vector<pair<OUString, OUString> >::const_iterator it_prop;
    OUString sVendorProperty(
        RTL_CONSTASCII_USTRINGPARAM("java.vendor"));
    OUString sVersionProperty(
        RTL_CONSTASCII_USTRINGPARAM("java.version"));
    OUString sHomeProperty(
        RTL_CONSTASCII_USTRINGPARAM("java.home"));
    OUString sAccessProperty(
        RTL_CONSTASCII_USTRINGPARAM("javax.accessibility.assistive_technologies"));

    bool bVersion = false;
    bool bVendor = false;
    bool bHome = false;
    bool bAccess = false;

    typedef vector<pair<OUString, OUString> >::const_iterator it_prop;
    for (it_prop i = props.begin(); i != props.end(); i++)
    {
        if(! bVendor && sVendorProperty.equals(i->first))
        {
            m_sVendor = i->second;
            bVendor = true;
        }
        else if (!bVersion && sVersionProperty.equals(i->first))
        {
            m_sVersion = i->second;
            bVersion = true;
        }
        else if (!bHome && sHomeProperty.equals(i->first))
        {
           OUString fileURL;
           if (osl_getFileURLFromSystemPath(i->second.pData,& fileURL.pData) ==
               osl_File_E_None)
           {
               //make sure that the drive letter have all the same case
               //otherwise file:///c:/jre and file:///C:/jre produce two
               //different objects!!!
               if (makeDriveLetterSame( & fileURL))
               {
                   m_sHome = fileURL;
                   bHome = true;
               }
           }
        }
        else if (!bAccess && sAccessProperty.equals(i->first))
        {
            if (i->second.getLength() > 0)
            {
                m_bAccessibility = true;
                bAccess = true;
            }
        }
        // the javax.accessibility.xxx property may not be set. Therefore we
        //must search through all properties.

    }
    if (!bVersion || !bVendor || !bHome)
        return false;

    // init m_sRuntimeLibrary
    OSL_ASSERT(m_sHome.getLength());
    //call virtual function to get the possible paths to the runtime library.

    int size = 0;
    char const* const* arRtPaths = getRuntimePaths( & size);
    vector<OUString> libpaths = getVectorFromCharArray(arRtPaths, size);

    bool bRt = false;
    typedef vector<OUString>::const_iterator i_path;
    for(i_path ip = libpaths.begin(); ip != libpaths.end(); ip++)
    {
        //Construct an absolute path to the possible runtime
        OUString usRt= m_sHome + *ip;
        DirectoryItem item;
        if(DirectoryItem::get(usRt, item) == File::E_None)
        {
            //found runtime lib
            m_sRuntimeLibrary = usRt;
            bRt = true;
            break;
        }
    }
    if (!bRt)
        return false;

    // init m_sLD_LIBRARY_PATH
    OSL_ASSERT(m_sHome.getLength());
    size = 0;
    char const * const * arLDPaths = getLibraryPaths( & size);
    vector<OUString> ld_paths = getVectorFromCharArray(arLDPaths, size);

    char arSep[]= {SAL_PATHSEPARATOR, 0};
    OUString sPathSep= OUString::createFromAscii(arSep);
    bool bLdPath = true;
    int c = 0;
    for(i_path il = ld_paths.begin(); il != ld_paths.end(); il ++, c++)
    {
        OUString usAbsUrl= m_sHome + *il;
        // convert to system path
        OUString usSysPath;
        if(File::getSystemPathFromFileURL(usAbsUrl, usSysPath) == File::E_None)
        {

            if(c > 0)
                m_sLD_LIBRARY_PATH+= sPathSep;
            m_sLD_LIBRARY_PATH+= usSysPath;
        }
        else
        {
            bLdPath = false;
            break;
        }
    }
    if (bLdPath == false)
        return false;

    return true;
}

char const* const* VendorBase::getRuntimePaths(int* /*size*/)
{
    return NULL;
}

char const* const* VendorBase::getLibraryPaths(int* /*size*/)
{
    return NULL;
}

const OUString & VendorBase::getVendor() const
{
    return m_sVendor;
}
const OUString & VendorBase::getVersion() const
{
    return m_sVersion;
}

const OUString & VendorBase::getHome() const
{
    return m_sHome;
}

const OUString & VendorBase::getLibraryPaths() const
{
    return m_sLD_LIBRARY_PATH;
}

const OUString & VendorBase::getRuntimeLibrary() const
{
    return m_sRuntimeLibrary;
}
bool VendorBase::supportsAccessibility() const
{
    return m_bAccessibility;
}

bool VendorBase::needsRestart() const
{
    if (getLibraryPaths().getLength() > 0)
        return true;
    return false;
}

int VendorBase::compareVersions(const rtl::OUString& /*sSecond*/) const
{
    OSL_ENSURE(0, "[Java framework] VendorBase::compareVersions must be "
               "overridden in derived class.");
    return 0;
}

}
<commit_msg>INTEGRATION: CWS pchfix02 (1.5.16); FILE MERGED 2006/09/01 17:31:40 kaib 1.5.16.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: vendorbase.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-16 17:47:02 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_jvmfwk.hxx"

#include "osl/file.hxx"

#include "vendorbase.hxx"
#include "util.hxx"
#include "sunjre.hxx"

using namespace std;
using namespace rtl;
using namespace osl;

namespace jfw_plugin
{
rtl::Reference<VendorBase> createInstance(createInstance_func pFunc,
                                          vector<pair<OUString, OUString> > properties);

//##############################################################################

MalformedVersionException::MalformedVersionException()
{}
MalformedVersionException::MalformedVersionException(
    const MalformedVersionException & )
{}
MalformedVersionException::~MalformedVersionException()
{}
MalformedVersionException &
MalformedVersionException::operator =(
    const MalformedVersionException &)
{
    return *this;
}
//##############################################################################

VendorBase::VendorBase(): m_bAccessibility(false)
{
}

char const* const * VendorBase::getJavaExePaths(int* size)
{
    static char const * ar[] = {
#ifdef WNT
        "java.exe",
        "bin/java.exe"
#elif UNX
        "java",
        "bin/java"
#endif
    };
    *size = sizeof(ar) / sizeof(char*);
    return ar;
}

rtl::Reference<VendorBase> VendorBase::createInstance()
{
    VendorBase *pBase = new VendorBase();
    return rtl::Reference<VendorBase>(pBase);
}

bool VendorBase::initialize(vector<pair<OUString, OUString> > props)
{
    //get java.vendor, java.version, java.home,
    //javax.accessibility.assistive_technologies from system properties

    OUString sVendor;
    typedef vector<pair<OUString, OUString> >::const_iterator it_prop;
    OUString sVendorProperty(
        RTL_CONSTASCII_USTRINGPARAM("java.vendor"));
    OUString sVersionProperty(
        RTL_CONSTASCII_USTRINGPARAM("java.version"));
    OUString sHomeProperty(
        RTL_CONSTASCII_USTRINGPARAM("java.home"));
    OUString sAccessProperty(
        RTL_CONSTASCII_USTRINGPARAM("javax.accessibility.assistive_technologies"));

    bool bVersion = false;
    bool bVendor = false;
    bool bHome = false;
    bool bAccess = false;

    typedef vector<pair<OUString, OUString> >::const_iterator it_prop;
    for (it_prop i = props.begin(); i != props.end(); i++)
    {
        if(! bVendor && sVendorProperty.equals(i->first))
        {
            m_sVendor = i->second;
            bVendor = true;
        }
        else if (!bVersion && sVersionProperty.equals(i->first))
        {
            m_sVersion = i->second;
            bVersion = true;
        }
        else if (!bHome && sHomeProperty.equals(i->first))
        {
           OUString fileURL;
           if (osl_getFileURLFromSystemPath(i->second.pData,& fileURL.pData) ==
               osl_File_E_None)
           {
               //make sure that the drive letter have all the same case
               //otherwise file:///c:/jre and file:///C:/jre produce two
               //different objects!!!
               if (makeDriveLetterSame( & fileURL))
               {
                   m_sHome = fileURL;
                   bHome = true;
               }
           }
        }
        else if (!bAccess && sAccessProperty.equals(i->first))
        {
            if (i->second.getLength() > 0)
            {
                m_bAccessibility = true;
                bAccess = true;
            }
        }
        // the javax.accessibility.xxx property may not be set. Therefore we
        //must search through all properties.

    }
    if (!bVersion || !bVendor || !bHome)
        return false;

    // init m_sRuntimeLibrary
    OSL_ASSERT(m_sHome.getLength());
    //call virtual function to get the possible paths to the runtime library.

    int size = 0;
    char const* const* arRtPaths = getRuntimePaths( & size);
    vector<OUString> libpaths = getVectorFromCharArray(arRtPaths, size);

    bool bRt = false;
    typedef vector<OUString>::const_iterator i_path;
    for(i_path ip = libpaths.begin(); ip != libpaths.end(); ip++)
    {
        //Construct an absolute path to the possible runtime
        OUString usRt= m_sHome + *ip;
        DirectoryItem item;
        if(DirectoryItem::get(usRt, item) == File::E_None)
        {
            //found runtime lib
            m_sRuntimeLibrary = usRt;
            bRt = true;
            break;
        }
    }
    if (!bRt)
        return false;

    // init m_sLD_LIBRARY_PATH
    OSL_ASSERT(m_sHome.getLength());
    size = 0;
    char const * const * arLDPaths = getLibraryPaths( & size);
    vector<OUString> ld_paths = getVectorFromCharArray(arLDPaths, size);

    char arSep[]= {SAL_PATHSEPARATOR, 0};
    OUString sPathSep= OUString::createFromAscii(arSep);
    bool bLdPath = true;
    int c = 0;
    for(i_path il = ld_paths.begin(); il != ld_paths.end(); il ++, c++)
    {
        OUString usAbsUrl= m_sHome + *il;
        // convert to system path
        OUString usSysPath;
        if(File::getSystemPathFromFileURL(usAbsUrl, usSysPath) == File::E_None)
        {

            if(c > 0)
                m_sLD_LIBRARY_PATH+= sPathSep;
            m_sLD_LIBRARY_PATH+= usSysPath;
        }
        else
        {
            bLdPath = false;
            break;
        }
    }
    if (bLdPath == false)
        return false;

    return true;
}

char const* const* VendorBase::getRuntimePaths(int* /*size*/)
{
    return NULL;
}

char const* const* VendorBase::getLibraryPaths(int* /*size*/)
{
    return NULL;
}

const OUString & VendorBase::getVendor() const
{
    return m_sVendor;
}
const OUString & VendorBase::getVersion() const
{
    return m_sVersion;
}

const OUString & VendorBase::getHome() const
{
    return m_sHome;
}

const OUString & VendorBase::getLibraryPaths() const
{
    return m_sLD_LIBRARY_PATH;
}

const OUString & VendorBase::getRuntimeLibrary() const
{
    return m_sRuntimeLibrary;
}
bool VendorBase::supportsAccessibility() const
{
    return m_bAccessibility;
}

bool VendorBase::needsRestart() const
{
    if (getLibraryPaths().getLength() > 0)
        return true;
    return false;
}

int VendorBase::compareVersions(const rtl::OUString& /*sSecond*/) const
{
    OSL_ENSURE(0, "[Java framework] VendorBase::compareVersions must be "
               "overridden in derived class.");
    return 0;
}

}
<|endoftext|>


<commit_before>/**
 * @file signal.cpp
 * @author Albert Uchytil (xuchyt03)
 * @brief SignalHandler
 */

#include "signal.hpp"

/**
 * Model to print stats.
 */
Simulation* SignalHandler::simulation = NULL;

/**
 * Handles received signals.
 */
void SignalHandler::handler(int signum)
{
  debug("SignalHandler", "signal handled");
  if (SignalHandler::simulation != NULL) {
    simulation->PrintStats();
    delete simulation;
  }
  exit(1);
}

/**
 * Sets up simulation to print when handling.
 *
 * @param simulation Model to watch
 */
void SignalHandler::SetupSim(Simulation *simulation)
{
  debug("SignalHandler", "setting up simulation for handling");
  SignalHandler::simulation = simulation;
}

/**
 * Sets up signal handling.
 */
void SignalHandler::SetupHandlers()
{
  debug("SignalHandler", "setting up signal handlers");
  if (signal((int)SIGTERM, SignalHandler::handler) == SIG_ERR ||
      signal((int)SIGQUIT, SignalHandler::handler) == SIG_ERR ||
      signal((int)SIGINT, SignalHandler::handler) == SIG_ERR)
    std::cerr << "Unable to register signal handlers" << std::endl;
}
<commit_msg>[signal] swithced to simulation insteda of model, hotfix<commit_after>/**
 * @file signal.cpp
 * @author Albert Uchytil (xuchyt03)
 * @brief SignalHandler
 */

#include "signal.hpp"

/**
 * Model to print stats.
 */
Simulation* SignalHandler::simulation = NULL;

/**
 * Handles received signals.
 */
void SignalHandler::handler(int signum)
{
  debug("SignalHandler", "signal handled");
  if (SignalHandler::simulation != NULL) {
    simulation->PrintStats();
  }
  exit(1);
}

/**
 * Sets up simulation to print when handling.
 *
 * @param simulation Model to watch
 */
void SignalHandler::SetupSim(Simulation *simulation)
{
  debug("SignalHandler", "setting up simulation for handling");
  SignalHandler::simulation = simulation;
}

/**
 * Sets up signal handling.
 */
void SignalHandler::SetupHandlers()
{
  debug("SignalHandler", "setting up signal handlers");
  if (signal((int)SIGTERM, SignalHandler::handler) == SIG_ERR ||
      signal((int)SIGQUIT, SignalHandler::handler) == SIG_ERR ||
      signal((int)SIGINT, SignalHandler::handler) == SIG_ERR)
    std::cerr << "Unable to register signal handlers" << std::endl;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <memory>
#include <unordered_map>

using std::swap;

//
// The classes

struct Shape
{
  virtual ~Shape()
  {
  }
  virtual double area() const = 0;
  virtual double perimeter() const = 0;
};

static const double pi = 3.14159265359;

class Circle : public Shape
{
  const double radius_;

public:
  double area() const override
  {
    return pi * radius_ * radius_;
  }

  double perimeter() const override
  {
    return 2 * pi * radius_;
  }

  Circle(double r) : radius_(r)
  {
  }
};

//
// The C bridge

extern "C" {

void* Circle_new(double r)
{
  return new (std::nothrow) Circle(r);
}

void Shape_delete(const void* shape)
{
  delete ((const Shape*)shape);
}

double Shape_area(const void* shape)
{
  return ((const Shape*)shape)->area();
}

double Shape_perimeter(const void* shape)
{
  return ((const Shape*)shape)->perimeter();
}
}

//
// The handles bridge

using HANDLE = const char*;

enum RC
{
  LOOKUP_FAIL = -999,
  SUCCESS = 0
};

struct TableEntry
{
  void* obj_ = nullptr;
  void (*del_)(const void*) = nullptr;

  TableEntry& operator=(TableEntry&& t)
  {
    swap(t.obj_, obj_);
    swap(t.del_, del_);
    t.~TableEntry();
    return *this;
  }

  ~TableEntry()
  {
    if (del_) del_(obj_);
  }
};

class HandleTable // not thread-safe
{

  std::unordered_map<std::string, TableEntry> handle_table;

public:
  struct LookupFailureException : public std::runtime_error
  {
    LookupFailureException(HANDLE handle) : std::runtime_error(handle)
    {
    }
  };

  void InsertOrOverwrite(HANDLE handle, void* object,
                         void (*deleter)(const void*))
  {
    TableEntry t;
    t.obj_ = object;
    t.del_ = deleter;
    handle_table[handle] = std::move(t);
  }

  void* Lookup(HANDLE handle) const
  {
    auto find_it = handle_table.find(handle);
    if (find_it != handle_table.end())
    {
      return find_it->second.obj_;
    }
    throw LookupFailureException(handle);
  }

  void* TryLookup(HANDLE handle) const
  {
    auto find_it = handle_table.find(handle);
    if (find_it != handle_table.end())
    {
      return find_it->second.obj_;
    }
    return nullptr;
  }
};

static HandleTable handle_table;

extern "C" {

void CircleH_new(HANDLE circle, double r, int* rc)
{
  handle_table.InsertOrOverwrite(circle, Circle_new(r), Shape_delete);
  *rc = SUCCESS;
}

void ShapeH_delete(HANDLE shape, int* rc)
{
  try
  {
    *rc = SUCCESS;
    Shape_delete(handle_table.Lookup(shape));
  }
  catch (const HandleTable::LookupFailureException& e)
  {
    *rc = LOOKUP_FAIL;
  }
}

double ShapeH_area(HANDLE shape, int* rc)
{
  try
  {
    *rc = SUCCESS;
    return Shape_area(handle_table.Lookup(shape));
  }
  catch (const HandleTable::LookupFailureException& e)
  {
    *rc = LOOKUP_FAIL;
    return 0.0;
  }
}

double ShapeH_perimeter(HANDLE shape, int* rc)
{
  try
  {
    *rc = SUCCESS;
    return Shape_perimeter(handle_table.Lookup(shape));
  }
  catch (const HandleTable::LookupFailureException& e)
  {
    *rc = LOOKUP_FAIL;
    return 0.0;
  }
}
}

int main(int argc, char* argv[])
{
  int rc;
  auto name = "myCircle";
  CircleH_new(name, 10, &rc);
  if (rc != SUCCESS)
  {
    std::cerr << "Failed to construct circle\n";
    return -1;
  }

  double area = ShapeH_area(name, &rc);
  if (rc != SUCCESS)
  {
    std::cerr << "Failed to get circle area\n";
    return -1;
  }
  std::cout << "Area=" << area << "\n";

  double perimeter = ShapeH_perimeter(name, &rc);
  if (rc != SUCCESS)
  {
    std::cerr << "Failed to get circle perimeter\n";
    return -1;
  }
  std::cout << "Perimeter=" << perimeter << "\n";
}

<commit_msg>assert not move assigning to self<commit_after>#include <iostream>
#include <cassert>
#include <memory>
#include <unordered_map>

using std::swap;

//
// The classes

struct Shape
{
  virtual ~Shape()
  {
  }
  virtual double area() const = 0;
  virtual double perimeter() const = 0;
};

static const double pi = 3.14159265359;

class Circle : public Shape
{
  const double radius_;

public:
  double area() const override
  {
    return pi * radius_ * radius_;
  }

  double perimeter() const override
  {
    return 2 * pi * radius_;
  }

  Circle(double r) : radius_(r)
  {
  }
};

//
// The C bridge

extern "C" {

void* Circle_new(double r)
{
  return new (std::nothrow) Circle(r);
}

void Shape_delete(const void* shape)
{
  delete ((const Shape*)shape);
}

double Shape_area(const void* shape)
{
  return ((const Shape*)shape)->area();
}

double Shape_perimeter(const void* shape)
{
  return ((const Shape*)shape)->perimeter();
}
}

//
// The handles bridge

using HANDLE = const char*;

enum RC
{
  LOOKUP_FAIL = -999,
  SUCCESS = 0
};

struct TableEntry
{
  void* obj_ = nullptr;
  void (*del_)(const void*) = nullptr;

  TableEntry& operator=(TableEntry&& t)
  {
    assert(&t != this);
    swap(t.obj_, obj_);
    swap(t.del_, del_);
    t.~TableEntry();
    return *this;
  }

  ~TableEntry()
  {
    if (del_) del_(obj_);
  }
};

class HandleTable // not thread-safe
{

  std::unordered_map<std::string, TableEntry> handle_table;

public:
  struct LookupFailureException : public std::runtime_error
  {
    LookupFailureException(HANDLE handle) : std::runtime_error(handle)
    {
    }
  };

  void InsertOrOverwrite(HANDLE handle, void* object,
                         void (*deleter)(const void*))
  {
    TableEntry t;
    t.obj_ = object;
    t.del_ = deleter;
    handle_table[handle] = std::move(t);
  }

  void* Lookup(HANDLE handle) const
  {
    auto find_it = handle_table.find(handle);
    if (find_it != handle_table.end())
    {
      return find_it->second.obj_;
    }
    throw LookupFailureException(handle);
  }

  void* TryLookup(HANDLE handle) const
  {
    auto find_it = handle_table.find(handle);
    if (find_it != handle_table.end())
    {
      return find_it->second.obj_;
    }
    return nullptr;
  }
};

static HandleTable handle_table;

extern "C" {

void CircleH_new(HANDLE circle, double r, int* rc)
{
  handle_table.InsertOrOverwrite(circle, Circle_new(r), Shape_delete);
  *rc = SUCCESS;
}

void ShapeH_delete(HANDLE shape, int* rc)
{
  try
  {
    *rc = SUCCESS;
    Shape_delete(handle_table.Lookup(shape));
  }
  catch (const HandleTable::LookupFailureException& e)
  {
    *rc = LOOKUP_FAIL;
  }
}

double ShapeH_area(HANDLE shape, int* rc)
{
  try
  {
    *rc = SUCCESS;
    return Shape_area(handle_table.Lookup(shape));
  }
  catch (const HandleTable::LookupFailureException& e)
  {
    *rc = LOOKUP_FAIL;
    return 0.0;
  }
}

double ShapeH_perimeter(HANDLE shape, int* rc)
{
  try
  {
    *rc = SUCCESS;
    return Shape_perimeter(handle_table.Lookup(shape));
  }
  catch (const HandleTable::LookupFailureException& e)
  {
    *rc = LOOKUP_FAIL;
    return 0.0;
  }
}
}

int main(int argc, char* argv[])
{
  int rc;
  auto name = "myCircle";
  CircleH_new(name, 10, &rc);
  if (rc != SUCCESS)
  {
    std::cerr << "Failed to construct circle\n";
    return -1;
  }

  double area = ShapeH_area(name, &rc);
  if (rc != SUCCESS)
  {
    std::cerr << "Failed to get circle area\n";
    return -1;
  }
  std::cout << "Area=" << area << "\n";

  double perimeter = ShapeH_perimeter(name, &rc);
  if (rc != SUCCESS)
  {
    std::cerr << "Failed to get circle perimeter\n";
    return -1;
  }
  std::cout << "Perimeter=" << perimeter << "\n";
}

<|endoftext|>


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

using namespace std;
vector <string> Census;

void Census2017(){
  // Census.push_back("Name @ GitHub link");
  Census.push_back("Allen Comp Sci @ https://github.com/AllenCompSci");
  Census.push_back("Mr. Hudson @ https://github.com/theshrewedshrew");
  Census.push_back("BEST Team 58 @ https://github.com/BESTTeam58");
  Census.push_back("TexasSnow @ https://github.com/TexasSnow");
  Census.push_back("hotdogshabab @ https://github.com/hotdogshabab");
  Census.push_back("alansunglee @ https://github.com/alansunglee");
  Census.push_back("Rahultheman12 @ https://github.com/Rahultheman12");
  Census.push_back("spicyboi @ https://github.com/spicyboi");
  Census.push_back("John Nguyen @ https://github.com/jawnlovesfreestuff");
  Census.push_back("Devin Petersen @ https://github.com/DevinPetersen");
  Census.push_back("Cameron Mathis @ https://github.com/Phylux");

}

void printCensus(){
  for(int i = 0; i < (int)Census.size(); i++){
    cout << "Hello World from "Your name" + Census[i] << "\n";

  }
}

void main(){
  Census2017();
  printCensus();
}
<commit_msg>Update HelloWorld.cpp<commit_after>#include <iostream>
#include <string>
#include <vector>

using namespace std;
vector <string> Census;

void Census2017(){
  // Census.push_back("Name @ GitHub link");
  Census.push_back("Allen Comp Sci @ https://github.com/AllenCompSci");
  Census.push_back("Mr. Hudson @ https://github.com/theshrewedshrew");
  Census.push_back("BEST Team 58 @ https://github.com/BESTTeam58");
  Census.push_back("TexasSnow @ https://github.com/TexasSnow");
  Census.push_back("hotdogshabab @ https://github.com/hotdogshabab");
  Census.push_back("alansunglee @ https://github.com/alansunglee");
  Census.push_back("Rahultheman12 @ https://github.com/Rahultheman12");
  Census.push_back("spicyboi @ https://github.com/spicyboi");
  Census.push_back("John Nguyen @ https://github.com/jawnlovesfreestuff");
  Census.push_back("Cameron Mathis @ https://github.com/Phylux");
  Census.push_back("Samuel Woon @ https://github.com/samuel-w")

}

void printCensus(){
  for(int i = 0; i < (int)Census.size(); i++){
    cout << "Hello World from "Your name" + Census[i] << "\n";

  }
}

void main(){
  Census2017();
  printCensus();
}
<|endoftext|>


<commit_before>#include "openmc/source.h"

#include <algorithm> // for move
#include <sstream> // for stringstream

#if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
#include <dlfcn.h> // for dlopen
#endif

#include <fmt/core.h>
#include "xtensor/xadapt.hpp"

#include "openmc/bank.h"
#include "openmc/cell.h"
#include "openmc/error.h"
#include "openmc/file_utils.h"
#include "openmc/hdf5_interface.h"
#include "openmc/material.h"
#include "openmc/message_passing.h"
#include "openmc/mgxs_interface.h"
#include "openmc/nuclide.h"
#include "openmc/capi.h"
#include "openmc/random_lcg.h"
#include "openmc/search.h"
#include "openmc/settings.h"
#include "openmc/simulation.h"
#include "openmc/state_point.h"
#include "openmc/xml_interface.h"

namespace openmc {

//==============================================================================
// Global variables
//==============================================================================

namespace model {

std::vector<SourceDistribution> external_sources;

}

//==============================================================================
// SourceDistribution implementation
//==============================================================================

SourceDistribution::SourceDistribution(UPtrSpace space, UPtrAngle angle, UPtrDist energy)
  : space_{std::move(space)}, angle_{std::move(angle)}, energy_{std::move(energy)} { }

SourceDistribution::SourceDistribution(pugi::xml_node node)
{
  // Check for particle type
  if (check_for_node(node, "particle")) {
    auto temp_str = get_node_value(node, "particle", true, true);
    if (temp_str == "neutron") {
      particle_ = Particle::Type::neutron;
    } else if (temp_str == "photon") {
      particle_ = Particle::Type::photon;
      settings::photon_transport = true;
    } else {
      fatal_error(std::string("Unknown source particle type: ") + temp_str);
    }
  }

  // Check for source strength
  if (check_for_node(node, "strength")) {
    strength_ = std::stod(get_node_value(node, "strength"));
  }

  // Check for external source file
  if (check_for_node(node, "file")) {
    // Copy path of source file
    settings::path_source = get_node_value(node, "file", false, true);

    // Check if source file exists
    if (!file_exists(settings::path_source)) {
      fatal_error(fmt::format("Source file '{}' does not exist.",
        settings::path_source));
    }
  } else if (check_for_node(node, "library")) {
     settings::path_source_library = get_node_value(node, "library", false, true);
     // check if it exists
     if (!file_exists(settings::path_source_library)) {
      	std::stringstream msg;
      	msg << "Library file " << settings::path_source_library << "' does not exist.";
	      fatal_error(msg);
     }
  } else {

    // Spatial distribution for external source
    if (check_for_node(node, "space")) {
      // Get pointer to spatial distribution
      pugi::xml_node node_space = node.child("space");

      // Check for type of spatial distribution and read
      std::string type;
      if (check_for_node(node_space, "type"))
        type = get_node_value(node_space, "type", true, true);
      if (type == "cartesian") {
        space_ = UPtrSpace{new CartesianIndependent(node_space)};
      } else if (type == "cylindrical") {
        space_ = UPtrSpace{new CylindricalIndependent(node_space)};
      } else if (type == "spherical") {
        space_ = UPtrSpace{new SphericalIndependent(node_space)};
      } else if (type == "box") {
        space_ = UPtrSpace{new SpatialBox(node_space)};
      } else if (type == "fission") {
        space_ = UPtrSpace{new SpatialBox(node_space, true)};
      } else if (type == "point") {
        space_ = UPtrSpace{new SpatialPoint(node_space)};
      } else {
        fatal_error(fmt::format(
          "Invalid spatial distribution for external source: {}", type));
      }

    } else {
      // If no spatial distribution specified, make it a point source
      space_ = UPtrSpace{new SpatialPoint()};
    }

    // Determine external source angular distribution
    if (check_for_node(node, "angle")) {
      // Get pointer to angular distribution
      pugi::xml_node node_angle = node.child("angle");

      // Check for type of angular distribution
      std::string type;
      if (check_for_node(node_angle, "type"))
        type = get_node_value(node_angle, "type", true, true);
      if (type == "isotropic") {
        angle_ = UPtrAngle{new Isotropic()};
      } else if (type == "monodirectional") {
        angle_ = UPtrAngle{new Monodirectional(node_angle)};
      } else if (type == "mu-phi") {
        angle_ = UPtrAngle{new PolarAzimuthal(node_angle)};
      } else {
        fatal_error(fmt::format(
          "Invalid angular distribution for external source: {}", type));
      }

    } else {
      angle_ = UPtrAngle{new Isotropic()};
    }

    // Determine external source energy distribution
    if (check_for_node(node, "energy")) {
      pugi::xml_node node_dist = node.child("energy");
      energy_ = distribution_from_xml(node_dist);
    } else {
      // Default to a Watt spectrum with parameters 0.988 MeV and 2.249 MeV^-1
      energy_ = UPtrDist{new Watt(0.988e6, 2.249e-6)};
    }
  }
}

Particle::Bank SourceDistribution::sample(uint64_t* seed) const
{
  Particle::Bank site;

  // Set weight to one by default
  site.wgt = 1.0;

  // Repeat sampling source location until a good site has been found
  bool found = false;
  int n_reject = 0;
  static int n_accept = 0;
  while (!found) {
    // Set particle type
    site.particle = particle_;

    // Sample spatial distribution
    site.r = space_->sample(seed);
    double xyz[] {site.r.x, site.r.y, site.r.z};

    // Now search to see if location exists in geometry
    int32_t cell_index, instance;
    int err = openmc_find_cell(xyz, &cell_index, &instance);
    found = (err != OPENMC_E_GEOMETRY);

    // Check if spatial site is in fissionable material
    if (found) {
      auto space_box = dynamic_cast<SpatialBox*>(space_.get());
      if (space_box) {
        if (space_box->only_fissionable()) {
          // Determine material
          const auto& c = model::cells[cell_index];
          auto mat_index = c->material_.size() == 1
            ? c->material_[0] : c->material_[instance];

          if (mat_index == MATERIAL_VOID) {
            found = false;
          } else {
            if (!model::materials[mat_index]->fissionable_) found = false;
          }
        }
      }
    }

    // Check for rejection
    if (!found) {
      ++n_reject;
      if (n_reject >= EXTSRC_REJECT_THRESHOLD &&
          static_cast<double>(n_accept)/n_reject <= EXTSRC_REJECT_FRACTION) {
        fatal_error("More than 95% of external source sites sampled were "
                    "rejected. Please check your external source definition.");
      }
    }
  }

  // Increment number of accepted samples
  ++n_accept;

  // Sample angle
  site.u = angle_->sample(seed);

  // Check for monoenergetic source above maximum particle energy
  auto p = static_cast<int>(particle_);
  auto energy_ptr = dynamic_cast<Discrete*>(energy_.get());
  if (energy_ptr) {
    auto energies = xt::adapt(energy_ptr->x());
    if (xt::any(energies > data::energy_max[p])) {
      fatal_error("Source energy above range of energies of at least "
                  "one cross section table");
    } else if (xt::any(energies < data::energy_min[p])) {
      fatal_error("Source energy below range of energies of at least "
                  "one cross section table");
    }
  }

  while (true) {
    // Sample energy spectrum
    site.E = energy_->sample(seed);

    // Resample if energy falls outside minimum or maximum particle energy
    if (site.E < data::energy_max[p] && site.E > data::energy_min[p]) break;
  }

  // Set delayed group
  site.delayed_group = 0;

  return site;
}

//==============================================================================
// Non-member functions
//==============================================================================

void initialize_source()
{
  write_message("Initializing source particles...", 5);

  if (settings::path_source != "") {
    // Read the source from a binary file instead of sampling from some
    // assumed source distribution

    write_message(fmt::format("Reading source file from {}...",
      settings::path_source), 6);

    // Open the binary file
    hid_t file_id = file_open(settings::path_source, 'r', true);

    // Read the file type
    std::string filetype;
    read_attribute(file_id, "filetype", filetype);

    // Check to make sure this is a source file
    if (filetype != "source" && filetype != "statepoint") {
      fatal_error("Specified starting source file not a source file type.");
    }

    // Read in the source bank
    read_source_bank(file_id);

    // Close file
    file_close(file_id);
  } else if ( settings::path_source_library != "" ) {
    // Get the source from a library object

    std::stringstream msg;
    msg << "Sampling from library source " << settings::path_source << "...";
    write_message(msg, 6);

    #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
    // Open the library
    void* source_library = dlopen(settings::path_source_library.c_str(),RTLD_LAZY);
    if(!source_library) {
      std::stringstream msg("Couldnt open source library " + settings::path_source_library);
      fatal_error(msg);
    }
    #else
    std::stringstream msg("This feature has not yet been implemented for non POSIX systems");
    fatal_error(msg);
    #endif

    // load the symbol
    typedef Particle::Bank (*sample_t)();

    // reset errors
    dlerror();

    // get the function from the library
    sample_t sample_source = (sample_t) dlsym(source_library, "sample_source");
    const char *dlsym_error = dlerror();

    // check for any dlsym errors
    if (dlsym_error) {
      std::cout << dlsym_error << std::endl;
      dlclose(source_library);
      fatal_error("Couldnt open the sample_source symbol");
    }

    // Generation source sites from specified distribution in the
    // library source
    for (int64_t i = 0; i < simulation::work_per_rank; ++i) {
      // initialize random number seed
      int64_t id = simulation::total_gen*settings::n_particles +
        simulation::work_index[mpi::rank] + i + 1;
      set_particle_seed(id);

      // sample external source distribution
      simulation::source_bank[i] = sample_source();
    }
    // release the library
    dlclose(source_library);

  } else {
    // Generation source sites from specified distribution in user input
    for (int64_t i = 0; i < simulation::work_per_rank; ++i) {
      // initialize random number seed
      int64_t id = simulation::total_gen*settings::n_particles +
        simulation::work_index[mpi::rank] + i + 1;
      uint64_t seed = init_seed(id, STREAM_SOURCE);

      // sample external source distribution
      simulation::source_bank[i] = sample_external_source(&seed);
    }
  }

  // Write out initial source
  if (settings::write_initial_source) {
    write_message("Writing out initial source...", 5);
    std::string filename = settings::path_output + "initial_source.h5";
    hid_t file_id = file_open(filename, 'w', true);
    write_source_bank(file_id);
    file_close(file_id);
  }
}

Particle::Bank sample_external_source(uint64_t* seed)
{
  // Determine total source strength
  double total_strength = 0.0;
  for (auto& s : model::external_sources)
    total_strength += s.strength();

  // Sample from among multiple source distributions
  int i = 0;
  if (model::external_sources.size() > 1) {
    double xi = prn(seed)*total_strength;
    double c = 0.0;
    for (; i < model::external_sources.size(); ++i) {
      c += model::external_sources[i].strength();
      if (xi < c) break;
    }
  }

  // Sample source site from i-th source distribution
  Particle::Bank site {model::external_sources[i].sample(seed)};

  // If running in MG, convert site.E to group
  if (!settings::run_CE) {
    site.E = lower_bound_index(data::mg.rev_energy_bins_.begin(),
      data::mg.rev_energy_bins_.end(), site.E);
    site.E = data::mg.num_energy_groups_ - site.E - 1.;
  }

  return site;
}

void free_memory_source()
{
  model::external_sources.clear();
}

void fill_source_bank_fixedsource()
{
  if (settings::path_source.empty() && settings::path_source_library.empty()) {
    for (int64_t i = 0; i < simulation::work_per_rank; ++i) {
      // initialize random number seed
      int64_t id = (simulation::total_gen + overall_generation()) *
        settings::n_particles + simulation::work_index[mpi::rank] + i + 1;
      uint64_t seed = init_seed(id, STREAM_SOURCE);

      // sample external source distribution
      simulation::source_bank[i] = sample_external_source(&seed);
    }
  } else if (settings::path_source.empty() && !settings::path_source.empty()) {
     std::stringstream msg;

    // Open the library
    void* source_library = dlopen(settings::path_source_library.c_str(),RTLD_LAZY);
    if(!source_library) {
      std::stringstream msg("Couldnt open source library " + settings::path_source_library);
      fatal_error(msg);
    }

    // load the symbol
    typedef Particle::Bank (*sample_t)();

    // reset errors
    dlerror();

    // get the function from the library
    sample_t sample_source = (sample_t) dlsym(source_library, "sample_source");
    const char *dlsym_error = dlerror();

    // check for any dlsym errors
    if (dlsym_error) {
      std::cout << dlsym_error << std::endl;
      dlclose(source_library);
      fatal_error("Couldnt open the sample_source symbol");
    }

    // Generation source sites from specified distribution in the
    // library source
    for (int64_t i = 0; i < simulation::work_per_rank; ++i) {
      // initialize random number seed
      int64_t id = simulation::total_gen*settings::n_particles +
        simulation::work_index[mpi::rank] + i + 1;
      set_particle_seed(id);

      // sample external source distribution
      simulation::source_bank[i] = sample_source();
    }

    // release the library
    dlclose(source_library);
  }
}

} // namespace openmc
<commit_msg>updated signatures according to new changes in how seed is set<commit_after>#include "openmc/source.h"

#include <algorithm> // for move
#include <sstream> // for stringstream

#if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
#include <dlfcn.h> // for dlopen
#endif

#include <fmt/core.h>
#include "xtensor/xadapt.hpp"

#include "openmc/bank.h"
#include "openmc/cell.h"
#include "openmc/error.h"
#include "openmc/file_utils.h"
#include "openmc/hdf5_interface.h"
#include "openmc/material.h"
#include "openmc/message_passing.h"
#include "openmc/mgxs_interface.h"
#include "openmc/nuclide.h"
#include "openmc/capi.h"
#include "openmc/random_lcg.h"
#include "openmc/search.h"
#include "openmc/settings.h"
#include "openmc/simulation.h"
#include "openmc/state_point.h"
#include "openmc/xml_interface.h"

namespace openmc {

//==============================================================================
// Global variables
//==============================================================================

namespace model {

std::vector<SourceDistribution> external_sources;

}

//==============================================================================
// SourceDistribution implementation
//==============================================================================

SourceDistribution::SourceDistribution(UPtrSpace space, UPtrAngle angle, UPtrDist energy)
  : space_{std::move(space)}, angle_{std::move(angle)}, energy_{std::move(energy)} { }

SourceDistribution::SourceDistribution(pugi::xml_node node)
{
  // Check for particle type
  if (check_for_node(node, "particle")) {
    auto temp_str = get_node_value(node, "particle", true, true);
    if (temp_str == "neutron") {
      particle_ = Particle::Type::neutron;
    } else if (temp_str == "photon") {
      particle_ = Particle::Type::photon;
      settings::photon_transport = true;
    } else {
      fatal_error(std::string("Unknown source particle type: ") + temp_str);
    }
  }

  // Check for source strength
  if (check_for_node(node, "strength")) {
    strength_ = std::stod(get_node_value(node, "strength"));
  }

  // Check for external source file
  if (check_for_node(node, "file")) {
    // Copy path of source file
    settings::path_source = get_node_value(node, "file", false, true);

    // Check if source file exists
    if (!file_exists(settings::path_source)) {
      fatal_error(fmt::format("Source file '{}' does not exist.",
        settings::path_source));
    }
  } else if (check_for_node(node, "library")) {
     settings::path_source_library = get_node_value(node, "library", false, true);
     // check if it exists
     if (!file_exists(settings::path_source_library)) {
      	std::stringstream msg;
      	msg << "Library file " << settings::path_source_library << "' does not exist.";
	      fatal_error(msg);
     }
  } else {

    // Spatial distribution for external source
    if (check_for_node(node, "space")) {
      // Get pointer to spatial distribution
      pugi::xml_node node_space = node.child("space");

      // Check for type of spatial distribution and read
      std::string type;
      if (check_for_node(node_space, "type"))
        type = get_node_value(node_space, "type", true, true);
      if (type == "cartesian") {
        space_ = UPtrSpace{new CartesianIndependent(node_space)};
      } else if (type == "cylindrical") {
        space_ = UPtrSpace{new CylindricalIndependent(node_space)};
      } else if (type == "spherical") {
        space_ = UPtrSpace{new SphericalIndependent(node_space)};
      } else if (type == "box") {
        space_ = UPtrSpace{new SpatialBox(node_space)};
      } else if (type == "fission") {
        space_ = UPtrSpace{new SpatialBox(node_space, true)};
      } else if (type == "point") {
        space_ = UPtrSpace{new SpatialPoint(node_space)};
      } else {
        fatal_error(fmt::format(
          "Invalid spatial distribution for external source: {}", type));
      }

    } else {
      // If no spatial distribution specified, make it a point source
      space_ = UPtrSpace{new SpatialPoint()};
    }

    // Determine external source angular distribution
    if (check_for_node(node, "angle")) {
      // Get pointer to angular distribution
      pugi::xml_node node_angle = node.child("angle");

      // Check for type of angular distribution
      std::string type;
      if (check_for_node(node_angle, "type"))
        type = get_node_value(node_angle, "type", true, true);
      if (type == "isotropic") {
        angle_ = UPtrAngle{new Isotropic()};
      } else if (type == "monodirectional") {
        angle_ = UPtrAngle{new Monodirectional(node_angle)};
      } else if (type == "mu-phi") {
        angle_ = UPtrAngle{new PolarAzimuthal(node_angle)};
      } else {
        fatal_error(fmt::format(
          "Invalid angular distribution for external source: {}", type));
      }

    } else {
      angle_ = UPtrAngle{new Isotropic()};
    }

    // Determine external source energy distribution
    if (check_for_node(node, "energy")) {
      pugi::xml_node node_dist = node.child("energy");
      energy_ = distribution_from_xml(node_dist);
    } else {
      // Default to a Watt spectrum with parameters 0.988 MeV and 2.249 MeV^-1
      energy_ = UPtrDist{new Watt(0.988e6, 2.249e-6)};
    }
  }
}

Particle::Bank SourceDistribution::sample(uint64_t* seed) const
{
  Particle::Bank site;

  // Set weight to one by default
  site.wgt = 1.0;

  // Repeat sampling source location until a good site has been found
  bool found = false;
  int n_reject = 0;
  static int n_accept = 0;
  while (!found) {
    // Set particle type
    site.particle = particle_;

    // Sample spatial distribution
    site.r = space_->sample(seed);
    double xyz[] {site.r.x, site.r.y, site.r.z};

    // Now search to see if location exists in geometry
    int32_t cell_index, instance;
    int err = openmc_find_cell(xyz, &cell_index, &instance);
    found = (err != OPENMC_E_GEOMETRY);

    // Check if spatial site is in fissionable material
    if (found) {
      auto space_box = dynamic_cast<SpatialBox*>(space_.get());
      if (space_box) {
        if (space_box->only_fissionable()) {
          // Determine material
          const auto& c = model::cells[cell_index];
          auto mat_index = c->material_.size() == 1
            ? c->material_[0] : c->material_[instance];

          if (mat_index == MATERIAL_VOID) {
            found = false;
          } else {
            if (!model::materials[mat_index]->fissionable_) found = false;
          }
        }
      }
    }

    // Check for rejection
    if (!found) {
      ++n_reject;
      if (n_reject >= EXTSRC_REJECT_THRESHOLD &&
          static_cast<double>(n_accept)/n_reject <= EXTSRC_REJECT_FRACTION) {
        fatal_error("More than 95% of external source sites sampled were "
                    "rejected. Please check your external source definition.");
      }
    }
  }

  // Increment number of accepted samples
  ++n_accept;

  // Sample angle
  site.u = angle_->sample(seed);

  // Check for monoenergetic source above maximum particle energy
  auto p = static_cast<int>(particle_);
  auto energy_ptr = dynamic_cast<Discrete*>(energy_.get());
  if (energy_ptr) {
    auto energies = xt::adapt(energy_ptr->x());
    if (xt::any(energies > data::energy_max[p])) {
      fatal_error("Source energy above range of energies of at least "
                  "one cross section table");
    } else if (xt::any(energies < data::energy_min[p])) {
      fatal_error("Source energy below range of energies of at least "
                  "one cross section table");
    }
  }

  while (true) {
    // Sample energy spectrum
    site.E = energy_->sample(seed);

    // Resample if energy falls outside minimum or maximum particle energy
    if (site.E < data::energy_max[p] && site.E > data::energy_min[p]) break;
  }

  // Set delayed group
  site.delayed_group = 0;

  return site;
}

//==============================================================================
// Non-member functions
//==============================================================================

void initialize_source()
{
  write_message("Initializing source particles...", 5);

  if (settings::path_source != "") {
    // Read the source from a binary file instead of sampling from some
    // assumed source distribution

    write_message(fmt::format("Reading source file from {}...",
      settings::path_source), 6);

    // Open the binary file
    hid_t file_id = file_open(settings::path_source, 'r', true);

    // Read the file type
    std::string filetype;
    read_attribute(file_id, "filetype", filetype);

    // Check to make sure this is a source file
    if (filetype != "source" && filetype != "statepoint") {
      fatal_error("Specified starting source file not a source file type.");
    }

    // Read in the source bank
    read_source_bank(file_id);

    // Close file
    file_close(file_id);
  } else if ( settings::path_source_library != "" ) {
    // Get the source from a library object

    std::stringstream msg;
    msg << "Sampling from library source " << settings::path_source << "...";
    write_message(msg, 6);

    #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
    // Open the library
    void* source_library = dlopen(settings::path_source_library.c_str(),RTLD_LAZY);
    if(!source_library) {
      std::stringstream msg("Couldnt open source library " + settings::path_source_library);
      fatal_error(msg);
    }
    #else
    std::stringstream msg("This feature has not yet been implemented for non POSIX systems");
    fatal_error(msg);
    #endif

    // load the symbol
    typedef Particle::Bank (*sample_t)(uint64_t *seed);

    // reset errors
    dlerror();

    // get the function from the library
    sample_t sample_source = (sample_t) dlsym(source_library, "sample_source");
    const char *dlsym_error = dlerror();

    // check for any dlsym errors
    if (dlsym_error) {
      std::cout << dlsym_error << std::endl;
      dlclose(source_library);
      fatal_error("Couldnt open the sample_source symbol");
    }

    // Generation source sites from specified distribution in the
    // library source
    for (int64_t i = 0; i < simulation::work_per_rank; ++i) {
      // initialize random number seed
      int64_t id = simulation::total_gen*settings::n_particles +
        simulation::work_index[mpi::rank] + i + 1;
      uint64_t seed = init_seed(id, STREAM_SOURCE);

      // sample external source distribution
      simulation::source_bank[i] = sample_source(&seed);
    }
    // release the library
    dlclose(source_library);

  } else {
    // Generation source sites from specified distribution in user input
    for (int64_t i = 0; i < simulation::work_per_rank; ++i) {
      // initialize random number seed
      int64_t id = simulation::total_gen*settings::n_particles +
        simulation::work_index[mpi::rank] + i + 1;
      uint64_t seed = init_seed(id, STREAM_SOURCE);

      // sample external source distribution
      simulation::source_bank[i] = sample_external_source(&seed);
    }
  }

  // Write out initial source
  if (settings::write_initial_source) {
    write_message("Writing out initial source...", 5);
    std::string filename = settings::path_output + "initial_source.h5";
    hid_t file_id = file_open(filename, 'w', true);
    write_source_bank(file_id);
    file_close(file_id);
  }
}

Particle::Bank sample_external_source(uint64_t* seed)
{
  // Determine total source strength
  double total_strength = 0.0;
  for (auto& s : model::external_sources)
    total_strength += s.strength();

  // Sample from among multiple source distributions
  int i = 0;
  if (model::external_sources.size() > 1) {
    double xi = prn(seed)*total_strength;
    double c = 0.0;
    for (; i < model::external_sources.size(); ++i) {
      c += model::external_sources[i].strength();
      if (xi < c) break;
    }
  }

  // Sample source site from i-th source distribution
  Particle::Bank site {model::external_sources[i].sample(seed)};

  // If running in MG, convert site.E to group
  if (!settings::run_CE) {
    site.E = lower_bound_index(data::mg.rev_energy_bins_.begin(),
      data::mg.rev_energy_bins_.end(), site.E);
    site.E = data::mg.num_energy_groups_ - site.E - 1.;
  }

  return site;
}

void free_memory_source()
{
  model::external_sources.clear();
}

void fill_source_bank_fixedsource()
{
  if (settings::path_source.empty() && settings::path_source_library.empty()) {
    for (int64_t i = 0; i < simulation::work_per_rank; ++i) {
      // initialize random number seed
      int64_t id = (simulation::total_gen + overall_generation()) *
        settings::n_particles + simulation::work_index[mpi::rank] + i + 1;
      uint64_t seed = init_seed(id, STREAM_SOURCE);

      // sample external source distribution
      simulation::source_bank[i] = sample_external_source(&seed);
    }
  } else if (settings::path_source.empty() && !settings::path_source.empty()) {
     std::stringstream msg;

    // Open the library
    void* source_library = dlopen(settings::path_source_library.c_str(),RTLD_LAZY);
    if(!source_library) {
      std::stringstream msg("Couldnt open source library " + settings::path_source_library);
      fatal_error(msg);
    }

    // load the symbol
    typedef Particle::Bank (*sample_t)(uint64_t *seed);

    // reset errors
    dlerror();

    // get the function from the library
    sample_t sample_source = (sample_t) dlsym(source_library, "sample_source");
    const char *dlsym_error = dlerror();

    // check for any dlsym errors
    if (dlsym_error) {
      std::cout << dlsym_error << std::endl;
      dlclose(source_library);
      fatal_error("Couldnt open the sample_source symbol");
    }

    // Generation source sites from specified distribution in the
    // library source
    for (int64_t i = 0; i < simulation::work_per_rank; ++i) {
      // initialize random number seed
      int64_t id = simulation::total_gen*settings::n_particles +
        simulation::work_index[mpi::rank] + i + 1;
      uint64_t seed = init_seed(id, STREAM_SOURCE);

      // sample external source distribution
      simulation::source_bank[i] = sample_source(&seed);
    }

    // release the library
    dlclose(source_library);
  }
}

} // namespace openmc
<|endoftext|>