<commit_before>#include "mirants/core/tcp_client.h"
#include "mirants/core/eventloop.h"
#include "mirants/core/sockaddr.h"
#include "mirants/core/tcp_connection.h"
#include "mirants/core/callback.h"
#include "mirants/core/buffer.h"
#include "mirants/util/logging.h"
#include "mirants/port/atomic_sequence_num.h"
#include <vector>

using namespace std::placeholders;

namespace sudoku {

class SudokuClient {
 public:
  SudokuClient(const std::string& name,
               mirants::EventLoop* ev,
               const mirants::SockAddr& addr,
               const std::vector<std::string>& vec)
      : num_(0),
        client_(name, ev, addr),
        vec_(vec) {
    client_.SetConnectionCallback(
        std::bind(&SudokuClient::ConnectCallback,this,  _1));
    client_.SetMessageCallback(
        std::bind(&SudokuClient::MessageCallback, this, _1, _2));
  }

  SudokuClient(const std::string& name,
               mirants::EventLoop* ev,
               const mirants::SockAddr& addr,
               std::vector<std::string>&& vec)
      : num_(0),
        client_(name, ev, addr),
        vec_(std::move(vec)) {
    client_.SetConnectionCallback(
        std::bind(&SudokuClient::ConnectCallback, this, _1));
    client_.SetMessageCallback(
        std::bind(&SudokuClient::MessageCallback, this, _1, _2));
  }

  void Connect() {
    client_.Connect();
  }

 private:
  void ConnectCallback(const mirants::TcpConnectionPtr& ptr) {
    MIRANTS_LOG(INFO) << "Start solve sudoku...";
    start_ = mirants::Timestamp::Now();
    for (size_t i = 0; i < vec_.size(); ++i) {
      ptr->SendMessage(vec_.at(i));
    }
  }

  void MessageCallback(const mirants::TcpConnectionPtr& ptr, mirants::Buffer* buf) {
    size_t size = buf->ReadableSize();
    while (size >= kCells + 2) {
      const char* crlf = buf->FindCRLF();
      if (crlf) {
        std::string res(buf->Peek(), crlf);
        buf->RetrieveUntil(crlf + 2);
        size = buf->ReadableSize();
        MIRANTS_LOG(INFO) << "The result is: " << res;
        ++num_;
        if (++num_ == static_cast<int64_t>(vec_.size())) {
          stop_ = mirants::Timestamp::Now();
          MIRANTS_LOG(INFO) << "\nStart time is: " << start_.FormatTimestamp()
                            << "\nFinish time is: " << stop_.FormatTimestamp()
                            << "\nTake MicroSeconds: "
                            << stop_.MicroSecondsSinceEpoch() - start_.MicroSecondsSinceEpoch();
        }
      } else {
        break;
      }
    }
  }

  static const int kCells = 81;
  int64_t num_;
  mirants::TcpClient client_;
  std::vector<std::string> vec_;
  mirants::Timestamp start_;
  mirants::Timestamp stop_;
};

}  // namespace sudoku

int main(int argc, char** argv) {
  if (argc != 3) {
    printf("Usage: %s server_ip dotimes\n", argv[0]);
    return 0;
  }
  int dotimes = atoi(argv[2]);
  if (dotimes <= 0) {
    return 0;
  }

  std::string message = "53  7    6  195    98    6 8   6   34  8 3  17   2   6 6    28    419  5    8  79\r\n";
  std::vector<std::string> vec(dotimes);
  for (int i = 0; i < dotimes; ++i) {
    vec.push_back(message);
  }
  mirants::EventLoop ev;
  mirants::SockAddr servaddr(argv[1], 5666);
  sudoku::SudokuClient client("SudokuClinet", &ev, servaddr, std::move(vec));
  client.Connect();
  ev.Loop();
}
<commit_msg>Update sudoku_client.cc<commit_after>#include "mirants/core/tcp_client.h"
#include "mirants/core/eventloop.h"
#include "mirants/core/sockaddr.h"
#include "mirants/core/tcp_connection.h"
#include "mirants/core/callback.h"
#include "mirants/core/buffer.h"
#include "mirants/util/logging.h"
#include <vector>

using namespace std::placeholders;

namespace sudoku {

class SudokuClient {
 public:
  SudokuClient(const std::string& name,
               mirants::EventLoop* ev,
               const mirants::SockAddr& addr,
               const std::vector<std::string>& vec)
      : num_(0),
        client_(name, ev, addr),
        vec_(vec) {
    client_.SetConnectionCallback(
        std::bind(&SudokuClient::ConnectCallback,this,  _1));
    client_.SetMessageCallback(
        std::bind(&SudokuClient::MessageCallback, this, _1, _2));
  }

  SudokuClient(const std::string& name,
               mirants::EventLoop* ev,
               const mirants::SockAddr& addr,
               std::vector<std::string>&& vec)
      : num_(0),
        client_(name, ev, addr),
        vec_(std::move(vec)) {
    client_.SetConnectionCallback(
        std::bind(&SudokuClient::ConnectCallback, this, _1));
    client_.SetMessageCallback(
        std::bind(&SudokuClient::MessageCallback, this, _1, _2));
  }

  void Connect() {
    client_.Connect();
  }

 private:
  void ConnectCallback(const mirants::TcpConnectionPtr& ptr) {
    MIRANTS_LOG(INFO) << "Start solve sudoku...";
    start_ = mirants::Timestamp::Now();
    for (size_t i = 0; i < vec_.size(); ++i) {
      ptr->SendMessage(vec_.at(i));
    }
  }

  void MessageCallback(const mirants::TcpConnectionPtr& ptr, mirants::Buffer* buf) {
    size_t size = buf->ReadableSize();
    while (size >= kCells + 2) {
      const char* crlf = buf->FindCRLF();
      if (crlf) {
        std::string res(buf->Peek(), crlf);
        buf->RetrieveUntil(crlf + 2);
        size = buf->ReadableSize();
        MIRANTS_LOG(INFO) << "The result is: " << res;
        ++num_;
        if (++num_ == static_cast<int64_t>(vec_.size())) {
          stop_ = mirants::Timestamp::Now();
          MIRANTS_LOG(INFO) << "\nStart time is: " << start_.FormatTimestamp()
                            << "\nFinish time is: " << stop_.FormatTimestamp()
                            << "\nTake MicroSeconds: "
                            << stop_.MicroSecondsSinceEpoch() - start_.MicroSecondsSinceEpoch();
        }
      } else {
        break;
      }
    }
  }

  static const int kCells = 81;
  int64_t num_;
  mirants::TcpClient client_;
  std::vector<std::string> vec_;
  mirants::Timestamp start_;
  mirants::Timestamp stop_;
};

}  // namespace sudoku

int main(int argc, char** argv) {
  if (argc != 3) {
    printf("Usage: %s server_ip dotimes\n", argv[0]);
    return 0;
  }
  int dotimes = atoi(argv[2]);
  if (dotimes <= 0) {
    return 0;
  }

  std::string message = "53  7    6  195    98    6 8   6   34  8 3  17   2   6 6    28    419  5    8  79\r\n";
  std::vector<std::string> vec(dotimes);
  for (int i = 0; i < dotimes; ++i) {
    vec.push_back(message);
  }
  mirants::EventLoop ev;
  mirants::SockAddr servaddr(argv[1], 5666);
  sudoku::SudokuClient client("SudokuClinet", &ev, servaddr, std::move(vec));
  client.Connect();
  ev.Loop();
}
<|endoftext|>


<commit_before>// Filename: INSProjectionBcCoef.C
// Last modified: <09.Oct.2007 18:42:29 griffith@box221.cims.nyu.edu>
// Created on 22 Feb 2007 by Boyce Griffith (boyce@trasnaform2.local)

#include "INSProjectionBcCoef.h"

/////////////////////////////// INCLUDES /////////////////////////////////////

#ifndef included_IBAMR_config
#include <IBAMR_config.h>
#define included_IBAMR_config
#endif

#ifndef included_SAMRAI_config
#include <SAMRAI_config.h>
#define included_SAMRAI_config
#endif

// STOOLS INCLUDES
#include <stools/PhysicalBoundaryUtilities.h>

// SAMRAI INCLUDES
#include <CellData.h>
#include <FaceData.h>
#include <tbox/Utilities.h>

// C++ STDLIB INCLUDES
#include <cassert>
#include <limits>

/////////////////////////////// NAMESPACE ////////////////////////////////////

