<commit_before>#include "interfaces/non_conservative/navier_stokes.h"
#include "pidomus.h"

#include "deal.II/base/numbers.h"

#include "Teuchos_CommandLineProcessor.hpp"
#include "Teuchos_GlobalMPISession.hpp"
#include "Teuchos_oblackholestream.hpp"
#include "Teuchos_StandardCatchMacros.hpp"
#include "Teuchos_Version.hpp"

#include "mpi.h"
#include <iostream>
#include <string>

void print_status(  std::string name,
                    std::string prm_file,
                    int dim,
                    int spacedim,
                    const MPI_Comm &comm);

int main (int argc, char *argv[])
{
  using namespace dealii;
  using namespace deal2lkit;

  Teuchos::CommandLineProcessor My_CLP;
  My_CLP.setDocString(
    ".__________        _______   ______   .___  ___.  __    __       _______. \n"
    "|_   __  __|      |       \\ /  __  \\  |   \\/   | |  |  |  |     /       | \n"
    "  | | | |   ______|  .--.  |  |  |  | |  \\  /  | |  |  |  |    |   (----` \n"
    "  | | | |  |______|  |  |  |  |  |  | |  |\\/|  | |  |  |  |     \\   \\     \n"
    "  | | | |         |  '--'  |  `--'  | |  |  |  | |  `--'  | .----)   |    \n"
    "  |_| |_|         |_______/ \\______/  |__|  |__|  \\______/  |_______/     \n\n"
  );

  std::string pde_name="navier_stokes";
  My_CLP.setOption("pde", &pde_name, "name of the PDE (heat, stokes, dynamic_stokes, or navier_stokes)");

  int spacedim = 2;
  My_CLP.setOption("spacedim", &spacedim, "dimensione of the whole space");

  int dim = 2;
  My_CLP.setOption("dim", &dim, "dimension of the problem");

  int n_threads = 0;
  My_CLP.setOption("n_threads", &n_threads, "number of threads");

  std::string prm_file=pde_name+".prm";
  My_CLP.setOption("prm", &prm_file, "name of the parameter file");

  // My_CLP.recogniseAllOptions(true);
  My_CLP.throwExceptions(false);

  Teuchos::CommandLineProcessor::EParseCommandLineReturn
  parseReturn= My_CLP.parse( argc, argv );

  if ( parseReturn == Teuchos::CommandLineProcessor::PARSE_HELP_PRINTED )
    {
      return 0;
    }
  if ( parseReturn != Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL   )
    {
      return 1; // Error!
    }

  Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv,
                                                      n_threads == 0 ? numbers::invalid_unsigned_int  : n_threads);

  const MPI_Comm &comm  = MPI_COMM_WORLD;

  Teuchos::oblackholestream blackhole;
  std::ostream &out = ( Utilities::MPI::this_mpi_process(comm) == 0 ? std::cout : blackhole );

  My_CLP.printHelpMessage(argv[0], out);

  deallog.depth_console (0);

  if (pde_name == "navier_stokes")
    {

      print_status(   "Navier-Stokes Equation",
                      prm_file,
                      dim,
                      spacedim,
                      comm);

      if (dim==2)
        {
          NavierStokes<2> energy;
          piDoMUS<2,2,3> navier_stokes_equation (energy);
          ParameterAcceptor::initialize(prm_file, pde_name+"_used.prm");
          ParameterAcceptor::prm.log_parameters(deallog);
          navier_stokes_equation.run ();
        }
      else
        {
          NavierStokes<3> energy;
          piDoMUS<3,3,4> navier_stokes_equation (energy);
          ParameterAcceptor::initialize(prm_file, pde_name+"_used.prm");
          ParameterAcceptor::prm.log_parameters(deallog);
          navier_stokes_equation.run ();
        }
    }
  else
    {
      out << std::endl
          << "============================================================="
          << std::endl
          << " ERROR:"
          << std::endl
          << "  " << pde_name << " needs to be implemented or it is bad name."
          << std::endl
          << "=============================================================";
    }

  out << std::endl;
  return 0;
}

void print_status(  std::string name,
                    std::string prm_file,
                    int dim,
                    int spacedim,
                    const MPI_Comm &comm)
{
  int numprocs  = Utilities::MPI::n_mpi_processes(comm);
  int myid      = Utilities::MPI::this_mpi_process(comm);

  Teuchos::oblackholestream blackhole;
  std::ostream &out = ( Utilities::MPI::this_mpi_process(comm) == 0 ? std::cout : blackhole );

  if (myid == 0)
    {
      out << std::endl
          << "============================================================="
          << std::endl
          << "    Name:   " << name
          // << std::endl
          // << "-------------------------------------------------------------"
          << std::endl
          << " Prm file:  " << prm_file
          << std::endl
          << " spacedim:  " << spacedim
          << std::endl
          << "      dim:  " << dim
          << std::endl
          << "    codim:  " << spacedim-dim
          << std::endl
          << "-------------------------------------------------------------"
          << std::endl;
    }
  out << " Process " << getpid() << " is " << myid
      << "   of " << numprocs << " processes" << std::endl;

  if (myid == 0)
    {
      out << "-------------------------------------------------------------"
          << std::endl;
      system("read -p \" Press [Enter] key to start...\"");
      out << "============================================================="
          <<std::endl<<std::endl;
    }
}
<commit_msg>indent<commit_after>#include "interfaces/non_conservative/navier_stokes.h"
#include "pidomus.h"

#include "deal.II/base/numbers.h"

#include "Teuchos_CommandLineProcessor.hpp"
#include "Teuchos_GlobalMPISession.hpp"
#include "Teuchos_oblackholestream.hpp"
#include "Teuchos_StandardCatchMacros.hpp"
#include "Teuchos_Version.hpp"

#include "mpi.h"
#include <iostream>
#include <string>

void print_status(  std::string name,
                    std::string prm_file,
                    int dim,
                    int spacedim,
                    const MPI_Comm &comm);

int main (int argc, char *argv[])
{
  using namespace dealii;
  using namespace deal2lkit;

  Teuchos::CommandLineProcessor My_CLP;
  My_CLP.setDocString(
    ".__________        _______   ______   .___  ___.  __    __       _______. \n"
    "|_   __  __|      |       \\ /  __  \\  |   \\/   | |  |  |  |     /       | \n"
    "  | | | |   ______|  .--.  |  |  |  | |  \\  /  | |  |  |  |    |   (----` \n"
    "  | | | |  |______|  |  |  |  |  |  | |  |\\/|  | |  |  |  |     \\   \\     \n"
    "  | | | |         |  '--'  |  `--'  | |  |  |  | |  `--'  | .----)   |    \n"
    "  |_| |_|         |_______/ \\______/  |__|  |__|  \\______/  |_______/     \n\n"
  );

  std::string pde_name="navier_stokes";
  My_CLP.setOption("pde", &pde_name, "name of the PDE (heat, stokes, dynamic_stokes, or navier_stokes)");

  int spacedim = 2;
  My_CLP.setOption("spacedim", &spacedim, "dimensione of the whole space");

  int dim = 2;
  My_CLP.setOption("dim", &dim, "dimension of the problem");

  int n_threads = 0;
  My_CLP.setOption("n_threads", &n_threads, "number of threads");

  std::string prm_file=pde_name+".prm";
  My_CLP.setOption("prm", &prm_file, "name of the parameter file");

  // My_CLP.recogniseAllOptions(true);
  My_CLP.throwExceptions(false);

  Teuchos::CommandLineProcessor::EParseCommandLineReturn
  parseReturn= My_CLP.parse( argc, argv );

  if ( parseReturn == Teuchos::CommandLineProcessor::PARSE_HELP_PRINTED )
    {
      return 0;
    }
  if ( parseReturn != Teuchos::CommandLineProcessor::PARSE_SUCCESSFUL   )
    {
      return 1; // Error!
    }

  Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv,
                                                      n_threads == 0 ? numbers::invalid_unsigned_int  : n_threads);

  const MPI_Comm &comm  = MPI_COMM_WORLD;

  Teuchos::oblackholestream blackhole;
  std::ostream &out = ( Utilities::MPI::this_mpi_process(comm) == 0 ? std::cout : blackhole );

  My_CLP.printHelpMessage(argv[0], out);

  deallog.depth_console (0);

  if (pde_name == "navier_stokes")
    {

      print_status(   "Navier-Stokes Equation",
                      prm_file,
                      dim,
                      spacedim,
                      comm);

      if (dim==2)
        {
          NavierStokes<2> energy;
          piDoMUS<2,2,3> navier_stokes_equation (energy);
          ParameterAcceptor::initialize(prm_file, pde_name+"_used.prm");
          ParameterAcceptor::prm.log_parameters(deallog);
          navier_stokes_equation.run ();
        }
      else
        {
          NavierStokes<3> energy;
          piDoMUS<3,3,4> navier_stokes_equation (energy);
          ParameterAcceptor::initialize(prm_file, pde_name+"_used.prm");
          ParameterAcceptor::prm.log_parameters(deallog);
          navier_stokes_equation.run ();
        }
    }
  else
    {
      out << std::endl
                << "============================================================="
                << std::endl
                << " ERROR:"
                << std::endl
                << "  " << pde_name << " needs to be implemented or it is bad name."
                << std::endl
                << "=============================================================";
    }

  out << std::endl;
  return 0;
}

