<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include <algorithm>
#include <memory>

#include <boost/variant/variant.hpp>

#include "ast/VariablesAnnotator.hpp"
#include "ast/SourceFile.hpp"
#include "ast/TypeTransformer.hpp"
#include "ast/IsConstantVisitor.hpp"
#include "ast/ASTVisitor.hpp"

#include "SemanticalException.hpp"
#include "Context.hpp"
#include "GlobalContext.hpp"
#include "FunctionContext.hpp"
#include "Types.hpp"
#include "Variable.hpp"
#include "Utils.hpp"
#include "VisitorUtils.hpp"
#include "SymbolTable.hpp"

using namespace eddic;

struct VariablesVisitor : public boost::static_visitor<> {
    AUTO_RECURSE_PROGRAM()
    AUTO_RECURSE_FUNCTION_CALLS()
    AUTO_RECURSE_SIMPLE_LOOPS()
    AUTO_RECURSE_BRANCHES()
    AUTO_RECURSE_BINARY_CONDITION()
    AUTO_RECURSE_BUILTIN_OPERATORS()
    AUTO_RECURSE_MINUS_PLUS_VALUES()
    AUTO_RECURSE_CAST_VALUES()
    AUTO_RECURSE_RETURN_VALUES()

    AUTO_IGNORE_FALSE()
    AUTO_IGNORE_TRUE()
    AUTO_IGNORE_LITERAL()
    AUTO_IGNORE_FLOAT()
    AUTO_IGNORE_INTEGER()
    AUTO_IGNORE_INTEGER_SUFFIX()
    AUTO_IGNORE_IMPORT()
    AUTO_IGNORE_STANDARD_IMPORT()
    AUTO_IGNORE_STRUCT()

    void operator()(ast::FunctionDeclaration& declaration){
        //Add all the parameters to the function context
        for(auto& parameter : declaration.Content->parameters){
            Type type = visit(ast::TypeTransformer(), parameter.parameterType);

            declaration.Content->context->addParameter(parameter.parameterName, type);
        }

        visit_each(*this, declaration.Content->instructions);
    }

    void operator()(ast::GlobalVariableDeclaration& declaration){
        if (declaration.Content->context->exists(declaration.Content->variableName)) {
            throw SemanticalException("The global Variable " + declaration.Content->variableName + " has already been declared", declaration.Content->position);
        }

        if(!visit(ast::IsConstantVisitor(), *declaration.Content->value)){
            throw SemanticalException("The value must be constant", declaration.Content->position);
        }

        declaration.Content->context->addVariable(declaration.Content->variableName,
                newSimpleType(declaration.Content->variableType, declaration.Content->constant), *declaration.Content->value);
    }

    void operator()(ast::GlobalArrayDeclaration& declaration){
        if (declaration.Content->context->exists(declaration.Content->arrayName)) {
            throw SemanticalException("The global Variable " + declaration.Content->arrayName + " has already been declared", declaration.Content->position);
        }

        declaration.Content->context->addVariable(declaration.Content->arrayName, newArrayType(declaration.Content->arrayType, declaration.Content->arraySize));
    }

    void operator()(ast::Foreach& foreach){
        if(foreach.Content->context->exists(foreach.Content->variableName)){
            throw SemanticalException("The foreach variable " + foreach.Content->variableName  + " has already been declared", foreach.Content->position);
        }

        foreach.Content->context->addVariable(foreach.Content->variableName, newType(foreach.Content->variableType));

        visit_each(*this, foreach.Content->instructions);
    }

    void operator()(ast::ForeachIn& foreach){
        if(foreach.Content->context->exists(foreach.Content->variableName)){
            throw SemanticalException("The foreach variable " + foreach.Content->variableName  + " has already been declared", foreach.Content->position);
        }

        if(!foreach.Content->context->exists(foreach.Content->arrayName)){
            throw SemanticalException("The foreach array " + foreach.Content->arrayName  + " has not been declared", foreach.Content->position);
        }

        static int generated = 0;

        foreach.Content->var = foreach.Content->context->addVariable(foreach.Content->variableName, newType(foreach.Content->variableType));
        foreach.Content->arrayVar = foreach.Content->context->getVariable(foreach.Content->arrayName);
        foreach.Content->iterVar = foreach.Content->context->addVariable("foreach_iter_" + toString(++generated), newType("int"));

        visit_each(*this, foreach.Content->instructions);
    }

    template<typename A>
    void annotateAssignment(A& assignment){
        if (!assignment.Content->context->exists(assignment.Content->variableName)) {
            throw SemanticalException("Variable " + assignment.Content->variableName + " has not  been declared", assignment.Content->position);
        }

        visit(*this, assignment.Content->value);

        assignment.Content->context->getVariable(assignment.Content->variableName)->addReference();
    }

    void operator()(ast::Assignment& assignment){
        annotateAssignment(assignment);
    }

    void operator()(ast::CompoundAssignment& assignment){
        annotateAssignment(assignment);
    }

    void operator()(ast::StructCompoundAssignment& assignment){
        annotateAssignment(assignment);
    }

    void operator()(ast::StructAssignment& assignment){
        annotateAssignment(assignment);

        auto var = (*assignment.Content->context)[assignment.Content->variableName];
        auto struct_name = var->type().type();
        auto struct_type = symbols.get_struct(struct_name);

        //Add a reference to the struct
        struct_type->add_reference();

        auto& members = assignment.Content->memberNames;
        for(std::size_t i = 0; i < members.size(); ++i){
            auto& member = members[i];

            if(!struct_type->member_exists(member)){
                throw SemanticalException("The struct " + struct_name + " has no member named " + member, assignment.Content->position);
            }

            //Add a reference to the member
            (*struct_type)[member]->add_reference();

            //If it is not the last member
            if(i != members.size() - 1){
                //The next member will be a member of the current member type
                struct_type = symbols.get_struct((*struct_type)[member]->type.type());
                struct_name = struct_type->name;
            }
        }
    }

    template<typename Operation>
    void annotateSuffixOrPrefixOperation(Operation& operation){
        if (!operation.Content->context->exists(operation.Content->variableName)) {
            throw SemanticalException("Variable " + operation.Content->variableName + " has not  been declared", operation.Content->position);
        }

        operation.Content->variable = operation.Content->context->getVariable(operation.Content->variableName);
        operation.Content->variable->addReference();
    }

    void operator()(ast::SuffixOperation& operation){
        annotateSuffixOrPrefixOperation(operation);
    }

    void operator()(ast::PrefixOperation& operation){
        annotateSuffixOrPrefixOperation(operation);
    }

    void operator()(ast::ArrayAssignment& assignment){
        if (!assignment.Content->context->exists(assignment.Content->variableName)) {
            throw SemanticalException("Array " + assignment.Content->variableName + " has not  been declared", assignment.Content->position);
        }

        visit(*this, assignment.Content->indexValue);
        visit(*this, assignment.Content->value);

        assignment.Content->context->getVariable(assignment.Content->variableName)->addReference();
    }

    void operator()(ast::VariableDeclaration& declaration){
        if (declaration.Content->context->exists(declaration.Content->variableName)) {
            throw SemanticalException("Variable " + declaration.Content->variableName + " has already been declared", declaration.Content->position);
        }

        visit_optional(*this, declaration.Content->value);

        //If it's a standard type
        if(is_standard_type(declaration.Content->variableType)){
            Type type = newSimpleType(declaration.Content->variableType, declaration.Content->const_);

            if(type.isConst()){
                if(!declaration.Content->value){
                    throw SemanticalException("A constant variable must have a value", declaration.Content->position);
                }

                if(!visit(ast::IsConstantVisitor(), *declaration.Content->value)){
                    throw SemanticalException("The value must be constant", declaration.Content->position);
                }

                declaration.Content->context->addVariable(declaration.Content->variableName, type, *declaration.Content->value);
            } else {
                declaration.Content->context->addVariable(declaration.Content->variableName, type);
            }
        }
        //If it's a custom type
        else {
            if(symbols.struct_exists(declaration.Content->variableType)){
                if(declaration.Content->const_){
                    throw SemanticalException("Custom types cannot be const", declaration.Content->position);
                }

                Type type = new_custom_type(declaration.Content->variableType);

                declaration.Content->context->addVariable(declaration.Content->variableName, type);
            } else {
                throw SemanticalException("The type \"" + declaration.Content->variableType + "\" does not exists", declaration.Content->position);
            }
        }
    }

    void operator()(ast::ArrayDeclaration& declaration){
        if (declaration.Content->context->exists(declaration.Content->arrayName)) {
            throw SemanticalException("The variable " + declaration.Content->arrayName + " has already been declared", declaration.Content->position);
        }

        Type type = newArrayType(declaration.Content->arrayType, declaration.Content->arraySize);
        declaration.Content->context->addVariable(declaration.Content->arrayName, type);
    }

    void operator()(ast::Swap& swap){
        if (swap.Content->lhs == swap.Content->rhs) {
            throw SemanticalException("Cannot swap a variable with itself", swap.Content->position);
        }

        if (!swap.Content->context->exists(swap.Content->lhs) || !swap.Content->context->exists(swap.Content->rhs)) {
            throw SemanticalException("Variable has not been declared in the swap", swap.Content->position);
        }

        swap.Content->lhs_var = swap.Content->context->getVariable(swap.Content->lhs);
        swap.Content->rhs_var = swap.Content->context->getVariable(swap.Content->rhs);

        //Reference both variables
        swap.Content->lhs_var->addReference();
        swap.Content->rhs_var->addReference();
    }

    void operator()(ast::VariableValue& variable){
        if (!variable.Content->context->exists(variable.Content->variableName)) {
            throw SemanticalException("Variable " + variable.Content->variableName + " has not been declared", variable.Content->position);
        }

        //Reference the variable
        variable.Content->var = variable.Content->context->getVariable(variable.Content->variableName);
        variable.Content->var->addReference();
    }

    void operator()(ast::StructValue& struct_){
        if (!struct_.Content->context->exists(struct_.Content->variableName)) {
            throw SemanticalException("Variable " + struct_.Content->variableName + " has not been declared", struct_.Content->position);
        }

        auto var = (*struct_.Content->context)[struct_.Content->variableName];
        auto struct_name = var->type().type();
        auto struct_type = symbols.get_struct(struct_name);

        if(!struct_type->member_exists(struct_.Content->memberNames[0])){ //TODO Handle several members
            throw SemanticalException("The struct " + struct_name + " has no member named " + struct_.Content->memberNames[0], struct_.Content->position);
        }

        //Reference the variable
        struct_.Content->variable = var;
        struct_.Content->variable->addReference();

        //Reference the member
        struct_type->add_reference();
        (*struct_type)[struct_.Content->memberNames[0]]->add_reference();
    }

    void operator()(ast::ArrayValue& array){
        if (!array.Content->context->exists(array.Content->arrayName)) {
            throw SemanticalException("Array " + array.Content->arrayName + " has not been declared", array.Content->position);
        }

        //Reference the variable
        array.Content->var = array.Content->context->getVariable(array.Content->arrayName);
        array.Content->var->addReference();

        visit(*this, array.Content->indexValue);
    }

    void operator()(ast::Expression& value){
        visit(*this, value.Content->first);

        for_each(value.Content->operations.begin(), value.Content->operations.end(),
            [&](ast::Operation& operation){ visit(*this, operation.get<1>()); });
    }
};

void ast::defineVariables(ast::SourceFile& program){
    VariablesVisitor visitor;
    visit_non_variant(visitor, program);
}
<commit_msg>Do the same verifications for struct compound assignment<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include <algorithm>
#include <memory>

#include <boost/variant/variant.hpp>

#include "ast/VariablesAnnotator.hpp"
#include "ast/SourceFile.hpp"
#include "ast/TypeTransformer.hpp"
#include "ast/IsConstantVisitor.hpp"
#include "ast/ASTVisitor.hpp"