namespace IBAMR
{
/////////////////////////////// STATIC ///////////////////////////////////////

/////////////////////////////// PUBLIC ///////////////////////////////////////

INSProjectionBcCoef::INSProjectionBcCoef(
    const int P_idx,
    SAMRAI::solv::RobinBcCoefStrategy<NDIM>* const P_bc_coef,
    const std::string& projection_type,
    const int u_idx,
    const std::vector<SAMRAI::solv::RobinBcCoefStrategy<NDIM>*>& u_bc_coefs,
    const bool homogeneous_bc)
    : d_P_idx(-1),
      d_P_bc_coef(NULL),
      d_projection_type(),
      d_u_idx(-1),
      d_u_bc_coefs(NDIM,NULL),
      d_homo_patch_data_idxs(),
      d_inhomo_patch_data_idxs(),
      d_homogeneous_bc(false),
      d_rho(std::numeric_limits<double>::quiet_NaN()),
      d_dt(std::numeric_limits<double>::quiet_NaN())
{
    setCurrentPressurePatchDataIndex(P_idx);
    setPressurePhysicalBcCoef(P_bc_coef);
    setProjectionType(projection_type);
    setIntermediateVelocityPatchDataIndex(u_idx);
    setVelocityPhysicalBcCoefs(u_bc_coefs);
    setHomogeneousBc(homogeneous_bc);
    return;
}// INSProjectionBcCoef

INSProjectionBcCoef::~INSProjectionBcCoef()
{
    // intentionally blank
    return;
}// ~INSProjectionBcCoef

void
INSProjectionBcCoef::setProblemCoefs(
    const double rho,
    const double dt)
{
    d_rho = rho;
    d_dt = dt;
    return;
}// setProblemCoefs

void
INSProjectionBcCoef::setCurrentPressurePatchDataIndex(
    const int P_idx)
{
    d_P_idx = P_idx;
    d_inhomo_patch_data_idxs.clear();
    if (d_u_idx != -1) d_inhomo_patch_data_idxs.insert(d_u_idx);
    d_inhomo_patch_data_idxs.insert(d_P_idx);
    return;
}// setCurrentPressurePatchDataIndex

void
INSProjectionBcCoef::setProjectionType(
    const std::string& projection_type)
{
    if (projection_type != "pressure_increment" && projection_type != "pressure_update")
    {
        TBOX_ERROR("INSProjectionBcCoef::setProjectionType():\n"
                   << "  invalid velocity projection type: " << projection_type << "\n"
                   << "  valid choices are: ``pressure_increment'' or ``pressure_update''" << endl);
    }
    d_projection_type = projection_type;
    return;
}// setProjectionType

void
INSProjectionBcCoef::setPressurePhysicalBcCoef(
    SAMRAI::solv::RobinBcCoefStrategy<NDIM>* const P_bc_coef)
{
    d_P_bc_coef = P_bc_coef;
    return;
}// setPressurePhysicalBcCoef

void
INSProjectionBcCoef::setIntermediateVelocityPatchDataIndex(
    const int u_idx)
{
    d_u_idx = u_idx;
    d_inhomo_patch_data_idxs.clear();
    d_inhomo_patch_data_idxs.insert(d_u_idx);
    if (d_P_idx != -1) d_inhomo_patch_data_idxs.insert(d_P_idx);
    return;
}// setIntermediateVelocityPatchDataIndex

void
INSProjectionBcCoef::setVelocityPhysicalBcCoefs(
    const std::vector<SAMRAI::solv::RobinBcCoefStrategy<NDIM>*>& u_bc_coefs)
{
    if (u_bc_coefs.size() != NDIM)
    {
        TBOX_ERROR("INSProjectionBcCoef::setVelocityPhysicalBcCoefs():\n"
                   << "  precisely NDIM boundary condition objects must be provided." << endl);
    }
    d_u_bc_coefs = u_bc_coefs;
    return;
}// setVelocityPhysicalBcCoefs

void
INSProjectionBcCoef::setTargetPatchDataIndex(
    const int target_idx)
{
    // intentionally blank
    return;
}// setTargetPatchDataIndex

void
INSProjectionBcCoef::setHomogeneousBc(
    const bool homogeneous_bc)
{
    d_homogeneous_bc = homogeneous_bc;
    return;
}// setHomogeneousBc

const std::set<int>&
INSProjectionBcCoef::getHomogeneousBcFillDataIndices() const
{
    return d_homo_patch_data_idxs;
}// getHomogeneousBcFillDataIndices

const std::set<int>&
INSProjectionBcCoef::getInhomogeneousBcFillDataIndices() const
{
    return d_inhomo_patch_data_idxs;
}// getInhomogeneousBcFillDataIndices

void
INSProjectionBcCoef::setBcCoefs(
    SAMRAI::tbox::Pointer<SAMRAI::pdat::ArrayData<NDIM,double> >& acoef_data,
    SAMRAI::tbox::Pointer<SAMRAI::pdat::ArrayData<NDIM,double> >& bcoef_data,
    SAMRAI::tbox::Pointer<SAMRAI::pdat::ArrayData<NDIM,double> >& gcoef_data,
    const SAMRAI::tbox::Pointer<SAMRAI::hier::Variable<NDIM> >& variable,
    const SAMRAI::hier::Patch<NDIM>& patch,
    const SAMRAI::hier::BoundaryBox<NDIM>& bdry_box,
    double fill_time) const
{
#if USING_OLD_ROBIN_BC_INTERFACE
    TBOX_ERROR("INSProjectionBcCoef::setBcCoefs():\n"
               << "  using incorrect SAMRAI::solv::RobinBcCoefStrategy interface." << endl);
#else
    setBcCoefs_private(acoef_data, bcoef_data, gcoef_data, variable, patch, bdry_box, fill_time);
#endif
    return;
}// setBcCoefs

void
INSProjectionBcCoef::setBcCoefs(
    SAMRAI::tbox::Pointer<SAMRAI::pdat::ArrayData<NDIM,double> >& acoef_data,
    SAMRAI::tbox::Pointer<SAMRAI::pdat::ArrayData<NDIM,double> >& gcoef_data,
    const SAMRAI::tbox::Pointer<SAMRAI::hier::Variable<NDIM> >& variable,
    const SAMRAI::hier::Patch<NDIM>& patch,
    const SAMRAI::hier::BoundaryBox<NDIM>& bdry_box,
    double fill_time) const
{
#if USING_OLD_ROBIN_BC_INTERFACE
    SAMRAI::tbox::Pointer<SAMRAI::pdat::ArrayData<NDIM,double> > bcoef_data =
        (acoef_data.isNull()
         ? SAMRAI::tbox::Pointer<SAMRAI::pdat::ArrayData<NDIM,double> >(NULL)
         : new SAMRAI::pdat::ArrayData<NDIM,double>(acoef_data->getBox(), acoef_data->getDepth()));
    setBcCoefs_private(acoef_data, bcoef_data, gcoef_data, variable, patch, bdry_box, fill_time);
#else
    TBOX_ERROR("INSProjectionBcCoef::setBcCoefs():\n"
               << "  using incorrect SAMRAI::solv::RobinBcCoefStrategy interface." << endl);
#endif
    return;
}// setBcCoefs

SAMRAI::hier::IntVector<NDIM>
INSProjectionBcCoef::numberOfExtensionsFillable() const
{
#ifdef DEBUG_CHECK_ASSERTIONS
    assert(d_u_bc_coefs.size() == NDIM);
    for (unsigned l = 0; l < d_u_bc_coefs.size(); ++l)
    {
        assert(d_u_bc_coefs[l] != NULL);
    }
#endif
    SAMRAI::hier::IntVector<NDIM> ret_val(std::numeric_limits<int>::max());
    for (int d = 0; d < NDIM; ++d)
    {
        ret_val = SAMRAI::hier::IntVector<NDIM>::min(
            ret_val, d_u_bc_coefs[d]->numberOfExtensionsFillable());
    }
    return ret_val;
}// numberOfExtensionsFillable

/////////////////////////////// PROTECTED ////////////////////////////////////

/////////////////////////////// PRIVATE //////////////////////////////////////

void
INSProjectionBcCoef::setBcCoefs_private(
    SAMRAI::tbox::Pointer<SAMRAI::pdat::ArrayData<NDIM,double> >& acoef_data,
    SAMRAI::tbox::Pointer<SAMRAI::pdat::ArrayData<NDIM,double> >& bcoef_data,
    SAMRAI::tbox::Pointer<SAMRAI::pdat::ArrayData<NDIM,double> >& gcoef_data,
    const SAMRAI::tbox::Pointer<SAMRAI::hier::Variable<NDIM> >& variable,
    const SAMRAI::hier::Patch<NDIM>& patch,
    const SAMRAI::hier::BoundaryBox<NDIM>& bdry_box,
    double fill_time) const
{
#ifdef DEBUG_CHECK_ASSERTIONS
    assert(d_u_bc_coefs.size() == NDIM);
    for (unsigned l = 0; l < d_u_bc_coefs.size(); ++l)
    {
        assert(d_u_bc_coefs[l] != NULL);
    }
#endif
    const int location_index   = bdry_box.getLocationIndex();
    const int bdry_normal_axis = location_index/2;
    const bool is_lower        = location_index%2 == 0;

    const SAMRAI::hier::Box<NDIM> bc_coef_box =
        STOOLS::PhysicalBoundaryUtilities::makeSideBoundaryCodim1Box(bdry_box);

    const bool fill_acoef_data = !acoef_data.isNull();
    const bool fill_bcoef_data = !bcoef_data.isNull();
    const bool fill_gcoef_data = !gcoef_data.isNull();

    // Set the normal velocity bc coefs.
#if USING_OLD_ROBIN_BC_INTERFACE
    d_u_bc_coefs[bdry_normal_axis]->setBcCoefs(
        acoef_data, gcoef_data, variable, patch, bdry_box, fill_time);
#else
    d_u_bc_coefs[bdry_normal_axis]->setBcCoefs(
        acoef_data, bcoef_data, gcoef_data, variable, patch, bdry_box, fill_time);
#endif

    // Loop over the boundary box and reset the homogeneous coefficients.
    for (SAMRAI::hier::Box<NDIM>::Iterator b(bc_coef_box); b; b++)
    {
        const SAMRAI::hier::Index<NDIM>& i = b();

        if (fill_acoef_data) (*acoef_data)(i,0) = 1.0-(*acoef_data)(i,0);
        if (fill_bcoef_data) (*bcoef_data)(i,0) = 1.0-(*bcoef_data)(i,0);
        if (fill_gcoef_data && d_homogeneous_bc) (*gcoef_data)(i,0) = 0.0;
    }

    // Loop over the boundary box and reset the inhomogeneous coefficients.
    if (!d_homogeneous_bc && fill_gcoef_data)
    {
        SAMRAI::tbox::Pointer<SAMRAI::pdat::FaceData<NDIM,double> > u_data = patch.getPatchData(d_u_idx);
        SAMRAI::tbox::Pointer<SAMRAI::pdat::CellData<NDIM,double> > P_data = patch.getPatchData(d_P_idx);
#ifdef DEBUG_CHECK_ASSERTIONS
        assert(!u_data.isNull());
        assert(!P_data.isNull());
        assert(fill_acoef_data || fill_bcoef_data);
#endif
        SAMRAI::tbox::Pointer<SAMRAI::pdat::ArrayData<NDIM,double> > pcoef_data =
            (acoef_data.isNull()
             ? new SAMRAI::pdat::ArrayData<NDIM,double>(bcoef_data->getBox(), bcoef_data->getDepth())
             : new SAMRAI::pdat::ArrayData<NDIM,double>(acoef_data->getBox(), acoef_data->getDepth()));

        if (d_P_bc_coef != NULL)
        {
            SAMRAI::tbox::Pointer<SAMRAI::pdat::ArrayData<NDIM,double> > null_data(NULL);
#if USING_OLD_ROBIN_BC_INTERFACE
            d_P_bc_coef->setBcCoefs(
                null_data, pcoef_data, variable, patch, bdry_box, fill_time);
#else
            d_P_bc_coef->setBcCoefs(
                null_data, null_data, pcoef_data, variable, patch, bdry_box, fill_time);
#endif
        }
        else
        {
            pcoef_data->fillAll(0.0);
        }

        const bool using_pressure_increment = (d_projection_type == "pressure_increment");
        for (SAMRAI::hier::Box<NDIM>::Iterator b(bc_coef_box); b; b++)
        {
            const SAMRAI::hier::Index<NDIM>& i = b();
            const SAMRAI::pdat::FaceIndex<NDIM> i_f(
                i, bdry_normal_axis, SAMRAI::pdat::FaceIndex<NDIM>::Lower);

            if ((fill_acoef_data && SAMRAI::tbox::Utilities::deq((*acoef_data)(i,0),1.0)) ||
                (fill_bcoef_data && SAMRAI::tbox::Utilities::deq((*bcoef_data)(i,0),0.0)))
            {
                SAMRAI::hier::Index<NDIM> i_intr0(i), i_intr1(i);
                if (is_lower)
                {
                    i_intr0(bdry_normal_axis) += 0;
                    i_intr1(bdry_normal_axis) += 1;
                }
                else
                {
                    i_intr0(bdry_normal_axis) -= 1;
                    i_intr1(bdry_normal_axis) -= 2;
                }

                const double P_bdry =
                    (using_pressure_increment
                     ? 1.5*(*P_data)(i_intr0) - 0.5*(*P_data)(i_intr1)
                     : 0.0);
                (*gcoef_data)(i,0) = (*pcoef_data)(i,0) - P_bdry;
            }
            else
            {
                (*gcoef_data)(i,0) = (is_lower ? -1.0 : +1.0)*(d_rho/d_dt)*((*u_data)(i_f) - (*gcoef_data)(i,0));
            }
        }
    }
    return;
}// setBcCoefs_private

/////////////////////////////// NAMESPACE ////////////////////////////////////

}// namespace IBAMR

/////////////////////////////// TEMPLATE INSTANTIATION ///////////////////////

//////////////////////////////////////////////////////////////////////////////
<commit_msg>interim commit.<commit_after>// Filename: INSProjectionBcCoef.C
// Last modified: <09.Oct.2007 21:22:23 griffith@box221.cims.nyu.edu>
// Created on 22 Feb 2007 by Boyce Griffith (boyce@trasnaform2.local)

#include "INSProjectionBcCoef.h"

/////////////////////////////// INCLUDES /////////////////////////////////////

#ifndef included_IBAMR_config
#include <IBAMR_config.h>
#define included_IBAMR_config
#endif

#ifndef included_SAMRAI_config
#include <SAMRAI_config.h>
#define included_SAMRAI_config
#endif

// STOOLS INCLUDES
#include <stools/PhysicalBoundaryUtilities.h>

// SAMRAI INCLUDES
#include <CellData.h>
#include <FaceData.h>
#include <tbox/Utilities.h>