void print_status(  std::string name,
                    std::string prm_file,
                    int dim,
                    int spacedim,
                    const MPI_Comm &comm)
{
  int numprocs  = Utilities::MPI::n_mpi_processes(comm);
  int myid      = Utilities::MPI::this_mpi_process(comm);

  Teuchos::oblackholestream blackhole;
  std::ostream &out = ( Utilities::MPI::this_mpi_process(comm) == 0 ? std::cout : blackhole );

  if (myid == 0)
    {
      out << std::endl
                << "============================================================="
                << std::endl
                << "    Name:   " << name
                // << std::endl
                // << "-------------------------------------------------------------"
                << std::endl
                << " Prm file:  " << prm_file
                << std::endl
                << " spacedim:  " << spacedim
                << std::endl
                << "      dim:  " << dim
                << std::endl
                << "    codim:  " << spacedim-dim
                << std::endl
                << "-------------------------------------------------------------"
                << std::endl;
    }
  out << " Process " << getpid() << " is " << myid
            << "   of " << numprocs << " processes" << std::endl;

  if (myid == 0)
    {
      out << "-------------------------------------------------------------"
                << std::endl;
      system("read -p \" Press [Enter] key to start...\"");
      out << "============================================================="
                <<std::endl<<std::endl;
    }
}
<|endoftext|>


<commit_before>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2014-2015 Esteban Tovagliari, The appleseedhq Organization
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

// appleseed.foundation headers.
#include "foundation/math/rng/serialmersennetwister.h"
#ifdef APPLESEED_USE_SSE
#include "foundation/math/rng/simdmersennetwister.h"
#endif
#include "foundation/utility/benchmark.h"

// Standard headers.
#include <cstddef>

using namespace foundation;

BENCHMARK_SUITE(Foundation_Math_Rng_SerialMersenneTwister)
{
    BENCHMARK_CASE(RandUint32)
    {
        SerialMersenneTwister rng;

        for (size_t i = 0; i < 1753117; ++i)
            rng.rand_uint32();
    }
}

#ifdef APPLESEED_USE_SSE

BENCHMARK_SUITE(Foundation_Math_Rng_SimdMersenneTwister)
{
    BENCHMARK_CASE(RandUint32)
    {
        SimdMersenneTwister rng;

        for (size_t i = 0; i < 1753117; ++i)
            rng.rand_uint32();
    }
}

#endif
<commit_msg>fixed and completed RNG benchmarks.<commit_after>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2014-2015 Esteban Tovagliari, The appleseedhq Organization
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

// appleseed.foundation headers.
#include "foundation/math/rng/lcg.h"
#include "foundation/math/rng/pcg.h"
#include "foundation/math/rng/serialmersennetwister.h"
#ifdef APPLESEED_USE_SSE
#include "foundation/math/rng/simdmersennetwister.h"
#endif
#include "foundation/math/rng/xorshift.h"
#include "foundation/platform/types.h"
#include "foundation/utility/benchmark.h"

// Standard headers.
#include <cstddef>

using namespace foundation;

BENCHMARK_SUITE(Foundation_Math_RNG)
{
    template <typename RNG>
    struct Fixture
    {
        RNG     m_rng;
        uint32  m_dummy;

        Fixture()
          : m_dummy(0)
        {
        }
    };

    BENCHMARK_CASE_F(LCG_RandUint32, Fixture<LCG>)
    {
        for (size_t i = 0; i < 250000; ++i)
        {
            m_dummy ^= m_rng.rand_uint32();
            m_dummy ^= m_rng.rand_uint32();
            m_dummy ^= m_rng.rand_uint32();
            m_dummy ^= m_rng.rand_uint32();
        }
    }

    BENCHMARK_CASE_F(PCG_RandUint32, Fixture<PCG>)
    {
        for (size_t i = 0; i < 250000; ++i)
        {
            m_dummy ^= m_rng.rand_uint32();
            m_dummy ^= m_rng.rand_uint32();
            m_dummy ^= m_rng.rand_uint32();
            m_dummy ^= m_rng.rand_uint32();
        }
    }

    BENCHMARK_CASE_F(SerialMersenneTwister_RandUint32, Fixture<SerialMersenneTwister>)
    {
        for (size_t i = 0; i < 250000; ++i)
        {
            m_dummy ^= m_rng.rand_uint32();
            m_dummy ^= m_rng.rand_uint32();
            m_dummy ^= m_rng.rand_uint32();
            m_dummy ^= m_rng.rand_uint32();
        }
    }

#ifdef APPLESEED_USE_SSE

    BENCHMARK_CASE_F(SimdMersenneTwister_RandUint32, Fixture<SimdMersenneTwister>)
    {
        for (size_t i = 0; i < 250000; ++i)
        {
            m_dummy ^= m_rng.rand_uint32();
            m_dummy ^= m_rng.rand_uint32();
            m_dummy ^= m_rng.rand_uint32();
            m_dummy ^= m_rng.rand_uint32();
        }
    }

#endif

    BENCHMARK_CASE_F(Xorshift_RandUint32, Fixture<Xorshift>)
    {
        for (size_t i = 0; i < 250000; ++i)
        {
            m_dummy ^= m_rng.rand_uint32();
            m_dummy ^= m_rng.rand_uint32();
            m_dummy ^= m_rng.rand_uint32();
            m_dummy ^= m_rng.rand_uint32();
        }
    }
}
<|endoftext|>


<commit_before>#pragma once

#include <cstddef>
#include <cstring>
#include <string>
#include <utility>
#include <iterator>
#include <iomanip>

namespace microbson
{
    typedef unsigned char byte;

    enum node_type {
        double_node = 0x01,
        string_node = 0x02,
        document_node = 0x03,
        binary_node = 0x05,
        boolean_node = 0x08,
        null_node = 0x0A,
        int32_node = 0x10,
        int64_node = 0x12,
        unknown_node = 0xFF
    };

    class document;

    template<typename T> struct type_converter { };

    template<> struct type_converter<double>
    {
        enum { node_type_code = double_node };
    };

    template<> struct type_converter<std::string>
    {
        enum { node_type_code = string_node };
    };

    template<> struct type_converter<document>
    {
        enum { node_type_code = document_node };
    };

    template<> struct type_converter<void*>
    {
        enum { node_type_code = binary_node };
    };

    template<> struct type_converter<bool>
    {
        enum { node_type_code = boolean_node };
    };

    template<> struct type_converter<int>
    {
        enum { node_type_code = int32_node };
    };

    template<> struct type_converter<long long>
    {
        enum { node_type_code = int64_node };
    };

    struct node
    {
        byte* bytes;

        node() : bytes(NULL) { }

        node(byte* bytes) : bytes(bytes) { }

        node_type get_type() const { return static_cast<node_type>(bytes[0]); }

        const char* get_name() const
        {
            return reinterpret_cast<const char*>( bytes + 1 );
        }

        size_t get_size() const
        {
            size_t result = 1U + strlen(get_name()) + 1U;

            switch (get_type())
            {
                case double_node:
                    result += sizeof(double);
                    break;
                case document_node:
                    result += *reinterpret_cast<int*>(bytes + result);
                    break;
                case string_node:
                case binary_node:
                    result += (
                        sizeof(int)
                            + *reinterpret_cast<int*>(bytes + result)
                            + 1U
                    );
                    break;
                case boolean_node:
                    result += 1U;
                case null_node:
                    break;
                case int32_node:
                    result += sizeof(int);
                    break;
                case int64_node:
                    result += sizeof(long long);
                    break;
                default:
                    result = 0U;
                    break;
            }

            return result;
        }

        void* get_data() const
        {
            return bytes + 1U + strlen(get_name()) + 1U;
        }

        bool valid(size_t size) const
        {
            return (size >= 2) && (get_size() <= size);
        }
    };

    class document
    {
        private:
            byte* bytes;
            size_t size;

            bool lookup(const char* name, node& result) const
            {
                byte* iterator = bytes + sizeof(int);
                size_t left = size - sizeof(int);
                bool found = false;

                result = node(iterator);

                while (result.valid(left))
                {
                    if (strcmp(result.get_name(), name) == 0)
                    {
                        found = true;
                        break;
                    }
                    else
                    {
                        iterator += result.get_size();
                        left -= result.get_size();
                        result = node(iterator);
                    }
                }

                return found;
            }

            template<typename T, typename W>
                T get(node _node) const
                {
                    return static_cast<T>(
                        *reinterpret_cast<W*>(_node.get_data())
                    );
                }

            std::string get_string(const node& _node) const
            {
                return std::string(
                    reinterpret_cast<const char*>(_node.get_data())
                        + sizeof(int),
                    *reinterpret_cast<int*>(_node.get_data())
                );
            }

            template<typename T, typename W>
                T get(const std::string& name, T _default) const
                {
                    node _node;

                    return lookup(name.c_str(), _node)
                        ? get<T, W>(_node)
                        : _default
                    ;
                }

            void dump(const node& _node, std::ostream& _stream) const
            {
                switch(_node.get_type())
                {
                    case double_node:
                        _stream << get<double, double>(_node);
                        break;
                    case string_node:
                        _stream << '"' << get_string(_node) << '"';
                        break;
                    case binary_node:
                        {
                            byte* bytes = reinterpret_cast<byte*>(
                                _node.get_data()
                            );
                            std::ios::fmtflags flags( _stream.flags() );

                            _stream
                                << std::hex
                                << std::setw(2)
                                << std::setfill('0')
                            ;
                            copy(
                                    bytes + 5U,
                                    bytes + 5U + *static_cast<int*>(
                                        _node.get_data()
                                    ),
                                    std::ostream_iterator<int>(_stream)
                            );
                            _stream.flags(flags);
                            break;
                        }
                    case boolean_node:
                        _stream << (get<bool, byte>(_node) ? "true" : "false");
                        break;
                    case null_node:
                        _stream << "(null)";
                        break;
                    case int32_node:
                        _stream << get<int, int>(_node);
                        break;
                    case int64_node:
                        _stream << get<long long, long long>(_node);
                        break;
                    default:
                        break;
                }
            }

        public:
            document() : bytes(NULL), size(0U) { }

            document(void* bytes, size_t count)
                : bytes(reinterpret_cast<byte*>(bytes)), size(count)
            {
            }

            bool valid() const
            {
                return (size >= 7U) && (bytes[size -1] == 0);
            }