#include "SemanticalException.hpp"
#include "Context.hpp"
#include "GlobalContext.hpp"
#include "FunctionContext.hpp"
#include "Types.hpp"
#include "Variable.hpp"
#include "Utils.hpp"
#include "VisitorUtils.hpp"
#include "SymbolTable.hpp"

using namespace eddic;

struct VariablesVisitor : public boost::static_visitor<> {
    AUTO_RECURSE_PROGRAM()
    AUTO_RECURSE_FUNCTION_CALLS()
    AUTO_RECURSE_SIMPLE_LOOPS()
    AUTO_RECURSE_BRANCHES()
    AUTO_RECURSE_BINARY_CONDITION()
    AUTO_RECURSE_BUILTIN_OPERATORS()
    AUTO_RECURSE_MINUS_PLUS_VALUES()
    AUTO_RECURSE_CAST_VALUES()
    AUTO_RECURSE_RETURN_VALUES()

    AUTO_IGNORE_FALSE()
    AUTO_IGNORE_TRUE()
    AUTO_IGNORE_LITERAL()
    AUTO_IGNORE_FLOAT()
    AUTO_IGNORE_INTEGER()
    AUTO_IGNORE_INTEGER_SUFFIX()
    AUTO_IGNORE_IMPORT()
    AUTO_IGNORE_STANDARD_IMPORT()
    AUTO_IGNORE_STRUCT()

    void operator()(ast::FunctionDeclaration& declaration){
        //Add all the parameters to the function context
        for(auto& parameter : declaration.Content->parameters){
            Type type = visit(ast::TypeTransformer(), parameter.parameterType);

            declaration.Content->context->addParameter(parameter.parameterName, type);
        }

        visit_each(*this, declaration.Content->instructions);
    }

    void operator()(ast::GlobalVariableDeclaration& declaration){
        if (declaration.Content->context->exists(declaration.Content->variableName)) {
            throw SemanticalException("The global Variable " + declaration.Content->variableName + " has already been declared", declaration.Content->position);
        }

        if(!visit(ast::IsConstantVisitor(), *declaration.Content->value)){
            throw SemanticalException("The value must be constant", declaration.Content->position);
        }

        declaration.Content->context->addVariable(declaration.Content->variableName,
                newSimpleType(declaration.Content->variableType, declaration.Content->constant), *declaration.Content->value);
    }

    void operator()(ast::GlobalArrayDeclaration& declaration){
        if (declaration.Content->context->exists(declaration.Content->arrayName)) {
            throw SemanticalException("The global Variable " + declaration.Content->arrayName + " has already been declared", declaration.Content->position);
        }

        declaration.Content->context->addVariable(declaration.Content->arrayName, newArrayType(declaration.Content->arrayType, declaration.Content->arraySize));
    }

    void operator()(ast::Foreach& foreach){
        if(foreach.Content->context->exists(foreach.Content->variableName)){
            throw SemanticalException("The foreach variable " + foreach.Content->variableName  + " has already been declared", foreach.Content->position);
        }

        foreach.Content->context->addVariable(foreach.Content->variableName, newType(foreach.Content->variableType));

        visit_each(*this, foreach.Content->instructions);
    }

    void operator()(ast::ForeachIn& foreach){
        if(foreach.Content->context->exists(foreach.Content->variableName)){
            throw SemanticalException("The foreach variable " + foreach.Content->variableName  + " has already been declared", foreach.Content->position);
        }

        if(!foreach.Content->context->exists(foreach.Content->arrayName)){
            throw SemanticalException("The foreach array " + foreach.Content->arrayName  + " has not been declared", foreach.Content->position);
        }

        static int generated = 0;

        foreach.Content->var = foreach.Content->context->addVariable(foreach.Content->variableName, newType(foreach.Content->variableType));
        foreach.Content->arrayVar = foreach.Content->context->getVariable(foreach.Content->arrayName);
        foreach.Content->iterVar = foreach.Content->context->addVariable("foreach_iter_" + toString(++generated), newType("int"));

        visit_each(*this, foreach.Content->instructions);
    }

    template<typename A>
    void annotateAssignment(A& assignment){
        if (!assignment.Content->context->exists(assignment.Content->variableName)) {
            throw SemanticalException("Variable " + assignment.Content->variableName + " has not  been declared", assignment.Content->position);
        }

        visit(*this, assignment.Content->value);

        assignment.Content->context->getVariable(assignment.Content->variableName)->addReference();
    }

    void operator()(ast::Assignment& assignment){
        annotateAssignment(assignment);
    }

    void operator()(ast::CompoundAssignment& assignment){
        annotateAssignment(assignment);
    }

    template<typename A>
    void verify_struct_assignment(A& assignment){
        annotateAssignment(assignment);

        auto var = (*assignment.Content->context)[assignment.Content->variableName];
        auto struct_name = var->type().type();
        auto struct_type = symbols.get_struct(struct_name);

        //Add a reference to the struct
        struct_type->add_reference();

        auto& members = assignment.Content->memberNames;
        for(std::size_t i = 0; i < members.size(); ++i){
            auto& member = members[i];

            if(!struct_type->member_exists(member)){
                throw SemanticalException("The struct " + struct_name + " has no member named " + member, assignment.Content->position);
            }

            //Add a reference to the member
            (*struct_type)[member]->add_reference();

            //If it is not the last member
            if(i != members.size() - 1){
                //The next member will be a member of the current member type
                struct_type = symbols.get_struct((*struct_type)[member]->type.type());
                struct_name = struct_type->name;
            }
        }
    }

    void operator()(ast::StructCompoundAssignment& assignment){
        verify_struct_assignment(assignment);
    }

    void operator()(ast::StructAssignment& assignment){
        verify_struct_assignment(assignment);
    }

    template<typename Operation>
    void annotateSuffixOrPrefixOperation(Operation& operation){
        if (!operation.Content->context->exists(operation.Content->variableName)) {
            throw SemanticalException("Variable " + operation.Content->variableName + " has not  been declared", operation.Content->position);
        }

        operation.Content->variable = operation.Content->context->getVariable(operation.Content->variableName);
        operation.Content->variable->addReference();
    }

    void operator()(ast::SuffixOperation& operation){
        annotateSuffixOrPrefixOperation(operation);
    }

    void operator()(ast::PrefixOperation& operation){
        annotateSuffixOrPrefixOperation(operation);
    }

    void operator()(ast::ArrayAssignment& assignment){
        if (!assignment.Content->context->exists(assignment.Content->variableName)) {
            throw SemanticalException("Array " + assignment.Content->variableName + " has not  been declared", assignment.Content->position);
        }

        visit(*this, assignment.Content->indexValue);
        visit(*this, assignment.Content->value);

        assignment.Content->context->getVariable(assignment.Content->variableName)->addReference();
    }

    void operator()(ast::VariableDeclaration& declaration){
        if (declaration.Content->context->exists(declaration.Content->variableName)) {
            throw SemanticalException("Variable " + declaration.Content->variableName + " has already been declared", declaration.Content->position);
        }

        visit_optional(*this, declaration.Content->value);

        //If it's a standard type
        if(is_standard_type(declaration.Content->variableType)){
            Type type = newSimpleType(declaration.Content->variableType, declaration.Content->const_);

            if(type.isConst()){
                if(!declaration.Content->value){
                    throw SemanticalException("A constant variable must have a value", declaration.Content->position);
                }

                if(!visit(ast::IsConstantVisitor(), *declaration.Content->value)){
                    throw SemanticalException("The value must be constant", declaration.Content->position);
                }

                declaration.Content->context->addVariable(declaration.Content->variableName, type, *declaration.Content->value);
            } else {
                declaration.Content->context->addVariable(declaration.Content->variableName, type);
            }
        }
        //If it's a custom type
        else {
            if(symbols.struct_exists(declaration.Content->variableType)){
                if(declaration.Content->const_){
                    throw SemanticalException("Custom types cannot be const", declaration.Content->position);
                }

                Type type = new_custom_type(declaration.Content->variableType);

                declaration.Content->context->addVariable(declaration.Content->variableName, type);
            } else {
                throw SemanticalException("The type \"" + declaration.Content->variableType + "\" does not exists", declaration.Content->position);
            }
        }
    }

    void operator()(ast::ArrayDeclaration& declaration){
        if (declaration.Content->context->exists(declaration.Content->arrayName)) {
            throw SemanticalException("The variable " + declaration.Content->arrayName + " has already been declared", declaration.Content->position);
        }

        Type type = newArrayType(declaration.Content->arrayType, declaration.Content->arraySize);
        declaration.Content->context->addVariable(declaration.Content->arrayName, type);
    }

    void operator()(ast::Swap& swap){
        if (swap.Content->lhs == swap.Content->rhs) {
            throw SemanticalException("Cannot swap a variable with itself", swap.Content->position);
        }

        if (!swap.Content->context->exists(swap.Content->lhs) || !swap.Content->context->exists(swap.Content->rhs)) {
            throw SemanticalException("Variable has not been declared in the swap", swap.Content->position);
        }

        swap.Content->lhs_var = swap.Content->context->getVariable(swap.Content->lhs);
        swap.Content->rhs_var = swap.Content->context->getVariable(swap.Content->rhs);

        //Reference both variables
        swap.Content->lhs_var->addReference();
        swap.Content->rhs_var->addReference();
    }

    void operator()(ast::VariableValue& variable){
        if (!variable.Content->context->exists(variable.Content->variableName)) {
            throw SemanticalException("Variable " + variable.Content->variableName + " has not been declared", variable.Content->position);
        }

        //Reference the variable
        variable.Content->var = variable.Content->context->getVariable(variable.Content->variableName);
        variable.Content->var->addReference();
    }

    void operator()(ast::StructValue& struct_){
        if (!struct_.Content->context->exists(struct_.Content->variableName)) {
            throw SemanticalException("Variable " + struct_.Content->variableName + " has not been declared", struct_.Content->position);
        }

        auto var = (*struct_.Content->context)[struct_.Content->variableName];
        auto struct_name = var->type().type();
        auto struct_type = symbols.get_struct(struct_name);

        if(!struct_type->member_exists(struct_.Content->memberNames[0])){ //TODO Handle several members
            throw SemanticalException("The struct " + struct_name + " has no member named " + struct_.Content->memberNames[0], struct_.Content->position);
        }

        //Reference the variable
        struct_.Content->variable = var;
        struct_.Content->variable->addReference();

        //Reference the member
        struct_type->add_reference();
        (*struct_type)[struct_.Content->memberNames[0]]->add_reference();
    }

    void operator()(ast::ArrayValue& array){
        if (!array.Content->context->exists(array.Content->arrayName)) {
            throw SemanticalException("Array " + array.Content->arrayName + " has not been declared", array.Content->position);
        }

        //Reference the variable
        array.Content->var = array.Content->context->getVariable(array.Content->arrayName);
        array.Content->var->addReference();

        visit(*this, array.Content->indexValue);
    }

    void operator()(ast::Expression& value){
        visit(*this, value.Content->first);

        for_each(value.Content->operations.begin(), value.Content->operations.end(),
            [&](ast::Operation& operation){ visit(*this, operation.get<1>()); });
    }
};

void ast::defineVariables(ast::SourceFile& program){
    VariablesVisitor visitor;
    visit_non_variant(visitor, program);
}
<|endoftext|>


<commit_before>/*!
   \file ViewManager.cpp
   \author Dane Gardner <dane.gardner@gmail.com>

   \section LICENSE
   This file is part of the Parallel Tools GUI Framework (PTGF)
   Copyright (C) 2010-2013 Argo Navis Technologies, LLC

   This library is free software; you can redistribute it and/or modify it
   under the terms of the GNU Lesser General Public License as published by the
   Free Software Foundation; either version 2.1 of the License, or (at your
   option) any later version.

   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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "ViewManagerPrivate.h"

#include <QDebug>

#include <PluginManager/PluginManager.h>

#include "AbstractView.h"
#include "IViewFactory.h"

namespace Core {
namespace ViewManager {

ViewManager &ViewManager::instance()
{
    static ViewManager m_Instance;
    return m_Instance;
}

/*!
   \internal
   \brief ViewManager::ViewManager
 */