// C++ STDLIB INCLUDES
#include <cassert>
#include <limits>

/////////////////////////////// NAMESPACE ////////////////////////////////////

namespace IBAMR
{
/////////////////////////////// STATIC ///////////////////////////////////////

/////////////////////////////// PUBLIC ///////////////////////////////////////

INSProjectionBcCoef::INSProjectionBcCoef(
    const int P_idx,
    SAMRAI::solv::RobinBcCoefStrategy<NDIM>* const P_bc_coef,
    const std::string& projection_type,
    const int u_idx,
    const std::vector<SAMRAI::solv::RobinBcCoefStrategy<NDIM>*>& u_bc_coefs,
    const bool homogeneous_bc)
    : d_P_idx(-1),
      d_P_bc_coef(NULL),
      d_projection_type(),
      d_u_idx(-1),
      d_u_bc_coefs(NDIM,NULL),
      d_homo_patch_data_idxs(),
      d_inhomo_patch_data_idxs(),
      d_homogeneous_bc(false),
      d_rho(std::numeric_limits<double>::quiet_NaN()),
      d_dt(std::numeric_limits<double>::quiet_NaN())
{
    setCurrentPressurePatchDataIndex(P_idx);
    setPressurePhysicalBcCoef(P_bc_coef);
    setProjectionType(projection_type);
    setIntermediateVelocityPatchDataIndex(u_idx);
    setVelocityPhysicalBcCoefs(u_bc_coefs);
    setHomogeneousBc(homogeneous_bc);
    return;
}// INSProjectionBcCoef

INSProjectionBcCoef::~INSProjectionBcCoef()
{
    // intentionally blank
    return;
}// ~INSProjectionBcCoef

void
INSProjectionBcCoef::setProblemCoefs(
    const double rho,
    const double dt)
{
    d_rho = rho;
    d_dt = dt;
    return;
}// setProblemCoefs

void
INSProjectionBcCoef::setCurrentPressurePatchDataIndex(
    const int P_idx)
{
    d_P_idx = P_idx;
    d_inhomo_patch_data_idxs.clear();
    if (d_u_idx != -1) d_inhomo_patch_data_idxs.insert(d_u_idx);
    d_inhomo_patch_data_idxs.insert(d_P_idx);
    return;
}// setCurrentPressurePatchDataIndex

void
INSProjectionBcCoef::setProjectionType(
    const std::string& projection_type)
{
    if (projection_type != "pressure_increment" && projection_type != "pressure_update")
    {
        TBOX_ERROR("INSProjectionBcCoef::setProjectionType():\n"
                   << "  invalid velocity projection type: " << projection_type << "\n"
                   << "  valid choices are: ``pressure_increment'' or ``pressure_update''" << endl);
    }
    d_projection_type = projection_type;
    return;
}// setProjectionType

void
INSProjectionBcCoef::setPressurePhysicalBcCoef(
    SAMRAI::solv::RobinBcCoefStrategy<NDIM>* const P_bc_coef)
{
    d_P_bc_coef = P_bc_coef;
    return;
}// setPressurePhysicalBcCoef

void
INSProjectionBcCoef::setIntermediateVelocityPatchDataIndex(
    const int u_idx)
{
    d_u_idx = u_idx;
    d_inhomo_patch_data_idxs.clear();
    d_inhomo_patch_data_idxs.insert(d_u_idx);
    if (d_P_idx != -1) d_inhomo_patch_data_idxs.insert(d_P_idx);
    return;
}// setIntermediateVelocityPatchDataIndex

void
INSProjectionBcCoef::setVelocityPhysicalBcCoefs(
    const std::vector<SAMRAI::solv::RobinBcCoefStrategy<NDIM>*>& u_bc_coefs)
{
    if (u_bc_coefs.size() != NDIM)
    {
        TBOX_ERROR("INSProjectionBcCoef::setVelocityPhysicalBcCoefs():\n"
                   << "  precisely NDIM boundary condition objects must be provided." << endl);
    }
    d_u_bc_coefs = u_bc_coefs;
    return;
}// setVelocityPhysicalBcCoefs

void
INSProjectionBcCoef::setTargetPatchDataIndex(
    const int target_idx)
{
    // intentionally blank
    return;
}// setTargetPatchDataIndex

void
INSProjectionBcCoef::setHomogeneousBc(
    const bool homogeneous_bc)
{
    d_homogeneous_bc = homogeneous_bc;
    return;
}// setHomogeneousBc

const std::set<int>&
INSProjectionBcCoef::getHomogeneousBcFillDataIndices() const
{
    return d_homo_patch_data_idxs;
}// getHomogeneousBcFillDataIndices

const std::set<int>&
INSProjectionBcCoef::getInhomogeneousBcFillDataIndices() const
{
    return d_inhomo_patch_data_idxs;
}// getInhomogeneousBcFillDataIndices

void
INSProjectionBcCoef::setBcCoefs(
    SAMRAI::tbox::Pointer<SAMRAI::pdat::ArrayData<NDIM,double> >& acoef_data,
    SAMRAI::tbox::Pointer<SAMRAI::pdat::ArrayData<NDIM,double> >& bcoef_data,
    SAMRAI::tbox::Pointer<SAMRAI::pdat::ArrayData<NDIM,double> >& gcoef_data,
    const SAMRAI::tbox::Pointer<SAMRAI::hier::Variable<NDIM> >& variable,
    const SAMRAI::hier::Patch<NDIM>& patch,
    const SAMRAI::hier::BoundaryBox<NDIM>& bdry_box,
    double fill_time) const
{
#if USING_OLD_ROBIN_BC_INTERFACE
    TBOX_ERROR("INSProjectionBcCoef::setBcCoefs():\n"
               << "  using incorrect SAMRAI::solv::RobinBcCoefStrategy interface." << endl);
#else
    setBcCoefs_private(acoef_data, bcoef_data, gcoef_data, variable, patch, bdry_box, fill_time);
#endif
    return;
}// setBcCoefs

void
INSProjectionBcCoef::setBcCoefs(
    SAMRAI::tbox::Pointer<SAMRAI::pdat::ArrayData<NDIM,double> >& acoef_data,
    SAMRAI::tbox::Pointer<SAMRAI::pdat::ArrayData<NDIM,double> >& gcoef_data,
    const SAMRAI::tbox::Pointer<SAMRAI::hier::Variable<NDIM> >& variable,
    const SAMRAI::hier::Patch<NDIM>& patch,
    const SAMRAI::hier::BoundaryBox<NDIM>& bdry_box,
    double fill_time) const
{
#if USING_OLD_ROBIN_BC_INTERFACE
    SAMRAI::tbox::Pointer<SAMRAI::pdat::ArrayData<NDIM,double> > bcoef_data =
        (acoef_data.isNull()
         ? SAMRAI::tbox::Pointer<SAMRAI::pdat::ArrayData<NDIM,double> >(NULL)
         : new SAMRAI::pdat::ArrayData<NDIM,double>(acoef_data->getBox(), acoef_data->getDepth()));
    setBcCoefs_private(acoef_data, bcoef_data, gcoef_data, variable, patch, bdry_box, fill_time);
#else
    TBOX_ERROR("INSProjectionBcCoef::setBcCoefs():\n"
               << "  using incorrect SAMRAI::solv::RobinBcCoefStrategy interface." << endl);
#endif
    return;
}// setBcCoefs

SAMRAI::hier::IntVector<NDIM>
INSProjectionBcCoef::numberOfExtensionsFillable() const
{
#ifdef DEBUG_CHECK_ASSERTIONS
    assert(d_u_bc_coefs.size() == NDIM);
    for (unsigned l = 0; l < d_u_bc_coefs.size(); ++l)
    {
        assert(d_u_bc_coefs[l] != NULL);
    }
#endif
    SAMRAI::hier::IntVector<NDIM> ret_val(std::numeric_limits<int>::max());
    for (int d = 0; d < NDIM; ++d)
    {
        ret_val = SAMRAI::hier::IntVector<NDIM>::min(
            ret_val, d_u_bc_coefs[d]->numberOfExtensionsFillable());
    }
    return ret_val;
}// numberOfExtensionsFillable

/////////////////////////////// PROTECTED ////////////////////////////////////

/////////////////////////////// PRIVATE //////////////////////////////////////

void
INSProjectionBcCoef::setBcCoefs_private(
    SAMRAI::tbox::Pointer<SAMRAI::pdat::ArrayData<NDIM,double> >& acoef_data,
    SAMRAI::tbox::Pointer<SAMRAI::pdat::ArrayData<NDIM,double> >& bcoef_data,
    SAMRAI::tbox::Pointer<SAMRAI::pdat::ArrayData<NDIM,double> >& gcoef_data,
    const SAMRAI::tbox::Pointer<SAMRAI::hier::Variable<NDIM> >& variable,
    const SAMRAI::hier::Patch<NDIM>& patch,
    const SAMRAI::hier::BoundaryBox<NDIM>& bdry_box,
    double fill_time) const
{
#ifdef DEBUG_CHECK_ASSERTIONS
    assert(d_u_bc_coefs.size() == NDIM);
    for (unsigned l = 0; l < d_u_bc_coefs.size(); ++l)
    {
        assert(d_u_bc_coefs[l] != NULL);
    }
#endif
    const int location_index   = bdry_box.getLocationIndex();
    const int bdry_normal_axis = location_index/2;
    const bool is_lower        = location_index%2 == 0;

    const SAMRAI::hier::Box<NDIM> bc_coef_box =
        STOOLS::PhysicalBoundaryUtilities::makeSideBoundaryCodim1Box(bdry_box);

    const bool fill_acoef_data = !acoef_data.isNull();
    const bool fill_bcoef_data = !bcoef_data.isNull();
    const bool fill_gcoef_data = !gcoef_data.isNull();

    // Set the normal velocity bc coefs.
#if USING_OLD_ROBIN_BC_INTERFACE
    d_u_bc_coefs[bdry_normal_axis]->setBcCoefs(
        acoef_data, gcoef_data, variable, patch, bdry_box, fill_time);
#else
    d_u_bc_coefs[bdry_normal_axis]->setBcCoefs(
        acoef_data, bcoef_data, gcoef_data, variable, patch, bdry_box, fill_time);
#endif

    // Loop over the boundary box and reset the homogeneous coefficients.
    for (SAMRAI::hier::Box<NDIM>::Iterator b(bc_coef_box); b; b++)
    {
        const SAMRAI::hier::Index<NDIM>& i = b();

        if (fill_acoef_data) (*acoef_data)(i,0) = 1.0-(*acoef_data)(i,0);
        if (fill_bcoef_data) (*bcoef_data)(i,0) = 1.0-(*bcoef_data)(i,0);
        if (fill_gcoef_data && d_homogeneous_bc) (*gcoef_data)(i,0) = 0.0;
    }

    // Loop over the boundary box and reset the inhomogeneous coefficients.
    if (!d_homogeneous_bc && fill_gcoef_data)
    {
        SAMRAI::tbox::Pointer<SAMRAI::pdat::FaceData<NDIM,double> > u_data = patch.getPatchData(d_u_idx);
        SAMRAI::tbox::Pointer<SAMRAI::pdat::CellData<NDIM,double> > P_data = patch.getPatchData(d_P_idx);
#ifdef DEBUG_CHECK_ASSERTIONS
        assert(!u_data.isNull());
        assert(!P_data.isNull());
        assert(fill_acoef_data || fill_bcoef_data);
#endif
        SAMRAI::tbox::Pointer<SAMRAI::pdat::ArrayData<NDIM,double> > pcoef_data =
            (acoef_data.isNull()
             ? new SAMRAI::pdat::ArrayData<NDIM,double>(bcoef_data->getBox(), bcoef_data->getDepth())
             : new SAMRAI::pdat::ArrayData<NDIM,double>(acoef_data->getBox(), acoef_data->getDepth()));

        if (d_P_bc_coef != NULL)
        {
            SAMRAI::tbox::Pointer<SAMRAI::pdat::ArrayData<NDIM,double> > null_data(NULL);
#if USING_OLD_ROBIN_BC_INTERFACE
            d_P_bc_coef->setBcCoefs(
                null_data, pcoef_data, variable, patch, bdry_box, fill_time);
#else
            d_P_bc_coef->setBcCoefs(
                null_data, null_data, pcoef_data, variable, patch, bdry_box, fill_time);
#endif
        }
        else
        {
            pcoef_data->fillAll(0.0);
        }

        const bool using_pressure_increment = (d_projection_type == "pressure_increment");
        for (SAMRAI::hier::Box<NDIM>::Iterator b(bc_coef_box); b; b++)
        {
            const SAMRAI::hier::Index<NDIM>& i = b();
            const SAMRAI::pdat::FaceIndex<NDIM> i_f(
                i, bdry_normal_axis, SAMRAI::pdat::FaceIndex<NDIM>::Lower);

            if ((fill_acoef_data && SAMRAI::tbox::Utilities::deq((*acoef_data)(i,0),1.0)) ||
                (fill_bcoef_data && SAMRAI::tbox::Utilities::deq((*bcoef_data)(i,0),0.0)))
            {
                SAMRAI::hier::Index<NDIM> i_intr(i), i_bdry(i);
                if (is_lower)
                {
                    i_bdry(bdry_normal_axis) -= 1;
                }
                else
                {
                    i_intr(bdry_normal_axis) -= 1;
                }

                const double P_bdry = (using_pressure_increment ? 0.5*((*P_data)(i_intr) + (*P_data)(i_bdry)) : 0.0);
                (*gcoef_data)(i,0) = (*pcoef_data)(i,0) - P_bdry;
            }
            else
            {
                (*gcoef_data)(i,0) = (is_lower ? -1.0 : +1.0)*(d_rho/d_dt)*((*u_data)(i_f) - (*gcoef_data)(i,0));
            }
        }
    }
    return;
}// setBcCoefs_private

/////////////////////////////// NAMESPACE ////////////////////////////////////

}// namespace IBAMR