            double get(const std::string& name, double _default) const
            {
                return get<double, double>(name, _default);
            }

            std::string get(
                const std::string& name,
                const std::string& _default
            ) const
            {
                node _node;
                bool found = lookup(name.c_str(), _node);
                std::string result(_default);

                if (found)
                    result = get_string(_node);

                return result;
            }

            document get(
                const std::string& name,
                const document& _default
            ) const
            {
                node _node;
                bool found = lookup(name.c_str(), _node);
                document result(_default);

                if (found)
                    result = document(_node.bytes, _node.get_size());

                return result;
            }

            std::pair<void*, size_t> get(const std::string& name) const
            {
                node _node;
                bool found = lookup(name.c_str(), _node);
                std::pair<void*, size_t> result(NULL, 0U);

                if (found) {
                    result.second = *reinterpret_cast<int*>(_node.get_data());
                    result.first = reinterpret_cast<byte*>(_node.get_data()) + 5U;
                }

                return result;
            }

            bool get(const std::string& name, bool _default) const
            {
                return get<bool, byte>(name, _default);
            }

            int get(const std::string& name, int _default) const
            {
                return get<int, int>(name, _default);
            }

            long long get(const std::string& name, long long _default) const
            {
                return get<long long, long long>(name, _default);
            }

            void dump(std::ostream& _stream) const
            {
                byte* iterator = bytes + sizeof(int);
                size_t left = size - sizeof(int);
                node _node(iterator);

                _stream << "{ ";

                while (_node.valid(left))
                {
                    _stream << _node.get_name() << " : ";

                    if (_node.get_type() == document_node)
                        document(
                                _node.get_data(),
                                *static_cast<int*>(_node.get_data())
                                ).dump(_stream);
                    else
                        dump(_node, _stream);

                    iterator += _node.get_size();
                    left -= _node.get_size();
                    _node = node(iterator);

                    if (_node.valid(left))
                        _stream << ", ";
                }

                _stream << " }";
            }

            bool contains(const std::string& name)
            {
                node _node;

                return lookup(name.c_str(), _node);
            }

            template<typename T>
            bool contains(const std::string& name)
            {
                node _node;
                bool found = lookup(name.c_str(), _node);

                return (
                    found
                    && (_node.get_type() == type_converter<T>::node_type_code)
                );
            }
    };
}
<commit_msg>Fix string size calculation in microbson.<commit_after>#pragma once

#include <cstddef>
#include <cstring>
#include <string>
#include <utility>
#include <iterator>
#include <iomanip>

namespace microbson
{
    typedef unsigned char byte;

    enum node_type {
        double_node = 0x01,
        string_node = 0x02,
        document_node = 0x03,
        binary_node = 0x05,
        boolean_node = 0x08,
        null_node = 0x0A,
        int32_node = 0x10,
        int64_node = 0x12,
        unknown_node = 0xFF
    };

    class document;

    template<typename T> struct type_converter { };

    template<> struct type_converter<double>
    {
        enum { node_type_code = double_node };
    };

    template<> struct type_converter<std::string>
    {
        enum { node_type_code = string_node };
    };

    template<> struct type_converter<document>
    {
        enum { node_type_code = document_node };
    };

    template<> struct type_converter<void*>
    {
        enum { node_type_code = binary_node };
    };

    template<> struct type_converter<bool>
    {
        enum { node_type_code = boolean_node };
    };

    template<> struct type_converter<int>
    {
        enum { node_type_code = int32_node };
    };

    template<> struct type_converter<long long>
    {
        enum { node_type_code = int64_node };
    };

    struct node
    {
        byte* bytes;

        node() : bytes(NULL) { }

        node(byte* bytes) : bytes(bytes) { }

        node_type get_type() const { return static_cast<node_type>(bytes[0]); }

        const char* get_name() const
        {
            return reinterpret_cast<const char*>( bytes + 1 );
        }

        size_t get_size() const
        {
            size_t result = 1U + strlen(get_name()) + 1U;

            switch (get_type())
            {
                case double_node:
                    result += sizeof(double);
                    break;
                case document_node:
                    result += *reinterpret_cast<int*>(bytes + result);
                    break;
                case string_node:
                case binary_node:
                    result += (
                        sizeof(int)
                            + *reinterpret_cast<int*>(bytes + result)
                            + 1U
                    );
                    break;
                case boolean_node:
                    result += 1U;
                case null_node:
                    break;
                case int32_node:
                    result += sizeof(int);
                    break;
                case int64_node:
                    result += sizeof(long long);
                    break;
                default:
                    result = 0U;
                    break;
            }

            return result;
        }

        void* get_data() const
        {
            return bytes + 1U + strlen(get_name()) + 1U;
        }

        bool valid(size_t size) const
        {
            return (size >= 2) && (get_size() <= size);
        }
    };

    class document
    {
        private:
            byte* bytes;
            size_t size;

            bool lookup(const char* name, node& result) const
            {
                byte* iterator = bytes + sizeof(int);
                size_t left = size - sizeof(int);
                bool found = false;

                result = node(iterator);

                while (result.valid(left))
                {
                    if (strcmp(result.get_name(), name) == 0)
                    {
                        found = true;
                        break;
                    }
                    else
                    {
                        iterator += result.get_size();
                        left -= result.get_size();
                        result = node(iterator);
                    }
                }

                return found;
            }

            template<typename T, typename W>
                T get(node _node) const
                {
                    return static_cast<T>(
                        *reinterpret_cast<W*>(_node.get_data())
                    );
                }

            std::string get_string(const node& _node) const
            {
                return std::string(
                    reinterpret_cast<const char*>(_node.get_data())
                        + sizeof(int),
                    *reinterpret_cast<int*>(_node.get_data()) - 1
                );
            }

            template<typename T, typename W>
                T get(const std::string& name, T _default) const
                {
                    node _node;

                    return lookup(name.c_str(), _node)
                        ? get<T, W>(_node)
                        : _default
                    ;
                }

            void dump(const node& _node, std::ostream& _stream) const
            {
                switch(_node.get_type())
                {
                    case double_node:
                        _stream << get<double, double>(_node);
                        break;
                    case string_node:
                        _stream << '"' << get_string(_node) << '"';
                        break;
                    case binary_node:
                        {
                            byte* bytes = reinterpret_cast<byte*>(
                                _node.get_data()
                            );
                            std::ios::fmtflags flags( _stream.flags() );

                            _stream
                                << std::hex
                                << std::setw(2)
                                << std::setfill('0')
                            ;
                            copy(
                                    bytes + 5U,
                                    bytes + 5U + *static_cast<int*>(
                                        _node.get_data()
                                    ),
                                    std::ostream_iterator<int>(_stream)
                            );
                            _stream.flags(flags);
                            break;
                        }
                    case boolean_node:
                        _stream << (get<bool, byte>(_node) ? "true" : "false");
                        break;
                    case null_node:
                        _stream << "(null)";
                        break;
                    case int32_node:
                        _stream << get<int, int>(_node);
                        break;
                    case int64_node:
                        _stream << get<long long, long long>(_node);
                        break;
                    default:
                        break;
                }
            }

        public:
            document() : bytes(NULL), size(0U) { }

            document(void* bytes, size_t count)
                : bytes(reinterpret_cast<byte*>(bytes)), size(count)
            {
            }

            bool valid() const
            {
                return (size >= 7U) && (bytes[size -1] == 0);
            }

            double get(const std::string& name, double _default) const
            {
                return get<double, double>(name, _default);
            }

            std::string get(
                const std::string& name,
                const std::string& _default
            ) const
            {
                node _node;
                bool found = lookup(name.c_str(), _node);
                std::string result(_default);

                if (found)
                    result = get_string(_node);

                return result;
            }

            document get(
                const std::string& name,
                const document& _default
            ) const
            {
                node _node;
                bool found = lookup(name.c_str(), _node);
                document result(_default);

                if (found)
                    result = document(_node.bytes, _node.get_size());

                return result;
            }

            std::pair<void*, size_t> get(const std::string& name) const
            {
                node _node;
                bool found = lookup(name.c_str(), _node);
                std::pair<void*, size_t> result(NULL, 0U);

                if (found) {
                    result.second = *reinterpret_cast<int*>(_node.get_data());
                    result.first = reinterpret_cast<byte*>(_node.get_data()) + 5U;
                }

                return result;
            }

            bool get(const std::string& name, bool _default) const
            {
                return get<bool, byte>(name, _default);
            }

            int get(const std::string& name, int _default) const
            {
                return get<int, int>(name, _default);
            }

            long long get(const std::string& name, long long _default) const
            {
                return get<long long, long long>(name, _default);
            }

            void dump(std::ostream& _stream) const
            {
                byte* iterator = bytes + sizeof(int);
                size_t left = size - sizeof(int);
                node _node(iterator);

                _stream << "{ ";

                while (_node.valid(left))
                {
                    _stream << _node.get_name() << " : ";

                    if (_node.get_type() == document_node)
                        document(
                                _node.get_data(),
                                *static_cast<int*>(_node.get_data())
                                ).dump(_stream);
                    else
                        dump(_node, _stream);

                    iterator += _node.get_size();
                    left -= _node.get_size();
                    _node = node(iterator);

                    if (_node.valid(left))
                        _stream << ", ";
                }

                _stream << " }";
            }

            bool contains(const std::string& name)
            {
                node _node;

                return lookup(name.c_str(), _node);
            }

            template<typename T>
            bool contains(const std::string& name)
            {
                node _node;
                bool found = lookup(name.c_str(), _node);

                return (
                    found
                    && (_node.get_type() == type_converter<T>::node_type_code)
                );
            }
    };
}
<|endoftext|>


<commit_before>#include <iostream>
#include <queue>
#include <utility>

using namespace std;
typedef  pair<int,int> node;