ViewManager::ViewManager() :
    QObject(0),
    d(new ViewManagerPrivate)
{
    d->q = this;
}

/*!
   \internal
   \brief ViewManager::~ViewManager
 */
ViewManager::~ViewManager()
{
}

/*!
   \internal
   \brief ViewManager::initialize
   \return true if successful
 */
bool ViewManager::initialize()
{
    if(d->m_Initialized) {
        return false;
    }

    try {

        PluginManager::PluginManager &pluginManager = PluginManager::PluginManager::instance();
        pluginManager.addObject(this);

        /* Check the object pool for anything we should manage */
        foreach(QObject *object, pluginManager.allObjects()) { d->pluginObjectRegistered(object); }
        connect(&pluginManager, SIGNAL(objectAdded(QObject*)), d.data(), SLOT(pluginObjectRegistered(QObject*)));
        connect(&pluginManager, SIGNAL(objectRemoving(QObject*)), d.data(), SLOT(pluginObjectDeregistered(QObject*)));

    } catch(...) {
        return false;
    }

    return d->m_Initialized = true;
}

/*!
   \internal
   \brief ViewManager::shutdown
 */
void ViewManager::shutdown()
{
    if(!d->m_Initialized) {
        return;
    }

    // ...
}

/*!
   \fn ViewManager::viewNames

   \brief Returns a list of names of views that can handle the supplied model.

   A NULL model will return all names.

   \param model
   \return
   \sa viewWidget
 */
QStringList ViewManager::viewNames(QAbstractItemModel *model)
{
    QStringList nameList;
    foreach(IViewFactory *viewPlugin, d->m_viewFactories.values()) {
        if(model) {
            if(viewPlugin->viewHandles(model)) {
                nameList.append(viewPlugin->viewName());
            }
        } else {
            nameList.append(viewPlugin->viewName());
        }
    }
    return nameList;
}

/*!
   \fn ViewManager::viewWidget

   \brief Creates the specified view using the supplied model, and returns it.

   You should not create a view from it's constructor directly, but rather from its associated IViewFactory
   through the ViewManager::viewWidget method.  For example:

   \code
   // Grab the instance of the ViewManager
   Core::ViewManager::ViewManager &viewManager = Core::ViewManager::ViewManager::instance();

   // Create your own data model
   QAbstractItemModel *model = new DataModel(data);

   // Check to see if this view can handle your model
   if(viewManager.viewNames(model).contains("A View Name")) {

       // Create the view using the model, and display it to the user
       QAbstractItemView *view = viewManager.viewWidget("A View Name", model);
       this->layout()->insertWidget(view);

   }
   \endcode

   If the creation should fail for some reason, a NULL pointer will be returned.  Failure can occur when: a name was
   not specified; a named view doesn't exist; a named view cannot handle the specified model.  A NULL model will not
   be checked, and will always return a view if it exists.

   The returned object does not have a parent, and should be immediately reparented, or deconstruction should be
   handled manually.

   \param name
   \param model
   \return
   \sa viewNames IViewFactory
 */
AbstractView *ViewManager::viewWidget(QString name, QAbstractItemModel *model)
{
    if(name.isEmpty()) {
        return NULL;
    }

    IViewFactory *viewPlugin = d->m_viewFactories.value(name, NULL);

    if(model != NULL && !viewPlugin->viewHandles(model)) {
        return NULL;
    }

    return viewPlugin->viewWidget(model);
}

/***** PRIVATE IMPLEMENTATION *****/
ViewManagerPrivate::ViewManagerPrivate() :
    QObject(NULL),
    m_Initialized(false)
{
}

void ViewManagerPrivate::registerViewFactory(IViewFactory *viewFactory)
{
    qDebug() << Q_FUNC_INFO << tr("Registering view: %1").arg(viewFactory->viewName());
    if(!m_viewFactories.contains(viewFactory->viewName())) {
        m_viewFactories.insert(viewFactory->viewName(), viewFactory);
    }
}

void ViewManagerPrivate::deregisterViewFactory(IViewFactory *viewFactory)
{
    if(m_viewFactories.contains(viewFactory->viewName())) {
        m_viewFactories.remove(viewFactory->viewName());
    }
}

void ViewManagerPrivate::pluginObjectRegistered(QObject *object)
{
    if(IViewFactory *viewFactory = qobject_cast<IViewFactory *>(object)) {
        registerViewFactory(viewFactory);
    }
}

void ViewManagerPrivate::pluginObjectDeregistered(QObject *object)
{
    if(IViewFactory *viewFactory = qobject_cast<IViewFactory *>(object)) {
        deregisterViewFactory(viewFactory);
    }
}

} // namespace ViewManager
} // namespace Core
<commit_msg>Fixed stray debug statement<commit_after>/*!
   \file ViewManager.cpp
   \author Dane Gardner <dane.gardner@gmail.com>

   \section LICENSE
   This file is part of the Parallel Tools GUI Framework (PTGF)
   Copyright (C) 2010-2013 Argo Navis Technologies, LLC

   This library is free software; you can redistribute it and/or modify it
   under the terms of the GNU Lesser General Public License as published by the
   Free Software Foundation; either version 2.1 of the License, or (at your
   option) any later version.

   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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "ViewManagerPrivate.h"

#include <QDebug>

#include <PluginManager/PluginManager.h>

#include "AbstractView.h"
#include "IViewFactory.h"

namespace Core {
namespace ViewManager {

ViewManager &ViewManager::instance()
{
    static ViewManager m_Instance;
    return m_Instance;
}

/*!
   \internal
   \brief ViewManager::ViewManager
 */
ViewManager::ViewManager() :
    QObject(0),
    d(new ViewManagerPrivate)
{
    d->q = this;
}

/*!
   \internal
   \brief ViewManager::~ViewManager
 */
ViewManager::~ViewManager()
{
}

/*!
   \internal
   \brief ViewManager::initialize
   \return true if successful
 */
bool ViewManager::initialize()
{
    if(d->m_Initialized) {
        return false;
    }

    try {

        PluginManager::PluginManager &pluginManager = PluginManager::PluginManager::instance();
        pluginManager.addObject(this);

        /* Check the object pool for anything we should manage */
        foreach(QObject *object, pluginManager.allObjects()) { d->pluginObjectRegistered(object); }
        connect(&pluginManager, SIGNAL(objectAdded(QObject*)), d.data(), SLOT(pluginObjectRegistered(QObject*)));
        connect(&pluginManager, SIGNAL(objectRemoving(QObject*)), d.data(), SLOT(pluginObjectDeregistered(QObject*)));

    } catch(...) {
        return false;
    }

    return d->m_Initialized = true;
}

/*!
   \internal
   \brief ViewManager::shutdown
 */
void ViewManager::shutdown()
{
    if(!d->m_Initialized) {
        return;
    }

    // ...
}

/*!
   \fn ViewManager::viewNames

   \brief Returns a list of names of views that can handle the supplied model.

   A NULL model will return all names.

   \param model
   \return
   \sa viewWidget
 */
QStringList ViewManager::viewNames(QAbstractItemModel *model)
{
    QStringList nameList;
    foreach(IViewFactory *viewPlugin, d->m_viewFactories.values()) {
        if(model) {
            if(viewPlugin->viewHandles(model)) {
                nameList.append(viewPlugin->viewName());
            }
        } else {
            nameList.append(viewPlugin->viewName());
        }
    }
    return nameList;
}

/*!
   \fn ViewManager::viewWidget

   \brief Creates the specified view using the supplied model, and returns it.

   You should not create a view from it's constructor directly, but rather from its associated IViewFactory
   through the ViewManager::viewWidget method.  For example:

   \code
   // Grab the instance of the ViewManager
   Core::ViewManager::ViewManager &viewManager = Core::ViewManager::ViewManager::instance();

   // Create your own data model
   QAbstractItemModel *model = new DataModel(data);

   // Check to see if this view can handle your model
   if(viewManager.viewNames(model).contains("A View Name")) {

       // Create the view using the model, and display it to the user
       QAbstractItemView *view = viewManager.viewWidget("A View Name", model);
       this->layout()->insertWidget(view);

   }
   \endcode

   If the creation should fail for some reason, a NULL pointer will be returned.  Failure can occur when: a name was
   not specified; a named view doesn't exist; a named view cannot handle the specified model.  A NULL model will not
   be checked, and will always return a view if it exists.

   The returned object does not have a parent, and should be immediately reparented, or deconstruction should be
   handled manually.

   \param name
   \param model
   \return
   \sa viewNames IViewFactory
 */
AbstractView *ViewManager::viewWidget(QString name, QAbstractItemModel *model)
{
    if(name.isEmpty()) {
        return NULL;
    }

    IViewFactory *viewPlugin = d->m_viewFactories.value(name, NULL);

    if(model != NULL && !viewPlugin->viewHandles(model)) {
        return NULL;
    }

    return viewPlugin->viewWidget(model);
}

/***** PRIVATE IMPLEMENTATION *****/
ViewManagerPrivate::ViewManagerPrivate() :
    QObject(NULL),
    m_Initialized(false)
{
}

void ViewManagerPrivate::registerViewFactory(IViewFactory *viewFactory)
{
    if(!m_viewFactories.contains(viewFactory->viewName())) {
        m_viewFactories.insert(viewFactory->viewName(), viewFactory);
    }
}

void ViewManagerPrivate::deregisterViewFactory(IViewFactory *viewFactory)
{
    if(m_viewFactories.contains(viewFactory->viewName())) {
        m_viewFactories.remove(viewFactory->viewName());
    }
}

void ViewManagerPrivate::pluginObjectRegistered(QObject *object)
{
    if(IViewFactory *viewFactory = qobject_cast<IViewFactory *>(object)) {
        registerViewFactory(viewFactory);
    }
}

void ViewManagerPrivate::pluginObjectDeregistered(QObject *object)
{
    if(IViewFactory *viewFactory = qobject_cast<IViewFactory *>(object)) {
        deregisterViewFactory(viewFactory);
    }
}

} // namespace ViewManager
} // namespace Core
<|endoftext|>


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

#include <SNR.hpp>

namespace PulsarSearch {

snrConf::snrConf() : nrThreadsD0(0), nrItemsD0(0) {}

snrConf::~snrConf() {}

std::string snrConf::print() const {
  return isa::utils::toString(nrThreadsD0) + " " + isa::utils::toString(nrItemsD0);
}

void readTunedSNRConf(tunedSNRConf & tunedSNR, const std::string & snrFilename) {
  unsigned int nrDMs = 0;
  unsigned int nrSamples = 0;
  std::string temp;
  std::string deviceName;
  PulsarSearch::snrConf * parameters = 0;
  std::ifstream snrFile;

  snrFile.open(snrFilename);
  while ( ! snrFile.eof() ) {
    unsigned int splitPoint = 0;

    std::getline(snrFile, temp);
    if ( ! std::isalpha(temp[0]) ) {
      continue;
    }
    parameters = new PulsarSearch::snrConf();

    splitPoint = temp.find(" ");
    deviceName = temp.substr(0, splitPoint);
    temp = temp.substr(splitPoint + 1);
    splitPoint = temp.find(" ");
    nrDMs = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));
    temp = temp.substr(splitPoint + 1);
    splitPoint = temp.find(" ");
    nrSamples = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));
    temp = temp.substr(splitPoint + 1);
    splitPoint = temp.find(" ");
    parameters->setNrThreadsD0(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));
    temp = temp.substr(splitPoint + 1);
    parameters->setNrItemsD0(isa::utils::castToType< std::string, unsigned int >(temp));

		if ( tunedSNR.count(deviceName) == 0 ) {
      std::map< unsigned int, std::map< unsigned int, PulsarSearch::snrConf * > * > * externalContainer = new std::map< unsigned int, std::map< unsigned int, PulsarSearch::snrConf * > * >();
      std::map< unsigned int, PulsarSearch::snrConf * > * internalContainer = new std::map< unsigned int, PulsarSearch::snrConf * >();

			internalContainer->insert(std::make_pair(nrSamples, parameters));
			externalContainer->insert(std::make_pair(nrDMs, internalContainer));
			tunedSNR.insert(std::make_pair(deviceName, externalContainer));
		} else if ( tunedSNR.at(deviceName)->count(nrDMs) == 0 ) {
      std::map< unsigned int, PulsarSearch::snrConf * > * internalContainer = new std::map< unsigned int, PulsarSearch::snrConf * >();

			internalContainer->insert(std::make_pair(nrSamples, parameters));
			tunedSNR.at(deviceName)->insert(std::make_pair(nrDMs, internalContainer));
		} else {
			tunedSNR.at(deviceName)->at(nrDMs)->insert(std::make_pair(nrSamples, parameters));
		}
  }
  snrFile.close();
}