/////////////////////////////// TEMPLATE INSTANTIATION ///////////////////////

//////////////////////////////////////////////////////////////////////////////
<|endoftext|>


<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "searchresultwindow.h"
#include "searchresulttreemodel.h"
#include "searchresulttreeitems.h"

#include <coreplugin/icore.h>
#include <utils/qtcassert.h>

#include <QtCore/QFile>
#include <QtCore/QTextStream>
#include <QtCore/QSettings>
#include <QtCore/QDebug>
#include <QtGui/QListWidget>
#include <QtGui/QToolButton>
#include <QtGui/QLineEdit>
#include <QtGui/QStackedWidget>
#include <QtGui/QLabel>

using namespace Find;
using namespace Find::Internal;

static const QString SETTINGSKEYSECTIONNAME("SearchResults");
static const QString SETTINGSKEYEXPANDRESULTS("ExpandResults");

SearchResultWindow::SearchResultWindow()
    : m_currentSearch(0),
    m_isShowingReplaceUI(false),
    m_focusReplaceEdit(false)
{
    m_widget = new QStackedWidget;
    m_widget->setWindowTitle(name());

    m_searchResultTreeView = new SearchResultTreeView(m_widget);
    m_searchResultTreeView->setFrameStyle(QFrame::NoFrame);
    m_searchResultTreeView->setAttribute(Qt::WA_MacShowFocusRect, false);
    m_widget->addWidget(m_searchResultTreeView);

    m_noMatchesFoundDisplay = new QListWidget(m_widget);
    m_noMatchesFoundDisplay->addItem(tr("No matches found!"));
    m_noMatchesFoundDisplay->setFrameStyle(QFrame::NoFrame);
    m_widget->addWidget(m_noMatchesFoundDisplay);

    m_expandCollapseToolButton = new QToolButton(m_widget);
    m_expandCollapseToolButton->setAutoRaise(true);
    m_expandCollapseToolButton->setCheckable(true);
    m_expandCollapseToolButton->setIcon(QIcon(":/find/images/expand.png"));
    m_expandCollapseToolButton->setToolTip(tr("Expand All"));

    m_replaceLabel = new QLabel(tr("Replace with:"), m_widget);
    m_replaceLabel->setContentsMargins(12, 0, 5, 0);
    m_replaceTextEdit = new QLineEdit(m_widget);
    m_replaceButton = new QToolButton(m_widget);
    m_replaceButton->setToolTip(tr("Replace all occurrences"));
    m_replaceButton->setText(tr("Replace"));
    m_replaceButton->setToolButtonStyle(Qt::ToolButtonTextOnly);
    m_replaceButton->setAutoRaise(true);
    m_replaceTextEdit->setTabOrder(m_replaceTextEdit, m_searchResultTreeView);

    connect(m_searchResultTreeView, SIGNAL(jumpToSearchResult(int,bool)),
            this, SLOT(handleJumpToSearchResult(int,bool)));
    connect(m_expandCollapseToolButton, SIGNAL(toggled(bool)), this, SLOT(handleExpandCollapseToolButton(bool)));
    connect(m_replaceTextEdit, SIGNAL(returnPressed()), this, SLOT(handleReplaceButton()));
    connect(m_replaceButton, SIGNAL(clicked()), this, SLOT(handleReplaceButton()));

    readSettings();
    setShowReplaceUI(false);
}

SearchResultWindow::~SearchResultWindow()
{
    writeSettings();
    delete m_currentSearch;
    m_currentSearch = 0;
    delete m_widget;
    m_widget = 0;
    m_items.clear();
}

void SearchResultWindow::setTextToReplace(const QString &textToReplace)
{
    m_replaceTextEdit->setText(textToReplace);
    m_replaceTextEdit->selectAll();
}

QString SearchResultWindow::textToReplace() const
{
    return m_replaceTextEdit->text();
}

void SearchResultWindow::setShowReplaceUI(bool show)
{
    m_searchResultTreeView->model()->setShowReplaceUI(show);
    m_replaceLabel->setVisible(show);
    m_replaceTextEdit->setVisible(show);
    m_replaceButton->setVisible(show);
    m_isShowingReplaceUI = show;
}

void SearchResultWindow::handleReplaceButton()
{
    QTC_ASSERT(m_currentSearch, return);
    // check if button is actually enabled, because this is also triggered
    // by pressing return in replace line edit
    if (m_replaceButton->isEnabled())
        m_currentSearch->replaceButtonClicked(m_replaceTextEdit->text(), checkedItems());
}

QList<SearchResultItem> SearchResultWindow::checkedItems() const
{
    QList<SearchResultItem> result;
    SearchResultTreeModel *model = m_searchResultTreeView->model();
    const int fileCount = model->rowCount(QModelIndex());
    for (int i = 0; i < fileCount; ++i) {
        QModelIndex fileIndex = model->index(i, 0, QModelIndex());
        SearchResultFile *fileItem = static_cast<SearchResultFile *>(fileIndex.internalPointer());
        Q_ASSERT(fileItem != 0);
        for (int rowIndex = 0; rowIndex < fileItem->childrenCount(); ++rowIndex) {
            QModelIndex textIndex = model->index(rowIndex, 0, fileIndex);
            SearchResultTextRow *rowItem = static_cast<SearchResultTextRow *>(textIndex.internalPointer());
            if (rowItem->checkState())
                result << m_items.at(rowItem->index());
        }
    }
    return result;
}

void SearchResultWindow::visibilityChanged(bool /*visible*/)
{
}

QWidget *SearchResultWindow::outputWidget(QWidget *)
{
    return m_widget;
}

QList<QWidget*> SearchResultWindow::toolBarWidgets() const
{
    return QList<QWidget*>() << m_expandCollapseToolButton << m_replaceLabel << m_replaceTextEdit << m_replaceButton;
}

SearchResult *SearchResultWindow::startNewSearch(SearchMode searchOrSearchAndReplace)
{
    clearContents();
    setShowReplaceUI(searchOrSearchAndReplace != SearchOnly);
    delete m_currentSearch;
    m_currentSearch = new SearchResult;
    return m_currentSearch;
}

void SearchResultWindow::finishSearch()
{
    if (m_items.count()) {
        m_replaceButton->setEnabled(true);
    } else {
        showNoMatchesFound();
    }
}

void SearchResultWindow::clearContents()
{
    m_replaceTextEdit->setEnabled(false);
    m_replaceButton->setEnabled(false);
    m_replaceTextEdit->clear();
    m_searchResultTreeView->clear();
    m_items.clear();
    m_widget->setCurrentWidget(m_searchResultTreeView);
    navigateStateChanged();
}

void SearchResultWindow::showNoMatchesFound()
{
    m_replaceTextEdit->setEnabled(false);
    m_replaceButton->setEnabled(false);
    m_widget->setCurrentWidget(m_noMatchesFoundDisplay);
}

bool SearchResultWindow::isEmpty() const
{
    return (m_searchResultTreeView->model()->rowCount() < 1);
}

int SearchResultWindow::numberOfResults() const
{
    return m_items.count();
}

bool SearchResultWindow::hasFocus()
{
    return m_searchResultTreeView->hasFocus() || (m_isShowingReplaceUI && m_replaceTextEdit->hasFocus());
}

bool SearchResultWindow::canFocus()
{
    return !m_items.isEmpty();
}

void SearchResultWindow::setFocus()
{
    if (!m_items.isEmpty()) {
        if (!m_isShowingReplaceUI) {
            m_searchResultTreeView->setFocus();
        } else {
            if (!m_widget->focusWidget()
                    || m_widget->focusWidget() == m_replaceTextEdit
                    || m_focusReplaceEdit) {
                m_replaceTextEdit->setFocus();
            } else {
                m_searchResultTreeView->setFocus();
            }
        }
    }
}

void SearchResultWindow::setTextEditorFont(const QFont &font)
{
    m_searchResultTreeView->setTextEditorFont(font);
}

void SearchResultWindow::handleJumpToSearchResult(int index, bool /* checked */)
{
    QTC_ASSERT(m_currentSearch, return);
    m_currentSearch->activated(m_items.at(index));
}

void SearchResultWindow::addResult(const QString &fileName, int lineNumber, const QString &rowText,
    int searchTermStart, int searchTermLength, const QVariant &userData)
{
    //qDebug()<<"###"<<fileName;
    m_widget->setCurrentWidget(m_searchResultTreeView);
    int index = m_items.size();
    SearchResultItem item;
    item.fileName = fileName;
    item.lineNumber = lineNumber;
    item.lineText = rowText;
    item.searchTermStart = searchTermStart;
    item.searchTermLength = searchTermLength;
    item.userData = userData;
    item.index = index;
    m_items.append(item);
    m_searchResultTreeView->appendResultLine(index, fileName, lineNumber, rowText, searchTermStart, searchTermLength);
    if (index == 0) {
        m_replaceTextEdit->setEnabled(true);
        // We didn't have an item before, set the focus to the search widget
        m_focusReplaceEdit = true;
        setFocus();
        m_focusReplaceEdit = false;
        m_searchResultTreeView->selectionModel()->select(m_searchResultTreeView->model()->index(0, 0, QModelIndex()), QItemSelectionModel::Select);
        emit navigateStateChanged();
    }
}