int re[1000000];
int main(int argc, char const *argv[])
{
	priority_queue<node> pq;

	pq.push(make_pair(1,2));
	node n;
	while(1){

		node n=pq.top();

		pq.pop();

		switch(n.second){
			case 2:
				pq.push(make_pair(n.first*2,3));
			break;
			case 3:
				pq.push(make_pair(n.first*3,5));
			break;
			case 5:
				pq.push(make_pair(n.first*5,0));
			break;
		}

	}
	return 0;
}<commit_msg>update 346588<commit_after>#include <iostream>
#include <queue>
#include <utility>

using namespace std;
typedef  pair<int,int> node;

int re[1000000];
int main(int argc, char const *argv[])
{
	priority_queue<node> pq;

	pq.push(make_pair(1,2));
	node n;
	int i=0;
	while(1){

		node n=pq.top();

		pq.pop();

		switch(n.second){
			case 2:
				pq.push(make_pair(n.first*2,3));
			break;
			case 3:
				pq.push(make_pair(n.first*3,5));
			break;
			case 5:
				pq.push(make_pair(n.first*5,0));
			break;
		}
		re[i++]=n.first;

	}
	return 0;
}<|endoftext|>


<commit_before>/*
 * EnvironmentMonitor.cpp
 *
 * Copyright (C) 2009-12 by RStudio, Inc.
 *
 * Unless you have received this program directly from RStudio pursuant
 * to the terms of a commercial license agreement with RStudio, then
 * this program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

#include "EnvironmentMonitor.hpp"

#include <r/RSexp.hpp>
#include <r/RInterface.hpp>
#include <session/SessionModuleContext.hpp>

#include "EnvironmentUtils.hpp"

using namespace core;

namespace session {
namespace modules {
namespace environment {
namespace {

bool compareVarName(const r::sexp::Variable& var1,
                    const r::sexp::Variable& var2)
{
   return var1.first < var2.first;
}

void enqueRefreshEvent()
{
   ClientEvent refreshEvent(client_events::kEnvironmentRefresh);
   module_context::enqueClientEvent(refreshEvent);
}

// if the given variable is an unevaluated promise, add it to the given
// list of variables
void addUnevaledPromise(std::vector<r::sexp::Variable>* pEnv,
                        const r::sexp::Variable& var)
{
   if (isUnevaluatedPromise(var.second))
   {
      pEnv->push_back(var);
   }
}

// if the given variable exists in the given list, remove it
void removeVarFromList(std::vector<r::sexp::Variable>* pEnv,
                       const r::sexp::Variable& var)
{
   std::vector<r::sexp::Variable>::iterator iter =
         std::find(pEnv->begin(), pEnv->end(), var);
   if (iter != pEnv->end())
   {
      pEnv->erase(iter);
   }
}

} // anonymous namespace

EnvironmentMonitor::EnvironmentMonitor() :
   initialized_(false)
{}

void EnvironmentMonitor::enqueRemovedEvent(const r::sexp::Variable& variable)
{
   ClientEvent removedEvent(client_events::kEnvironmentRemoved, variable.first);
   module_context::enqueClientEvent(removedEvent);
}

void EnvironmentMonitor::enqueAssignedEvent(const r::sexp::Variable& variable)
{
   // get object info
   json::Value objInfo = varToJson(getMonitoredEnvironment(), variable);

   // enque event
   ClientEvent assignedEvent(client_events::kEnvironmentAssigned, objInfo);
   module_context::enqueClientEvent(assignedEvent);
}

void EnvironmentMonitor::setMonitoredEnvironment(SEXP pEnvironment)
{
   environment_.set(pEnvironment);

   // init the environment by doing an initial check for changes
   initialized_ = false;
   checkForChanges();
}

SEXP EnvironmentMonitor::getMonitoredEnvironment()
{
   return environment_.get();
}

void EnvironmentMonitor::listEnv(std::vector<r::sexp::Variable>* pEnv)
{
   r::sexp::Protect rProtect;
   r::sexp::listEnvironment(getMonitoredEnvironment(), false, &rProtect, pEnv);
}

void EnvironmentMonitor::checkForChanges()
{
   // information about the current environment
   std::vector<r::sexp::Variable> currentEnv ;
   std::vector<r::sexp::Variable> currentPromises;

   // list of assigns/removes (includes both value changes and promise
   // evaluations)
   std::vector<r::sexp::Variable> addedVars;
   std::vector<r::sexp::Variable> removedVars;

   // get the set of variables and promises in the current environment
   listEnv(&currentEnv);

   // R returns an environment list sorted in dictionary order. Since the
   // set difference algorithms below use simple string comparisons to
   // establish order, we need to re-sort the list into canonical order
   // to avoid the algorithms detecting superfluous insertions.
   std::sort(currentEnv.begin(), currentEnv.end(), compareVarName);

   std::for_each(currentEnv.begin(), currentEnv.end(),
                 boost::bind(addUnevaledPromise, &currentPromises, _1));

   bool refreshEnqueued = false;
   if (!initialized_)
   {
      if (getMonitoredEnvironment() == R_GlobalEnv)
      {
         enqueRefreshEvent();
         refreshEnqueued = true;
      }
      initialized_ = true;
   }
   else
   {
      if (currentEnv != lastEnv_)
      {
         // optimize for empty currentEnv (user reset workspace) or empty
         // lastEnv_ (startup) by just sending a single refresh event
         // only do this for the global environment--while debugging local
         // environments, the environment object list is sent down as part of
         // the context depth event.
         if ((currentEnv.empty() || lastEnv_.empty())
             && getMonitoredEnvironment() == R_GlobalEnv)
         {
            enqueRefreshEvent();
            refreshEnqueued = true;
         }
         else
         {
            std::set_difference(lastEnv_.begin(), lastEnv_.end(),
                                currentEnv.begin(), currentEnv.end(),
                                std::back_inserter(removedVars),
                                compareVarName);

            // fire removed event for deletes
            std::for_each(removedVars.begin(),
                          removedVars.end(),
                          boost::bind(&EnvironmentMonitor::enqueRemovedEvent,
                                      this, _1));

            // remove deleted objects from the list of uneval'ed promises
            // so we'll stop monitoring them for evaluation
            std::for_each(removedVars.begin(),
                          removedVars.end(),
                          boost::bind(removeVarFromList, &unevaledPromises_, _1));

            // find adds & assigns (all variable name/value combinations in the
            // current environment but NOT in the previous environment)
            std::set_difference(currentEnv.begin(), currentEnv.end(),
                                lastEnv_.begin(), lastEnv_.end(),
                                std::back_inserter(addedVars));
         }
      }
      // if a refresh is scheduled there's no need to emit add events one by one
      if (!refreshEnqueued)
      {
         // have any promises been evaluated since we last checked?
         if (currentPromises != unevaledPromises_)
         {
            // for each promise that is in the set of promises we are monitoring
            // for evaluation but not in the set of currently tracked promises,
            // we assume this to be an eval--process as an assign
            std::set_difference(unevaledPromises_.begin(), unevaledPromises_.end(),
                                currentPromises.begin(), currentPromises.end(),
                                std::back_inserter(addedVars));
         }

         // fire assigned event for adds, assigns, and promise evaluations
         std::for_each(addedVars.begin(),
                       addedVars.end(),
                       boost::bind(&EnvironmentMonitor::enqueAssignedEvent,
                                    this, _1));
      }
   }

   unevaledPromises_ = currentPromises;
   lastEnv_ = currentEnv;
}

} // namespace environment
} // namespace modules
} // namespace session
<commit_msg>fix promise evaluation display when promise SEXP is simultaneously eval'ed and assigned<commit_after>/*
 * EnvironmentMonitor.cpp
 *
 * Copyright (C) 2009-12 by RStudio, Inc.
 *
 * Unless you have received this program directly from RStudio pursuant
 * to the terms of a commercial license agreement with RStudio, then
 * this program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

#include "EnvironmentMonitor.hpp"

#include <r/RSexp.hpp>
#include <r/RInterface.hpp>
#include <session/SessionModuleContext.hpp>

#include "EnvironmentUtils.hpp"

using namespace core;

namespace session {
namespace modules {
namespace environment {
namespace {

bool compareVarName(const r::sexp::Variable& var1,
                    const r::sexp::Variable& var2)
{
   return var1.first < var2.first;
}

void enqueRefreshEvent()
{
   ClientEvent refreshEvent(client_events::kEnvironmentRefresh);
   module_context::enqueClientEvent(refreshEvent);
}

// if the given variable is an unevaluated promise, add it to the given
// list of variables
void addUnevaledPromise(std::vector<r::sexp::Variable>* pEnv,
                        const r::sexp::Variable& var)
{
   if (isUnevaluatedPromise(var.second))
   {
      pEnv->push_back(var);
   }
}

// If the given variable exists in the given list, remove it. Compares on name
// only.
void removeVarFromList(std::vector<r::sexp::Variable>* pEnv,
                       const r::sexp::Variable& var)
{
   for (std::vector<r::sexp::Variable>::iterator iter = pEnv->begin();
        iter != pEnv->end(); iter++)
   {
      if (iter->first == var.first)
      {
         pEnv->erase(iter);
         break;
      }
   }
}

} // anonymous namespace

EnvironmentMonitor::EnvironmentMonitor() :
   initialized_(false)
{}

void EnvironmentMonitor::enqueRemovedEvent(const r::sexp::Variable& variable)
{
   ClientEvent removedEvent(client_events::kEnvironmentRemoved, variable.first);
   module_context::enqueClientEvent(removedEvent);
}

void EnvironmentMonitor::enqueAssignedEvent(const r::sexp::Variable& variable)
{
   // get object info
   json::Value objInfo = varToJson(getMonitoredEnvironment(), variable);

   // enque event
   ClientEvent assignedEvent(client_events::kEnvironmentAssigned, objInfo);
   module_context::enqueClientEvent(assignedEvent);
}

void EnvironmentMonitor::setMonitoredEnvironment(SEXP pEnvironment)
{
   environment_.set(pEnvironment);

   // init the environment by doing an initial check for changes
   initialized_ = false;
   checkForChanges();
}

SEXP EnvironmentMonitor::getMonitoredEnvironment()
{
   return environment_.get();
}

void EnvironmentMonitor::listEnv(std::vector<r::sexp::Variable>* pEnv)
{
   r::sexp::Protect rProtect;
   r::sexp::listEnvironment(getMonitoredEnvironment(), false, &rProtect, pEnv);
}

void EnvironmentMonitor::checkForChanges()
{
   // information about the current environment
   std::vector<r::sexp::Variable> currentEnv ;
   std::vector<r::sexp::Variable> currentPromises;

   // list of assigns/removes (includes both value changes and promise
   // evaluations)
   std::vector<r::sexp::Variable> addedVars;
   std::vector<r::sexp::Variable> removedVars;

   // get the set of variables and promises in the current environment
   listEnv(&currentEnv);

   // R returns an environment list sorted in dictionary order. Since the
   // set difference algorithms below use simple string comparisons to
   // establish order, we need to re-sort the list into canonical order
   // to avoid the algorithms detecting superfluous insertions.
   std::sort(currentEnv.begin(), currentEnv.end(), compareVarName);

   std::for_each(currentEnv.begin(), currentEnv.end(),
                 boost::bind(addUnevaledPromise, &currentPromises, _1));

   bool refreshEnqueued = false;
   if (!initialized_)
   {
      if (getMonitoredEnvironment() == R_GlobalEnv)
      {
         enqueRefreshEvent();
         refreshEnqueued = true;
      }
      initialized_ = true;
   }
   else
   {
      if (currentEnv != lastEnv_)
      {
         // optimize for empty currentEnv (user reset workspace) or empty
         // lastEnv_ (startup) by just sending a single refresh event
         // only do this for the global environment--while debugging local
         // environments, the environment object list is sent down as part of
         // the context depth event.
         if ((currentEnv.empty() || lastEnv_.empty())
             && getMonitoredEnvironment() == R_GlobalEnv)
         {
            enqueRefreshEvent();
            refreshEnqueued = true;
         }
         else
         {
            std::set_difference(lastEnv_.begin(), lastEnv_.end(),
                                currentEnv.begin(), currentEnv.end(),
                                std::back_inserter(removedVars),
                                compareVarName);

            // fire removed event for deletes
            std::for_each(removedVars.begin(),
                          removedVars.end(),
                          boost::bind(&EnvironmentMonitor::enqueRemovedEvent,
                                      this, _1));

            // remove deleted objects from the list of uneval'ed promises
            // so we'll stop monitoring them for evaluation
            std::for_each(removedVars.begin(),
                          removedVars.end(),
                          boost::bind(removeVarFromList, &unevaledPromises_, _1));

            // find adds & assigns (all variable name/value combinations in the
            // current environment but NOT in the previous environment)
            std::set_difference(currentEnv.begin(), currentEnv.end(),
                                lastEnv_.begin(), lastEnv_.end(),
                                std::back_inserter(addedVars));

            // remove assigned objects from the list of uneval'ed promises
            // (otherwise, we double-assign in the case where a promise SEXP
            // is simultaneously forced/evaluated and assigned a new value)
            std::for_each(addedVars.begin(),
                          addedVars.end(),
                          boost::bind(removeVarFromList, &unevaledPromises_, _1));

         }
      }
      // if a refresh is scheduled there's no need to emit add events one by one
      if (!refreshEnqueued)
      {
         // have any promises been evaluated since we last checked?
         if (currentPromises != unevaledPromises_)
         {
            // for each promise that is in the set of promises we are monitoring
            // for evaluation but not in the set of currently tracked promises,
            // we assume this to be an eval--process as an assign
            std::set_difference(unevaledPromises_.begin(), unevaledPromises_.end(),
                                currentPromises.begin(), currentPromises.end(),
                                std::back_inserter(addedVars));
         }

         // fire assigned event for adds, assigns, and promise evaluations
         std::for_each(addedVars.begin(),
                       addedVars.end(),
                       boost::bind(&EnvironmentMonitor::enqueAssignedEvent,
                                    this, _1));
      }
   }

   unevaledPromises_ = currentPromises;
   lastEnv_ = currentEnv;
}

} // namespace environment
} // namespace modules
} // namespace session
<|endoftext|>


<commit_before>//
//  application_context.cpp
//  usbtest
//
//  Created by Kristoffer Andersen on 13/07/15.
//  Copyright (c) 2015 Monolit ApS. All rights reserved.
//

#include "application_context.h"
#include "application_controller_interface.h"
#include <display_painter.h>
#include "consoles.h"
#include <mbed_interface.h>

extern "C" {
#include <project.h>
}

void faultExceptionHandler()
{
    mbed_die();
}

using namespace mono;

ApplicationContext ApplicationContext::singleton;
IApplicationContext *IApplicationContext::Instance = NULL; //&(ApplicationContext::singleton);

ApplicationContext::ApplicationContext() : IApplicationContext(&pwrMgmt, &runLoop, &dispController), dispController()
{
    PWM_Start();
    PWM_WriteCompare1(0);
    PWM_WriteCompare2(0);
}

int ApplicationContext::exec()
{
    runLoop.exec();

    return 0;
}

void ApplicationContext::setMonoApplication(mono::IApplication *monoApp)
{
    this->application = monoApp;

    //CyIntSetSysVector(CY_INT_NMI_IRQN, &faultExceptionHandler);
    CyIntSetSysVector(CY_INT_HARD_FAULT_IRQN, &faultExceptionHandler);
    //CyIntSetSysVector(CY_INT_MEM_MANAGE_IRQN, &faultExceptionHandler);
    //CyIntSetSysVector(CY_INT_BUS_FAULT_IRQN, &faultExceptionHandler);
    //CyIntSetSysVector(CY_INT_USAGE_FAULT_IRQN, &faultExceptionHandler);

    //PowerSystem->onSystemPowerOnReset();
    //pwrMgmt.processResetAwarenessQueue();

    //defaultSerial.printf("Display init deactivated\n\t");
    mono::IApplicationContext::Instance->DisplayController->init();

    monoApp->monoWakeFromReset();

}

void ApplicationContext::sleepForMs(uint32_t ms)
{
    uint8_t ticks = 1;
    while ((1u << ticks) < ms) {
        ticks++;
    }

    defaultSerial.printf("Setting CTW to: %i for ms: %i\n\r",ticks, ms);
    *((reg8*)CYREG_PM_TW_CFG1) = 0x0F & ticks;
    PM_TW_CFG2 = PM_TW_CFG2 | 0x0C; // CTW enable and CTW interrupts
    defaultSerial.printf("CTW CFG Reg: 0x%x\n\r",PM_TW_CFG2);
    enterSleepMode();
}

void ApplicationContext::enterSleepMode()
{
    this->application->monoWillGotoSleep();

    PowerManager->EnterSleep();

    this->application->monoWakeFromSleep();

}

void ApplicationContext::_softwareReset()
{
    Bootloadable_SET_RUN_TYPE(Bootloadable_START_APP);
    CySoftwareReset();
    while(1); // silence compiler warning
}

void ApplicationContext::_softwareResetToBootloader()
{
    Bootloadable_SET_RUN_TYPE(Bootloadable_START_BTLDR);
    CySoftwareReset();
    while(1); // silence compiler warning
}

void ApplicationContext::resetOnUserButton()
{
    debug("Mono will reset on user button!\n\r");
    this->runLoop.setResetOnUserButton(true);
}

<commit_msg>fault handler call mbed directly<commit_after>//
//  application_context.cpp
//  usbtest
//
//  Created by Kristoffer Andersen on 13/07/15.
//  Copyright (c) 2015 Monolit ApS. All rights reserved.
//

#include "application_context.h"
#include "application_controller_interface.h"
#include <display_painter.h>
#include "consoles.h"
#include <mbed_interface.h>

extern "C" {
#include <project.h>
}

using namespace mono;

ApplicationContext ApplicationContext::singleton;
IApplicationContext *IApplicationContext::Instance = NULL; //&(ApplicationContext::singleton);

ApplicationContext::ApplicationContext() : IApplicationContext(&pwrMgmt, &runLoop, &dispController), dispController()
{
    PWM_Start();
    PWM_WriteCompare1(0);
    PWM_WriteCompare2(0);
}

int ApplicationContext::exec()
{
    runLoop.exec();

    return 0;
}

void ApplicationContext::setMonoApplication(mono::IApplication *monoApp)
{
    this->application = monoApp;

    //CyIntSetSysVector(CY_INT_NMI_IRQN, &faultExceptionHandler);
    CyIntSetSysVector(CY_INT_HARD_FAULT_IRQN, &mbed_die);
    //CyIntSetSysVector(CY_INT_MEM_MANAGE_IRQN, &faultExceptionHandler);
    //CyIntSetSysVector(CY_INT_BUS_FAULT_IRQN, &faultExceptionHandler);
    //CyIntSetSysVector(CY_INT_USAGE_FAULT_IRQN, &faultExceptionHandler);

    //PowerSystem->onSystemPowerOnReset();
    pwrMgmt.processResetAwarenessQueue();

    //defaultSerial.printf("Display init deactivated\n\t");
    mono::IApplicationContext::Instance->DisplayController->init();

    monoApp->monoWakeFromReset();

}

void ApplicationContext::sleepForMs(uint32_t ms)
{
    uint8_t ticks = 1;
    while ((1u << ticks) < ms) {
        ticks++;
    }

    defaultSerial.printf("Setting CTW to: %i for ms: %i\n\r",ticks, ms);
    *((reg8*)CYREG_PM_TW_CFG1) = 0x0F & ticks;
    PM_TW_CFG2 = PM_TW_CFG2 | 0x0C; // CTW enable and CTW interrupts
    defaultSerial.printf("CTW CFG Reg: 0x%x\n\r",PM_TW_CFG2);
    enterSleepMode();
}

void ApplicationContext::enterSleepMode()
{
    this->application->monoWillGotoSleep();

    PowerManager->EnterSleep();

    this->application->monoWakeFromSleep();

}

void ApplicationContext::_softwareReset()
{
    Bootloadable_SET_RUN_TYPE(Bootloadable_START_APP);
    CySoftwareReset();
    while(1); // silence compiler warning
}

void ApplicationContext::_softwareResetToBootloader()
{
    Bootloadable_SET_RUN_TYPE(Bootloadable_START_BTLDR);
    CySoftwareReset();
    while(1); // silence compiler warning
}

void ApplicationContext::resetOnUserButton()
{
    debug("Mono will reset on user button!\n\r");
    this->runLoop.setResetOnUserButton(true);
}

<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/initfiles/p9_psi_scom.C $  */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016                             */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
#include "p9_psi_scom.H"
#include <stdint.h>
#include <stddef.h>
#include <fapi2.H>