void readTunedSNRDedispersedConf(tunedSNRDedispersedConf & tunedSNR, const std::string & snrFilename) {
	std::string temp;
	std::ifstream snrFile(snrFilename);

	while ( ! snrFile.eof() ) {
		unsigned int splitPoint = 0;

		std::getline(snrFile, temp);
		if ( ! std::isalpha(temp[0]) ) {
			continue;
		}
		std::string deviceName;
		unsigned int nrDMs = 0;
    PulsarSearch::snrDedispersedConf parameters;

		splitPoint = temp.find(" ");
		deviceName = temp.substr(0, splitPoint);
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		nrDMs = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		parameters.setNrDMsPerBlock(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		parameters.setNrDMsPerThread(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));

		if ( tunedSNR.count(deviceName) == 0 ) {
      std::map< unsigned int, PulsarSearch::snrDedispersedConf > container;

			container.insert(std::make_pair(nrDMs, parameters));
			tunedSNR.insert(std::make_pair(deviceName, container));
		} else {
			tunedSNR[deviceName].insert(std::make_pair(nrDMs, parameters));
		}
	}
}

void readTunedSNRFoldedConf(tunedSNRFoldedConf & tunedSNR, const std::string & snrFilename) {
	std::string temp;
	std::ifstream snrFile(snrFilename);

	while ( ! snrFile.eof() ) {
		unsigned int splitPoint = 0;

		std::getline(snrFile, temp);
		if ( ! std::isalpha(temp[0]) ) {
			continue;
		}
		std::string deviceName;
		unsigned int nrDMs = 0;
		unsigned int nrPeriods = 0;
    PulsarSearch::snrFoldedConf parameters;

		splitPoint = temp.find(" ");
		deviceName = temp.substr(0, splitPoint);
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		nrDMs = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		nrPeriods = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		parameters.setNrDMsPerBlock(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		parameters.setNrPeriodsPerBlock(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		parameters.setNrDMsPerThread(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));
		temp = temp.substr(splitPoint + 1);
		parameters.setNrPeriodsPerThread(isa::utils::castToType< std::string, unsigned int >(temp));

		if ( tunedSNR.count(deviceName) == 0 ) {
      std::map< unsigned int, std::map< unsigned int, PulsarSearch::snrFoldedConf > > externalContainer;
      std::map< unsigned int, PulsarSearch::snrFoldedConf > internalContainer;

			internalContainer.insert(std::make_pair(nrPeriods, parameters));
			externalContainer.insert(std::make_pair(nrDMs, internalContainer));
			tunedSNR.insert(std::make_pair(deviceName, externalContainer));
		} else if ( tunedSNR[deviceName].count(nrDMs) == 0 ) {
      std::map< unsigned int, PulsarSearch::snrFoldedConf > internalContainer;

			internalContainer.insert(std::make_pair(nrPeriods, parameters));
			tunedSNR[deviceName].insert(std::make_pair(nrDMs, internalContainer));
		} else {
			tunedSNR[deviceName][nrDMs].insert(std::make_pair(nrPeriods, parameters));
		}
	}
}

} // PulsarSearch

<commit_msg>Removing spurious parts introduced during the merge.<commit_after>// Copyright 2015 Alessio Sclocco <a.sclocco@vu.nl>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <SNR.hpp>

namespace PulsarSearch {

snrConf::snrConf() : nrThreadsD0(0), nrItemsD0(0) {}

snrConf::~snrConf() {}

std::string snrConf::print() const {
  return isa::utils::toString(nrThreadsD0) + " " + isa::utils::toString(nrItemsD0);
}

void readTunedSNRConf(tunedSNRConf & tunedSNR, const std::string & snrFilename) {
  unsigned int nrDMs = 0;
  unsigned int nrSamples = 0;
  std::string temp;
  std::string deviceName;
  PulsarSearch::snrConf * parameters = 0;
  std::ifstream snrFile;

  snrFile.open(snrFilename);
  while ( ! snrFile.eof() ) {
    unsigned int splitPoint = 0;

    std::getline(snrFile, temp);
    if ( ! std::isalpha(temp[0]) ) {
      continue;
    }
    parameters = new PulsarSearch::snrConf();

    splitPoint = temp.find(" ");
    deviceName = temp.substr(0, splitPoint);
    temp = temp.substr(splitPoint + 1);
    splitPoint = temp.find(" ");
    nrDMs = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));
    temp = temp.substr(splitPoint + 1);
    splitPoint = temp.find(" ");
    nrSamples = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));
    temp = temp.substr(splitPoint + 1);
    splitPoint = temp.find(" ");
    parameters->setNrThreadsD0(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));
    temp = temp.substr(splitPoint + 1);
    parameters->setNrItemsD0(isa::utils::castToType< std::string, unsigned int >(temp));

		if ( tunedSNR.count(deviceName) == 0 ) {
      std::map< unsigned int, std::map< unsigned int, PulsarSearch::snrConf * > * > * externalContainer = new std::map< unsigned int, std::map< unsigned int, PulsarSearch::snrConf * > * >();
      std::map< unsigned int, PulsarSearch::snrConf * > * internalContainer = new std::map< unsigned int, PulsarSearch::snrConf * >();

			internalContainer->insert(std::make_pair(nrSamples, parameters));
			externalContainer->insert(std::make_pair(nrDMs, internalContainer));
			tunedSNR.insert(std::make_pair(deviceName, externalContainer));
		} else if ( tunedSNR.at(deviceName)->count(nrDMs) == 0 ) {
      std::map< unsigned int, PulsarSearch::snrConf * > * internalContainer = new std::map< unsigned int, PulsarSearch::snrConf * >();

			internalContainer->insert(std::make_pair(nrSamples, parameters));
			tunedSNR.at(deviceName)->insert(std::make_pair(nrDMs, internalContainer));
		} else {
			tunedSNR.at(deviceName)->at(nrDMs)->insert(std::make_pair(nrSamples, parameters));
		}
  }
  snrFile.close();
}

void readTunedSNRDedispersedConf(tunedSNRDedispersedConf & tunedSNR, const std::string & snrFilename) {
	std::string temp;
	std::ifstream snrFile(snrFilename);

	while ( ! snrFile.eof() ) {
		unsigned int splitPoint = 0;

		std::getline(snrFile, temp);
		if ( ! std::isalpha(temp[0]) ) {
			continue;
		}
		std::string deviceName;
		unsigned int nrDMs = 0;
    PulsarSearch::snrDedispersedConf parameters;

		splitPoint = temp.find(" ");
		deviceName = temp.substr(0, splitPoint);
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		nrDMs = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		parameters.setNrDMsPerBlock(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));
		temp = temp.substr(splitPoint + 1);
		splitPoint = temp.find(" ");
		parameters.setNrDMsPerThread(isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)));

		if ( tunedSNR.count(deviceName) == 0 ) {
      std::map< unsigned int, PulsarSearch::snrDedispersedConf > container;

			container.insert(std::make_pair(nrDMs, parameters));
			tunedSNR.insert(std::make_pair(deviceName, container));
		} else {
			tunedSNR[deviceName].insert(std::make_pair(nrDMs, parameters));
		}
	}
}

} // PulsarSearch

<|endoftext|>


<commit_before>#ifndef DUNE_DETAILED_SOLVERS_STATIONARY_LINEAR_ELLIPTIC_MODEL_PARAMETRIC_THERMALBLOCK_HH
#define DUNE_DETAILED_SOLVERS_STATIONARY_LINEAR_ELLIPTIC_MODEL_PARAMETRIC_THERMALBLOCK_HH

#ifdef HAVE_CMAKE_CONFIG
  #include "cmake_config.h"
#elif defined (HAVE_CONFIG_H)
  #include <config.h>
#endif // ifdef HAVE_CMAKE_CONFIG

#include <vector>

#include <dune/common/shared_ptr.hh>

#include <dune/stuff/common/parameter/tree.hh>
#include <dune/stuff/common/string.hh>
#include <dune/stuff/function/parametric/separable/checkerboard.hh>

#include "../../default.hh"
#include "default.hh"

namespace Dune {
namespace Detailed {
namespace Solvers {
namespace Stationary {
namespace Linear {
namespace Elliptic {
namespace Model {

template< class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim >
class SeparableThermalblock;

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

  typedef typename BaseType::DomainFieldType  DomainFieldType;
  static const int                            dimDomain = BaseType::dimDomain;
  typedef typename BaseType::RangeFieldType   RangeFieldType;
  static const int                            dimRange = BaseType::dimRange;
  typedef typename BaseType::ParamFieldType   ParamFieldType;
  static const int                            maxParamDim = BaseType::maxParamDim;

  typedef typename Dune::Stuff::Function::SeparableCheckerboard< DomainFieldType, dimDomain, RangeFieldType, dimRange >
                                          CheckerboardFunctionType;
  typedef typename BaseType::FunctionType FunctionType;

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

  SeparableThermalblock(const Dune::shared_ptr< const CheckerboardFunctionType > _diffusion,
                        const Dune::shared_ptr< const FunctionType > _force,
                        const Dune::shared_ptr< const FunctionType > _dirichlet,
                        const Dune::shared_ptr< const FunctionType > _neumann)
    : BaseType(_diffusion, _force, _dirichlet, _neumann)
  {}

  SeparableThermalblock(const ThisType& other)
    : BaseType(other.diffusion(),
               other.force(),
               other.dirichlet(),
               other.neumann())
  {}

  ThisType& operator=(const ThisType& other)
  {
    if (this != &other) {
      BaseType::operator=(other);
    }
    return *this;
  }

  static ThisType createFromDescription(const Dune::ParameterTree& _description, const std::string _subName = id())
  {
    // get correct description
    typedef Stuff::Common::ExtendedParameterTree DescriptionType;
    DescriptionType description;
    if (_description.hasSub(_subName))
      description = _description.sub(_subName);
    else
      description = _description;
    // create the checkerboard diffusion
    const DescriptionType diffusionDescription = description.sub("diffusion");
    const shared_ptr< const CheckerboardFunctionType > diffusion(new CheckerboardFunctionType(
        CheckerboardFunctionType::createFromDescription(diffusionDescription)));
    // create the rest of the functions
    //   * therefore create a fake diffusion subdescription,
    description.sub("diffusion") = CheckerboardFunctionType::createSampleDescription();
    description["diffusion.type"] = "function.parametric.separable.checkerboard";
    //   * create a default model
    const BaseType baseModel = BaseType::createFromDescription(description);
    // create and return
    return ThisType(diffusion,
                    baseModel.force(),
                    baseModel.dirichlet(),
                    baseModel.neumann());
  } // static ThisType createFromParamTree(const Dune::ParameterTree& paramTree, const std::string subName = id())
}; // class SeparableThermalblock

} // namespace Model
} // namespace Elliptic
} // namespace Linear
} // namespace Stationary
} // namespace Solvers
} // namespace Detailed
} // namespace Dune