void SearchResultWindow::handleExpandCollapseToolButton(bool checked)
{
    m_searchResultTreeView->setAutoExpandResults(checked);
    if (checked)
        m_searchResultTreeView->expandAll();
    else
        m_searchResultTreeView->collapseAll();
}

void SearchResultWindow::readSettings()
{
    QSettings *s = Core::ICore::instance()->settings();
    if (s) {
        s->beginGroup(SETTINGSKEYSECTIONNAME);
        m_expandCollapseToolButton->setChecked(s->value(SETTINGSKEYEXPANDRESULTS, m_initiallyExpand).toBool());
        s->endGroup();
    }
}

void SearchResultWindow::writeSettings()
{
    QSettings *s = Core::ICore::instance()->settings();
    if (s) {
        s->beginGroup(SETTINGSKEYSECTIONNAME);
        s->setValue(SETTINGSKEYEXPANDRESULTS, m_expandCollapseToolButton->isChecked());
        s->endGroup();
    }
}

int SearchResultWindow::priorityInStatusBar() const
{
    return 80;
}

bool SearchResultWindow::canNext()
{
    return m_items.count() > 0;
}

bool SearchResultWindow::canPrevious()
{
    return m_items.count() > 0;
}

void SearchResultWindow::goToNext()
{
    if (m_items.count() == 0)
        return;
    QModelIndex idx = m_searchResultTreeView->model()->next(m_searchResultTreeView->currentIndex());
    if (idx.isValid()) {
        m_searchResultTreeView->setCurrentIndex(idx);
        m_searchResultTreeView->emitJumpToSearchResult(idx);
    }
}
void SearchResultWindow::goToPrev()
{
    if (!m_searchResultTreeView->model()->rowCount())
        return;
    QModelIndex idx = m_searchResultTreeView->model()->prev(m_searchResultTreeView->currentIndex());
    if (idx.isValid()) {
        m_searchResultTreeView->setCurrentIndex(idx);
        m_searchResultTreeView->emitJumpToSearchResult(idx);
    }
}

bool SearchResultWindow::canNavigate()
{
    return true;
}
<commit_msg>Fixed a few focus issues we had in the search result window (in replace mode).<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "searchresultwindow.h"
#include "searchresulttreemodel.h"
#include "searchresulttreeitems.h"

#include <coreplugin/icore.h>
#include <utils/qtcassert.h>

#include <QtCore/QFile>
#include <QtCore/QTextStream>
#include <QtCore/QSettings>
#include <QtCore/QDebug>
#include <QtGui/QListWidget>
#include <QtGui/QToolButton>
#include <QtGui/QLineEdit>
#include <QtGui/QStackedWidget>
#include <QtGui/QLabel>

using namespace Find;
using namespace Find::Internal;

static const QString SETTINGSKEYSECTIONNAME("SearchResults");
static const QString SETTINGSKEYEXPANDRESULTS("ExpandResults");

SearchResultWindow::SearchResultWindow()
    : m_currentSearch(0),
    m_isShowingReplaceUI(false),
    m_focusReplaceEdit(false)
{
    m_widget = new QStackedWidget;
    m_widget->setWindowTitle(name());

    m_searchResultTreeView = new SearchResultTreeView(m_widget);
    m_searchResultTreeView->setFrameStyle(QFrame::NoFrame);
    m_searchResultTreeView->setAttribute(Qt::WA_MacShowFocusRect, false);
    m_widget->addWidget(m_searchResultTreeView);

    m_noMatchesFoundDisplay = new QListWidget(m_widget);
    m_noMatchesFoundDisplay->addItem(tr("No matches found!"));
    m_noMatchesFoundDisplay->setFrameStyle(QFrame::NoFrame);
    m_widget->addWidget(m_noMatchesFoundDisplay);

    m_expandCollapseToolButton = new QToolButton(m_widget);
    m_expandCollapseToolButton->setAutoRaise(true);
    m_expandCollapseToolButton->setCheckable(true);
    m_expandCollapseToolButton->setIcon(QIcon(":/find/images/expand.png"));
    m_expandCollapseToolButton->setToolTip(tr("Expand All"));

    m_replaceLabel = new QLabel(tr("Replace with:"), m_widget);
    m_replaceLabel->setContentsMargins(12, 0, 5, 0);
    m_replaceTextEdit = new QLineEdit(m_widget);
    m_replaceButton = new QToolButton(m_widget);
    m_replaceButton->setToolTip(tr("Replace all occurrences"));
    m_replaceButton->setText(tr("Replace"));
    m_replaceButton->setToolButtonStyle(Qt::ToolButtonTextOnly);
    m_replaceButton->setAutoRaise(true);
    m_replaceTextEdit->setTabOrder(m_replaceTextEdit, m_searchResultTreeView);

    connect(m_searchResultTreeView, SIGNAL(jumpToSearchResult(int,bool)),
            this, SLOT(handleJumpToSearchResult(int,bool)));
    connect(m_expandCollapseToolButton, SIGNAL(toggled(bool)), this, SLOT(handleExpandCollapseToolButton(bool)));
    connect(m_replaceTextEdit, SIGNAL(returnPressed()), this, SLOT(handleReplaceButton()));
    connect(m_replaceButton, SIGNAL(clicked()), this, SLOT(handleReplaceButton()));

    readSettings();
    setShowReplaceUI(false);
}

SearchResultWindow::~SearchResultWindow()
{
    writeSettings();
    delete m_currentSearch;
    m_currentSearch = 0;
    delete m_widget;
    m_widget = 0;
    m_items.clear();
}

void SearchResultWindow::setTextToReplace(const QString &textToReplace)
{
    m_replaceTextEdit->setText(textToReplace);
}

QString SearchResultWindow::textToReplace() const
{
    return m_replaceTextEdit->text();
}

void SearchResultWindow::setShowReplaceUI(bool show)
{
    m_searchResultTreeView->model()->setShowReplaceUI(show);
    m_replaceLabel->setVisible(show);
    m_replaceTextEdit->setVisible(show);
    m_replaceButton->setVisible(show);
    m_isShowingReplaceUI = show;
}

void SearchResultWindow::handleReplaceButton()
{
    QTC_ASSERT(m_currentSearch, return);
    // check if button is actually enabled, because this is also triggered
    // by pressing return in replace line edit
    if (m_replaceButton->isEnabled())
        m_currentSearch->replaceButtonClicked(m_replaceTextEdit->text(), checkedItems());
}

QList<SearchResultItem> SearchResultWindow::checkedItems() const
{
    QList<SearchResultItem> result;
    SearchResultTreeModel *model = m_searchResultTreeView->model();
    const int fileCount = model->rowCount(QModelIndex());
    for (int i = 0; i < fileCount; ++i) {
        QModelIndex fileIndex = model->index(i, 0, QModelIndex());
        SearchResultFile *fileItem = static_cast<SearchResultFile *>(fileIndex.internalPointer());
        Q_ASSERT(fileItem != 0);
        for (int rowIndex = 0; rowIndex < fileItem->childrenCount(); ++rowIndex) {
            QModelIndex textIndex = model->index(rowIndex, 0, fileIndex);
            SearchResultTextRow *rowItem = static_cast<SearchResultTextRow *>(textIndex.internalPointer());
            if (rowItem->checkState())
                result << m_items.at(rowItem->index());
        }
    }
    return result;
}

void SearchResultWindow::visibilityChanged(bool /*visible*/)
{
}

QWidget *SearchResultWindow::outputWidget(QWidget *)
{
    return m_widget;
}

QList<QWidget*> SearchResultWindow::toolBarWidgets() const
{
    return QList<QWidget*>() << m_expandCollapseToolButton << m_replaceLabel << m_replaceTextEdit << m_replaceButton;
}

SearchResult *SearchResultWindow::startNewSearch(SearchMode searchOrSearchAndReplace)
{
    clearContents();
    setShowReplaceUI(searchOrSearchAndReplace != SearchOnly);
    delete m_currentSearch;
    m_currentSearch = new SearchResult;
    return m_currentSearch;
}

void SearchResultWindow::finishSearch()
{
    if (m_items.count()) {
        m_replaceButton->setEnabled(true);
    } else {
        showNoMatchesFound();
    }
}

void SearchResultWindow::clearContents()
{
    m_replaceTextEdit->setEnabled(false);
    m_replaceButton->setEnabled(false);
    m_replaceTextEdit->clear();
    m_searchResultTreeView->clear();
    m_items.clear();
    m_widget->setCurrentWidget(m_searchResultTreeView);
    navigateStateChanged();
}

void SearchResultWindow::showNoMatchesFound()
{
    m_replaceTextEdit->setEnabled(false);
    m_replaceButton->setEnabled(false);
    m_widget->setCurrentWidget(m_noMatchesFoundDisplay);
}

bool SearchResultWindow::isEmpty() const
{
    return (m_searchResultTreeView->model()->rowCount() < 1);
}

int SearchResultWindow::numberOfResults() const
{
    return m_items.count();
}

bool SearchResultWindow::hasFocus()
{
    return m_searchResultTreeView->hasFocus() || (m_isShowingReplaceUI && m_replaceTextEdit->hasFocus());
}

bool SearchResultWindow::canFocus()
{
    return !m_items.isEmpty();
}

void SearchResultWindow::setFocus()
{
    if (!m_items.isEmpty()) {
        if (!m_isShowingReplaceUI) {
            m_searchResultTreeView->setFocus();
        } else {
            if (!m_widget->focusWidget()
                    || m_widget->focusWidget() == m_replaceTextEdit
                    || m_focusReplaceEdit) {
                m_replaceTextEdit->setFocus();
                m_replaceTextEdit->selectAll();
            } else {
                m_searchResultTreeView->setFocus();
            }
        }
    }
}

void SearchResultWindow::setTextEditorFont(const QFont &font)
{
    m_searchResultTreeView->setTextEditorFont(font);
}

void SearchResultWindow::handleJumpToSearchResult(int index, bool /* checked */)
{
    QTC_ASSERT(m_currentSearch, return);
    m_currentSearch->activated(m_items.at(index));
}

void SearchResultWindow::addResult(const QString &fileName, int lineNumber, const QString &rowText,
    int searchTermStart, int searchTermLength, const QVariant &userData)
{
    //qDebug()<<"###"<<fileName;
    m_widget->setCurrentWidget(m_searchResultTreeView);
    int index = m_items.size();
    SearchResultItem item;
    item.fileName = fileName;
    item.lineNumber = lineNumber;
    item.lineText = rowText;
    item.searchTermStart = searchTermStart;
    item.searchTermLength = searchTermLength;
    item.userData = userData;
    item.index = index;
    m_items.append(item);
    m_searchResultTreeView->appendResultLine(index, fileName, lineNumber, rowText, searchTermStart, searchTermLength);
    if (index == 0) {
        m_replaceTextEdit->setEnabled(true);
        // We didn't have an item before, set the focus to the search widget
        m_focusReplaceEdit = true;
        setFocus();
        m_focusReplaceEdit = false;
        m_searchResultTreeView->selectionModel()->select(m_searchResultTreeView->model()->index(0, 0, QModelIndex()), QItemSelectionModel::Select);
        emit navigateStateChanged();
    }
}

void SearchResultWindow::handleExpandCollapseToolButton(bool checked)
{
    m_searchResultTreeView->setAutoExpandResults(checked);
    if (checked)
        m_searchResultTreeView->expandAll();
    else
        m_searchResultTreeView->collapseAll();
}

void SearchResultWindow::readSettings()
{
    QSettings *s = Core::ICore::instance()->settings();
    if (s) {
        s->beginGroup(SETTINGSKEYSECTIONNAME);
        m_expandCollapseToolButton->setChecked(s->value(SETTINGSKEYEXPANDRESULTS, m_initiallyExpand).toBool());
        s->endGroup();
    }
}