using namespace fapi2;

constexpr uint64_t literal_0xFE00000000000000 = 0xFE00000000000000;
constexpr uint64_t literal_0x0000000000000000 = 0x0000000000000000;
constexpr uint64_t literal_0b00111001000000101111111111111 = 0b00111001000000101111111111111;
constexpr uint64_t literal_0b00000000000000000000000000000 = 0b00000000000000000000000000000;
constexpr uint64_t literal_0b11000110001010010000000000000 = 0b11000110001010010000000000000;
constexpr uint64_t literal_0x000 = 0x000;
constexpr uint64_t literal_0b00000 = 0b00000;

fapi2::ReturnCode p9_psi_scom(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& TGT0)
{
    {
        fapi2::ATTR_EC_Type   l_chip_ec;
        fapi2::ATTR_NAME_Type l_chip_id;
        FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_NAME, TGT0, l_chip_id));
        FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_EC, TGT0, l_chip_ec));
        fapi2::buffer<uint64_t> l_scom_buffer;
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x4011803ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 7, 0, uint64_t>(literal_0xFE00000000000000 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x4011803ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x4011806ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 7, 0, uint64_t>(literal_0x0000000000000000 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x4011806ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x4011807ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 7, 0, uint64_t>(literal_0x0000000000000000 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x4011807ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5012903ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 29, 35, uint64_t>(literal_0b00111001000000101111111111111 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5012903ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5012906ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 29, 35, uint64_t>(literal_0b00000000000000000000000000000 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5012906ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5012907ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 29, 35, uint64_t>(literal_0b11000110001010010000000000000 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5012907ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x501290full, l_scom_buffer ));

            l_scom_buffer.insert<16, 12, 52, uint64_t>(literal_0x000 );
            l_scom_buffer.insert<48, 5, 59, uint64_t>(literal_0b00000 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x501290full, l_scom_buffer));
        }

    };
fapi_try_exit:
    return fapi2::current_err;
}
<commit_msg>PSI FIR updates<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/initfiles/p9_psi_scom.C $  */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2017                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
#include "p9_psi_scom.H"
#include <stdint.h>
#include <stddef.h>
#include <fapi2.H>