#endif // DUNE_DETAILED_SOLVERS_STATIONARY_LINEAR_ELLIPTIC_MODEL_PARAMETRIC_THERMALBLOCK_HH
<commit_msg>[...elliptic.model...separable.thermalblock] added createSampleDescription()<commit_after>#ifndef DUNE_DETAILED_SOLVERS_STATIONARY_LINEAR_ELLIPTIC_MODEL_PARAMETRIC_THERMALBLOCK_HH
#define DUNE_DETAILED_SOLVERS_STATIONARY_LINEAR_ELLIPTIC_MODEL_PARAMETRIC_THERMALBLOCK_HH

#ifdef HAVE_CMAKE_CONFIG
  #include "cmake_config.h"
#elif defined (HAVE_CONFIG_H)
  #include <config.h>
#endif // ifdef HAVE_CMAKE_CONFIG

#include <vector>

#include <dune/common/shared_ptr.hh>

#include <dune/stuff/common/parameter/tree.hh>
#include <dune/stuff/common/string.hh>
#include <dune/stuff/function/parametric/separable/checkerboard.hh>
#include <dune/stuff/function.hh>

#include "../../default.hh"
#include "default.hh"

namespace Dune {
namespace Detailed {
namespace Solvers {
namespace Stationary {
namespace Linear {
namespace Elliptic {
namespace Model {

template< class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim >
class SeparableThermalblock;

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

  typedef typename BaseType::DomainFieldType  DomainFieldType;
  static const int                            dimDomain = BaseType::dimDomain;
  typedef typename BaseType::RangeFieldType   RangeFieldType;
  static const int                            dimRange = BaseType::dimRange;
  typedef typename BaseType::ParamFieldType   ParamFieldType;
  static const int                            maxParamDim = BaseType::maxParamDim;

  typedef typename Dune::Stuff::Function::SeparableCheckerboard< DomainFieldType, dimDomain, RangeFieldType, dimRange >
                                          CheckerboardFunctionType;
  typedef typename BaseType::FunctionType FunctionType;

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

  SeparableThermalblock(const Dune::shared_ptr< const CheckerboardFunctionType > _diffusion,
                        const Dune::shared_ptr< const FunctionType > _force,
                        const Dune::shared_ptr< const FunctionType > _dirichlet,
                        const Dune::shared_ptr< const FunctionType > _neumann)
    : BaseType(_diffusion, _force, _dirichlet, _neumann)
  {}

  SeparableThermalblock(const ThisType& other)
    : BaseType(other.diffusion(),
               other.force(),
               other.dirichlet(),
               other.neumann())
  {}

  ThisType& operator=(const ThisType& other)
  {
    if (this != &other) {
      BaseType::operator=(other);
    }
    return *this;
  }

  static Dune::ParameterTree createSampleDescription(const std::string subName = "")
  {
    Dune::Stuff::Common::ExtendedParameterTree description;
    description.add(Dune::Stuff::Function::createSampleDescription< DomainFieldType, dimDomain,
                                                                    RangeFieldType, dimRange >("function.separable.checkerboard"),
                    "diffusion");
    description["diffusion.name"] = "diffusion";
    description.add(Dune::Stuff::Function::createSampleDescription< DomainFieldType, dimDomain,
                                                                    RangeFieldType, dimRange >("function.expression"),
                    "force");
    description["force.name"] = "force";
    description["force.expression"] = "1.0";
    description["force.order"] = "0";
    description.add(Dune::Stuff::Function::createSampleDescription< DomainFieldType, dimDomain,
                                                                    RangeFieldType, dimRange >("function.expression"),
                    "neumann");
    description["neumann.name"] = "neumann";
    description["neumann.expression"] = "0.1";
    description["neumann.order"] = "0";
    description.add(Dune::Stuff::Function::createSampleDescription< DomainFieldType, dimDomain,
                                                                    RangeFieldType, dimRange >("function.expression"),
                    "dirichlet");
    description["dirichlet.name"] = "dirichlet";
    description["dirichlet.expression"] = "0.1*x[0]";
    description["dirichlet.order"] = "1";
    if (subName.empty())
      return description;
    else {
      Dune::Stuff::Common::ExtendedParameterTree extendedDescription;
      extendedDescription.add(description, subName);
      return extendedDescription;
    }
  }

  static ThisType createFromDescription(const Dune::ParameterTree& _description, const std::string _subName = id())
  {
    // get correct description
    typedef Stuff::Common::ExtendedParameterTree DescriptionType;
    DescriptionType description;
    if (_description.hasSub(_subName))
      description = _description.sub(_subName);
    else
      description = _description;
    // create the checkerboard diffusion
    const DescriptionType diffusionDescription = description.sub("diffusion");
    const shared_ptr< const CheckerboardFunctionType > diffusion(new CheckerboardFunctionType(
        CheckerboardFunctionType::createFromDescription(diffusionDescription)));
    // create the rest of the functions
    //   * therefore create a fake diffusion subdescription,
    description.sub("diffusion") = CheckerboardFunctionType::createSampleDescription();
    description["diffusion.type"] = "function.separable.checkerboard";
    //   * create a default model
    const BaseType baseModel = BaseType::createFromDescription(description);
    // create and return
    return ThisType(diffusion,
                    baseModel.force(),
                    baseModel.dirichlet(),
                    baseModel.neumann());
  } // static ThisType createFromParamTree(const Dune::ParameterTree& paramTree, const std::string subName = id())
}; // class SeparableThermalblock

} // namespace Model
} // namespace Elliptic
} // namespace Linear
} // namespace Stationary
} // namespace Solvers
} // namespace Detailed
} // namespace Dune

#endif // DUNE_DETAILED_SOLVERS_STATIONARY_LINEAR_ELLIPTIC_MODEL_PARAMETRIC_THERMALBLOCK_HH
<|endoftext|>


<commit_before>// v8
#include <v8.h>

// node
#include <node.h>
#include <node_version.h>

// stl
#include <sstream>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>

// osr
#include "ogr_spatialref.h"
//#include "ogr_core.h"
//#include "cpl_conv.h"
#include "cpl_string.h"
//#include "ogr_p.h"
//#include "cpl_multiproc.h"
//#include "ogr_srs_api.h"

using namespace node;
using namespace v8;

#define TOSTR(obj) (*String::Utf8Value((obj)->ToString()))

/*
OGRERR_DICT = { 1 : (OGRException, "Not enough data."),
                2 : (OGRException, "Not enough memory."),
                3 : (OGRException, "Unsupported geometry type."),
                4 : (OGRException, "Unsupported operation."),
                5 : (OGRException, "Corrupt data."),
                6 : (OGRException, "OGR failure."),
                7 : (SRSException, "Unsupported SRS."),
                8 : (OGRException, "Invalid handle."),
                }
*/

static Handle<Value> parse(const Arguments& args)
{
    HandleScope scope;

    if (args.Length() != 1 || !args[0]->IsString())
      return ThrowException(Exception::TypeError(
        String::New("first argument must be srs string in any form readable by OGR, like WKT (.prj file) or a proj4 string")));

    OGRSpatialReference oSRS;

    Local<Object> result = Object::New();

    result->Set(String::NewSymbol("input"), args[0]->ToString());
    // intialize as undefined
    result->Set(String::NewSymbol("proj4"), Undefined());
    result->Set(String::NewSymbol("srid"), Undefined());
    result->Set(String::NewSymbol("auth"), Undefined());
    result->Set(String::NewSymbol("pretty_wkt"), Undefined());
    result->Set(String::NewSymbol("esri"), Undefined());
    result->Set(String::NewSymbol("name"), Undefined());

    std::string wkt_string = TOSTR(args[0]->ToString());

    const char *wkt_char = wkt_string.data();

    bool error = false;

    Handle<Value> err;

    if( oSRS.SetFromUserInput(wkt_char) != OGRERR_NONE )
    {
        error = true;
        std::ostringstream s;
        s << "OGR Error type #" << CPLE_AppDefined
          << " problem occured importing from srs wkt: " << wkt_string << ".\n";;
        err = ThrowException(Exception::TypeError(String::New(s.str().c_str())));

        // try again to import from ESRI
        oSRS.Clear();
        char **wkt_lines = NULL;
        wkt_lines = CSLTokenizeString2( wkt_char, " \t\n",
                                CSLT_HONOURSTRINGS | CSLT_ALLOWEMPTYTOKENS );
        if( oSRS.importFromESRI(wkt_lines) != OGRERR_NONE )
        {
            error = true;
            oSRS.Clear();
            //std::ostringstream s;
            //s << "b: OGR Error type #" << CPLE_AppDefined
            //  << " problem occured importing assuming esri wkt " << wkt_string << ".\n";
            //err = ThrowException(Exception::TypeError(String::New(s.str().c_str())));
        }
        else
        {
            error = false;
            std::clog << "imported assuming esri format...\n";
            result->Set(String::NewSymbol("esri"), Boolean::New(true));
        }
    }
    else
    {
        error = false;
        if (wkt_string.substr(0,6) == "ESRI::")
        {
            result->Set(String::NewSymbol("esri"), Boolean::New(true));
        }
        else
        {
            result->Set(String::NewSymbol("esri"), Boolean::New(false));
        }
    }

    if (error)
        return err;

    char  *srs_output = NULL;
    if( oSRS.Validate() == OGRERR_NONE)
        result->Set(String::NewSymbol("valid"), Boolean::New(true));
    else if (oSRS.Validate() == OGRERR_UNSUPPORTED_SRS)
        result->Set(String::NewSymbol("valid"), Boolean::New(false));
    else
        result->Set(String::NewSymbol("valid"), Boolean::New(false));

    // TODO - trim output of proj4 result
    if (oSRS.exportToProj4( &srs_output ) != OGRERR_NONE )
    {
        std::ostringstream s;
        s << "OGR Error type #" << CPLE_AppDefined
          << " problem occured when converting to proj4 format " << wkt_string << ".\n";
        // for now let proj4 errors be non-fatal so that some info can be known...
        //std::clog << s.str();
        //return ThrowException(Exception::TypeError(String::New(s.str().c_str())));

    }
    else
    {
        // proj4 strings from osr have an uneeded trailing slash, so we trim it...
        result->Set(String::NewSymbol("proj4"), String::New(CPLString(srs_output).Trim()));
    }

    CPLFree( srs_output );

    if (oSRS.AutoIdentifyEPSG() != OGRERR_NONE )
    {
        /*std::ostringstream s;
        s << "OGR Error type #" << CPLE_AppDefined
          << " problem occured when attempting to auto identify epsg code " << wkt_string << ".\n";
        std::clog << s.str();
        */
        //return ThrowException(Exception::TypeError(String::New(s.str().c_str())));
    }

    if (oSRS.IsGeographic())
    {
        result->Set(String::NewSymbol("is_geographic"), Boolean::New(true));
        const char *code = oSRS.GetAuthorityCode("GEOGCS");
        if (code)
            result->Set(String::NewSymbol("srid"), Integer::New(atoi(code)));
        const char *auth = oSRS.GetAuthorityName("GEOGCS");
        if (auth)
            result->Set(String::NewSymbol("auth"), String::New(auth));
        const char *name = oSRS.GetAttrValue("GEOGCS");
        if (name)
            result->Set(String::NewSymbol("name"), String::New(name));
    }
    else
    {
        result->Set(String::NewSymbol("is_geographic"), Boolean::New(false));
        const char *code = oSRS.GetAuthorityCode("PROJCS");
        if (code)
            result->Set(String::NewSymbol("srid"), Integer::New(atoi(code)));
        const char *auth = oSRS.GetAuthorityName("PROJCS");
        if (auth)
            result->Set(String::NewSymbol("auth"), String::New(auth));
        const char *name = oSRS.GetAttrValue("PROJCS");
        if (name)
            result->Set(String::NewSymbol("name"), String::New(name));
    }

    char  *srs_output2 = NULL;
    if (oSRS.exportToPrettyWkt( &srs_output2 , 0) != OGRERR_NONE )
    {
        // this does not yet actually return errors
        std::ostringstream s;
        s << "OGR Error type #" << CPLE_AppDefined
          << " problem occured when converting to pretty wkt format " << wkt_string << ".\n";
        //std::clog << s.str();
        //return ThrowException(Exception::TypeError(String::New(s.str().c_str())));
    }
    else
    {
        result->Set(String::NewSymbol("pretty_wkt"), String::New(srs_output2));
    }

    CPLFree( srs_output2 );
    //OGRSpatialReference::DestroySpatialReference( &oSRS );
    return scope.Close(result);
}