void SearchResultWindow::writeSettings()
{
    QSettings *s = Core::ICore::instance()->settings();
    if (s) {
        s->beginGroup(SETTINGSKEYSECTIONNAME);
        s->setValue(SETTINGSKEYEXPANDRESULTS, m_expandCollapseToolButton->isChecked());
        s->endGroup();
    }
}

int SearchResultWindow::priorityInStatusBar() const
{
    return 80;
}

bool SearchResultWindow::canNext()
{
    return m_items.count() > 0;
}

bool SearchResultWindow::canPrevious()
{
    return m_items.count() > 0;
}

void SearchResultWindow::goToNext()
{
    if (m_items.count() == 0)
        return;
    QModelIndex idx = m_searchResultTreeView->model()->next(m_searchResultTreeView->currentIndex());
    if (idx.isValid()) {
        m_searchResultTreeView->setCurrentIndex(idx);
        m_searchResultTreeView->emitJumpToSearchResult(idx);
    }
}
void SearchResultWindow::goToPrev()
{
    if (!m_searchResultTreeView->model()->rowCount())
        return;
    QModelIndex idx = m_searchResultTreeView->model()->prev(m_searchResultTreeView->currentIndex());
    if (idx.isValid()) {
        m_searchResultTreeView->setCurrentIndex(idx);
        m_searchResultTreeView->emitJumpToSearchResult(idx);
    }
}

bool SearchResultWindow::canNavigate()
{
    return true;
}
<|endoftext|>


<commit_before>/*
Copyright (c) 2009 Stephen John Bush

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.
*/

#ifndef _MSC_VER
#define _POSIX_SOURCE
#endif

//#define TRACING

#ifdef _POSIX_SOURCE
	#include <config.h>

	#include <cstdlib>
	#include <iostream>
	#include <string>
	#include <stdio.h>
#ifdef HAVE_BACKTRACE
	#include <execinfo.h>
#endif

#endif
	//for signal
	#include <signal.h>

//C4530: C++ exception handler used, but unwind semantics are not enabled.
#pragma warning (disable: 4530)

#include <exodus/mvimpl.h>
#include <exodus/mv.h>

//Simple implementation of an additional output to the console:
#ifdef _MSC_VER
#include <exodus/StackWalker.h>
class MyStackWalker : public StackWalker
{
public:

	exodus::var returnlines;

	MyStackWalker() : StackWalker(), returnlines("")
	{}

	MyStackWalker(DWORD dwProcessId, HANDLE hProcess)
	: StackWalker(dwProcessId, hProcess), returnlines("")
	{}
	virtual void OnOutput(LPCSTR szText)
	{
		//printf(szText);

		//printf("fgets:%s", path);
		exodus::var line=exodus::var(szText).convert("\x0d\x0a","");//.outputl("path=");
		exodus::var filename=line.field(":",1,2);//.outputl("filename=");
		exodus::var lineno=filename.field2(" ",-1);//.outputl("lineno=");
		filename.splicer(-(lineno.length()+1),999999,"");
		lineno.substrer(2,lineno.length()-2);
		if (filename.index("stackwalker.cpp")||filename.index("debug.cpp")||filename.index("crtexe.c"))
			return;
		if (lineno.isnum()&&lineno)
		{
			exodus::var linetext=filename.field2(exodus::SLASH,-1) ^ ":" ^ lineno;
			exodus::var filetext;
	//ALN:NOTE: .osread could itself throw exception and we will have loop :(
	// Changed to read directly with default locale. If no locale specified (as it was in original version of the code)
			if (filetext.osread(filename))
//			if (filetext.osread(filename, L""))		// avoid to read C++ source as UTF8
			{
				linetext^=": " ^ filetext.field("\x0A",lineno).trimf(" \t");
				if (linetext.index("backtrace("))
					return;
			}
			//outputl(linetext);
			returnlines^=exodus::FM^linetext;
		}

//		StackWalker::OnOutput(szText);
	}
};
#endif

#ifndef HAVE_BACKTRACE
#define NOBACKTRACE
#endif

namespace exodus {

void addbacktraceline(const var& sourcefilename, const var& lineno, var& returnlines)
{

#ifdef TRACING
	sourcefilename.outputl("SOURCEFILENAME=");
	lineno.outputl("LINENO=");
#endif

	if (not lineno || not lineno.isnum())
		return;

	var linetext=sourcefilename ^ ":" ^ lineno;

	//get the source file text
	var filetext;
	if (filetext.osread(sourcefilename)) {
	}

	//change DOS/WIN and MAC line ends to lf only
	filetext.swapper("\x0D\x0A","\x0A").converter("\x0D","\x0A");

	//extract the source line
	var line=filetext.field("\x0A",lineno).trimf(" \t");

	//suppress confusing and unhelpful exodus macros
	if (
		(line == "programexit()" || line == "libraryexit()" || line == "classexit()")
	or
		(line == "}" && sourcefilename.substr(-2,2) == ".h")
	)
		return;

	//outputl(linetext);
	linetext^=": " ^ line;

	returnlines^=FM^linetext;

	return;
}

//http://www.delorie.com/gnu/docs/glibc/libc_665.html
var backtrace()
{

#ifdef _MSC_VER
	//logputl("backtrace() not implemented on windows yet");
	//var().abort("");
	MyStackWalker sw;
	sw.ShowCallstack();
	return sw.returnlines;
#elif !defined(HAVE_BACKTRACE)
	printf("backtrace() not available");
	return L"";
#else

	var internaladdresses="";

#define BACKTRACE_MAXADDRESSES 500
	void *addresses[BACKTRACE_MAXADDRESSES];

/* example of TRACE from osx 64
Stack frames: 8
Backtrace 0: 0x10000c313
0   libexodus-11.5.0.dylib              0x000000010000c313 _ZN6exodus9backtraceEv + 99
Backtrace 1: 0x10001ec51
1   libexodus-11.5.0.dylib              0x000000010001ec51 _ZN6exodus11MVExceptionC2ERKNS_3varE + 129
Backtrace 2: 0x10001f314
2   libexodus-11.5.0.dylib              0x000000010001f314 _ZN6exodus12MVUnassignedC2ERKNS_3varE + 52
Backtrace 3: 0x10000e193
3   libexodus-11.5.0.dylib              0x000000010000e193 _ZNK6exodus3var3putERSo + 243
Backtrace 4: 0x10000e322
4   libexodus-11.5.0.dylib              0x000000010000e322 _ZNK6exodus3var7outputlEv + 34
Backtrace 5: 0x10000143f
5   steve                               0x000000010000143f _ZN13ExodusProgram4mainEv + 77
Backtrace 6: 0x1000010e6
6   steve                               0x00000001000010e6 main + 99
Backtrace 7: 0x100000f64
7   steve                               0x0000000100000f64 start + 52
*/

	//TODO autodetect if addr2line or dwalfdump/dSYM is available

#ifdef __APPLE__
	int size = ::backtrace(addresses, BACKTRACE_MAXADDRESSES);
	char **strings = backtrace_symbols(addresses, size);
//printf("Stack frames: %d\n", size);

	var returnlines="";

	for(int i = 0; i < size; i++) {

#ifdef TRACING
		//each string is like:
		//6   steve                               0x00000001000010e6 main + 99
		//////////////////////////////////////////////////////////////////////
		printf("%s\n", strings[i]);
#endif
		//parse one string for object filename and offset
		var onestring=var(strings[i]).trim();
		var objectfilename=onestring.field(L" ",2);
		var objectoffset=onestring.field(L" ",3);

		//looking for a dwarfdump line like this:
		//Line table file: 'steve.cpp' line 14, column 0 with start address 0x000000010000109e
		//////////////////////////////////////////////////////////////////////////////////////

		//get a dwarfdump line containing source filename and line number
		var debugfilename=objectfilename^".dSYM";
		var cmd=L"dwarfdump "^debugfilename^L" --lookup "^objectoffset^L" |grep \"Line table file: \" 2> /dev/null";
		var result=cmd.osshellread();
#ifdef TRACING
	cmd.outputl("CMD=");
	result.outputl("RESULT=");
#endif
		if (not result)
			continue;

		//parse the dwarfdump line for source filename and line number
		var sourcefilename=result.field("'",2);
		var lineno=result.field("'",3).trim().field(" ",2).field(",",1);

		addbacktraceline(sourcefilename,lineno,returnlines);

	}

	free(strings);
	return returnlines.substr(2);

//not __APPLE_
#else

	int size = ::backtrace(addresses, BACKTRACE_MAXADDRESSES);
#ifdef TRACING
	char **strings = backtrace_symbols(addresses, size);
	printf("Stack frames: %d\n", size);
#endif

	for(int i = 0; i < size; i++)
	{
		//#pragma warning (disable: 4311)
		internaladdresses^=" " ^ var((long long) addresses[i]).oconv("MX");

#ifdef TRACING
		if (sizeof addresses[i] == 4)
			printf("Backtrace %d: %X\n", i, (unsigned int)(long long)addresses[i]);
		else
			printf("Backtrace %d: %#llx\n", i, (long long)addresses[i]);
		printf("%s\n", strings[i]);
#endif

	}

#ifdef TRACING
	free(strings);
#endif

	FILE *fp;
	//int status;
	char path[1024];

	var binaryfilename=EXECPATH2.field(" ",1);
	if (binaryfilename == binaryfilename.convert("/\\:",""))
		binaryfilename="`which " ^ binaryfilename ^ "`";

#ifdef __APPLE__
	var oscmd="atos -o " ^ binaryfilename.quote() ^ " " ^ internaladdresses;
#else
	var oscmd="addr2line -e " ^ binaryfilename.quote() ^ " " ^ internaladdresses;
#endif
	//oscmd.outputl();

#ifdef TRACING
	printf("EXECPATH = %s\n",EXECPATH2.toString().c_str());
	printf("executing %s\n",oscmd.toString().c_str());
#endif

	/* Open the command for reading. */
	fp = popen(oscmd.toString().c_str(), "r");
	if (fp == NULL)
	{
		printf("Failed to run command\n" );
		return L"";
	}

#ifdef TRACING
	printf("reading output of addr2line\n");
#endif

	var returnlines="";

	/* Read the output a line at a time - output it. */
	while (fgets(path, sizeof(path)-1, fp) != NULL)
	{

#ifdef TRACING
		printf("fgets:%s", path);
#endif

		var path2=var(path).convert("\x0d\x0a","");//.outputl("path=");
		var sourcefilename=path2.field(":",1);//.outputl("filename=");
		var lineno=path2.field(":",2);//.outputl("lineno=");

		addbacktraceline(sourcefilename,lineno,returnlines);
	}

	/* close */
	pclose(fp);

	return returnlines.substr(2);
#endif

#endif

}

void SIGINT_handler (int sig)
{
	//ignore more of this signal
	//var().breakoff()
	//faster/safer
	signal(sig, SIG_IGN);

	//duplicated in init and B
	backtrace().convert(FM,"\n").outputl();

	for (;;)
	{

		printf ("\nInterrupted. (C)ontinue (E)nd (B)acktrace\n");

		output("? ");
		var cmd;
		if (! cmd.input())
		continue;
		var cmd1=cmd[1].ucase();

		if (cmd1 == "C")
			break;

		else if (cmd1=="E")

			var().abort("Aborted. User interrupt");

		else if (cmd1=="B")

			//duplicated in init and B
			backtrace().convert(FM,"\n").outputl();

	}

	//stop ignoreing this signal
	//var().breakon()
	//faster/safer
	signal(SIGINT, SIGINT_handler);
}

void var::breakoff() const
{
	//ignore more of this signal
	signal(SIGINT, SIG_IGN);
}

void var::breakon() const
{
	signal(SIGINT,  SIGINT_handler); /* this line will redirect ctrl+c signal*/
}

}//namespace exodus
<commit_msg>fix "addr2line: '/home/neosys/testsort': No such file" type messages<commit_after>/*
Copyright (c) 2009 Stephen John Bush

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.
*/