using namespace fapi2;

constexpr uint64_t literal_0xFE00000000000000 = 0xFE00000000000000;
constexpr uint64_t literal_0x0000000000000000 = 0x0000000000000000;
constexpr uint64_t literal_0b00111111000000100000011011111 = 0b00111111000000100000011011111;
constexpr uint64_t literal_0b00000000000000000000000000000 = 0b00000000000000000000000000000;
constexpr uint64_t literal_0b11000000001010011111100100000 = 0b11000000001010011111100100000;
constexpr uint64_t literal_0x000 = 0x000;
constexpr uint64_t literal_0b00000 = 0b00000;

fapi2::ReturnCode p9_psi_scom(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& TGT0)
{
    {
        fapi2::ATTR_EC_Type   l_chip_ec;
        fapi2::ATTR_NAME_Type l_chip_id;
        FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_NAME, TGT0, l_chip_id));
        FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_EC, TGT0, l_chip_ec));
        fapi2::buffer<uint64_t> l_scom_buffer;
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x4011803ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 7, 0, uint64_t>(literal_0xFE00000000000000 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x4011803ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x4011806ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 7, 0, uint64_t>(literal_0x0000000000000000 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x4011806ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x4011807ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 7, 0, uint64_t>(literal_0x0000000000000000 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x4011807ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5012903ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 29, 35, uint64_t>(literal_0b00111111000000100000011011111 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5012903ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5012906ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 29, 35, uint64_t>(literal_0b00000000000000000000000000000 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5012906ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x5012907ull, l_scom_buffer ));

            l_scom_buffer.insert<0, 29, 35, uint64_t>(literal_0b11000000001010011111100100000 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x5012907ull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x501290full, l_scom_buffer ));

            l_scom_buffer.insert<16, 12, 52, uint64_t>(literal_0x000 );
            l_scom_buffer.insert<48, 5, 59, uint64_t>(literal_0b00000 );
            FAPI_TRY(fapi2::putScom(TGT0, 0x501290full, l_scom_buffer));
        }

    };
fapi_try_exit:
    return fapi2::current_err;
}
<|endoftext|>


<commit_before>/*
 *  Bubble.cpp
 *  openc2e
 *
 *  Created by Alyssa Milburn on Sat Apr 26 2008.
 *  Copyright (c) 2008 Alyssa Milburn. All rights reserved.
 *
 *  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 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.
 *
 */

#include "Bubble.h"
#include "World.h"
#include "Engine.h"
#include "Backend.h"
#include "Camera.h"
#include "creaturesImage.h"

// class BubblePart *ourPart;

Bubble::Bubble(unsigned char family, unsigned char genus, unsigned short species, unsigned int plane,
		std::string spritefile, unsigned int firstimage, unsigned int imagecount,
		unsigned int tx, unsigned int ty, unsigned int twidth, unsigned int theight,
		unsigned int bgcolour, unsigned int tcolour)
		: CompoundAgent(family, genus, species, plane, spritefile, firstimage, imagecount) {
	ourPart = new BubblePart(this, 1, tx, ty);
	addPart(ourPart);
	ourPart->textwidth = twidth;
	ourPart->textheight = theight;
	ourPart->backgroundcolour = bgcolour;
	ourPart->textcolour = tcolour;

	ourPart->editable = false;
}

void Bubble::setText(std::string s) {
	ourPart->setText(s);
}

std::string Bubble::getText() {
	return ourPart->text;
}

void Bubble::setEditing(bool e) {
	ourPart->editable = e;
	if (e)
		world.setFocus(ourPart); // gain focus
	else if (world.focusagent == AgentRef(this) && world.focuspart == ourPart->id)
		world.setFocus(0); // lose focus
}

void Bubble::setTimeout(unsigned int t) {
	timeout = t;
}

void Bubble::tick() {
	CompoundAgent::tick();

	if (!paused && timeout) {
		timeout--;
		if (timeout == 0) kill();
	}
}

void Bubble::turnIntoSpeech() {
	newBubble((Agent *)world.hand(), true, getText());

	// TODO: announce via shou
	// TODO: add to speech history

	kill();
}

Bubble *Bubble::newBubble(Agent *parent, bool speech, std::string text) {
	assert(engine.version < 3);

	assert(parent);

	bool leftside = false;
	// TODO: cope with wrap
	if (parent->x - world.camera->getX() < world.camera->getWidth() / 2) leftside = true;

	int pose;
	if (engine.version == 1) {
		// C1 poses
		if (speech)
			pose = leftside ? 10 : 9;
		else
			pose = leftside ? 12 : 11;
	} else {
		// C2 poses
		// pose adjusted on setText() if necessary
		if (speech)
			pose = leftside ? 21 : 18;
		else
			pose = leftside ? 27 : 24;
	}

	int plane;
	if (engine.version == 1) {
		plane = 9000;
	} else {
		// C2
		if (parent == (Agent *)world.hand())
			plane = 9999;
		else
			plane = 9995;
	}

	int xoffset = (engine.version == 1) ? 6 : 8;
	int yoffset = (engine.version == 1) ? 3 : 8;
	int twidth = (engine.version == 1) ? 144 : 95; // extended to fit text upon setText()

	Bubble *ourBubble = new Bubble(2, 1, speech ? 2 : 1, plane, "syst", pose, engine.version == 1 ? 1 : 3, xoffset, yoffset, twidth, 12, 0, 0);
	ourBubble->finishInit();
	ourBubble->leftside = leftside;

	ourBubble->attr = 32; // floating
	ourBubble->floatTo(parent);

	// TODO: fix positioning
	if (leftside)
		ourBubble->moveTo(parent->x + parent->getWidth() - 2, parent->y - ourBubble->getHeight());
	else
		ourBubble->moveTo(parent->x - ourBubble->getWidth() + 2, parent->y - ourBubble->getHeight());

	ourBubble->setText(text);

	if (speech)
		ourBubble->setTimeout(2 * 10); // TODO: 2s is probably not right
	else
		ourBubble->setEditing(true);

	return ourBubble;
}

/*
  class BubblePart : public CompoundPart {
	bool editable;
	std::string text;
	unsigned int textwidth, textheight;
	unsigned int backgroundcolour, textcolour;
*/

BubblePart::BubblePart(Bubble *p, unsigned int _id, int x, int y) : CompoundPart(p, _id, x, y, 1) {
	editable = false;
	textwidth = 0;
	textheight = 0;
	textoffset = 0; // doesn't matter when text is empty
}

void BubblePart::partRender(class Surface *renderer, int xoffset, int yoffset) {
	renderer->renderText(xoffset + x + textoffset, yoffset + y, text, textcolour, backgroundcolour);
}