extern "C" {

  static void init (Handle<Object> target)
  {

    NODE_SET_METHOD(target, "_parse", parse);

    // versions of deps
    Local<Object> versions = Object::New();
    versions->Set(String::NewSymbol("node"), String::New(NODE_VERSION+1));
    versions->Set(String::NewSymbol("v8"), String::New(V8::GetVersion()));
    // ogr/osr ?
    target->Set(String::NewSymbol("versions"), versions);

  }

  NODE_MODULE(_srs, init);
}
<commit_msg>cleanup<commit_after>// v8
#include <v8.h>

// node
#include <node.h>
#include <node_version.h>

// stl
#include <sstream>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>

// osr
#include "ogr_spatialref.h"
#include "cpl_error.h" // CPLE_AppDefined
#include "cpl_conv.h" // CPLFree
#include "cpl_string.h" // CPLString

using namespace node;
using namespace v8;

#define TOSTR(obj) (*String::Utf8Value((obj)->ToString()))

/*
OGRERR_DICT = { 1 : (OGRException, "Not enough data."),
                2 : (OGRException, "Not enough memory."),
                3 : (OGRException, "Unsupported geometry type."),
                4 : (OGRException, "Unsupported operation."),
                5 : (OGRException, "Corrupt data."),
                6 : (OGRException, "OGR failure."),
                7 : (SRSException, "Unsupported SRS."),
                8 : (OGRException, "Invalid handle."),
                }
*/

static Handle<Value> parse(const Arguments& args)
{
    HandleScope scope;

    if (args.Length() != 1 || !args[0]->IsString())
      return ThrowException(Exception::TypeError(
        String::New("first argument must be srs string in any form readable by OGR, like WKT (.prj file) or a proj4 string")));

    OGRSpatialReference oSRS;

    Local<Object> result = Object::New();

    result->Set(String::NewSymbol("input"), args[0]->ToString());
    // intialize as undefined
    result->Set(String::NewSymbol("proj4"), Undefined());
    result->Set(String::NewSymbol("srid"), Undefined());
    result->Set(String::NewSymbol("auth"), Undefined());
    result->Set(String::NewSymbol("pretty_wkt"), Undefined());
    result->Set(String::NewSymbol("esri"), Undefined());
    result->Set(String::NewSymbol("name"), Undefined());

    std::string wkt_string = TOSTR(args[0]->ToString());

    const char *wkt_char = wkt_string.data();

    bool error = false;

    Handle<Value> err;

    if( oSRS.SetFromUserInput(wkt_char) != OGRERR_NONE )
    {
        error = true;
        std::ostringstream s;
        s << "OGR Error type #" << CPLE_AppDefined
          << " problem occured importing from srs wkt: " << wkt_string << ".\n";;
        err = ThrowException(Exception::TypeError(String::New(s.str().c_str())));

        // try again to import from ESRI
        oSRS.Clear();
        char **wkt_lines = NULL;
        wkt_lines = CSLTokenizeString2( wkt_char, " \t\n",
                                CSLT_HONOURSTRINGS | CSLT_ALLOWEMPTYTOKENS );
        if( oSRS.importFromESRI(wkt_lines) != OGRERR_NONE )
        {
            error = true;
            oSRS.Clear();
        }
        else
        {
            error = false;
            result->Set(String::NewSymbol("esri"), Boolean::New(true));
        }
    }
    else
    {
        error = false;
        if (wkt_string.substr(0,6) == "ESRI::")
        {
            result->Set(String::NewSymbol("esri"), Boolean::New(true));
        }
        else
        {
            result->Set(String::NewSymbol("esri"), Boolean::New(false));
        }
    }

    if (error)
        return err;

    char  *srs_output = NULL;
    if( oSRS.Validate() == OGRERR_NONE)
        result->Set(String::NewSymbol("valid"), Boolean::New(true));
    else if (oSRS.Validate() == OGRERR_UNSUPPORTED_SRS)
        result->Set(String::NewSymbol("valid"), Boolean::New(false));
    else
        result->Set(String::NewSymbol("valid"), Boolean::New(false));

    // TODO - trim output of proj4 result
    if (oSRS.exportToProj4( &srs_output ) != OGRERR_NONE )
    {
        //std::ostringstream s;
        //s << "OGR Error type #" << CPLE_AppDefined
        //  << " problem occured when converting to proj4 format " << wkt_string << ".\n";
        // for now let proj4 errors be non-fatal so that some info can be known...
        //std::clog << s.str();
        //return ThrowException(Exception::TypeError(String::New(s.str().c_str())));

    }
    else
    {
        // proj4 strings from osr have an uneeded trailing slash, so we trim it...
        result->Set(String::NewSymbol("proj4"), String::New(CPLString(srs_output).Trim()));
    }

    CPLFree( srs_output );

    if (oSRS.AutoIdentifyEPSG() != OGRERR_NONE )
    {
        /*std::ostringstream s;
        s << "OGR Error type #" << CPLE_AppDefined
          << " problem occured when attempting to auto identify epsg code " << wkt_string << ".\n";
        std::clog << s.str();
        */
        //return ThrowException(Exception::TypeError(String::New(s.str().c_str())));
    }

    if (oSRS.IsGeographic())
    {
        result->Set(String::NewSymbol("is_geographic"), Boolean::New(true));
        const char *code = oSRS.GetAuthorityCode("GEOGCS");
        if (code)
            result->Set(String::NewSymbol("srid"), Integer::New(atoi(code)));
        const char *auth = oSRS.GetAuthorityName("GEOGCS");
        if (auth)
            result->Set(String::NewSymbol("auth"), String::New(auth));
        const char *name = oSRS.GetAttrValue("GEOGCS");
        if (name)
            result->Set(String::NewSymbol("name"), String::New(name));
    }
    else
    {
        result->Set(String::NewSymbol("is_geographic"), Boolean::New(false));
        const char *code = oSRS.GetAuthorityCode("PROJCS");
        if (code)
            result->Set(String::NewSymbol("srid"), Integer::New(atoi(code)));
        const char *auth = oSRS.GetAuthorityName("PROJCS");
        if (auth)
            result->Set(String::NewSymbol("auth"), String::New(auth));
        const char *name = oSRS.GetAttrValue("PROJCS");
        if (name)
            result->Set(String::NewSymbol("name"), String::New(name));
    }

    char  *srs_output2 = NULL;
    if (oSRS.exportToPrettyWkt( &srs_output2 , 0) != OGRERR_NONE )
    {
        // this does not yet actually return errors
        //std::ostringstream s;
        //s << "OGR Error type #" << CPLE_AppDefined
        //  << " problem occured when converting to pretty wkt format " << wkt_string << ".\n";
        //std::clog << s.str();
        //return ThrowException(Exception::TypeError(String::New(s.str().c_str())));
    }
    else
    {
        result->Set(String::NewSymbol("pretty_wkt"), String::New(srs_output2));
    }

    CPLFree( srs_output2 );
    //OGRSpatialReference::DestroySpatialReference( &oSRS );
    return scope.Close(result);
}

extern "C" {

  static void init (Handle<Object> target)
  {

    NODE_SET_METHOD(target, "_parse", parse);

    // versions of deps
    Local<Object> versions = Object::New();
    versions->Set(String::NewSymbol("node"), String::New(NODE_VERSION+1));
    versions->Set(String::NewSymbol("v8"), String::New(V8::GetVersion()));
    // ogr/osr ?
    target->Set(String::NewSymbol("versions"), versions);

  }

  NODE_MODULE(_srs, init);
}
<|endoftext|>


<commit_before>#include <QAction>
#include <QDir>
#include <QFileDialog>
#include <QFileInfo>
#include <QLayout>
#include <QListWidgetItem>
#include <QMessageBox>
#include <QPushButton>
#include <QInputDialog>
#include <QWidget>
#include <iostream>

#include "app.h"
#include "db.h"
#include "executables.h"
#include "settings.h"
#include "models/platform.h"
#include "ui_app.h"

App::App(int & argc, char** argv) :
	QApplication(argc,argv),
	mainWidget(nullptr),
	executablesWidget(nullptr),
	settingsWidget(nullptr),
	scraping(nullptr),
	import(nullptr),
	platforms(nullptr) {
	setApplicationName("mehstation-config");
	connect(this, SIGNAL(aboutToQuit()), SLOT(onQuit()));
}

App::~App() {
	if (scraping != nullptr) {
		delete scraping;
	}
	if (platforms != nullptr) {
		delete platforms;
	}
}

bool App::loadWindow() {
	this->ui.setupUi(&this->mainWidget);

	/*
	 * Menu
	 */

	// Quit action
	QAction* actionQuit = this->ui.actionQuit;
	connect(actionQuit, SIGNAL(triggered()), this, SLOT(onClickQuit()));
	// Open action
	QAction* actionOpen = this->ui.actionOpen;
	connect(actionOpen, SIGNAL(triggered()), this, SLOT(onClickOpen()));
	connect(&fileDialog, SIGNAL(fileSelected(const QString&)), this, SLOT(onFileSelected(const QString&)));
	// Scraping action
	connect(this->ui.actionScraping, SIGNAL(triggered()), this, SLOT(onOpenScraping()));
	// Import from ES
	connect(this->ui.actionImport, SIGNAL(triggered()), this, SLOT(onImport()));

	QAction* actionAbout = this->ui.actionAbout;
	connect(actionAbout, SIGNAL(triggered()), this, SLOT(onAbout()));

	/*
	 * Platforms list
	 */

	// Select an entry
	QListWidget* listPlatforms = this->ui.listPlatforms;
	connect(listPlatforms, SIGNAL(currentItemChanged(QListWidgetItem*, QListWidgetItem*)), this, SLOT(onPlatformSelected(QListWidgetItem*, QListWidgetItem*)));

	QPushButton *deletePlatform = this->ui.deletePlatform;
	connect(deletePlatform, SIGNAL(clicked()), this, SLOT(onDeletePlatform()));

	QPushButton *addPlatform = this->ui.addPlatform;
	connect(addPlatform, SIGNAL(clicked()), this, SLOT(onNewPlatform()));
	addPlatform->setEnabled(true);

	// NOTE We forces the use of the non-native dialog because with the native
	// NOTE the slot onFileSelected is called two times. - remy
	fileDialog.setOption(QFileDialog::DontUseNativeDialog, true);

	// Prepares the scraping window
	this->scraping = new Scraping(this);

	this->import = new Import(this);

	return true;
}

void App::showWindow() {
	this->mainWidget.show();
	this->mainWidget.raise();
}

void App::onQuit() {
	std::cout << "Exiting mehstation-config." << std::endl;

	// Closes all windows.
	if (this->scraping != nullptr) {
		delete this->scraping;
		this->scraping = nullptr;
	}

	if (this->import != nullptr) {
		delete this->import;
		this->import = nullptr;
	}
}

void App::onClickQuit() {
	this->exit();
}