#ifndef _MSC_VER
#define _POSIX_SOURCE
#endif

//#define TRACING

#ifdef _POSIX_SOURCE
	#include <config.h>

	#include <cstdlib>
	#include <iostream>
	#include <string>
	#include <stdio.h>
#ifdef HAVE_BACKTRACE
	#include <execinfo.h>
#endif

#endif
	//for signal
	#include <signal.h>

//C4530: C++ exception handler used, but unwind semantics are not enabled.
#pragma warning (disable: 4530)

#include <exodus/mvimpl.h>
#include <exodus/mv.h>

//Simple implementation of an additional output to the console:
#ifdef _MSC_VER
#include <exodus/StackWalker.h>
class MyStackWalker : public StackWalker
{
public:

	exodus::var returnlines;

	MyStackWalker() : StackWalker(), returnlines("")
	{}

	MyStackWalker(DWORD dwProcessId, HANDLE hProcess)
	: StackWalker(dwProcessId, hProcess), returnlines("")
	{}
	virtual void OnOutput(LPCSTR szText)
	{
		//printf(szText);

		//printf("fgets:%s", path);
		exodus::var line=exodus::var(szText).convert("\x0d\x0a","");//.outputl("path=");
		exodus::var filename=line.field(":",1,2);//.outputl("filename=");
		exodus::var lineno=filename.field2(" ",-1);//.outputl("lineno=");
		filename.splicer(-(lineno.length()+1),999999,"");
		lineno.substrer(2,lineno.length()-2);
		if (filename.index("stackwalker.cpp")||filename.index("debug.cpp")||filename.index("crtexe.c"))
			return;
		if (lineno.isnum()&&lineno)
		{
			exodus::var linetext=filename.field2(exodus::SLASH,-1) ^ ":" ^ lineno;
			exodus::var filetext;
	//ALN:NOTE: .osread could itself throw exception and we will have loop :(
	// Changed to read directly with default locale. If no locale specified (as it was in original version of the code)
			if (filetext.osread(filename))
//			if (filetext.osread(filename, L""))		// avoid to read C++ source as UTF8
			{
				linetext^=": " ^ filetext.field("\x0A",lineno).trimf(" \t");
				if (linetext.index("backtrace("))
					return;
			}
			//outputl(linetext);
			returnlines^=exodus::FM^linetext;
		}

//		StackWalker::OnOutput(szText);
	}
};
#endif

#ifndef HAVE_BACKTRACE
#define NOBACKTRACE
#endif

namespace exodus {

void addbacktraceline(const var& sourcefilename, const var& lineno, var& returnlines)
{

#ifdef TRACING
	sourcefilename.outputl("SOURCEFILENAME=");
	lineno.outputl("LINENO=");
#endif

	if (not lineno || not lineno.isnum())
		return;

	var linetext=sourcefilename ^ ":" ^ lineno;

	//get the source file text
	var filetext;
	if (filetext.osread(sourcefilename)) {
	}

	//change DOS/WIN and MAC line ends to lf only
	filetext.swapper("\x0D\x0A","\x0A").converter("\x0D","\x0A");

	//extract the source line
	var line=filetext.field("\x0A",lineno).trimf(" \t");

	//suppress confusing and unhelpful exodus macros
	if (
		(line == "programexit()" || line == "libraryexit()" || line == "classexit()")
	or
		(line == "}" && sourcefilename.substr(-2,2) == ".h")
	)
		return;

	//outputl(linetext);
	linetext^=": " ^ line;

	returnlines^=FM^linetext;

	return;
}

//http://www.delorie.com/gnu/docs/glibc/libc_665.html
var backtrace()
{

#ifdef _MSC_VER
	//logputl("backtrace() not implemented on windows yet");
	//var().abort("");
	MyStackWalker sw;
	sw.ShowCallstack();
	return sw.returnlines;
#elif !defined(HAVE_BACKTRACE)
	printf("backtrace() not available");
	return L"";
#else

	var internaladdresses="";

#define BACKTRACE_MAXADDRESSES 500
	void *addresses[BACKTRACE_MAXADDRESSES];

/* example of TRACE from osx 64
Stack frames: 8
Backtrace 0: 0x10000c313
0   libexodus-11.5.0.dylib              0x000000010000c313 _ZN6exodus9backtraceEv + 99
Backtrace 1: 0x10001ec51
1   libexodus-11.5.0.dylib              0x000000010001ec51 _ZN6exodus11MVExceptionC2ERKNS_3varE + 129
Backtrace 2: 0x10001f314
2   libexodus-11.5.0.dylib              0x000000010001f314 _ZN6exodus12MVUnassignedC2ERKNS_3varE + 52
Backtrace 3: 0x10000e193
3   libexodus-11.5.0.dylib              0x000000010000e193 _ZNK6exodus3var3putERSo + 243
Backtrace 4: 0x10000e322
4   libexodus-11.5.0.dylib              0x000000010000e322 _ZNK6exodus3var7outputlEv + 34
Backtrace 5: 0x10000143f
5   steve                               0x000000010000143f _ZN13ExodusProgram4mainEv + 77
Backtrace 6: 0x1000010e6
6   steve                               0x00000001000010e6 main + 99
Backtrace 7: 0x100000f64
7   steve                               0x0000000100000f64 start + 52
*/

	//TODO autodetect if addr2line or dwalfdump/dSYM is available

#ifdef __APPLE__
	int size = ::backtrace(addresses, BACKTRACE_MAXADDRESSES);
	char **strings = backtrace_symbols(addresses, size);
//printf("Stack frames: %d\n", size);

	var returnlines="";

	for(int i = 0; i < size; i++) {

#ifdef TRACING
		//each string is like:
		//6   steve                               0x00000001000010e6 main + 99
		//////////////////////////////////////////////////////////////////////
		printf("%s\n", strings[i]);
#endif
		//parse one string for object filename and offset
		var onestring=var(strings[i]).trim();
		var objectfilename=onestring.field(L" ",2);
		var objectoffset=onestring.field(L" ",3);

		//looking for a dwarfdump line like this:
		//Line table file: 'steve.cpp' line 14, column 0 with start address 0x000000010000109e
		//////////////////////////////////////////////////////////////////////////////////////

		//get a dwarfdump line containing source filename and line number
		var debugfilename=objectfilename^".dSYM";
		var cmd=L"dwarfdump "^debugfilename^L" --lookup "^objectoffset^L" |grep \"Line table file: \" 2> /dev/null";
		var result=cmd.osshellread();
#ifdef TRACING
	cmd.outputl("CMD=");
	result.outputl("RESULT=");
#endif
		if (not result)
			continue;

		//parse the dwarfdump line for source filename and line number
		var sourcefilename=result.field("'",2);
		var lineno=result.field("'",3).trim().field(" ",2).field(",",1);

		addbacktraceline(sourcefilename,lineno,returnlines);

	}

	free(strings);
	return returnlines.substr(2);

//not __APPLE_
#else

	int size = ::backtrace(addresses, BACKTRACE_MAXADDRESSES);
#ifdef TRACING
	char **strings = backtrace_symbols(addresses, size);
	printf("Stack frames: %d\n", size);
#endif

	for(int i = 0; i < size; i++)
	{
		//#pragma warning (disable: 4311)
		internaladdresses^=" " ^ var((long long) addresses[i]).oconv("MX");

#ifdef TRACING
		if (sizeof addresses[i] == 4)
			printf("Backtrace %d: %X\n", i, (unsigned int)(long long)addresses[i]);
		else
			printf("Backtrace %d: %#llx\n", i, (long long)addresses[i]);
		printf("%s\n", strings[i]);
#endif

	}

#ifdef TRACING
	free(strings);
#endif

	FILE *fp;
	//int status;
	char path[1024];

	var binaryfilename=EXECPATH2.field(" ",1);
	//if (binaryfilename == binaryfilename.convert("/\\:",""))
	if (not binaryfilename.osdir())
	{
		var temp="which " ^ binaryfilename.field2(SLASH,-1);
		temp=temp.osshellread().field("\n",1).field("\r",1);
		if (temp)
			binaryfilename=temp;
	}
#ifdef __APPLE__
	var oscmd="atos -o " ^ binaryfilename.quote() ^ " " ^ internaladdresses;
#else
	var oscmd="addr2line -e " ^ binaryfilename.quote() ^ " " ^ internaladdresses;
#endif
	//oscmd.outputl();

#ifdef TRACING
	printf("EXECPATH = %s\n",EXECPATH2.toString().c_str());
	printf("executing %s\n",oscmd.toString().c_str());
#endif

	/* Open the command for reading. */
	fp = popen(oscmd.toString().c_str(), "r");
	if (fp == NULL)
	{
		printf("Failed to run command\n" );
		return L"";
	}

#ifdef TRACING
	printf("reading output of addr2line\n");
#endif

	var returnlines="";

	/* Read the output a line at a time - output it. */
	while (fgets(path, sizeof(path)-1, fp) != NULL)
	{

#ifdef TRACING
		printf("fgets:%s", path);
#endif

		var path2=var(path).convert("\x0d\x0a","");//.outputl("path=");
		var sourcefilename=path2.field(":",1);//.outputl("filename=");
		var lineno=path2.field(":",2);//.outputl("lineno=");

		addbacktraceline(sourcefilename,lineno,returnlines);
	}

	/* close */
	pclose(fp);

	return returnlines.substr(2);
#endif

#endif

}

void SIGINT_handler (int sig)
{
	//ignore more of this signal
	//var().breakoff()
	//faster/safer
	signal(sig, SIG_IGN);

	//duplicated in init and B
	backtrace().convert(FM,"\n").outputl();

	for (;;)
	{

		printf ("\nInterrupted. (C)ontinue (E)nd (B)acktrace\n");

		output("? ");
		var cmd;
		if (! cmd.input())
		continue;
		var cmd1=cmd[1].ucase();

		if (cmd1 == "C")
			break;

		else if (cmd1=="E")

			var().abort("Aborted. User interrupt");

		else if (cmd1=="B")

			//duplicated in init and B
			backtrace().convert(FM,"\n").outputl();

	}

	//stop ignoreing this signal
	//var().breakon()
	//faster/safer
	signal(SIGINT, SIGINT_handler);
}

void var::breakoff() const
{
	//ignore more of this signal
	signal(SIGINT, SIG_IGN);
}

void var::breakon() const
{
	signal(SIGINT,  SIGINT_handler); /* this line will redirect ctrl+c signal*/
}

}//namespace exodus
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2012, Willow Garage, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the Willow Garage, Inc. nor the names of its
 *       contributors may be used to endorse or promote products derived from
 *       this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include <QEvent>
#include <QMouseEvent>
#include <QPaintEvent>
#include <QPainter>
#include <QTreeView>

#include "rviz/properties/splitter_handle.h"