void BubblePart::gainFocus() {
	assert(editable);
}

void BubblePart::loseFocus() {
	parent->kill();
}

void BubblePart::handleKey(char c) {
	// TODO: reject invalid chars

	setText(text + c);
}

void BubblePart::handleSpecialKey(char c) {
	switch (c) {
		case 8: // backspace
			if (text.size() == 0) { loseFocus(); return; }
			{ std::string s = text;
			s.erase(s.begin() + (s.size() - 1));
			setText(s); }
			if (text.size() == 0) { loseFocus(); return; }
			break;

		case 13: // return
			((Bubble *)parent)->turnIntoSpeech(); // TODO: omg hax
			break;
	}
}

unsigned int BubblePart::poseForWidth(unsigned int width) {
	if (engine.version == 1) return 0;
	SpritePart *s;
	if (!(s = dynamic_cast<SpritePart *>(parent->part(0)))) return 0;
	unsigned int sprite = s->getFirstImg();
	while (sprite < s->getFirstImg()+2 && width > s->getSprite()->width(sprite) - 17)
		sprite++;
	return sprite - s->getFirstImg();
}

void BubblePart::setText(std::string str) {
	unsigned int twidth = engine.backend->textWidth(str);
	unsigned int pose = poseForWidth(twidth);
	SpritePart *s;
	if ((s = dynamic_cast<SpritePart *>(parent->part(0)))) {
		if (pose != s->getPose()) {
			s->setPose(pose);
			textwidth = s->getWidth() - 17;
			Bubble* p = (Bubble*)parent; // TODO: omg hax
			if (!p->leftside)
				p->moveTo(p->floatingagent->x - p->getWidth() + 2, p->floatingagent->y - p->getHeight());
		}
	}
	if (twidth > textwidth) return;

	text = str;
	textoffset = (textwidth - twidth) / 2;
}

/* vim: set noet: */
<commit_msg>make BubblePart::setText only mess with poses/width in C2<commit_after>/*
 *  Bubble.cpp
 *  openc2e
 *
 *  Created by Alyssa Milburn on Sat Apr 26 2008.
 *  Copyright (c) 2008 Alyssa Milburn. All rights reserved.
 *
 *  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 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.
 *
 */

#include "Bubble.h"
#include "World.h"
#include "Engine.h"
#include "Backend.h"
#include "Camera.h"
#include "creaturesImage.h"

// class BubblePart *ourPart;

Bubble::Bubble(unsigned char family, unsigned char genus, unsigned short species, unsigned int plane,
		std::string spritefile, unsigned int firstimage, unsigned int imagecount,
		unsigned int tx, unsigned int ty, unsigned int twidth, unsigned int theight,
		unsigned int bgcolour, unsigned int tcolour)
		: CompoundAgent(family, genus, species, plane, spritefile, firstimage, imagecount) {
	ourPart = new BubblePart(this, 1, tx, ty);
	addPart(ourPart);
	ourPart->textwidth = twidth;
	ourPart->textheight = theight;
	ourPart->backgroundcolour = bgcolour;
	ourPart->textcolour = tcolour;

	ourPart->editable = false;
}

void Bubble::setText(std::string s) {
	ourPart->setText(s);
}

std::string Bubble::getText() {
	return ourPart->text;
}

void Bubble::setEditing(bool e) {
	ourPart->editable = e;
	if (e)
		world.setFocus(ourPart); // gain focus
	else if (world.focusagent == AgentRef(this) && world.focuspart == ourPart->id)
		world.setFocus(0); // lose focus
}

void Bubble::setTimeout(unsigned int t) {
	timeout = t;
}

void Bubble::tick() {
	CompoundAgent::tick();

	if (!paused && timeout) {
		timeout--;
		if (timeout == 0) kill();
	}
}

void Bubble::turnIntoSpeech() {
	newBubble((Agent *)world.hand(), true, getText());

	// TODO: announce via shou
	// TODO: add to speech history

	kill();
}

Bubble *Bubble::newBubble(Agent *parent, bool speech, std::string text) {
	assert(engine.version < 3);

	assert(parent);

	bool leftside = false;
	// TODO: cope with wrap
	if (parent->x - world.camera->getX() < world.camera->getWidth() / 2) leftside = true;

	int pose;
	if (engine.version == 1) {
		// C1 poses
		if (speech)
			pose = leftside ? 10 : 9;
		else
			pose = leftside ? 12 : 11;
	} else {
		// C2 poses
		// pose adjusted on setText() if necessary
		if (speech)
			pose = leftside ? 21 : 18;
		else
			pose = leftside ? 27 : 24;
	}

	int plane;
	if (engine.version == 1) {
		plane = 9000;
	} else {
		// C2
		if (parent == (Agent *)world.hand())
			plane = 9999;
		else
			plane = 9995;
	}

	int xoffset = (engine.version == 1) ? 6 : 8;
	int yoffset = (engine.version == 1) ? 3 : 8;
	int twidth = (engine.version == 1) ? 144 : 95; // extended to fit text upon setText()

	Bubble *ourBubble = new Bubble(2, 1, speech ? 2 : 1, plane, "syst", pose, engine.version == 1 ? 1 : 3, xoffset, yoffset, twidth, 12, 0, 0);
	ourBubble->finishInit();
	ourBubble->leftside = leftside;

	ourBubble->attr = 32; // floating
	ourBubble->floatTo(parent);

	// TODO: fix positioning
	if (leftside)
		ourBubble->moveTo(parent->x + parent->getWidth() - 2, parent->y - ourBubble->getHeight());
	else
		ourBubble->moveTo(parent->x - ourBubble->getWidth() + 2, parent->y - ourBubble->getHeight());

	ourBubble->setText(text);

	if (speech)
		ourBubble->setTimeout(2 * 10); // TODO: 2s is probably not right
	else
		ourBubble->setEditing(true);

	return ourBubble;
}

/*
  class BubblePart : public CompoundPart {
	bool editable;
	std::string text;
	unsigned int textwidth, textheight;
	unsigned int backgroundcolour, textcolour;
*/

BubblePart::BubblePart(Bubble *p, unsigned int _id, int x, int y) : CompoundPart(p, _id, x, y, 1) {
	editable = false;
	textwidth = 0;
	textheight = 0;
	textoffset = 0; // doesn't matter when text is empty
}

void BubblePart::partRender(class Surface *renderer, int xoffset, int yoffset) {
	renderer->renderText(xoffset + x + textoffset, yoffset + y, text, textcolour, backgroundcolour);
}

void BubblePart::gainFocus() {
	assert(editable);
}

void BubblePart::loseFocus() {
	parent->kill();
}

void BubblePart::handleKey(char c) {
	// TODO: reject invalid chars

	setText(text + c);
}

void BubblePart::handleSpecialKey(char c) {
	switch (c) {
		case 8: // backspace
			if (text.size() == 0) { loseFocus(); return; }
			{ std::string s = text;
			s.erase(s.begin() + (s.size() - 1));
			setText(s); }
			if (text.size() == 0) { loseFocus(); return; }
			break;

		case 13: // return
			((Bubble *)parent)->turnIntoSpeech(); // TODO: omg hax
			break;
	}
}

unsigned int BubblePart::poseForWidth(unsigned int width) {
	if (engine.version == 1) return 0;
	SpritePart *s;
	if (!(s = dynamic_cast<SpritePart *>(parent->part(0)))) return 0;
	unsigned int sprite = s->getFirstImg();
	while (sprite < s->getFirstImg()+2 && width > s->getSprite()->width(sprite) - 17)
		sprite++;
	return sprite - s->getFirstImg();
}

void BubblePart::setText(std::string str) {
	unsigned int twidth = engine.backend->textWidth(str);

	if (engine.version == 2) {
		unsigned int pose = poseForWidth(twidth);
		SpritePart *s;
		if ((s = dynamic_cast<SpritePart *>(parent->part(0)))) {
			if (pose != s->getPose()) {
				s->setPose(pose);
				textwidth = s->getWidth() - 17;
				Bubble* p = (Bubble*)parent; // TODO: omg hax
				if (!p->leftside)
					p->moveTo(p->floatingagent->x - p->getWidth() + 2, p->floatingagent->y - p->getHeight());
			}
		}
	}
	if (twidth > textwidth) return;

	text = str;
	textoffset = (textwidth - twidth) / 2;
}

/* vim: set noet: */
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_memdiag.C $  */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file p9_mss_memdiag.C
/// @brief Mainstore pattern testing
///
// *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com>
// *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB

#include <fapi2.H>
#include <p9_mss_memdiag.H>

#include <lib/utils/poll.H>
#include <lib/utils/find.H>
#include <lib/utils/count_dimm.H>
#include <lib/mcbist/address.H>
#include <lib/mcbist/memdiags.H>
#include <lib/mcbist/mcbist.H>
#include <lib/mc/port.H>
#include <lib/ecc/ecc.H>

using fapi2::TARGET_TYPE_MCBIST;
using fapi2::TARGET_TYPE_SYSTEM;
using fapi2::TARGET_TYPE_MCA;