void App::onAbout() {
	QMessageBox::about(NULL, "mehstation config", "mehstation configuration
Interface to setup your mehstation
Bad code written by Rémy 'remeh' Mathieu");
}

void App::onClickOpen() {
	this->fileDialog.show();
}

void App::onOpenScraping() {
	scraping->show();
	scraping->getPlatforms();
}

void App::onImport() {
	import->show();
	import->reset();
}

void App::onNewPlatform() {
	QString name = QInputDialog::getText(NULL, "Platform name ?", "Enter a name for the new platform");
	if (name.length() == 0) {
		return;
	}
	Platform p = this->getDb()->createNewPlatform(name);
	this->platforms->append(p);
	PlatformItem* item = new PlatformItem(p.name, p.id);
	QListWidget* listPlatforms = this->getPlatformListWidget();
	listPlatforms->addItem(item);
	listPlatforms->setCurrentItem(item);
	this->onPlatformSelected(NULL, item);
}

void App::onDeletePlatform() {
	QMessageBox::StandardButton result = QMessageBox::question(NULL, "Deletion confirmation", "Are you sure to delete this platform along with all its executables and executable resources ? This can't be undone!");
	if (result == QMessageBox::StandardButton::Yes) {
		this->getDb()->deletePlatform(this->selectedPlatform);
		QListWidget* listPlatforms = this->getPlatformListWidget();
		delete listPlatforms->currentItem();
		if (listPlatforms->currentItem() != NULL) {
			this->onPlatformSelected(NULL, listPlatforms->currentItem());
		}
	}
}

void App::updatePlatformList() {
	QListWidget* listPlatforms = this->getPlatformListWidget();
	QListWidgetItem* item = listPlatforms->currentItem();
	if (item != NULL) {
		item->setText(this->selectedPlatform.name);
	}
}

inline QListWidget* App::getPlatformListWidget() {
	return this->ui.listPlatforms;
}

void App::onPlatformSelected(QListWidgetItem* item, QListWidgetItem*) {
	if (item == NULL || platforms == NULL) {
		return;
	}

	item->setSelected(true);

	// look for the platform in the list of loaded platforms.
	Platform p;
	Platform clickedPlatform;
	foreach (p, *platforms) {
		if (p.id == item->data(MEH_ROLE_PLATFORM_ITEM).toInt()) {
			clickedPlatform = p;

			this->scraping->setPlatformId(p.id);
			this->import->setPlatformId(p.id);

			if (p.id >= 0) {
				this->ui.actionScraping->setEnabled(true);
				this->ui.actionImport->setEnabled(true);
			} else {
				this->ui.actionScraping->setEnabled(false);
				this->ui.actionImport->setEnabled(false);
			}

			break;
		}
	}

	// same platform, stop here.
	if (clickedPlatform.id == this->selectedPlatform.id)   {
		return;
	}

	this->selectedPlatform = clickedPlatform;

	// create the executable widget.
	if (this->executablesWidget != nullptr) {
		delete this->executablesWidget;
	}
	if (this->settingsWidget != nullptr) {
		delete this->settingsWidget;
	}

	QWidget* executablesTab = this->ui.executables;
	Executables* executables = new Executables(this, NULL);
	executablesTab->layout()->addWidget(executables);
	// load all the executables of this platform and assign it to the widget.
	executables->setExecutables(this->db.getExecutables(this->selectedPlatform.id));
	this->executablesWidget = executables;

	QWidget* settingsTab = this->ui.settings;
	Settings* settings = new Settings(this, NULL);
	settingsTab->layout()->addWidget(settings);
	this->settingsWidget = settings;

	// enable the tab
	QWidget* tabWidget = this->ui.tabWidget;
	tabWidget->setEnabled(true);

	QPushButton *deletePlatform = this->ui.deletePlatform;
	deletePlatform->setEnabled(true);
}

// onFileSelected called when a database file has been selected.
void App::onFileSelected(const QString& filename) {
	QFile file(filename);
	if (!file.exists()) {
		QMessageBox msgBox(QMessageBox::Critical, "Error", "This file doesn't exist. Please select an existing database.");
		msgBox.exec();
		return;
	}

	// open the database
	db.open(filename);

	if (this->platforms != nullptr) {
		delete this->platforms;
	}
	QList<Platform>* platforms = db.getPlatforms();

	QListWidget* listPlatforms = this->getPlatformListWidget();
	listPlatforms->clear();

	if (platforms != nullptr) {
		// store the list pointer
		this->platforms = platforms;

		// add all platforms in the view.
		Platform p;
		foreach (p, *platforms) {
			PlatformItem* item = new PlatformItem(p.name, p.id);
			listPlatforms->addItem(item);
		}
	}
}

QString App::mehtadataPath() {
	QFileInfo current(QDir::currentPath() + "/mehtadata");

	if (current.exists() && current.isFile()) {
		return "./mehtadata";
	}

#ifdef Q_OS_LINUX
	current = QFileInfo("/usr/bin/mehtadata");

	if (current.exists() && current.isFile()) {
		return "/usr/bin/mehtadata";
	}
#endif

	return "";
}
<commit_msg>Add .exe on windows when looking for mehtadata<commit_after>#include <QAction>
#include <QDebug>
#include <QDir>
#include <QFileDialog>
#include <QFileInfo>
#include <QLayout>
#include <QListWidgetItem>
#include <QMessageBox>
#include <QPushButton>
#include <QInputDialog>
#include <QWidget>
#include <iostream>

#include "app.h"
#include "db.h"
#include "executables.h"
#include "settings.h"
#include "models/platform.h"
#include "ui_app.h"

App::App(int & argc, char** argv) :
	QApplication(argc,argv),
	mainWidget(nullptr),
	executablesWidget(nullptr),
	settingsWidget(nullptr),
	scraping(nullptr),
	import(nullptr),
	platforms(nullptr) {
	setApplicationName("mehstation-config");
	connect(this, SIGNAL(aboutToQuit()), SLOT(onQuit()));
}

App::~App() {
	if (scraping != nullptr) {
		delete scraping;
	}
	if (platforms != nullptr) {
		delete platforms;
	}
}

bool App::loadWindow() {
	this->ui.setupUi(&this->mainWidget);

	/*
	 * Menu
	 */

	// Quit action
	QAction* actionQuit = this->ui.actionQuit;
	connect(actionQuit, SIGNAL(triggered()), this, SLOT(onClickQuit()));
	// Open action
	QAction* actionOpen = this->ui.actionOpen;
	connect(actionOpen, SIGNAL(triggered()), this, SLOT(onClickOpen()));
	connect(&fileDialog, SIGNAL(fileSelected(const QString&)), this, SLOT(onFileSelected(const QString&)));
	// Scraping action
	connect(this->ui.actionScraping, SIGNAL(triggered()), this, SLOT(onOpenScraping()));
	// Import from ES
	connect(this->ui.actionImport, SIGNAL(triggered()), this, SLOT(onImport()));

	QAction* actionAbout = this->ui.actionAbout;
	connect(actionAbout, SIGNAL(triggered()), this, SLOT(onAbout()));

	/*
	 * Platforms list
	 */

	// Select an entry
	QListWidget* listPlatforms = this->ui.listPlatforms;
	connect(listPlatforms, SIGNAL(currentItemChanged(QListWidgetItem*, QListWidgetItem*)), this, SLOT(onPlatformSelected(QListWidgetItem*, QListWidgetItem*)));

	QPushButton *deletePlatform = this->ui.deletePlatform;
	connect(deletePlatform, SIGNAL(clicked()), this, SLOT(onDeletePlatform()));

	QPushButton *addPlatform = this->ui.addPlatform;
	connect(addPlatform, SIGNAL(clicked()), this, SLOT(onNewPlatform()));
	addPlatform->setEnabled(true);

	// NOTE We forces the use of the non-native dialog because with the native
	// NOTE the slot onFileSelected is called two times. - remy
	fileDialog.setOption(QFileDialog::DontUseNativeDialog, true);

	// Prepares the scraping window
	this->scraping = new Scraping(this);

	this->import = new Import(this);

	return true;
}

void App::showWindow() {
	this->mainWidget.show();
	this->mainWidget.raise();
}

void App::onQuit() {
	std::cout << "Exiting mehstation-config." << std::endl;

	// Closes all windows.
	if (this->scraping != nullptr) {
		delete this->scraping;
		this->scraping = nullptr;
	}

	if (this->import != nullptr) {
		delete this->import;
		this->import = nullptr;
	}
}

void App::onClickQuit() {
	this->exit();
}

void App::onAbout() {
	QMessageBox::about(NULL, "mehstation config", "mehstation configuration
Interface to setup your mehstation
Bad code written by Rémy 'remeh' Mathieu");
}

void App::onClickOpen() {
	this->fileDialog.show();
}

void App::onOpenScraping() {
	scraping->show();
	scraping->getPlatforms();
}

void App::onImport() {
	import->show();
	import->reset();
}

void App::onNewPlatform() {
	QString name = QInputDialog::getText(NULL, "Platform name ?", "Enter a name for the new platform");
	if (name.length() == 0) {
		return;
	}
	Platform p = this->getDb()->createNewPlatform(name);
	this->platforms->append(p);
	PlatformItem* item = new PlatformItem(p.name, p.id);
	QListWidget* listPlatforms = this->getPlatformListWidget();
	listPlatforms->addItem(item);
	listPlatforms->setCurrentItem(item);
	this->onPlatformSelected(NULL, item);
}

void App::onDeletePlatform() {
	QMessageBox::StandardButton result = QMessageBox::question(NULL, "Deletion confirmation", "Are you sure to delete this platform along with all its executables and executable resources ? This can't be undone!");
	if (result == QMessageBox::StandardButton::Yes) {
		this->getDb()->deletePlatform(this->selectedPlatform);
		QListWidget* listPlatforms = this->getPlatformListWidget();
		delete listPlatforms->currentItem();
		if (listPlatforms->currentItem() != NULL) {
			this->onPlatformSelected(NULL, listPlatforms->currentItem());
		}
	}
}

void App::updatePlatformList() {
	QListWidget* listPlatforms = this->getPlatformListWidget();
	QListWidgetItem* item = listPlatforms->currentItem();
	if (item != NULL) {
		item->setText(this->selectedPlatform.name);
	}
}

inline QListWidget* App::getPlatformListWidget() {
	return this->ui.listPlatforms;
}

void App::onPlatformSelected(QListWidgetItem* item, QListWidgetItem*) {
	if (item == NULL || platforms == NULL) {
		return;
	}

	item->setSelected(true);

	// look for the platform in the list of loaded platforms.
	Platform p;
	Platform clickedPlatform;
	foreach (p, *platforms) {
		if (p.id == item->data(MEH_ROLE_PLATFORM_ITEM).toInt()) {
			clickedPlatform = p;

			this->scraping->setPlatformId(p.id);
			this->import->setPlatformId(p.id);

			if (p.id >= 0) {
				this->ui.actionScraping->setEnabled(true);
				this->ui.actionImport->setEnabled(true);
			} else {
				this->ui.actionScraping->setEnabled(false);
				this->ui.actionImport->setEnabled(false);
			}

			break;
		}
	}

	// same platform, stop here.
	if (clickedPlatform.id == this->selectedPlatform.id)   {
		return;
	}

	this->selectedPlatform = clickedPlatform;

	// create the executable widget.
	if (this->executablesWidget != nullptr) {
		delete this->executablesWidget;
	}
	if (this->settingsWidget != nullptr) {
		delete this->settingsWidget;
	}

	QWidget* executablesTab = this->ui.executables;
	Executables* executables = new Executables(this, NULL);
	executablesTab->layout()->addWidget(executables);
	// load all the executables of this platform and assign it to the widget.
	executables->setExecutables(this->db.getExecutables(this->selectedPlatform.id));
	this->executablesWidget = executables;

	QWidget* settingsTab = this->ui.settings;
	Settings* settings = new Settings(this, NULL);
	settingsTab->layout()->addWidget(settings);
	this->settingsWidget = settings;

	// enable the tab
	QWidget* tabWidget = this->ui.tabWidget;
	tabWidget->setEnabled(true);

	QPushButton *deletePlatform = this->ui.deletePlatform;
	deletePlatform->setEnabled(true);
}

// onFileSelected called when a database file has been selected.
void App::onFileSelected(const QString& filename) {
	QFile file(filename);
	if (!file.exists()) {
		QMessageBox msgBox(QMessageBox::Critical, "Error", "This file doesn't exist. Please select an existing database.");
		msgBox.exec();
		return;
	}

	// open the database
	db.open(filename);

	if (this->platforms != nullptr) {
		delete this->platforms;
	}
	QList<Platform>* platforms = db.getPlatforms();

	QListWidget* listPlatforms = this->getPlatformListWidget();
	listPlatforms->clear();

	if (platforms != nullptr) {
		// store the list pointer
		this->platforms = platforms;

		// add all platforms in the view.
		Platform p;
		foreach (p, *platforms) {
			PlatformItem* item = new PlatformItem(p.name, p.id);
			listPlatforms->addItem(item);
		}
	}
}

QString App::mehtadataPath() {
	QString mehtadata("/mehtadata");

#ifdef Q_OS_WIN
	mehtadata += ".exe";
#endif

	QFileInfo current(QDir::currentPath() + mehtadata);

	if (current.exists() && current.isFile()) {
		return QDir::currentPath() + mehtadata;
	}

	qDebug() << QString( QDir::currentPath() + mehtadata );

#ifdef Q_OS_LINUX
	current = QFileInfo("/usr/bin/mehtadata");

	if (current.exists() && current.isFile()) {
		return "/usr/bin/mehtadata";
	}
#endif

	return "";
}
<|endoftext|>


<commit_before>/* bzflag
* Copyright (c) 1993 - 2005 Tim Riker
*
* This package is free software;  you can redistribute it and/or
* modify it under the terms of the license found in the file
* named LICENSE that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/

/* bzflag special common - 1st one */
#include "common.h"

#include <iostream>
#include <string>

#include "WorldEventManager.h"

//-------------------BaseEventData--------------------
BaseEventData::BaseEventData()
{
	eventType = eNullEvent;
}

//-------------------CTFCaptureEventData--------------------
CTFCaptureEventData::CTFCaptureEventData()
{
	eventType = eCaptureEvent;
	teamCAped = -1;
	teamCaping = -1;
	playerCaping = -1;
}

CTFCaptureEventData::~CTFCaptureEventData()
{
}

//-------------------PlayerDieEventData--------------------
PlayerDieEventData::PlayerDieEventData()
{
	eventType = ePlayerDieEvent;
	playerID = -1;
	teamID = -1;
	killerID = -1;
	killerTeamID = -1;

	pos[0] = pos[1] = pos[2] = 0.0f;
	rot = 0.0f;
	time = 0.0;
}

PlayerDieEventData::~PlayerDieEventData()
{
}

//-------------------PlayerSpawnEventData--------------------
PlayerSpawnEventData::PlayerSpawnEventData()
{
	eventType = ePlayerSpawnEvent;
	playerID = -1;
	teamID = -1;

	pos[0] = pos[1] = pos[2] = 0.0f;
	rot = 0.0f;
	time = 0.0;
}

PlayerSpawnEventData::~PlayerSpawnEventData()
{
}

//-------------------ZoneEntryExitEventData--------------------
ZoneEntryExitEventData::ZoneEntryExitEventData()
{
	eventType = eZoneEntryEvent;
	playerID = -1;
	teamID = -1;
	zoneID = -1;

	pos[0] = pos[1] = pos[2] = 0.0f;
	rot = 0.0f;
	time = 0.0;
}

ZoneEntryExitEventData::~ZoneEntryExitEventData()
{
}

//-------------------PlayerJoinPartEventData--------------------
PlayerJoinPartEventData::PlayerJoinPartEventData()
{
	eventType = ePlayerJoinEvent;

	playerID = -1;
	teamID = -1;
	time = 0.0;
}

PlayerJoinPartEventData::~PlayerJoinPartEventData()
{
}

//-------------------WorldEventManager--------------------
WorldEventManager::WorldEventManager()
{
}

WorldEventManager::~WorldEventManager()
{
	tmEventMap::iterator teamItr = eventtMap.begin();
	while ( teamItr != eventtMap.end() )
	{
		tmEventTypeList::iterator eventItr = teamItr->second.begin();
		while (eventItr == teamItr->second.end())
		{
			tvEventList::iterator itr = eventItr->second.begin();
			while ( itr != eventItr->second.end() )
			{
				if ((*itr) && (*itr)->autoDelete())
					delete (*itr++);
			}
			eventItr++;
		}
		teamItr++;
	}
}

void WorldEventManager::addEvent ( teEventType eventType, int team, BaseEventHandaler* theEvetnt )
{
	if (!theEvetnt)
		return;

	tmEventTypeList*	teamEvents = getTeamEventList(team);

	if (teamEvents->find(eventType) == teamEvents->end())
	{
		tvEventList newList;
		(*teamEvents)[eventType] = newList;
	}

	teamEvents->find(eventType)->second.push_back(theEvetnt);
}

void WorldEventManager::removeEvent ( teEventType eventType, int team, BaseEventHandaler* theEvetnt )
{
	if (!theEvetnt)
		return;

	tmEventTypeList*	teamEvents = getTeamEventList(team);

	if (teamEvents->find(eventType) == teamEvents->end())
		return;

	tmEventTypeList::iterator eventTypeItr = teamEvents->begin();
	if ( eventTypeItr != teamEvents->end() )
	{
		tvEventList::iterator itr = eventTypeItr->second.begin();
		while (itr == eventTypeItr->second.end())
		{
			if (*itr == theEvetnt)
				itr = eventTypeItr->second.erase(itr);
			else
				itr++;
		}
	}
}

tvEventList WorldEventManager::getEventList ( teEventType eventType, int team )

{
	tvEventList	eventList;

	tmEventTypeList*	teamEvents = getTeamEventList(team);

	tmEventTypeList::iterator teamItr = teamEvents->find(eventType);
	if ( teamItr == teamEvents->end() )
		return eventList;

	eventList = teamItr->second;
	return eventList;
}

void WorldEventManager::callEvents ( teEventType eventType, int team, BaseEventData	*eventData )
{
	if (!eventData)
		return;

	tvEventList	eventList = getEventList(eventType,team);

	for ( unsigned int i = 0; i < eventList.size(); i++)
		eventList[i]->process(eventData);
}

tmEventTypeList* WorldEventManager::getTeamEventList ( int team )
{
	if (eventtMap.find(team) == eventtMap.end())
	{
		tmEventTypeList newList;
		eventtMap[team] = newList;
	}
	return &(eventtMap.find(team)->second);
}

// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>really make sure you don't delete a null<commit_after>/* bzflag
* Copyright (c) 1993 - 2005 Tim Riker
*
* This package is free software;  you can redistribute it and/or
* modify it under the terms of the license found in the file
* named LICENSE that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/

/* bzflag special common - 1st one */
#include "common.h"

#include <iostream>
#include <string>

#include "WorldEventManager.h"

//-------------------BaseEventData--------------------
BaseEventData::BaseEventData()
{
	eventType = eNullEvent;
}

//-------------------CTFCaptureEventData--------------------
CTFCaptureEventData::CTFCaptureEventData()
{
	eventType = eCaptureEvent;
	teamCAped = -1;
	teamCaping = -1;
	playerCaping = -1;
}

CTFCaptureEventData::~CTFCaptureEventData()
{
}

//-------------------PlayerDieEventData--------------------
PlayerDieEventData::PlayerDieEventData()
{
	eventType = ePlayerDieEvent;
	playerID = -1;
	teamID = -1;
	killerID = -1;
	killerTeamID = -1;

	pos[0] = pos[1] = pos[2] = 0.0f;
	rot = 0.0f;
	time = 0.0;
}

PlayerDieEventData::~PlayerDieEventData()
{
}

//-------------------PlayerSpawnEventData--------------------
PlayerSpawnEventData::PlayerSpawnEventData()
{
	eventType = ePlayerSpawnEvent;
	playerID = -1;
	teamID = -1;

	pos[0] = pos[1] = pos[2] = 0.0f;
	rot = 0.0f;
	time = 0.0;
}

PlayerSpawnEventData::~PlayerSpawnEventData()
{
}

//-------------------ZoneEntryExitEventData--------------------
ZoneEntryExitEventData::ZoneEntryExitEventData()
{
	eventType = eZoneEntryEvent;
	playerID = -1;
	teamID = -1;
	zoneID = -1;

	pos[0] = pos[1] = pos[2] = 0.0f;
	rot = 0.0f;
	time = 0.0;
}

ZoneEntryExitEventData::~ZoneEntryExitEventData()
{
}

//-------------------PlayerJoinPartEventData--------------------
PlayerJoinPartEventData::PlayerJoinPartEventData()
{
	eventType = ePlayerJoinEvent;

	playerID = -1;
	teamID = -1;
	time = 0.0;
}

PlayerJoinPartEventData::~PlayerJoinPartEventData()
{
}

//-------------------WorldEventManager--------------------
WorldEventManager::WorldEventManager()
{
}

WorldEventManager::~WorldEventManager()
{
	tmEventMap::iterator teamItr = eventtMap.begin();
	while ( teamItr != eventtMap.end() )
	{
		tmEventTypeList::iterator eventItr = teamItr->second.begin();
		while (eventItr == teamItr->second.end())
		{
			tvEventList::iterator itr = eventItr->second.begin();
			while ( itr != eventItr->second.end() )
			{
				if ((*itr) && (*itr)->autoDelete())
					delete (*itr++);
				*itr = NULL;
			}
			eventItr++;
		}
		teamItr++;
	}
}

void WorldEventManager::addEvent ( teEventType eventType, int team, BaseEventHandaler* theEvetnt )
{
	if (!theEvetnt)
		return;

	tmEventTypeList*	teamEvents = getTeamEventList(team);

	if (teamEvents->find(eventType) == teamEvents->end())
	{
		tvEventList newList;
		(*teamEvents)[eventType] = newList;
	}

	teamEvents->find(eventType)->second.push_back(theEvetnt);
}

void WorldEventManager::removeEvent ( teEventType eventType, int team, BaseEventHandaler* theEvetnt )
{
	if (!theEvetnt)
		return;

	tmEventTypeList*	teamEvents = getTeamEventList(team);

	if (teamEvents->find(eventType) == teamEvents->end())
		return;

	tmEventTypeList::iterator eventTypeItr = teamEvents->begin();
	if ( eventTypeItr != teamEvents->end() )
	{
		tvEventList::iterator itr = eventTypeItr->second.begin();
		while (itr == eventTypeItr->second.end())
		{
			if (*itr == theEvetnt)
				itr = eventTypeItr->second.erase(itr);
			else
				itr++;
		}
	}
}

tvEventList WorldEventManager::getEventList ( teEventType eventType, int team )

{
	tvEventList	eventList;

	tmEventTypeList*	teamEvents = getTeamEventList(team);

	tmEventTypeList::iterator teamItr = teamEvents->find(eventType);
	if ( teamItr == teamEvents->end() )
		return eventList;

	eventList = teamItr->second;
	return eventList;
}

void WorldEventManager::callEvents ( teEventType eventType, int team, BaseEventData	*eventData )
{
	if (!eventData)
		return;

	tvEventList	eventList = getEventList(eventType,team);

	for ( unsigned int i = 0; i < eventList.size(); i++)
		eventList[i]->process(eventData);
}

tmEventTypeList* WorldEventManager::getTeamEventList ( int team )
{
	if (eventtMap.find(team) == eventtMap.end())
	{
		tmEventTypeList newList;
		eventtMap[team] = newList;
	}
	return &(eventtMap.find(team)->second);
}

// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>