namespace rviz
{

SplitterHandle::SplitterHandle( QTreeView* parent )
  : QWidget( parent )
  , parent_( parent )
  , first_column_size_ratio_( 0.5f )
  , color_( 128, 128, 128, 64 )
{
  setCursor( Qt::SplitHCursor );
  int w = 7;
  setGeometry( parent_->width() / 2 - w/2, 0, w, parent_->height() );
  parent_->installEventFilter( this );
}

bool SplitterHandle::eventFilter( QObject* event_target, QEvent* event )
{
  if( event_target == parent_ && event->type() == QEvent::Resize )
  {
    updateGeometry();
  }
  return false; // Return false regardless so resize event also does its normal job.
}

void SplitterHandle::updateGeometry()
{
  int content_width = parent_->contentsRect().width();
  int new_column_width = int( first_column_size_ratio_ * content_width );
  parent_->setColumnWidth( 0, new_column_width );
  parent_->setColumnWidth( 1, content_width - new_column_width );
  setGeometry( new_column_width - width() / 2, 0, width(), parent_->height() );
}

void SplitterHandle::setRatio( float ratio )
{
  first_column_size_ratio_ = ratio;
  updateGeometry();
}

float SplitterHandle::getRatio()
{
  return first_column_size_ratio_;
}

void SplitterHandle::mousePressEvent( QMouseEvent* event )
{
  if( event->button() == Qt::LeftButton )
  {
    x_press_offset_ = event->x();
  }
}

void SplitterHandle::mouseMoveEvent( QMouseEvent* event )
{
  int padding = 55;

  if( event->buttons() & Qt::LeftButton )
  {
    QPoint pos_rel_parent = parent_->mapFromGlobal( event->globalPos() );

    int new_x = pos_rel_parent.x() - x_press_offset_;

    if( new_x > parent_->width() - width() - padding )
    {
      new_x = parent_->width() - width() - padding;
    }

    if( new_x < padding )
    {
      new_x = padding;
    }

    if( new_x != x() )
    {
      int new_column_width = new_x + width() / 2 - parent_->contentsRect().x();
      first_column_size_ratio_ = new_column_width / (float) parent_->contentsRect().width();
      updateGeometry();
    }
  }
}

void SplitterHandle::paintEvent( QPaintEvent* event )
{
  QPainter painter( this );
  painter.setPen( color_ );
  painter.drawLine( width() / 2, 0, width() / 2, height() );
}

} // end namespace rviz
<commit_msg>fixed update of SplitterHandle<commit_after>/*
 * Copyright (c) 2012, Willow Garage, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the Willow Garage, Inc. nor the names of its
 *       contributors may be used to endorse or promote products derived from
 *       this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include <QEvent>
#include <QMouseEvent>
#include <QPaintEvent>
#include <QPainter>
#include <QTreeView>

#include "rviz/properties/splitter_handle.h"

namespace rviz
{

SplitterHandle::SplitterHandle( QTreeView* parent )
  : QWidget( parent )
  , parent_( parent )
  , first_column_size_ratio_( 0.5f )
  , color_( 128, 128, 128, 64 )
{
  setCursor( Qt::SplitHCursor );
  updateGeometry();
  parent_->installEventFilter( this );
}

bool SplitterHandle::eventFilter( QObject* event_target, QEvent* event )
{
  if( event_target == parent_ && event->type() == QEvent::UpdateRequest )
  {
    updateGeometry();
  }
  return false; // Return false regardless so resize event also does its normal job.
}

void SplitterHandle::updateGeometry()
{
  int w = 7;
  int content_width = parent_->contentsRect().width();
  int new_column_width = int( first_column_size_ratio_ * content_width );
  parent_->setColumnWidth( 0, new_column_width );
  parent_->setColumnWidth( 1, content_width - new_column_width );
  setGeometry( new_column_width - w / 2 + parent_->columnViewportPosition(0), 0, w, parent_->height() );
}

void SplitterHandle::setRatio( float ratio )
{
  first_column_size_ratio_ = ratio;
  updateGeometry();
}

float SplitterHandle::getRatio()
{
  return first_column_size_ratio_;
}

void SplitterHandle::mousePressEvent( QMouseEvent* event )
{
  if( event->button() == Qt::LeftButton )
  {
    // position of mouse press inside this QWidget
    x_press_offset_ = event->x();
  }
}

void SplitterHandle::mouseMoveEvent( QMouseEvent* event )
{
  int padding = 55;

  if( event->buttons() & Qt::LeftButton )
  {
    QPoint pos_rel_parent = parent_->mapFromGlobal( event->globalPos() );

    int new_x = pos_rel_parent.x() - x_press_offset_ - parent_->columnViewportPosition(0);

    if( new_x > parent_->width() - width() - padding )
    {
      new_x = parent_->width() - width() - padding;
    }

    if( new_x < padding )
    {
      new_x = padding;
    }

    if( new_x != x() )
    {
      int new_column_width = new_x + width() / 2 - parent_->contentsRect().x();
      first_column_size_ratio_ = new_column_width / (float) parent_->contentsRect().width();
      updateGeometry();
    }
  }
}

void SplitterHandle::paintEvent( QPaintEvent* event )
{
  QPainter painter( this );
  painter.setPen( color_ );
  painter.drawLine( 1+width() / 2, 0, 1+width() / 2, height() );
}

} // end namespace rviz
<|endoftext|>


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

                  Ȩ (C), 2001-2011, IOT CopyRight

 ******************************************************************************
       : Server.cc
       :
         : ChenZhen
     : 2017217
  ޸   :
     :
  б   :
  ޸ʷ   :
  1.       : 2017217
           : ChenZhen
    ޸   : ļ

******************************************************************************/

/*----------------------------------------------*
 * ͷļ                                   *
 *----------------------------------------------*/
#include <iostream>
#include <unistd.h>

#include "Server.h"

/*****************************************************************************
     : Server.Server
   : 캯
   :
   :
   ֵ  :
 ú  :
   :

 ޸ʷ      :
  1.       : 2017217
           : ChenZhen
    ޸   : ɺ

*****************************************************************************/
Server::Server()
{
    this->m_InnerHandleThread       = NULL;
    this->m_OuterHandleThread       = NULL;
    this->m_OuterTimerThread        = NULL;
    this->m_tag                     = 0;
}

/*****************************************************************************
     : Server.~Server
   :
   :
   :
   ֵ  :
 ú  :
   :

 ޸ʷ      :
  1.       : 2017217
           : ChenZhen
    ޸   : ɺ

*****************************************************************************/
Server::~Server()
{

}

/*****************************************************************************
     : Server.GetTag
   : ȡTAG
   :
   :
   ֵ  : int
 ú  :
   :

 ޸ʷ      :
  1.       : 2017217
           : ChenZhen
    ޸   : ɺ

*****************************************************************************/
int Server::GetTag()
{
    return this->m_tag;
}

/*****************************************************************************
     : Server.Init
   : ʼ
   :
   :
   ֵ  : int
 ú  :
   :

 ޸ʷ      :
  1.       : 2017217
           : ChenZhen
    ޸   : ɺ

*****************************************************************************/
int Server::Init(string configPath)
{
    m_configPath = configPath;

    return 0;
}

/*****************************************************************************
     : Server.Run
   : з
   :
   :
   ֵ  : int
 ú  :
   :

 ޸ʷ      :
  1.       : 2017217
           : ChenZhen
    ޸   : ɺ

*****************************************************************************/
int Server::Run()
{
    /* Handle */
    this->m_OuterHandleThread = new OuterHandleThread(this);
    this->m_InnerHandleThread = new InnerHandleThread(this);
    this->m_OuterTimerThread  = new OuterTimerThread(this);

    while(1)
    {
        //sleep(1);
    }

    return 0;
}

<commit_msg>SV-19: modify some files for compile<commit_after>/******************************************************************************

                  Ȩ (C), 2001-2011, IOT CopyRight

 ******************************************************************************
       : Server.cc
       :
         : ChenZhen
     : 2017217
  ޸   :
     :
  б   :
  ޸ʷ   :
  1.       : 2017217
           : ChenZhen
    ޸   : ļ

******************************************************************************/

/*----------------------------------------------*
 * ͷļ                                   *
 *----------------------------------------------*/
#include <iostream>
#include <unistd.h>

#include "Server.h"

/*****************************************************************************
     : Server.Server
   : 캯
   :
   :
   ֵ  :
 ú  :
   :

 ޸ʷ      :
  1.       : 2017217
           : ChenZhen
    ޸   : ɺ

*****************************************************************************/
Server::Server()
{
    this->m_InnerHandleThread       = NULL;
    this->m_OuterHandleThread       = NULL;
    this->m_OuterTimerThread        = NULL;
    this->m_tag                     = 0;
}

/*****************************************************************************
     : Server.~Server
   :
   :
   :
   ֵ  :
 ú  :
   :

 ޸ʷ      :
  1.       : 2017217
           : ChenZhen
    ޸   : ɺ

*****************************************************************************/
Server::~Server()
{

}

/*****************************************************************************
     : Server.GetTag
   : ȡTAG
   :
   :
   ֵ  : int
 ú  :
   :

 ޸ʷ      :
  1.       : 2017217
           : ChenZhen
    ޸   : ɺ

*****************************************************************************/
int Server::GetTag()
{
    return this->m_tag;
}

/*****************************************************************************
     : Server.Init
   : ʼ
   :
   :
   ֵ  : int
 ú  :
   :

 ޸ʷ      :
  1.       : 2017217
           : ChenZhen
    ޸   : ɺ

*****************************************************************************/
int Server::Init(string configPath)
{
    m_configPath = configPath;

    return 0;
}

/*****************************************************************************
     : Server.Run
   : з
   :
   :
   ֵ  : int
 ú  :
   :

 ޸ʷ      :
  1.       : 2017217
           : ChenZhen
    ޸   : ɺ

*****************************************************************************/
int Server::Run()
{
    /* Handle */
    //this->m_OuterHandleThread = new OuterHandleThread(this);
    //this->m_InnerHandleThread = new InnerHandleThread(this);
    //this->m_OuterTimerThread  = new OuterTimerThread(this);

    while(1)
    {
        //sleep(1);
    }

    return 0;
}

<|endoftext|>


<commit_before>#include "NL_InputProcessor.h"
#include "NL_InputEvents.h"

#include <assert.h>

namespace NLE
{
	InputProcessor::InputProcessor() :
		_initialized(false)
	{

	}

	InputProcessor::~InputProcessor()
	{

	}

	bool InputProcessor::initialize(Core::IEngine& engine)
	{

		_procedure = [&](){
		};

		_initialized = true;
		return _initialized;
	}

	void InputProcessor::release()
	{

	}

	bool InputProcessor::initialized()
	{
		return _initialized;
	}

	std::function<void()> const& InputProcessor::getExecutionProcedure()
	{
		return _procedure;
	}

	Core::ISystem& InputProcessor::getInterface()
	{
		return *this;
	}

	void InputProcessor::attachEventPollingOperation(std::function<void()> operation)
	{
	}

	void InputProcessor::processEvent(INPUT::Event& event)
	{
	}
}

<commit_msg>added InputProcessor<commit_after>#include "NL_InputProcessor.h"
#include "NL_InputEvents.h"

#include <assert.h>

namespace NLE
{
	InputProcessor::InputProcessor() :
		_initialized(false)
	{

	}

	InputProcessor::~InputProcessor()
	{

	}

	bool InputProcessor::initialize(Core::IEngine& engine)
	{
		assert(!_initialized && _eventPoller);

		_procedure = [&](){
			_eventPoller();
		};

		_initialized = true;
		return _initialized;
	}

	void InputProcessor::release()
	{

	}

	bool InputProcessor::initialized()
	{
		return _initialized;
	}

	std::function<void()> const& InputProcessor::getExecutionProcedure()
	{
		return _procedure;
	}

	Core::ISystem& InputProcessor::getInterface()
	{
		return *this;
	}

	void InputProcessor::attachEventPollingOperation(std::function<void()> operation)
	{
		_eventPoller = operation;
	}

	void InputProcessor::processEvent(INPUT::Event& event)
	{
		printf("Processing event\n");
	}
}
<|endoftext|>