extern "C"
{
    ///
    /// @brief Pattern test the DRAM
    /// @param[in] i_target the McBIST of the ports of the dram you're training
    /// @return FAPI2_RC_SUCCESS iff ok
    ///
    fapi2::ReturnCode p9_mss_memdiag( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target )
    {
        FAPI_INF("Start memdiag");

        // If there are no DIMM we don't need to bother. In fact, we can't as we didn't setup
        // attributes for the PHY, etc.
        if (mss::count_dimm(i_target) == 0)
        {
            FAPI_INF("... skipping mem_diags %s - no DIMM ...", mss::c_str(i_target));
            return fapi2::FAPI2_RC_SUCCESS;
        }

        uint8_t l_sim = false;
        FAPI_TRY( mss::is_simulation( l_sim) );

        // Read the bad_dq_bitmap attribute and place corresponding symbol and chip marks
        for (const auto& l_mca : mss::find_targets<TARGET_TYPE_MCA>(i_target))
        {
            fapi2::buffer<uint8_t> l_repairs_applied;
            fapi2::buffer<uint8_t> l_repairs_exceeded;
            std::vector<uint64_t> l_ranks;

            FAPI_TRY( mss::restore_repairs( l_mca, l_repairs_applied, l_repairs_exceeded) );

            // assert if we have exceeded the allowed repairs
            for (const auto& l_dimm : mss::find_targets<fapi2::TARGET_TYPE_DIMM>(l_mca))
            {
                FAPI_ASSERT( !(l_repairs_exceeded.getBit(mss::index(l_dimm))),
                             fapi2::MSS_MEMDIAGS_REPAIRS_EXCEEDED().set_TARGET(l_dimm),
                             "p9_mss_memdiag bad bit repairs exceeded %s", mss::c_str(l_dimm) );
            }

#ifdef __HOSTBOOT_MODULE
            // assert if both chip and symbol marks exist for any given rank
            FAPI_TRY( mss::rank::ranks(l_mca, l_ranks) );

            for (const auto l_rank : l_ranks)
            {
                if (l_repairs_applied.getBit(l_rank))
                {
                    uint64_t l_galois = 0;
                    mss::states l_confirmed = mss::NO;
                    // check for chip mark in hardware mark store
                    FAPI_TRY( mss::ecc::get_hwms(l_mca, l_rank, l_galois, l_confirmed) );

                    if (l_confirmed)
                    {
                        auto l_type = mss::ecc::fwms::mark_type::CHIP;
                        auto l_region = mss::ecc::fwms::mark_region::DISABLED;
                        auto l_addr = mss::mcbist::address(0);
                        // check for symbol mark in firmware mark store
                        FAPI_TRY( mss::ecc::get_fwms(l_mca, l_rank, l_galois, l_type, l_region, l_addr) );

                        FAPI_ASSERT( l_region == mss::ecc::fwms::mark_region::DISABLED,
                                     fapi2::MSS_MEMDIAGS_CHIPMARK_AND_SYMBOLMARK().set_TARGET(l_mca).set_RANK(l_rank),
                                     "p9_mss_memdiag both chip mark and symbol mark on rank %d: %s", l_rank, mss::c_str(l_mca) );
                    }
                }
            }

#endif
        }

        // We start the sf_init (write 0's) and it'll tickle the MCBIST complete FIR. PRD will see that
        // and start a background scrub.
        FAPI_TRY( memdiags::sf_init(i_target, mss::mcbist::PATTERN_0) );

        // If we're in the sim, we want to poll for the FIR bit. I don't think this ever really happens
        // unless we're expressly testing this API.
        if (l_sim)
        {
            // Poll for the fir bit. We expect this to be set ...
            fapi2::buffer<uint64_t> l_status;

            // A small vector of addresses to poll during the polling loop
            const std::vector<mss::poll_probe<fapi2::TARGET_TYPE_MCBIST>> l_probes =
            {
                {i_target, "mcbist current address", MCBIST_MCBMCATQ},
            };

            mss::poll_parameters l_poll_parameters;
            bool l_poll_results = mss::poll(i_target, MCBIST_MCBISTFIRQ, l_poll_parameters,
                                            [&l_status](const size_t poll_remaining,
                                                    const fapi2::buffer<uint64_t>& stat_reg) -> bool
            {
                FAPI_DBG("mcbist firq 0x%llx, remaining: %d", stat_reg, poll_remaining);
                l_status = stat_reg;
                return l_status.getBit<MCBIST_MCBISTFIRQ_MCBIST_PROGRAM_COMPLETE>() == true;
            },
            l_probes);

            FAPI_ASSERT( l_poll_results == true,
                         fapi2::MSS_MEMDIAGS_SUPERFAST_INIT_FAILED_TO_INIT().set_TARGET(i_target),
                         "p9_mss_memdiags timedout %s", mss::c_str(i_target) );
        }

    fapi_try_exit:
        FAPI_INF("End memdiag");
        return fapi2::current_err;
    }
}
<commit_msg>Move find API to share among memory controllers<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_memdiag.C $  */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file p9_mss_memdiag.C
/// @brief Mainstore pattern testing
///
// *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com>
// *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB

#include <fapi2.H>
#include <p9_mss_memdiag.H>

#include <lib/utils/poll.H>
#include <generic/memory/lib/utils/find.H>
#include <lib/utils/count_dimm.H>
#include <lib/mcbist/address.H>
#include <lib/mcbist/memdiags.H>
#include <lib/mcbist/mcbist.H>
#include <lib/mc/port.H>
#include <lib/ecc/ecc.H>

using fapi2::TARGET_TYPE_MCBIST;
using fapi2::TARGET_TYPE_SYSTEM;
using fapi2::TARGET_TYPE_MCA;

extern "C"
{
    ///
    /// @brief Pattern test the DRAM
    /// @param[in] i_target the McBIST of the ports of the dram you're training
    /// @return FAPI2_RC_SUCCESS iff ok
    ///
    fapi2::ReturnCode p9_mss_memdiag( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target )
    {
        FAPI_INF("Start memdiag");

        // If there are no DIMM we don't need to bother. In fact, we can't as we didn't setup
        // attributes for the PHY, etc.
        if (mss::count_dimm(i_target) == 0)
        {
            FAPI_INF("... skipping mem_diags %s - no DIMM ...", mss::c_str(i_target));
            return fapi2::FAPI2_RC_SUCCESS;
        }

        uint8_t l_sim = false;
        FAPI_TRY( mss::is_simulation( l_sim) );

        // Read the bad_dq_bitmap attribute and place corresponding symbol and chip marks
        for (const auto& l_mca : mss::find_targets<TARGET_TYPE_MCA>(i_target))
        {
            fapi2::buffer<uint8_t> l_repairs_applied;
            fapi2::buffer<uint8_t> l_repairs_exceeded;
            std::vector<uint64_t> l_ranks;

            FAPI_TRY( mss::restore_repairs( l_mca, l_repairs_applied, l_repairs_exceeded) );

            // assert if we have exceeded the allowed repairs
            for (const auto& l_dimm : mss::find_targets<fapi2::TARGET_TYPE_DIMM>(l_mca))
            {
                FAPI_ASSERT( !(l_repairs_exceeded.getBit(mss::index(l_dimm))),
                             fapi2::MSS_MEMDIAGS_REPAIRS_EXCEEDED().set_TARGET(l_dimm),
                             "p9_mss_memdiag bad bit repairs exceeded %s", mss::c_str(l_dimm) );
            }

#ifdef __HOSTBOOT_MODULE
            // assert if both chip and symbol marks exist for any given rank
            FAPI_TRY( mss::rank::ranks(l_mca, l_ranks) );

            for (const auto l_rank : l_ranks)
            {
                if (l_repairs_applied.getBit(l_rank))
                {
                    uint64_t l_galois = 0;
                    mss::states l_confirmed = mss::NO;
                    // check for chip mark in hardware mark store
                    FAPI_TRY( mss::ecc::get_hwms(l_mca, l_rank, l_galois, l_confirmed) );

                    if (l_confirmed)
                    {
                        auto l_type = mss::ecc::fwms::mark_type::CHIP;
                        auto l_region = mss::ecc::fwms::mark_region::DISABLED;
                        auto l_addr = mss::mcbist::address(0);
                        // check for symbol mark in firmware mark store
                        FAPI_TRY( mss::ecc::get_fwms(l_mca, l_rank, l_galois, l_type, l_region, l_addr) );

                        FAPI_ASSERT( l_region == mss::ecc::fwms::mark_region::DISABLED,
                                     fapi2::MSS_MEMDIAGS_CHIPMARK_AND_SYMBOLMARK().set_TARGET(l_mca).set_RANK(l_rank),
                                     "p9_mss_memdiag both chip mark and symbol mark on rank %d: %s", l_rank, mss::c_str(l_mca) );
                    }
                }
            }

#endif
        }

        // We start the sf_init (write 0's) and it'll tickle the MCBIST complete FIR. PRD will see that
        // and start a background scrub.
        FAPI_TRY( memdiags::sf_init(i_target, mss::mcbist::PATTERN_0) );

        // If we're in the sim, we want to poll for the FIR bit. I don't think this ever really happens
        // unless we're expressly testing this API.
        if (l_sim)
        {
            // Poll for the fir bit. We expect this to be set ...
            fapi2::buffer<uint64_t> l_status;

            // A small vector of addresses to poll during the polling loop
            const std::vector<mss::poll_probe<fapi2::TARGET_TYPE_MCBIST>> l_probes =
            {
                {i_target, "mcbist current address", MCBIST_MCBMCATQ},
            };

            mss::poll_parameters l_poll_parameters;
            bool l_poll_results = mss::poll(i_target, MCBIST_MCBISTFIRQ, l_poll_parameters,
                                            [&l_status](const size_t poll_remaining,
                                                    const fapi2::buffer<uint64_t>& stat_reg) -> bool
            {
                FAPI_DBG("mcbist firq 0x%llx, remaining: %d", stat_reg, poll_remaining);
                l_status = stat_reg;
                return l_status.getBit<MCBIST_MCBISTFIRQ_MCBIST_PROGRAM_COMPLETE>() == true;
            },
            l_probes);

            FAPI_ASSERT( l_poll_results == true,
                         fapi2::MSS_MEMDIAGS_SUPERFAST_INIT_FAILED_TO_INIT().set_TARGET(i_target),
                         "p9_mss_memdiags timedout %s", mss::c_str(i_target) );
        }

    fapi_try_exit:
        FAPI_INF("End memdiag");
        return fapi2::current_err;
    }
}
<|endoftext|>