<commit_before>// The libMesh Finite Element Library.
// Copyright (C) 2002-2017 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner

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

// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.

// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

//
FEMSystem Example 3 - Unsteady Linear Elasticity with
// FEMSystem

// \author Paul Bauman
// \date 2015
//
// This example shows how to solve the three-dimensional transient
// linear elasticity equations using the DifferentiableSystem class framework.
// This is just Systems of Equations Example 6 recast.

// C++ includes
#include <iomanip>

// Basic include files
#include "libmesh/equation_systems.h"
#include "libmesh/error_vector.h"
#include "libmesh/getpot.h"
#include "libmesh/exodusII_io.h"
#include "libmesh/kelly_error_estimator.h"
#include "libmesh/mesh.h"
#include "libmesh/mesh_generation.h"

// The systems and solvers we may use
#include "elasticity_system.h"
#include "libmesh/diff_solver.h"
#include "libmesh/newmark_solver.h"
#include "libmesh/steady_solver.h"
#include "libmesh/euler_solver.h"
#include "libmesh/euler2_solver.h"
#include "libmesh/elem.h"
#include "libmesh/newton_solver.h"
#include "libmesh/eigen_sparse_linear_solver.h"

#define x_scaling 1.3

// Bring in everything from the libMesh namespace
using namespace libMesh;

// The main program.
int main (int argc, char ** argv)
{
  // Initialize libMesh.
  LibMeshInit init (argc, argv);

  // Parse the input file
  GetPot infile("fem_system_ex3.in");

  // Override input file arguments from the commannd line
  infile.parse_command_line(argc, argv);

  // Read in parameters from the input file
  const Real deltat           = infile("deltat", 0.25);
  unsigned int n_timesteps    = infile("n_timesteps", 1);

#ifdef LIBMESH_HAVE_EXODUS_API
  const unsigned int write_interval    = infile("write_interval", 1);
#endif

  // Initialize the cantilever mesh
  const unsigned int dim = 3;

  // Make sure libMesh was compiled for 3D
  libmesh_example_requires(dim == LIBMESH_DIM, "3D support");

  // Create a 3D mesh distributed across the default MPI communicator.
  Mesh mesh(init.comm(), dim);
  MeshTools::Generation::build_cube (mesh,
                                     32,
                                     8,
                                     4,
                                     0., 1.*x_scaling,
                                     0., 0.3,
                                     0., 0.1,
                                     HEX8);

  // Print information about the mesh to the screen.
  mesh.print_info();

  // Let's add some node and edge boundary conditions.
  // Each processor should know about each boundary condition it can
  // see, so we loop over all elements, not just local elements.
  MeshBase::const_element_iterator       el     = mesh.elements_begin();
  const MeshBase::const_element_iterator end_el = mesh.elements_end();
  for ( ; el != end_el; ++el)
    {
      const Elem * elem = *el;

      unsigned int
        side_max_x = 0, side_min_y = 0,
        side_max_y = 0, side_max_z = 0;
      bool
        found_side_max_x = false, found_side_max_y = false,
        found_side_min_y = false, found_side_max_z = false;
      for (unsigned int side=0; side<elem->n_sides(); side++)
        {
          if (mesh.get_boundary_info().has_boundary_id(elem, side, BOUNDARY_ID_MAX_X))
            {
              side_max_x = side;
              found_side_max_x = true;
            }

          if (mesh.get_boundary_info().has_boundary_id(elem, side, BOUNDARY_ID_MIN_Y))
            {
              side_min_y = side;
              found_side_min_y = true;
            }

          if (mesh.get_boundary_info().has_boundary_id(elem, side, BOUNDARY_ID_MAX_Y))
            {
              side_max_y = side;
              found_side_max_y = true;
            }

          if (mesh.get_boundary_info().has_boundary_id(elem, side, BOUNDARY_ID_MAX_Z))
            {
              side_max_z = side;
              found_side_max_z = true;
            }
        }

      // If elem has sides on boundaries
      // BOUNDARY_ID_MAX_X, BOUNDARY_ID_MAX_Y, BOUNDARY_ID_MAX_Z
      // then let's set a node boundary condition
      if (found_side_max_x && found_side_max_y && found_side_max_z)
        for (unsigned int n=0; n<elem->n_nodes(); n++)
          if (elem->is_node_on_side(n, side_max_x) &&
              elem->is_node_on_side(n, side_max_y) &&
              elem->is_node_on_side(n, side_max_z))
            mesh.get_boundary_info().add_node(elem->node_ptr(n), NODE_BOUNDARY_ID);

      // If elem has sides on boundaries
      // BOUNDARY_ID_MAX_X and BOUNDARY_ID_MIN_Y
      // then let's set an edge boundary condition
      if (found_side_max_x && found_side_min_y)
        for (unsigned int e=0; e<elem->n_edges(); e++)
          if (elem->is_edge_on_side(e, side_max_x) &&
              elem->is_edge_on_side(e, side_min_y))
            mesh.get_boundary_info().add_edge(elem, e, EDGE_BOUNDARY_ID);
    }

  // Create an equation systems object.
  EquationSystems equation_systems (mesh);

  // Declare the system "Navier-Stokes" and its variables.
  ElasticitySystem & system =
    equation_systems.add_system<ElasticitySystem> ("Linear Elasticity");

  // Solve this as a time-dependent or steady system
  std::string time_solver = infile("time_solver","DIE!");

  ExplicitSystem * v_system;
  ExplicitSystem * a_system;

  if( time_solver == std::string("newmark") )
    {
      // Create ExplicitSystem to help output velocity
      v_system = &equation_systems.add_system<ExplicitSystem> ("Velocity");
      v_system->add_variable("u_vel", FIRST, LAGRANGE);
      v_system->add_variable("v_vel", FIRST, LAGRANGE);
      v_system->add_variable("w_vel", FIRST, LAGRANGE);

      // Create ExplicitSystem to help output acceleration
      a_system = &equation_systems.add_system<ExplicitSystem> ("Acceleration");
      a_system->add_variable("u_accel", FIRST, LAGRANGE);
      a_system->add_variable("v_accel", FIRST, LAGRANGE);
      a_system->add_variable("w_accel", FIRST, LAGRANGE);
    }

  if( time_solver == std::string("newmark"))
    system.time_solver.reset(new NewmarkSolver(system));

  else if( time_solver == std::string("euler") )
    {
      system.time_solver.reset(new EulerSolver(system));
      EulerSolver & euler_solver = libmesh_cast_ref<EulerSolver &>(*(system.time_solver.get()));
      euler_solver.theta = infile("theta", 1.0);
    }

  else if( time_solver == std::string("euler2") )
    {
      system.time_solver.reset(new Euler2Solver(system));
      Euler2Solver & euler_solver = libmesh_cast_ref<Euler2Solver &>(*(system.time_solver.get()));
      euler_solver.theta = infile("theta", 1.0);
    }

  else if( time_solver == std::string("steady"))
    {
      system.time_solver.reset(new SteadySolver(system));
      libmesh_assert_equal_to (n_timesteps, 1);
    }
  else
    libmesh_error_msg(std::string("ERROR: invalud time_solver ")+time_solver);

  // Initialize the system
  equation_systems.init ();

  // Set the time stepping options
  system.deltat = deltat;

  // And the nonlinear solver options
  DiffSolver & solver = *(system.time_solver->diff_solver().get());
  solver.quiet = infile("solver_quiet", true);
  solver.verbose = !solver.quiet;
  solver.max_nonlinear_iterations = infile("max_nonlinear_iterations", 15);
  solver.relative_step_tolerance = infile("relative_step_tolerance", 1.e-3);
  solver.relative_residual_tolerance = infile("relative_residual_tolerance", 0.0);
  solver.absolute_residual_tolerance = infile("absolute_residual_tolerance", 0.0);

  // And the linear solver options
  solver.max_linear_iterations = infile("max_linear_iterations", 50000);
  solver.initial_linear_tolerance = infile("initial_linear_tolerance", 1.e-3);

  // Print information about the system to the screen.
  equation_systems.print_info();

  // If we're using EulerSolver or Euler2Solver, and we're using EigenSparseLinearSolver,
  // then we need to reset the EigenSparseLinearSolver to use SPARSELU because BICGSTAB
  // chokes on the Jacobian matrix we give it and Eigen's GMRES currently doesn't work.
  NewtonSolver * newton_solver = dynamic_cast<NewtonSolver *>( &solver );
  if( newton_solver &&
      (time_solver == std::string("euler") || time_solver == std::string("euler2") ) )
    {
      LinearSolver<Number> & linear_solver = newton_solver->get_linear_solver();
      EigenSparseLinearSolver<Number> * eigen_linear_solver =
        dynamic_cast<EigenSparseLinearSolver<Number> *>(&linear_solver);

      if( eigen_linear_solver )
        eigen_linear_solver->set_solver_type(SPARSELU);
    }

  if( time_solver == std::string("newmark") )
    {
      NewmarkSolver * newmark = cast_ptr<NewmarkSolver*>(system.time_solver.get());
      newmark->compute_initial_accel();

      // Copy over initial velocity and acceleration for output.
      // Note we can do this because of the matching variables/FE spaces
      *(v_system->solution) = system.get_vector("_old_solution_rate");
      *(a_system->solution) = system.get_vector("_old_solution_accel");
    }

#ifdef LIBMESH_HAVE_EXODUS_API
  // Output initial state
  {
    std::ostringstream file_name;

    // We write the file in the ExodusII format.
    file_name << std::string("out.")+time_solver+std::string(".e-s.")
              << std::setw(3)
              << std::setfill('0')
              << std::right
              << 0;

    ExodusII_IO(mesh).write_timestep(file_name.str(),
                                     equation_systems,
                                     1, // This number indicates how many time steps
                                        // are being written to the file
                                     system.time);
  }
#endif // #ifdef LIBMESH_HAVE_EXODUS_API

  // Now we begin the timestep loop to compute the time-accurate
  // solution of the equations.
  for (unsigned int t_step=0; t_step != n_timesteps; ++t_step)
    {
      // A pretty update message
      libMesh::out << "\n\nSolving time step "
                   << t_step
                   << ", time = "
                   << system.time
                   << std::endl;

      system.solve();

      // Advance to the next timestep in a transient problem
      system.time_solver->advance_timestep();

      // Copy over updated velocity and acceleration for output.
      // Note we can do this because of the matching variables/FE spaces
      if( time_solver == std::string("newmark") )
        {
          *(v_system->solution) = system.get_vector("_old_solution_rate");
          *(a_system->solution) = system.get_vector("_old_solution_accel");
        }

#ifdef LIBMESH_HAVE_EXODUS_API
      // Write out this timestep if we're requested to
      if ((t_step+1)%write_interval == 0)
        {
          std::ostringstream file_name;

          // We write the file in the ExodusII format.
          file_name << std::string("out.")+time_solver+std::string(".e-s.")
                    << std::setw(3)
                    << std::setfill('0')
                    << std::right
                    << t_step+1;

          ExodusII_IO(mesh).write_timestep(file_name.str(),
                                           equation_systems,
                                           1, // This number indicates how many time steps
                                              // are being written to the file
                                           system.time);
        }
#endif // #ifdef LIBMESH_HAVE_EXODUS_API
    }

  // All done.
  return 0;
}
<commit_msg>fix for --disable-optional && make installcheck<commit_after>// The libMesh Finite Element Library.
// Copyright (C) 2002-2017 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner

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

// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.

// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

//
FEMSystem Example 3 - Unsteady Linear Elasticity with
// FEMSystem

// \author Paul Bauman
// \date 2015
//
// This example shows how to solve the three-dimensional transient
// linear elasticity equations using the DifferentiableSystem class framework.
// This is just Systems of Equations Example 6 recast.

// C++ includes
#include <iomanip>

// Basic include files
#include "libmesh/equation_systems.h"
#include "libmesh/error_vector.h"
#include "libmesh/getpot.h"
#include "libmesh/exodusII_io.h"
#include "libmesh/kelly_error_estimator.h"
#include "libmesh/mesh.h"
#include "libmesh/mesh_generation.h"

// The systems and solvers we may use
#include "elasticity_system.h"
#include "libmesh/diff_solver.h"
#include "libmesh/newmark_solver.h"
#include "libmesh/steady_solver.h"
#include "libmesh/euler_solver.h"
#include "libmesh/euler2_solver.h"
#include "libmesh/elem.h"
#include "libmesh/newton_solver.h"
#include "libmesh/eigen_sparse_linear_solver.h"

#define x_scaling 1.3

// Bring in everything from the libMesh namespace
using namespace libMesh;

// The main program.
int main (int argc, char ** argv)
{
  // Initialize libMesh.
  LibMeshInit init (argc, argv);

  // Parse the input file
  GetPot infile("fem_system_ex3.in");

  // Override input file arguments from the commannd line
  infile.parse_command_line(argc, argv);

  // Read in parameters from the input file
  const Real deltat           = infile("deltat", 0.25);
  unsigned int n_timesteps    = infile("n_timesteps", 1);

#ifdef LIBMESH_HAVE_EXODUS_API
  const unsigned int write_interval    = infile("write_interval", 1);
#endif

  // Initialize the cantilever mesh
  const unsigned int dim = 3;

  // Make sure libMesh was compiled for 3D
  libmesh_example_requires(dim == LIBMESH_DIM, "3D support");

  // Create a 3D mesh distributed across the default MPI communicator.
  Mesh mesh(init.comm(), dim);
  MeshTools::Generation::build_cube (mesh,
                                     32,
                                     8,
                                     4,
                                     0., 1.*x_scaling,
                                     0., 0.3,
                                     0., 0.1,
                                     HEX8);

  // Print information about the mesh to the screen.
  mesh.print_info();

  // Let's add some node and edge boundary conditions.
  // Each processor should know about each boundary condition it can
  // see, so we loop over all elements, not just local elements.
  MeshBase::const_element_iterator       el     = mesh.elements_begin();
  const MeshBase::const_element_iterator end_el = mesh.elements_end();
  for ( ; el != end_el; ++el)
    {
      const Elem * elem = *el;

      unsigned int
        side_max_x = 0, side_min_y = 0,
        side_max_y = 0, side_max_z = 0;
      bool
        found_side_max_x = false, found_side_max_y = false,
        found_side_min_y = false, found_side_max_z = false;
      for (unsigned int side=0; side<elem->n_sides(); side++)
        {
          if (mesh.get_boundary_info().has_boundary_id(elem, side, BOUNDARY_ID_MAX_X))
            {
              side_max_x = side;
              found_side_max_x = true;
            }

          if (mesh.get_boundary_info().has_boundary_id(elem, side, BOUNDARY_ID_MIN_Y))
            {
              side_min_y = side;
              found_side_min_y = true;
            }

          if (mesh.get_boundary_info().has_boundary_id(elem, side, BOUNDARY_ID_MAX_Y))
            {
              side_max_y = side;
              found_side_max_y = true;
            }

          if (mesh.get_boundary_info().has_boundary_id(elem, side, BOUNDARY_ID_MAX_Z))
            {
              side_max_z = side;
              found_side_max_z = true;
            }
        }

      // If elem has sides on boundaries
      // BOUNDARY_ID_MAX_X, BOUNDARY_ID_MAX_Y, BOUNDARY_ID_MAX_Z
      // then let's set a node boundary condition
      if (found_side_max_x && found_side_max_y && found_side_max_z)
        for (unsigned int n=0; n<elem->n_nodes(); n++)
          if (elem->is_node_on_side(n, side_max_x) &&
              elem->is_node_on_side(n, side_max_y) &&
              elem->is_node_on_side(n, side_max_z))
            mesh.get_boundary_info().add_node(elem->node_ptr(n), NODE_BOUNDARY_ID);

      // If elem has sides on boundaries
      // BOUNDARY_ID_MAX_X and BOUNDARY_ID_MIN_Y
      // then let's set an edge boundary condition
      if (found_side_max_x && found_side_min_y)
        for (unsigned int e=0; e<elem->n_edges(); e++)
          if (elem->is_edge_on_side(e, side_max_x) &&
              elem->is_edge_on_side(e, side_min_y))
            mesh.get_boundary_info().add_edge(elem, e, EDGE_BOUNDARY_ID);
    }

  // Create an equation systems object.
  EquationSystems equation_systems (mesh);

  // Declare the system "Navier-Stokes" and its variables.
  ElasticitySystem & system =
    equation_systems.add_system<ElasticitySystem> ("Linear Elasticity");

  // Solve this as a time-dependent or steady system
  std::string time_solver = infile("time_solver","DIE!");

  ExplicitSystem * v_system;
  ExplicitSystem * a_system;

  if( time_solver == std::string("newmark") )
    {
      // Create ExplicitSystem to help output velocity
      v_system = &equation_systems.add_system<ExplicitSystem> ("Velocity");
      v_system->add_variable("u_vel", FIRST, LAGRANGE);
      v_system->add_variable("v_vel", FIRST, LAGRANGE);
      v_system->add_variable("w_vel", FIRST, LAGRANGE);

      // Create ExplicitSystem to help output acceleration
      a_system = &equation_systems.add_system<ExplicitSystem> ("Acceleration");
      a_system->add_variable("u_accel", FIRST, LAGRANGE);
      a_system->add_variable("v_accel", FIRST, LAGRANGE);
      a_system->add_variable("w_accel", FIRST, LAGRANGE);
    }

  if( time_solver == std::string("newmark"))
    system.time_solver.reset(new NewmarkSolver(system));

  else if( time_solver == std::string("euler") )
    {
      system.time_solver.reset(new EulerSolver(system));
      EulerSolver & euler_solver = libmesh_cast_ref<EulerSolver &>(*(system.time_solver.get()));
      euler_solver.theta = infile("theta", 1.0);
    }

  else if( time_solver == std::string("euler2") )
    {
      system.time_solver.reset(new Euler2Solver(system));
      Euler2Solver & euler_solver = libmesh_cast_ref<Euler2Solver &>(*(system.time_solver.get()));
      euler_solver.theta = infile("theta", 1.0);
    }

  else if( time_solver == std::string("steady"))
    {
      system.time_solver.reset(new SteadySolver(system));
      libmesh_assert_equal_to (n_timesteps, 1);
    }
  else
    libmesh_error_msg(std::string("ERROR: invalud time_solver ")+time_solver);

  // Initialize the system
  equation_systems.init ();

  // Set the time stepping options
  system.deltat = deltat;

  // And the nonlinear solver options
  DiffSolver & solver = *(system.time_solver->diff_solver().get());
  solver.quiet = infile("solver_quiet", true);
  solver.verbose = !solver.quiet;
  solver.max_nonlinear_iterations = infile("max_nonlinear_iterations", 15);
  solver.relative_step_tolerance = infile("relative_step_tolerance", 1.e-3);
  solver.relative_residual_tolerance = infile("relative_residual_tolerance", 0.0);
  solver.absolute_residual_tolerance = infile("absolute_residual_tolerance", 0.0);

  // And the linear solver options
  solver.max_linear_iterations = infile("max_linear_iterations", 50000);
  solver.initial_linear_tolerance = infile("initial_linear_tolerance", 1.e-3);

  // Print information about the system to the screen.
  equation_systems.print_info();

  // If we're using EulerSolver or Euler2Solver, and we're using EigenSparseLinearSolver,
  // then we need to reset the EigenSparseLinearSolver to use SPARSELU because BICGSTAB
  // chokes on the Jacobian matrix we give it and Eigen's GMRES currently doesn't work.
  NewtonSolver * newton_solver = dynamic_cast<NewtonSolver *>( &solver );
  if( newton_solver &&
      (time_solver == std::string("euler") || time_solver == std::string("euler2") ) )
    {
      LinearSolver<Number> & linear_solver = newton_solver->get_linear_solver();
#ifdef LIBMESH_HAVE_EIGEN_SPARSE
      EigenSparseLinearSolver<Number> * eigen_linear_solver =
        dynamic_cast<EigenSparseLinearSolver<Number> *>(&linear_solver);

      if( eigen_linear_solver )
        eigen_linear_solver->set_solver_type(SPARSELU);
#endif
    }

  if( time_solver == std::string("newmark") )
    {
      NewmarkSolver * newmark = cast_ptr<NewmarkSolver*>(system.time_solver.get());
      newmark->compute_initial_accel();

      // Copy over initial velocity and acceleration for output.
      // Note we can do this because of the matching variables/FE spaces
      *(v_system->solution) = system.get_vector("_old_solution_rate");
      *(a_system->solution) = system.get_vector("_old_solution_accel");
    }

#ifdef LIBMESH_HAVE_EXODUS_API
  // Output initial state
  {
    std::ostringstream file_name;

    // We write the file in the ExodusII format.
    file_name << std::string("out.")+time_solver+std::string(".e-s.")
              << std::setw(3)
              << std::setfill('0')
              << std::right
              << 0;

    ExodusII_IO(mesh).write_timestep(file_name.str(),
                                     equation_systems,
                                     1, // This number indicates how many time steps
                                        // are being written to the file
                                     system.time);
  }
#endif // #ifdef LIBMESH_HAVE_EXODUS_API

  // Now we begin the timestep loop to compute the time-accurate
  // solution of the equations.
  for (unsigned int t_step=0; t_step != n_timesteps; ++t_step)
    {
      // A pretty update message
      libMesh::out << "\n\nSolving time step "
                   << t_step
                   << ", time = "
                   << system.time
                   << std::endl;

      system.solve();

      // Advance to the next timestep in a transient problem
      system.time_solver->advance_timestep();

      // Copy over updated velocity and acceleration for output.
      // Note we can do this because of the matching variables/FE spaces
      if( time_solver == std::string("newmark") )
        {
          *(v_system->solution) = system.get_vector("_old_solution_rate");
          *(a_system->solution) = system.get_vector("_old_solution_accel");
        }

#ifdef LIBMESH_HAVE_EXODUS_API
      // Write out this timestep if we're requested to
      if ((t_step+1)%write_interval == 0)
        {
          std::ostringstream file_name;

          // We write the file in the ExodusII format.
          file_name << std::string("out.")+time_solver+std::string(".e-s.")
                    << std::setw(3)
                    << std::setfill('0')
                    << std::right
                    << t_step+1;

          ExodusII_IO(mesh).write_timestep(file_name.str(),
                                           equation_systems,
                                           1, // This number indicates how many time steps
                                              // are being written to the file
                                           system.time);
        }
#endif // #ifdef LIBMESH_HAVE_EXODUS_API
    }

  // All done.
  return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: plugcon.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: svesik $ $Date: 2001-11-12 12:41:28 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _PLUGCON_HXX
#define _PLUGCON_HXX

#include <stdarg.h>
#include <string.h>

#include <list>

#ifndef _LIST_HXX
#include <tools/list.hxx>
#endif

#ifndef _MEDIATOR_HXX
#include <plugin/unx/mediator.hxx>
#endif

#if defined SOLARIS
#define USE_MOTIF
#endif

#define Window      XLIB_Window
#define Font        XLIB_Font
#define KeyCode     XLIB_KeyCode
#define Time        XLIB_Time
#define Cursor      XLIB_Cursor
#define Region      XLIB_Region
#define String      XLIB_String
#define Boolean     XLIB_Boolean
#define XPointer    XLIB_XPointer
#include <X11/Xlib.h>
#include <X11/Intrinsic.h>
#include <X11/Shell.h>
#include <X11/IntrinsicP.h>     /* Intrinsics Definitions*/
#include <X11/StringDefs.h>    /* Standard Name-String definitions*/
#if defined USE_MOTIF
#include <Xm/DrawingA.h>
#else
#include <X11/Xaw/Label.h>
#endif
#include <X11/Xatom.h>
#define XP_UNIX
#include <stdio.h>
#ifndef _NPAPI_H_
#include <npsdk/npupp.h>
#include <npsdk/npapi.h>
#endif
#undef Window
#undef Font
#undef KeyCode
#undef Time
#undef Cursor
#undef String
#undef Region
#undef Boolean
#undef XPointer

class ConnectorInstance
{
public:
    NPP                         instance;
    NPWindow                    window;
    NPSetWindowCallbackStruct   ws_info;
    char*                       pMimeType;
    void*                       pShell;
    void*                       pWidget;

    int nArg;
    char** argn;
    char** argv;
    char* pArgnBuf;
    char* pArgvBuf;
    NPSavedData aData;

    ConnectorInstance( NPP inst, char* type,
                       int args, char* pargnbuf, ULONG nargnbytes,
                       char* pargvbuf, ULONG nargvbytes,
                       char* savedata, ULONG savebytes );
    ~ConnectorInstance();
};

class PluginConnector;

DECLARE_LIST( NPStreamList, NPStream* );
DECLARE_LIST( InstanceList, ConnectorInstance* );
DECLARE_LIST( PluginConnectorList, PluginConnector* );

class PluginConnector : public Mediator
{
    friend NPError NPN_DestroyStream( NPP, NPStream*, NPError );
    friend NPError NPN_NewStream( NPP, NPMIMEType, const char*,
                                  NPStream** );
protected:
    NAMESPACE_VOS(OMutex)               m_aUserEventMutex;

    static PluginConnectorList          allConnectors;

    DECL_LINK( NewMessageHdl, Mediator* );
    DECL_LINK( WorkOnNewMessageHdl, Mediator* );

    NPStreamList    m_aNPWrapStreams;
    InstanceList    m_aInstances;

    ULONG   FillBuffer( char*&, char*, ULONG, va_list );
public:
    PluginConnector( int nSocket );
    ~PluginConnector();

    virtual MediatorMessage* WaitForAnswer( ULONG nMessageID );
    MediatorMessage*    Transact( char*, ULONG, ... );
    MediatorMessage*    Transact( UINT32, ... );
    void                Respond( ULONG nID, char*, ULONG, ... );
    ULONG               Send( UINT32, ... );

    UINT32  GetStreamID( NPStream* pStream );
    UINT32  GetNPPID( NPP );

    NPError GetNPError( MediatorMessage* pMes )
    {
        NPError* pErr = (NPError*)pMes->GetBytes();
        NPError aErr = *pErr;
        delete pErr;
        return aErr;
    }

    void CallWorkHandler()
    {
        LINK( this, PluginConnector, WorkOnNewMessageHdl ).
            Call( (Mediator*)this );
    }
};

enum CommandAtoms
{
        eNPN_GetURL,
        eNPN_GetURLNotify,
        eNPN_DestroyStream,
        eNPN_NewStream,
        eNPN_PostURLNotify,
        eNPN_PostURL,
        eNPN_RequestRead,
        eNPN_Status,
        eNPN_Version,
        eNPN_Write,
        eNPN_UserAgent,

        eNPP_DestroyStream,
        eNPP_Destroy,
        eNPP_NewStream,
        eNPP_New,
        eNPP_SetWindow,
        eNPP_StreamAsFile,
        eNPP_URLNotify,
        eNPP_WriteReady,
        eNPP_Write,
        eNPP_GetMIMEDescription,
        eNPP_Initialize,
        eNPP_Shutdown,

        eMaxCommand
};

char* GetCommandName( CommandAtoms );
void resizePlugin( NPP, UINT32, UINT32 );

#define POST_STRING( x ) x ? x : const_cast<char*>(""), x ? strlen(x) : 1

#endif // _PLUGCON_HXX
<commit_msg>INTEGRATION: CWS vcl09 (1.4.102); FILE MERGED 2003/05/08 18:46:19 pl 1.4.102.1: #109426# make rpnp.so work on Linux<commit_after>/*************************************************************************
 *
 *  $RCSfile: plugcon.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: vg $ $Date: 2003-05-28 12:38:03 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _PLUGCON_HXX
#define _PLUGCON_HXX

#include <stdarg.h>
#include <string.h>

#include <list>

#ifndef _LIST_HXX
#include <tools/list.hxx>
#endif

#ifndef _MEDIATOR_HXX
#include <plugin/unx/mediator.hxx>
#endif

#if defined SOLARIS
#define USE_MOTIF
#endif

#define Window      XLIB_Window
#define Font        XLIB_Font
#define KeyCode     XLIB_KeyCode
#define Time        XLIB_Time
#define Cursor      XLIB_Cursor
#define Region      XLIB_Region
#define String      XLIB_String
#define Boolean     XLIB_Boolean
#define XPointer    XLIB_XPointer
#include <X11/Xlib.h>
#include <X11/Intrinsic.h>
#include <X11/Shell.h>
#include <X11/IntrinsicP.h>     /* Intrinsics Definitions*/
#include <X11/StringDefs.h>    /* Standard Name-String definitions*/
#if defined USE_MOTIF
#include <Xm/DrawingA.h>
#else
#include <X11/Xaw/Label.h>
#endif
#include <X11/Xatom.h>
#define XP_UNIX
#include <stdio.h>
#ifndef _NPAPI_H_
#include <npsdk/npupp.h>
#include <npsdk/npapi.h>
#endif
#undef Window
#undef Font
#undef KeyCode
#undef Time
#undef Cursor
#undef String
#undef Region
#undef Boolean
#undef XPointer

class ConnectorInstance
{
public:
    NPP                         instance;
    NPWindow                    window;
    NPSetWindowCallbackStruct   ws_info;
    char*                       pMimeType;
    void*                       pShell;
    void*                       pWidget;

    int nArg;
    char** argn;
    char** argv;
    char* pArgnBuf;
    char* pArgvBuf;
    NPSavedData aData;

    ConnectorInstance( NPP inst, char* type,
                       int args, char* pargnbuf, ULONG nargnbytes,
                       char* pargvbuf, ULONG nargvbytes,
                       char* savedata, ULONG savebytes );
    ~ConnectorInstance();
};

class PluginConnector;

DECLARE_LIST( NPStreamList, NPStream* );
DECLARE_LIST( InstanceList, ConnectorInstance* );
DECLARE_LIST( PluginConnectorList, PluginConnector* );

class PluginConnector : public Mediator
{
    friend NPError NPN_DestroyStream( NPP, NPStream*, NPError );
    friend NPError NPN_NewStream( NPP, NPMIMEType, const char*,
                                  NPStream** );
protected:
    NAMESPACE_VOS(OMutex)               m_aUserEventMutex;

    static PluginConnectorList          allConnectors;

    DECL_LINK( NewMessageHdl, Mediator* );
    DECL_LINK( WorkOnNewMessageHdl, Mediator* );

    NPStreamList    m_aNPWrapStreams;
    InstanceList    m_aInstances;

    ULONG   FillBuffer( char*&, char*, ULONG, va_list );
public:
    PluginConnector( int nSocket );
    ~PluginConnector();

    virtual MediatorMessage* WaitForAnswer( ULONG nMessageID );
    MediatorMessage*    Transact( char*, ULONG, ... );
    MediatorMessage*    Transact( UINT32, ... );
    void                Respond( ULONG nID, char*, ULONG, ... );
    ULONG               Send( UINT32, ... );

    UINT32  GetStreamID( NPStream* pStream );
    UINT32  GetNPPID( NPP );

    NPError GetNPError( MediatorMessage* pMes )
    {
        NPError* pErr = (NPError*)pMes->GetBytes();
        NPError aErr = *pErr;
        delete [] pErr;
        return aErr;
    }

    void CallWorkHandler()
    {
        LINK( this, PluginConnector, WorkOnNewMessageHdl ).
            Call( (Mediator*)this );
    }
};

enum CommandAtoms
{
        eNPN_GetURL,
        eNPN_GetURLNotify,
        eNPN_DestroyStream,
        eNPN_NewStream,
        eNPN_PostURLNotify,
        eNPN_PostURL,
        eNPN_RequestRead,
        eNPN_Status,
        eNPN_Version,
        eNPN_Write,
        eNPN_UserAgent,

        eNPP_DestroyStream,
        eNPP_Destroy,
        eNPP_NewStream,
        eNPP_New,
        eNPP_SetWindow,
        eNPP_StreamAsFile,
        eNPP_URLNotify,
        eNPP_WriteReady,
        eNPP_Write,
        eNPP_GetMIMEDescription,
        eNPP_Initialize,
        eNPP_Shutdown,

        eMaxCommand
};

char* GetCommandName( CommandAtoms );

#define POST_STRING( x ) x ? x : const_cast<char*>(""), x ? strlen(x) : 1

#endif // _PLUGCON_HXX
<|endoftext|>


<commit_before>/*
    This file is part of libakonadi.

    Copyright (c) 2006 Till Adam <adam@kde.org>
    Copyright (c) 2007 Volker Krause <vkrause@kde.org>
    Copyright (c) 2007 Bruno Virlet <bruno.virlet@gmail.com>

    This library is free software; you can redistribute it and/or modify it
    under the terms of the GNU Library 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 Library General Public
    License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to the
    Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
    02110-1301, USA.
*/

#include "agentbase.h"
#include "agentbase_p.h"

#include "agent.h"
#include "kcrash.h"
#include "agentadaptor.h"
#include "monitor_p.h"
#include "xdgbasedirs.h"

#include <libakonadi/session.h>
#include <libakonadi/changerecorder.h>
#include <libakonadi/itemfetchjob.h>

#include <kaboutdata.h>
#include <kcmdlineargs.h>
#include <kdebug.h>
#include <klocale.h>

#include <QtCore/QDir>
#include <QtCore/QTimer>
#include <QtGui/QApplication>
#include <QtDBus/QtDBus>

#include <signal.h>
#include <stdlib.h>

using namespace Akonadi;

static AgentBase *sAgentBase = 0;

/* FIXME Already defined in ResourceBase: which one to keep ?
void crashHandler( int signal )
{
  if ( sAgentBase )
    sAgentBase->crashHandler( signal );

  exit( 255 );
}*/

AgentBasePrivate::AgentBasePrivate( AgentBase *parent )
  : q_ptr( parent ),
    mSettings( 0 )
{
}

AgentBasePrivate::~AgentBasePrivate()
{
  monitor->setConfig( 0 );
  delete mSettings;
}

void AgentBasePrivate::init()
{
  Q_Q( AgentBase );
  mTracer = new org::kde::Akonadi::Tracer( QLatin1String( "org.kde.Akonadi" ), QLatin1String( "/tracing" ),
                                           QDBusConnection::sessionBus(), q );

  if ( !QDBusConnection::sessionBus().registerService( QLatin1String( "org.kde.Akonadi.Agent." ) + mId ) )
    q->error( QString::fromLatin1( "Unable to register service at dbus: %1" ).arg( QDBusConnection::sessionBus().lastError().message() ) );

  new AgentAdaptor( q );
  if ( !QDBusConnection::sessionBus().registerObject( QLatin1String( "/" ), q, QDBusConnection::ExportAdaptors ) )
    q->error( QString::fromLatin1( "Unable to register object at dbus: %1" ).arg( QDBusConnection::sessionBus().lastError().message() ) );

  mSettings = new QSettings( QString::fromLatin1( "%1/agent_config_%2" ).arg( XdgBaseDirs::saveDir( "config", QLatin1String( "akonadi" ) ), mId ), QSettings::IniFormat );

  session = new Session( mId.toLatin1(), q );
  monitor = new ChangeRecorder( q );
  monitor->ignoreSession( session );
  monitor->setConfig( mSettings );

  q->connect( monitor, SIGNAL( itemAdded( const Akonadi::Item&, const Akonadi::Collection& ) ),
              q, SLOT( itemAdded( const Akonadi::Item&, const Akonadi::Collection& ) ) );
  q->connect( monitor, SIGNAL( itemChanged( const Akonadi::Item&, const QStringList& ) ),
              q, SLOT( itemChanged( const Akonadi::Item&, const QStringList& ) ) );
  q->connect( monitor, SIGNAL( itemRemoved( const Akonadi::DataReference& ) ),
           q, SLOT( itemRemoved( const Akonadi::DataReference& ) ) );
  q->connect( monitor, SIGNAL(collectionAdded(Akonadi::Collection,Akonadi::Collection)),
              q, SLOT(collectionAdded(Akonadi::Collection,Akonadi::Collection)) );
  q->connect( monitor, SIGNAL( collectionChanged( const Akonadi::Collection& ) ),
              q, SLOT( collectionChanged( const Akonadi::Collection& ) ) );
  q->connect( monitor, SIGNAL( collectionRemoved( int, const QString& ) ),
              q, SLOT( collectionRemoved( int, const QString& ) ) );

  // initial configuration
  bool initialized = mSettings->value( QLatin1String( "Agent/Initialized" ), false ).toBool();
  if ( !initialized ) {
    QTimer::singleShot( 0, q, SLOT(configure()) ); // finish construction first
    mSettings->setValue( QLatin1String( "Agent/Initialized" ), true );
  }
}

AgentBase::AgentBase( const QString & id )
  : d_ptr( new AgentBasePrivate( this ) )
{
  KCrash::init();
  // FIXME See above KCrash::setEmergencyMethod( ::crashHandler );
  sAgentBase = this;
  d_ptr->mId = id;
  d_ptr->init();
}

AgentBase::AgentBase( AgentBasePrivate* d, const QString &id ) :
    d_ptr( d )
{
  KCrash::init();
  // FIXME See above KCrash::setEmergencyMethod( ::crashHandler );
  sAgentBase = this;
  d_ptr->mId = id;
  d_ptr->init();
}

AgentBase::~AgentBase()
{
  delete d_ptr;
}

static char* sAppName = 0;

QString AgentBase::parseArguments( int argc, char **argv )
{
  QString identifier;
  if ( argc < 3 ) {
    kDebug( 5250 ) << "Not enough arguments passed...";
    exit( 1 );
  }

  for ( int i = 1; i < argc - 1; ++i ) {
    if ( QLatin1String( argv[ i ] ) == QLatin1String( "--identifier" ) )
      identifier = QLatin1String( argv[ i + 1 ] );
  }

  if ( identifier.isEmpty() ) {
    kDebug( 5250 ) << "Identifier argument missing";
    exit( 1 );
  }

  sAppName = qstrdup( identifier.toLatin1().constData() );
  KCmdLineArgs::init( argc, argv, sAppName, 0, ki18n("Akonadi Agent"),"0.1" ,
                      ki18n("Akonadi Agent") );

  KCmdLineOptions options;
  options.add("identifier <argument>", ki18n("Agent identifier"));
  KCmdLineArgs::addCmdLineOptions( options );

  return identifier;
}

int AgentBase::init( AgentBase *r )
{
  QApplication::setQuitOnLastWindowClosed( false );
  int rv = kapp->exec();
  delete r;
  delete[] sAppName;
  return rv;
}

void AgentBase::configure()
{
}

void AgentBase::quit()
{
  Q_D( AgentBase );
  aboutToQuit();

  if ( d->mSettings ) {
    d->monitor->setConfig( 0 );
    d->mSettings->sync();
  }

  QCoreApplication::exit( 0 );
}

void AgentBase::aboutToQuit()
{
}

void AgentBase::cleanup()
{
  Q_D( AgentBase );
  const QString fileName = d->mSettings->fileName();

  /**
   * First destroy the settings object...
   */
  d->monitor->setConfig( 0 );
  delete d->mSettings;
  d->mSettings = 0;

  /**
   * ... then remove the file from hd.
   */
  QFile::remove( fileName );

  QCoreApplication::exit( 0 );
}

void AgentBase::crashHandler( int signal )
{
  /**
   * If we retrieved a SIGINT or SIGTERM we close normally
   */
  if ( signal == SIGINT || signal == SIGTERM )
    quit();
}

QString AgentBase::identifier() const
{
  return d_ptr->mId;
}

void AgentBase::itemAdded( const Item &item, const Collection &collection )
{
  Q_UNUSED( item );
  Q_UNUSED( collection );
}

void AgentBase::itemChanged( const Item &item, const QStringList &partIdentifiers )
{
  Q_UNUSED( item );
  Q_UNUSED( partIdentifiers );
}

void AgentBase::itemRemoved( const DataReference &ref )
{
  Q_UNUSED( ref );
}

void AgentBase::collectionAdded( const Akonadi::Collection &collection, const Akonadi::Collection &parent )
{
  Q_UNUSED( collection );
}

void AgentBase::collectionChanged( const Collection &collection )
{
  Q_UNUSED( collection );
}

void AgentBase::collectionRemoved( int id, const QString &remoteId )
{
  Q_UNUSED( id );
  Q_UNUSED( remoteId );
}

QSettings* AgentBase::settings()
{
  return d_ptr->mSettings;
}

Session* AgentBase::session()
{
  return d_ptr->session;
}

void AgentBase::warning( const QString& message )
{
  Q_D( AgentBase );
  d->mTracer->warning( QString::fromLatin1( "AgentBase(%1)" ).arg( d->mId ), message );
}

void AgentBase::error( const QString& message )
{
  Q_D( AgentBase );
  d->mTracer->error( QString::fromLatin1( "AgentBase(%1)" ).arg( d->mId ), message );
}

ChangeRecorder * AgentBase::monitor() const
{
  return d_ptr->monitor;
}

#include "agent.moc"
#include "agentbase.moc"
<commit_msg>Dirty hack to finally fix the "notification don't work anymore after adding/removing an agent" bug.<commit_after>/*
    This file is part of libakonadi.

    Copyright (c) 2006 Till Adam <adam@kde.org>
    Copyright (c) 2007 Volker Krause <vkrause@kde.org>
    Copyright (c) 2007 Bruno Virlet <bruno.virlet@gmail.com>

    This library is free software; you can redistribute it and/or modify it
    under the terms of the GNU Library 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 Library General Public
    License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to the
    Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
    02110-1301, USA.
*/

#include "agentbase.h"
#include "agentbase_p.h"

#include "agent.h"
#include "kcrash.h"
#include "agentadaptor.h"
#include "monitor_p.h"
#include "xdgbasedirs.h"

#include <libakonadi/session.h>
#include <libakonadi/changerecorder.h>
#include <libakonadi/itemfetchjob.h>

#include <kaboutdata.h>
#include <kcmdlineargs.h>
#include <kdebug.h>
#include <klocale.h>

#include <QtCore/QDir>
#include <QtCore/QTimer>
#include <QtGui/QApplication>
#include <QtDBus/QtDBus>

#include <signal.h>
#include <stdlib.h>

using namespace Akonadi;

static AgentBase *sAgentBase = 0;

/* FIXME Already defined in ResourceBase: which one to keep ?
void crashHandler( int signal )
{
  if ( sAgentBase )
    sAgentBase->crashHandler( signal );

  exit( 255 );
}*/

AgentBasePrivate::AgentBasePrivate( AgentBase *parent )
  : q_ptr( parent ),
    mSettings( 0 )
{
}

AgentBasePrivate::~AgentBasePrivate()
{
  monitor->setConfig( 0 );
  delete mSettings;
}

void AgentBasePrivate::init()
{
  Q_Q( AgentBase );
  mTracer = new org::kde::Akonadi::Tracer( QLatin1String( "org.kde.Akonadi" ), QLatin1String( "/tracing" ),
                                           QDBusConnection::sessionBus(), q );

  if ( !QDBusConnection::sessionBus().registerService( QLatin1String( "org.kde.Akonadi.Agent." ) + mId ) )
    q->error( QString::fromLatin1( "Unable to register service at dbus: %1" ).arg( QDBusConnection::sessionBus().lastError().message() ) );

  new AgentAdaptor( q );
  if ( !QDBusConnection::sessionBus().registerObject( QLatin1String( "/" ), q, QDBusConnection::ExportAdaptors ) )
    q->error( QString::fromLatin1( "Unable to register object at dbus: %1" ).arg( QDBusConnection::sessionBus().lastError().message() ) );

  mSettings = new QSettings( QString::fromLatin1( "%1/agent_config_%2" ).arg( XdgBaseDirs::saveDir( "config", QLatin1String( "akonadi" ) ), mId ), QSettings::IniFormat );

  session = new Session( mId.toLatin1(), q );
  monitor = new ChangeRecorder( q );
  monitor->ignoreSession( session );
  monitor->setConfig( mSettings );

  q->connect( monitor, SIGNAL( itemAdded( const Akonadi::Item&, const Akonadi::Collection& ) ),
              q, SLOT( itemAdded( const Akonadi::Item&, const Akonadi::Collection& ) ) );
  q->connect( monitor, SIGNAL( itemChanged( const Akonadi::Item&, const QStringList& ) ),
              q, SLOT( itemChanged( const Akonadi::Item&, const QStringList& ) ) );
  q->connect( monitor, SIGNAL( itemRemoved( const Akonadi::DataReference& ) ),
           q, SLOT( itemRemoved( const Akonadi::DataReference& ) ) );
  q->connect( monitor, SIGNAL(collectionAdded(Akonadi::Collection,Akonadi::Collection)),
              q, SLOT(collectionAdded(Akonadi::Collection,Akonadi::Collection)) );
  q->connect( monitor, SIGNAL( collectionChanged( const Akonadi::Collection& ) ),
              q, SLOT( collectionChanged( const Akonadi::Collection& ) ) );
  q->connect( monitor, SIGNAL( collectionRemoved( int, const QString& ) ),
              q, SLOT( collectionRemoved( int, const QString& ) ) );

  // initial configuration
  bool initialized = mSettings->value( QLatin1String( "Agent/Initialized" ), false ).toBool();
  if ( !initialized ) {
    QTimer::singleShot( 0, q, SLOT(configure()) ); // finish construction first
    mSettings->setValue( QLatin1String( "Agent/Initialized" ), true );
  }
}

AgentBase::AgentBase( const QString & id )
  : d_ptr( new AgentBasePrivate( this ) )
{
  KCrash::init();
  // FIXME See above KCrash::setEmergencyMethod( ::crashHandler );
  sAgentBase = this;
  d_ptr->mId = id;
  d_ptr->init();
}

AgentBase::AgentBase( AgentBasePrivate* d, const QString &id ) :
    d_ptr( d )
{
  KCrash::init();
  // FIXME See above KCrash::setEmergencyMethod( ::crashHandler );
  sAgentBase = this;
  d_ptr->mId = id;
  d_ptr->init();
}

AgentBase::~AgentBase()
{
  delete d_ptr;
}

static char* sAppName = 0;

QString AgentBase::parseArguments( int argc, char **argv )
{
  QString identifier;
  if ( argc < 3 ) {
    kDebug( 5250 ) << "Not enough arguments passed...";
    exit( 1 );
  }

  for ( int i = 1; i < argc - 1; ++i ) {
    if ( QLatin1String( argv[ i ] ) == QLatin1String( "--identifier" ) )
      identifier = QLatin1String( argv[ i + 1 ] );
  }

  if ( identifier.isEmpty() ) {
    kDebug( 5250 ) << "Identifier argument missing";
    exit( 1 );
  }

  sAppName = qstrdup( identifier.toLatin1().constData() );
  KCmdLineArgs::init( argc, argv, sAppName, 0, ki18n("Akonadi Agent"),"0.1" ,
                      ki18n("Akonadi Agent") );

  KCmdLineOptions options;
  options.add("identifier <argument>", ki18n("Agent identifier"));
  KCmdLineArgs::addCmdLineOptions( options );

  return identifier;
}

int AgentBase::init( AgentBase *r )
{
  QApplication::setQuitOnLastWindowClosed( false );
  int rv = kapp->exec();
  delete r;
  delete[] sAppName;
  return rv;
}

void AgentBase::configure()
{
}

void AgentBase::quit()
{
  Q_D( AgentBase );
  aboutToQuit();

  if ( d->mSettings ) {
    d->monitor->setConfig( 0 );
    d->mSettings->sync();
  }

  QCoreApplication::exit( 0 );
}

void AgentBase::aboutToQuit()
{
}

void AgentBase::cleanup()
{
  Q_D( AgentBase );
  const QString fileName = d->mSettings->fileName();

  /**
   * First destroy the settings object...
   */
  d->monitor->setConfig( 0 );
  delete d->mSettings;
  d->mSettings = 0;

  /**
   * ... then remove the file from hd.
   */
  QFile::remove( fileName );

  // ### HACK FIXME
  // Using QCoreApplication::quit() breaks change notifications
  // for some clients/agents, no idea why
//   QCoreApplication::quit();
  exit( 0 );
}

void AgentBase::crashHandler( int signal )
{
  /**
   * If we retrieved a SIGINT or SIGTERM we close normally
   */
  if ( signal == SIGINT || signal == SIGTERM )
    quit();
}

QString AgentBase::identifier() const
{
  return d_ptr->mId;
}

void AgentBase::itemAdded( const Item &item, const Collection &collection )
{
  Q_UNUSED( item );
  Q_UNUSED( collection );
}

void AgentBase::itemChanged( const Item &item, const QStringList &partIdentifiers )
{
  Q_UNUSED( item );
  Q_UNUSED( partIdentifiers );
}

void AgentBase::itemRemoved( const DataReference &ref )
{
  Q_UNUSED( ref );
}

void AgentBase::collectionAdded( const Akonadi::Collection &collection, const Akonadi::Collection &parent )
{
  Q_UNUSED( collection );
}

void AgentBase::collectionChanged( const Collection &collection )
{
  Q_UNUSED( collection );
}

void AgentBase::collectionRemoved( int id, const QString &remoteId )
{
  Q_UNUSED( id );
  Q_UNUSED( remoteId );
}

QSettings* AgentBase::settings()
{
  return d_ptr->mSettings;
}

Session* AgentBase::session()
{
  return d_ptr->session;
}

void AgentBase::warning( const QString& message )
{
  Q_D( AgentBase );
  d->mTracer->warning( QString::fromLatin1( "AgentBase(%1)" ).arg( d->mId ), message );
}

void AgentBase::error( const QString& message )
{
  Q_D( AgentBase );
  d->mTracer->error( QString::fromLatin1( "AgentBase(%1)" ).arg( d->mId ), message );
}

ChangeRecorder * AgentBase::monitor() const
{
  return d_ptr->monitor;
}

#include "agent.moc"
#include "agentbase.moc"
<|endoftext|>


<commit_before>#include "movegen.h"
#include "board.h"
#include "defs.h"
#include <iostream>

MoveGen::MoveGen(Board board) {
  setBoard(board);
}

MoveGen::MoveGen() {
  Board board;
  setBoard(board);
}

void MoveGen::setBoard(Board board) {
  _moves = MoveList();
  _board = board;
  genMoves();
}

MoveList MoveGen::getMoves() {
  return _moves;
}

void MoveGen::genMoves() {
  if (_board.WHITE_TO_MOVE) {
    genWhiteMoves();
  } else {
    genBlackMoves();
  }
}

void MoveGen::genWhiteMoves() {
  genWhitePawnMoves();
  genWhiteRookMoves();
  genWhiteKnightMoves();
  genWhiteBishopMoves();
  genWhiteKingMoves();
  genWhiteQueenMoves();
}

void MoveGen::genBlackMoves() {
  genBlackPawnMoves();
  genBlackRookMoves();
  genBlackKnightMoves();
  genBlackBishopMoves();
  genBlackKingMoves();
  genBlackQueenMoves();
}

void MoveGen::printMoves() {
  for(auto move : getMoves()) {
    std::cout << move.getNotation() << std::endl;
  }
}

void MoveGen::genPawnPromotions(unsigned int from, unsigned int to, unsigned int flags) {
  _moves.push_back(CMove(from, to, flags | CMove::QUEEN_PROMOTION));
  _moves.push_back(CMove(from, to, flags | CMove::KNIGHT_PROMOTION));
  _moves.push_back(CMove(from, to, flags | CMove::ROOK_PROMOTION));
  _moves.push_back(CMove(from, to, flags | CMove::BISHOP_PROMOTION));
}

void MoveGen::genWhitePawnMoves() {
  U64 movedPawns1 = _board.WHITE_PAWNS << 8;
  U64 movedPawns2 = (_board.WHITE_PAWNS & RANK_2) << 16;

  U64 leftAttacks = (_board.WHITE_PAWNS << 7) & (~FILE_H);
  U64 rightAttacks = (_board.WHITE_PAWNS << 9) & (~FILE_A);

  U64 attackablePieces = _board.BLACK_ATTACKABLE | _board.EN_PASSANT;

  for(U64 i=0;i<64;i++) {
    U64 square = static_cast<U64>(1) << i;

    if ((movedPawns1 & square) && (square & _board.NOT_OCCUPIED)) {
      if (square & RANK_8) {
        genPawnPromotions(i-8, i);
      } else {
        _moves.push_back(CMove(i-8, i));
      }
    }

    if ((movedPawns2 & square) && (square & _board.NOT_OCCUPIED) && ((square >> 8) & _board.NOT_OCCUPIED)) {
      _moves.push_back(CMove(i-16, i));
    }

    if ((leftAttacks & square) && (square & attackablePieces)) {
      if (square & RANK_8) {
        genPawnPromotions(i-7, i, CMove::CAPTURE);
      } else {
        _moves.push_back(CMove(i-7, i, CMove::CAPTURE));
      }
    }

    if ((rightAttacks & square) && (square & attackablePieces)) {
      if (square & RANK_8) {
        genPawnPromotions(i-9, i, CMove::CAPTURE);
      } else {
        _moves.push_back(CMove(i-9, i, CMove::CAPTURE));
      }
    }
  }
}

void MoveGen::genBlackPawnMoves() {
  U64 movedPawns1 = _board.BLACK_PAWNS >> 8;
  U64 movedPawns2 = (_board.BLACK_PAWNS & RANK_7) >> 16;

  U64 leftAttacks = (_board.BLACK_PAWNS >> 9) & (~FILE_H);
  U64 rightAttacks = (_board.BLACK_PAWNS >> 7) & (~FILE_A);

  U64 attackablePieces = _board.WHITE_ATTACKABLE | _board.EN_PASSANT;

  for(U64 i=0;i<64;i++) {
    U64 square = static_cast<U64>(1) << i;

    if ((movedPawns1 & square) && (square & _board.NOT_OCCUPIED)) {
      if (square & RANK_1) {
        genPawnPromotions(i+8, i);
      } else {
        _moves.push_back(CMove(i+8, i));
      }
    }

    if ((movedPawns2 & square) && (square & _board.NOT_OCCUPIED) && ((square << 8) & _board.NOT_OCCUPIED)) {
      _moves.push_back(CMove(i+16, i));
    }

    if ((leftAttacks & square) && (square & attackablePieces)) {
      if (square & RANK_1) {
        genPawnPromotions(i+9, i, CMove::CAPTURE);
      } else {
        _moves.push_back(CMove(i+9, i, CMove::CAPTURE));
      }
    }

    if ((rightAttacks & square) && (square & attackablePieces)) {
      if (square & RANK_1) {
        genPawnPromotions(i+7, i, CMove::CAPTURE);
      } else {
        _moves.push_back(CMove(i+7, i, CMove::CAPTURE));
      }
    }
  }
}

void MoveGen::genWhiteKingMoves() {
  genKingMoves(_board.WHITE_KING, _board.WHITE_PIECES, _board.BLACK_ATTACKABLE);

  if (_board.whiteCanCastleKs()) {
    _moves.push_back(CMove(e1, g1, CMove::KSIDE_CASTLE));
  }
  if (_board.whiteCanCastleQs()) {
    _moves.push_back(CMove(e1, b1, CMove::QSIDE_CASTLE));
  }
}

void MoveGen::genBlackKingMoves() {
  genKingMoves(_board.BLACK_KING, _board.BLACK_PIECES, _board.WHITE_ATTACKABLE);

  if (_board.blackCanCastleKs()) {
    _moves.push_back(CMove(e8, h8, CMove::KSIDE_CASTLE));
  }
  if (_board.blackCanCastleQs()) {
    _moves.push_back(CMove(e8, c8, CMove::QSIDE_CASTLE));
  }
}

void MoveGen::genKingMoves(U64 king, U64 own, U64 attackable) {
  if (king == 0) {
    return;
  }

  int kingIndex = __builtin_ffsll(king) - 1;

  U64 moves = _board.getKingAttacksForSquare(kingIndex, own);

  addMoves(kingIndex, moves, attackable);
}

void MoveGen::genWhiteKnightMoves() {
  genKnightMoves(_board.WHITE_KNIGHTS, _board.WHITE_PIECES, _board.BLACK_ATTACKABLE);
}

void MoveGen::genBlackKnightMoves() {
  genKnightMoves(_board.BLACK_KNIGHTS, _board.BLACK_PIECES, _board.WHITE_ATTACKABLE);
}

void MoveGen::genKnightMoves(U64 knights, U64 own, U64 attackable) {
  for(int from=0;from<64;from++) {
    U64 fromSquare = static_cast<U64>(1) << from;
    if ((fromSquare & knights) == 0) {
      continue;
    }

    U64 moves = _board.getKnightAttacksForSquare(from, own);

    addMoves(from, moves, attackable);
  }
}

void MoveGen::genWhiteBishopMoves() {
  genBishopMoves(_board.WHITE_BISHOPS, _board.WHITE_PIECES, _board.BLACK_PIECES);
}

void MoveGen::genBlackBishopMoves() {
  genBishopMoves(_board.BLACK_BISHOPS, _board.BLACK_PIECES, _board.BLACK_PIECES);
}

void MoveGen::genBishopMoves(U64 bishops, U64 own, U64 attackable) {
  for(int from=0;from<64;from++) {
    U64 fromSquare = U64(1) << from;
    if((fromSquare & bishops) == 0) {
      continue;
    }

    U64 moves = _board.getBishopAttacksForSquare(from, own);

    addMoves(from, moves, attackable);
  }
}

void MoveGen::genWhiteRookMoves() {
  genRookMoves(_board.WHITE_ROOKS, _board.WHITE_PIECES, _board.BLACK_ATTACKABLE);
}

void MoveGen::genBlackRookMoves() {
  genRookMoves(_board.BLACK_ROOKS, _board.BLACK_PIECES, _board.WHITE_ATTACKABLE);
}

void MoveGen::genRookMoves(U64 rooks, U64 own, U64 attackable) {
  for(int from=0;from<64;from++) {
    U64 fromSquare = U64(1) << from;
    if((fromSquare & rooks) == 0) {
      continue;
    }

    U64 moves = _board.getRookAttacksForSquare(from, own);

    addMoves(from, moves, attackable);
  }
}

void MoveGen::genWhiteQueenMoves() {
  genQueenMoves(_board.WHITE_QUEENS, _board.WHITE_PIECES, _board.BLACK_ATTACKABLE);
}

void MoveGen::genBlackQueenMoves() {
  genQueenMoves(_board.BLACK_QUEENS, _board.BLACK_PIECES, _board.WHITE_ATTACKABLE);
}

void MoveGen::genQueenMoves(U64 queens, U64 own, U64 attackable) {
  for(int from=0;from<64;from++) {
    U64 fromSquare = U64(1) << from;
    if((fromSquare & queens) == 0) {
      continue;
    }

    U64 moves = _board.getQueenAttacksForSquare(from, own);

    addMoves(from, moves, attackable);
  }
}

void MoveGen::addMoves(int from, U64 moves, U64 attackable) {
  for(int to=0;to<64;to++) {
    U64 toSquare = U64(1) << to;
    if ((toSquare & moves) == 0) {
      continue;
    }

    // Ignore any moves to squares occupied by kings
    if ((toSquare & (_board.WHITE_KING | _board.BLACK_KING))) {
      continue;
    }

    if(toSquare & attackable) {
      _moves.push_back(CMove(from, to, CMove::CAPTURE));
    } else {
      _moves.push_back(CMove(from, to));
    }
  }
}
<commit_msg>Fix pieces attacking kings<commit_after>#include "movegen.h"
#include "board.h"
#include "defs.h"
#include <iostream>

MoveGen::MoveGen(Board board) {
  setBoard(board);
}

MoveGen::MoveGen() {
  Board board;
  setBoard(board);
}

void MoveGen::setBoard(Board board) {
  _moves = MoveList();
  _board = board;
  genMoves();
}

MoveList MoveGen::getMoves() {
  return _moves;
}

void MoveGen::genMoves() {
  if (_board.WHITE_TO_MOVE) {
    genWhiteMoves();
  } else {
    genBlackMoves();
  }
}

void MoveGen::genWhiteMoves() {
  genWhitePawnMoves();
  genWhiteRookMoves();
  genWhiteKnightMoves();
  genWhiteBishopMoves();
  genWhiteKingMoves();
  genWhiteQueenMoves();
}

void MoveGen::genBlackMoves() {
  genBlackPawnMoves();
  genBlackRookMoves();
  genBlackKnightMoves();
  genBlackBishopMoves();
  genBlackKingMoves();
  genBlackQueenMoves();
}

void MoveGen::printMoves() {
  for(auto move : getMoves()) {
    std::cout << move.getNotation() << std::endl;
  }
}

void MoveGen::genPawnPromotions(unsigned int from, unsigned int to, unsigned int flags) {
  _moves.push_back(CMove(from, to, flags | CMove::QUEEN_PROMOTION));
  _moves.push_back(CMove(from, to, flags | CMove::KNIGHT_PROMOTION));
  _moves.push_back(CMove(from, to, flags | CMove::ROOK_PROMOTION));
  _moves.push_back(CMove(from, to, flags | CMove::BISHOP_PROMOTION));
}

void MoveGen::genWhitePawnMoves() {
  U64 movedPawns1 = _board.WHITE_PAWNS << 8;
  U64 movedPawns2 = (_board.WHITE_PAWNS & RANK_2) << 16;

  U64 leftAttacks = (_board.WHITE_PAWNS << 7) & (~FILE_H);
  U64 rightAttacks = (_board.WHITE_PAWNS << 9) & (~FILE_A);

  U64 attackablePieces = _board.BLACK_ATTACKABLE | _board.EN_PASSANT;

  for(U64 i=0;i<64;i++) {
    U64 square = static_cast<U64>(1) << i;

    if ((movedPawns1 & square) && (square & _board.NOT_OCCUPIED)) {
      if (square & RANK_8) {
        genPawnPromotions(i-8, i);
      } else {
        _moves.push_back(CMove(i-8, i));
      }
    }

    if ((movedPawns2 & square) && (square & _board.NOT_OCCUPIED) && ((square >> 8) & _board.NOT_OCCUPIED)) {
      _moves.push_back(CMove(i-16, i));
    }

    if ((leftAttacks & square) && (square & attackablePieces)) {
      if (square & RANK_8) {
        genPawnPromotions(i-7, i, CMove::CAPTURE);
      } else {
        _moves.push_back(CMove(i-7, i, CMove::CAPTURE));
      }
    }

    if ((rightAttacks & square) && (square & attackablePieces)) {
      if (square & RANK_8) {
        genPawnPromotions(i-9, i, CMove::CAPTURE);
      } else {
        _moves.push_back(CMove(i-9, i, CMove::CAPTURE));
      }
    }
  }
}

void MoveGen::genBlackPawnMoves() {
  U64 movedPawns1 = _board.BLACK_PAWNS >> 8;
  U64 movedPawns2 = (_board.BLACK_PAWNS & RANK_7) >> 16;

  U64 leftAttacks = (_board.BLACK_PAWNS >> 9) & (~FILE_H);
  U64 rightAttacks = (_board.BLACK_PAWNS >> 7) & (~FILE_A);

  U64 attackablePieces = _board.WHITE_ATTACKABLE | _board.EN_PASSANT;

  for(U64 i=0;i<64;i++) {
    U64 square = static_cast<U64>(1) << i;

    if ((movedPawns1 & square) && (square & _board.NOT_OCCUPIED)) {
      if (square & RANK_1) {
        genPawnPromotions(i+8, i);
      } else {
        _moves.push_back(CMove(i+8, i));
      }
    }

    if ((movedPawns2 & square) && (square & _board.NOT_OCCUPIED) && ((square << 8) & _board.NOT_OCCUPIED)) {
      _moves.push_back(CMove(i+16, i));
    }

    if ((leftAttacks & square) && (square & attackablePieces)) {
      if (square & RANK_1) {
        genPawnPromotions(i+9, i, CMove::CAPTURE);
      } else {
        _moves.push_back(CMove(i+9, i, CMove::CAPTURE));
      }
    }

    if ((rightAttacks & square) && (square & attackablePieces)) {
      if (square & RANK_1) {
        genPawnPromotions(i+7, i, CMove::CAPTURE);
      } else {
        _moves.push_back(CMove(i+7, i, CMove::CAPTURE));
      }
    }
  }
}

void MoveGen::genWhiteKingMoves() {
  genKingMoves(_board.WHITE_KING, _board.WHITE_PIECES, _board.BLACK_ATTACKABLE);

  if (_board.whiteCanCastleKs()) {
    _moves.push_back(CMove(e1, g1, CMove::KSIDE_CASTLE));
  }
  if (_board.whiteCanCastleQs()) {
    _moves.push_back(CMove(e1, b1, CMove::QSIDE_CASTLE));
  }
}

void MoveGen::genBlackKingMoves() {
  genKingMoves(_board.BLACK_KING, _board.BLACK_PIECES, _board.WHITE_ATTACKABLE);

  if (_board.blackCanCastleKs()) {
    _moves.push_back(CMove(e8, h8, CMove::KSIDE_CASTLE));
  }
  if (_board.blackCanCastleQs()) {
    _moves.push_back(CMove(e8, c8, CMove::QSIDE_CASTLE));
  }
}

void MoveGen::genKingMoves(U64 king, U64 own, U64 attackable) {
  if (king == 0) {
    return;
  }

  int kingIndex = __builtin_ffsll(king) - 1;

  U64 moves = _board.getKingAttacksForSquare(kingIndex, own);

  addMoves(kingIndex, moves, attackable);
}

void MoveGen::genWhiteKnightMoves() {
  genKnightMoves(_board.WHITE_KNIGHTS, _board.WHITE_PIECES, _board.BLACK_ATTACKABLE);
}

void MoveGen::genBlackKnightMoves() {
  genKnightMoves(_board.BLACK_KNIGHTS, _board.BLACK_PIECES, _board.WHITE_ATTACKABLE);
}

void MoveGen::genKnightMoves(U64 knights, U64 own, U64 attackable) {
  for(int from=0;from<64;from++) {
    U64 fromSquare = static_cast<U64>(1) << from;
    if ((fromSquare & knights) == 0) {
      continue;
    }

    U64 moves = _board.getKnightAttacksForSquare(from, own);

    addMoves(from, moves, attackable);
  }
}

void MoveGen::genWhiteBishopMoves() {
  genBishopMoves(_board.WHITE_BISHOPS, _board.WHITE_PIECES, _board.BLACK_ATTACKABLE);
}

void MoveGen::genBlackBishopMoves() {
  genBishopMoves(_board.BLACK_BISHOPS, _board.BLACK_PIECES, _board.WHITE_ATTACKABLE);
}

void MoveGen::genBishopMoves(U64 bishops, U64 own, U64 attackable) {
  for(int from=0;from<64;from++) {
    U64 fromSquare = U64(1) << from;
    if((fromSquare & bishops) == 0) {
      continue;
    }

    U64 moves = _board.getBishopAttacksForSquare(from, own);

    addMoves(from, moves, attackable);
  }
}

void MoveGen::genWhiteRookMoves() {
  genRookMoves(_board.WHITE_ROOKS, _board.WHITE_PIECES, _board.BLACK_ATTACKABLE);
}

void MoveGen::genBlackRookMoves() {
  genRookMoves(_board.BLACK_ROOKS, _board.BLACK_PIECES, _board.WHITE_ATTACKABLE);
}

void MoveGen::genRookMoves(U64 rooks, U64 own, U64 attackable) {
  for(int from=0;from<64;from++) {
    U64 fromSquare = U64(1) << from;
    if((fromSquare & rooks) == 0) {
      continue;
    }

    U64 moves = _board.getRookAttacksForSquare(from, own);

    addMoves(from, moves, attackable);
  }
}

void MoveGen::genWhiteQueenMoves() {
  genQueenMoves(_board.WHITE_QUEENS, _board.WHITE_PIECES, _board.BLACK_ATTACKABLE);
}

void MoveGen::genBlackQueenMoves() {
  genQueenMoves(_board.BLACK_QUEENS, _board.BLACK_PIECES, _board.WHITE_ATTACKABLE);
}

void MoveGen::genQueenMoves(U64 queens, U64 own, U64 attackable) {
  for(int from=0;from<64;from++) {
    U64 fromSquare = U64(1) << from;
    if((fromSquare & queens) == 0) {
      continue;
    }

    U64 moves = _board.getQueenAttacksForSquare(from, own);

    addMoves(from, moves, attackable);
  }
}

void MoveGen::addMoves(int from, U64 moves, U64 attackable) {
  for(int to=0;to<64;to++) {
    U64 toSquare = U64(1) << to;
    if ((toSquare & moves) == 0) {
      continue;
    }

    // Ignore any moves to squares occupied by kings
    if ((toSquare & (_board.WHITE_KING | _board.BLACK_KING))) {
      continue;
    }

    if(toSquare & attackable) {
      _moves.push_back(CMove(from, to, CMove::CAPTURE));
    } else {
      _moves.push_back(CMove(from, to));
    }
  }
}
<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <typeinfo>
#include <cstdlib>
#include <stdlib.h>
#include "Persona.h"
#include "Administrador.h"
#include "Repartidor.h"
#include "Baraja.h"
#include "Carta.h"
#include "Jugador.h"
#include "Mesa.h"

using namespace std;

int main(){
	vector<Persona*> vPersona;
	vector<Mesa*> vMesa;
	Administrador* adminDefecto=new Administrador("admin",23,"1234",5,"Gerente Tiempo Completo",10000);
	vPersona.push_back(adminDefecto);
	bool salir=false;
	do{
	//Login
		Persona* personaActual;
		string Nombre;
		string ID;
		cout<<"Bienvenido al programa."<<endl;
		cout<<"Ingrese (salir) en nombre o identidad para salir"<<endl;
		cout<<"Ingrese nombre: ";
		cin>>Nombre;
		cout<<"Ingrese identidad: ";
		cin>>ID;
		if (Nombre.compare("salir")==0||ID.compare("salir")==0){
			break;
		}
		bool existeUsuario=false;
		for (int i = 0; i < vPersona.size(); ++i){
			if (Nombre.compare(vPersona[i]->getNombre())==0){
				if (ID.compare(vPersona[i]->getID())==0){
					personaActual=vPersona[i];
					existeUsuario=true;
				}
			}
		}
		if (existeUsuario==false){
			cout<<"No existe el usuario"<<endl;
		}
		//Si es un administrador
		if (personaActual->getTipo().compare("Administrador")==0){
			int opcMenu;
			do{
				cout<<"Menú"<<endl;
				cout<<"1. Agregar"<<endl;
				cout<<"2. Listar"<<endl;
				cout<<"3. Modificar"<<endl;
				cout<<"4. Eliminar"<<endl;
				cout<<"5. Salir"<<endl;
				cout<<"Ingrese opción: "<<endl;
				cin>>opcMenu;
				switch(opcMenu){
					case 1:{
						cout<<"Menú agregar"<<endl;
						cout<<"1. Administrador"<<endl;
						cout<<"2. Repartidor"<<endl;
						cout<<"3. Jugador"<<endl;
						cout<<"4. Mesa"<<endl;
						int opcAgregar;
						cout<<"Ingrese la opción: ";
						cin>>opcAgregar;
						switch(opcAgregar){
							case 1:{
								string nombre;
								cout<<"Ingrese nombre: ";
								cin>>nombre;
								int edad;
								cout<<"Ingrese edad: ";
								cin>>edad;
								string id;
								cout<<"Ingrese id: ";
								cin>>id;
								int experiencia;
								cout<<"Ingrese experiencia: ";
								cin>>experiencia;
								string rango;
								cout<<"Ingrese rango: ";
								cin>>rango;
								double sueldo;
								cout<<"Ingrese sueldo: ";
								cin>>sueldo;
								Administrador* temporal=new Administrador(nombre,edad,id,experiencia,rango,sueldo);
								vPersona.push_back(temporal);
								break;
							}
							case 2:{
								string nombre;
								cout<<"Ingrese nombre: ";
								cin>>nombre;
								int edad;
								cout<<"Ingrese edad: ";
								cin>>edad;
								string id;
								cout<<"Ingrese id: ";
								cin>>id;
								double dificultad;
								cout<<"Ingrese dificultad: ";
								cin>>dificultad;
								Repartidor* temporal=new Repartidor(nombre,edad,id,dificultad);
								vPersona.push_back(temporal);
								break;
							}
							case 3:{
								string nombre;
								cout<<"Ingrese nombre: ";
								cin>>nombre;
								int edad;
								cout<<"Ingrese edad: ";
								cin>>edad;
								string id;
								cout<<"Ingrese id: ";
								cin>>id;
								string procedencia;
								cout<<"Ingrese procedencia: ";
								cin>>procedencia;
								string apodo;
								cout<<"Ingrese apodo: ";
								cin>>apodo;
								double dinero;
								cout<<"Ingrese dinero: ";
								cin>>dinero;
								Jugador* temporal=new Jugador(nombre,edad,id,procedencia,apodo,dinero);
								vPersona.push_back(temporal);
								break;
							}
							case 4:{
								int numero;
								cout<<"Ingrese numero de mesa: ";
								cin>>numero;
								string tipo;
								cout<<"Ingrese tipo (vip,clasica,viajero): ";
								cin>>tipo;
								int pos;
								Mesa* temporal=new Mesa(numero,tipo);
								do{
									for(int i=0;i<vPersona.size();i++){
										if (vPersona[i]->getTipo().compare("Jugador")==0){
											cout<<"Nombre: "<<" = "<<vPersona[i]->getNombre()<<endl;
											cout<<"Edad: "<<" = "<<vPersona[i]->getEdad()<<endl;
											cout<<"ID: "<<" = "<<vPersona[i]->getID()<<endl;
											Jugador* temporal=dynamic_cast<Jugador*>(vPersona[i]);
											cout<<"Procedencia: "<<" = "<<temporal->getProcedencia()<<endl;
											cout<<"Apodo: "<<" = "<<temporal->getApodo()<<endl;
											cout<<"Dinero: "<<" = "<<temporal->getDinero()<<endl;
										}
										cout<<endl;
									}
									int pos;
									cout<<"Ingrese posicion del jugador o (-1) para salir: ";
									cin>>pos;
									Jugador* jugadorTemporal=dynamic_cast<Jugador*>(vPersona[pos]);
									temporal->Jugadores.push_back(jugadorTemporal);
								}while(pos!=-1);
								for(int i=0;i<vPersona.size();i++){
									if (vPersona[i]->getTipo().compare("Repartidor")==0){
										cout<<"Nombre: "<<" = "<<vPersona[i]->getNombre()<<endl;
										cout<<"Edad: "<<" = "<<vPersona[i]->getEdad()<<endl;
										cout<<"ID: "<<" = "<<vPersona[i]->getID()<<endl;
									}
									cout<<endl;
								}
								int pos1;
								cout<<"Ingrese posicion del jugador: ";
								cin>>pos1;
								Repartidor* repartidorTemporal=dynamic_cast<Repartidor*>(vPersona[pos1]);
								temporal->repartidor=repartidorTemporal;
								vMesa.push_back(temporal);
								break;
							}
						}
						break;
					}//fin agregar
					case 2:{
						cout<<"Menú listar"<<endl;
						cout<<"1. Personas"<<endl;
						cout<<"2. Mesas"<<endl;
						int opcListar;
						cout<<"Ingrese la opción: ";
						cin>>opcListar;
						cout<<endl;
						switch(opcListar){
							case 1:{
								for(int i=0;i<vPersona.size();i++){
									cout<<"Nombre: "<<" = "<<vPersona[i]->getNombre()<<endl;
									cout<<"Edad: "<<" = "<<vPersona[i]->getEdad()<<endl;
									cout<<"ID: "<<" = "<<vPersona[i]->getID()<<endl;
									if (vPersona[i]->getTipo().compare("Administrador")==0){
										Administrador* temporal=dynamic_cast<Administrador*>(vPersona[i]);
										cout<<"Experiencia: "<<" = "<<temporal->getExperiencia()<<endl;
										cout<<"Rango: "<<" = "<<temporal->getRango()<<endl;
										cout<<"Sueldo: "<<" = "<<temporal->getSueldo()<<endl;
									}
									if (vPersona[i]->getTipo().compare("Repartidor")==0){
										Repartidor* temporal=dynamic_cast<Repartidor*>(vPersona[i]);
										cout<<"Dificultad: "<<" = "<<temporal->getDificultad()<<endl;
										cout<<"Dinero del casino: "<<" = "<<temporal->getDineroCasino()<<endl;
									}
									if (vPersona[i]->getTipo().compare("Jugador")==0){
										Jugador* temporal=dynamic_cast<Jugador*>(vPersona[i]);
										cout<<"Procedencia: "<<" = "<<temporal->getProcedencia()<<endl;
										cout<<"Apodo: "<<" = "<<temporal->getApodo()<<endl;
										cout<<"Dinero: "<<" = "<<temporal->getDinero()<<endl;
									}
									cout<<endl;
								}
								break;
							}
							case 2:{
								for(int i=0;i<vMesa.size();i++){
									cout<<"Numero: "<<" = "<<vMesa[i]->getNumero()<<endl;
									cout<<"Tipo: "<<" = "<<vMesa[i]->getTipo()<<endl;
									cout<<endl;
								}
								break;
							}
							case 3:{
								break;
							}
						}
					}//fin listar
					case 3:{

					}//fin modificar
					case 4:{
						cout<<"Ingrese a listar para ver las posiciones"<<endl;
						cout<<"Desea eliminar"<<endl;
						cout<<"1. Persona"<<endl;
						cout<<"2. Mesa"<<endl;
						int respuesta;
						cout<<"Ingrese opcion: ";
						cin>>respuesta;
						if (respuesta==1){
							cout<<"Ingrese posicion: ";
							int posPersona;
							cin>>posPersona;
							vPersona.erase(vPersona.begin()+posPersona);
							cout<<"Eliminado"<<endl;
						}
						if (respuesta==2){
							cout<<"Ingrese posicion: ";
							int posPersona;
							cin>>posPersona;
							vMesa.erase(vMesa.begin()+posPersona);
							cout<<"Eliminado"<<endl;
						}
					}//fin eliminar
				}
			}while(opcMenu!=5);
		}
		//Si es un repartidor
		if (personaActual->getTipo().compare("Repartidor")==0){
			cout<<"No se puede jugar con un repartidor"<<endl;
		}
		//Si es un jugador
		if (personaActual->getTipo().compare("Jugador")==0){
			vector<int> posiciones;
			bool existeCarta;
			do{
				existeCarta=false;
				int x=rand()%52;
				for (int i = 0; i < 52; ++i){
				}
			} while (existeCarta==true);
		}
		cout<<endl;
	}while(salir==false);

	//Deletes
	for (int i = 0; i < vPersona.size(); ++i){
		delete vPersona[i];
	}
	for (int i = 0; i < vMesa.size(); ++i){
		delete vMesa[i];
	}
}
<commit_msg>Se finalizó el proyecto<commit_after>#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <typeinfo>
#include <cstdlib>
#include <stdlib.h>
#include "Persona.h"
#include "Administrador.h"
#include "Repartidor.h"
#include "Baraja.h"
#include "Carta.h"
#include "Jugador.h"
#include "Mesa.h"

using namespace std;

int main(){
	vector<Persona*> vPersona;
	vector<Mesa*> vMesa;
	Administrador* adminDefecto=new Administrador("admin",23,"1234",5,"Gerente Tiempo Completo",10000);
	vPersona.push_back(adminDefecto);
	bool salir=false;
	do{
	//Login
		Persona* personaActual;
		string Nombre;
		string ID;
		cout<<"Bienvenido al programa."<<endl;
		cout<<"Ingrese (salir) en nombre o identidad para salir"<<endl;
		cout<<"Ingrese nombre: ";
		cin>>Nombre;
		cout<<"Ingrese identidad: ";
		cin>>ID;
		if (Nombre.compare("salir")==0||ID.compare("salir")==0){
			break;
		}
		bool existeUsuario=false;
		for (int i = 0; i < vPersona.size(); ++i){
			if (Nombre.compare(vPersona[i]->getNombre())==0){
				if (ID.compare(vPersona[i]->getID())==0){
					personaActual=vPersona[i];
					existeUsuario=true;
				}
			}
		}
		if (existeUsuario==false){
			cout<<"No existe el usuario"<<endl;
		}
		//Si es un administrador
		if (personaActual->getTipo().compare("Administrador")==0){
			int opcMenu;
			do{
				cout<<"Menú"<<endl;
				cout<<"1. Agregar"<<endl;
				cout<<"2. Listar"<<endl;
				cout<<"3. Modificar"<<endl;
				cout<<"4. Eliminar"<<endl;
				cout<<"5. Salir"<<endl;
				cout<<"Ingrese opción: "<<endl;
				cin>>opcMenu;
				switch(opcMenu){
					case 1:{
						cout<<"Menú agregar"<<endl;
						cout<<"1. Administrador"<<endl;
						cout<<"2. Repartidor"<<endl;
						cout<<"3. Jugador"<<endl;
						cout<<"4. Mesa"<<endl;
						int opcAgregar;
						cout<<"Ingrese la opción: ";
						cin>>opcAgregar;
						switch(opcAgregar){
							case 1:{
								string nombre;
								cout<<"Ingrese nombre: ";
								cin>>nombre;
								int edad;
								cout<<"Ingrese edad: ";
								cin>>edad;
								string id;
								cout<<"Ingrese id: ";
								cin>>id;
								int experiencia;
								cout<<"Ingrese experiencia: ";
								cin>>experiencia;
								string rango;
								cout<<"Ingrese rango: ";
								cin>>rango;
								double sueldo;
								cout<<"Ingrese sueldo: ";
								cin>>sueldo;
								Administrador* temporal=new Administrador(nombre,edad,id,experiencia,rango,sueldo);
								vPersona.push_back(temporal);
								break;
							}
							case 2:{
								string nombre;
								cout<<"Ingrese nombre: ";
								cin>>nombre;
								int edad;
								cout<<"Ingrese edad: ";
								cin>>edad;
								string id;
								cout<<"Ingrese id: ";
								cin>>id;
								double dificultad;
								cout<<"Ingrese dificultad: ";
								cin>>dificultad;
								Repartidor* temporal=new Repartidor(nombre,edad,id,dificultad);
								vPersona.push_back(temporal);
								break;
							}
							case 3:{
								string nombre;
								cout<<"Ingrese nombre: ";
								cin>>nombre;
								int edad;
								cout<<"Ingrese edad: ";
								cin>>edad;
								string id;
								cout<<"Ingrese id: ";
								cin>>id;
								string procedencia;
								cout<<"Ingrese procedencia: ";
								cin>>procedencia;
								string apodo;
								cout<<"Ingrese apodo: ";
								cin>>apodo;
								double dinero;
								cout<<"Ingrese dinero: ";
								cin>>dinero;
								Jugador* temporal=new Jugador(nombre,edad,id,procedencia,apodo,dinero);
								vPersona.push_back(temporal);
								break;
							}
							case 4:{
								int numero;
								cout<<"Ingrese numero de mesa: ";
								cin>>numero;
								string tipo;
								cout<<"Ingrese tipo (vip,clasica,viajero): ";
								cin>>tipo;
								int pos;
								Mesa* temporal=new Mesa(numero,tipo);
								do{
									for(int i=0;i<vPersona.size();i++){
										if (vPersona[i]->getTipo().compare("Jugador")==0){
											cout<<"Nombre: "<<" = "<<vPersona[i]->getNombre()<<endl;
											cout<<"Edad: "<<" = "<<vPersona[i]->getEdad()<<endl;
											cout<<"ID: "<<" = "<<vPersona[i]->getID()<<endl;
											Jugador* temporal=dynamic_cast<Jugador*>(vPersona[i]);
											cout<<"Procedencia: "<<" = "<<temporal->getProcedencia()<<endl;
											cout<<"Apodo: "<<" = "<<temporal->getApodo()<<endl;
											cout<<"Dinero: "<<" = "<<temporal->getDinero()<<endl;
										}
										cout<<endl;
									}
									int pos;
									cout<<"Ingrese posicion del jugador o (-1) para salir: ";
									cin>>pos;
									Jugador* jugadorTemporal=dynamic_cast<Jugador*>(vPersona[pos]);
									temporal->Jugadores.push_back(jugadorTemporal);
								}while(pos!=-1);
								for(int i=0;i<vPersona.size();i++){
									if (vPersona[i]->getTipo().compare("Repartidor")==0){
										cout<<"Nombre: "<<" = "<<vPersona[i]->getNombre()<<endl;
										cout<<"Edad: "<<" = "<<vPersona[i]->getEdad()<<endl;
										cout<<"ID: "<<" = "<<vPersona[i]->getID()<<endl;
									}
									cout<<endl;
								}
								int pos1;
								cout<<"Ingrese posicion del jugador: ";
								cin>>pos1;
								Repartidor* repartidorTemporal=dynamic_cast<Repartidor*>(vPersona[pos1]);
								temporal->repartidor=repartidorTemporal;
								vMesa.push_back(temporal);
								break;
							}
						}
						break;
					}//fin agregar
					case 2:{
						cout<<"Menú listar"<<endl;
						cout<<"1. Personas"<<endl;
						cout<<"2. Mesas"<<endl;
						int opcListar;
						cout<<"Ingrese la opción: ";
						cin>>opcListar;
						cout<<endl;
						switch(opcListar){
							case 1:{
								for(int i=0;i<vPersona.size();i++){
									cout<<"Nombre: "<<" = "<<vPersona[i]->getNombre()<<endl;
									cout<<"Edad: "<<" = "<<vPersona[i]->getEdad()<<endl;
									cout<<"ID: "<<" = "<<vPersona[i]->getID()<<endl;
									if (vPersona[i]->getTipo().compare("Administrador")==0){
										Administrador* temporal=dynamic_cast<Administrador*>(vPersona[i]);
										cout<<"Experiencia: "<<" = "<<temporal->getExperiencia()<<endl;
										cout<<"Rango: "<<" = "<<temporal->getRango()<<endl;
										cout<<"Sueldo: "<<" = "<<temporal->getSueldo()<<endl;
									}
									if (vPersona[i]->getTipo().compare("Repartidor")==0){
										Repartidor* temporal=dynamic_cast<Repartidor*>(vPersona[i]);
										cout<<"Dificultad: "<<" = "<<temporal->getDificultad()<<endl;
										cout<<"Dinero del casino: "<<" = "<<temporal->getDineroCasino()<<endl;
									}
									if (vPersona[i]->getTipo().compare("Jugador")==0){
										Jugador* temporal=dynamic_cast<Jugador*>(vPersona[i]);
										cout<<"Procedencia: "<<" = "<<temporal->getProcedencia()<<endl;
										cout<<"Apodo: "<<" = "<<temporal->getApodo()<<endl;
										cout<<"Dinero: "<<" = "<<temporal->getDinero()<<endl;
									}
									cout<<endl;
								}
								break;
							}
							case 2:{
								for(int i=0;i<vMesa.size();i++){
									cout<<"Numero: "<<" = "<<vMesa[i]->getNumero()<<endl;
									cout<<"Tipo: "<<" = "<<vMesa[i]->getTipo()<<endl;
									cout<<endl;
								}
								break;
							}
							case 3:{
								break;
							}
						}
						break;
					}//fin listar
					case 3:{

					}//fin modificar
					case 4:{
						cout<<"Ingrese a listar para ver las posiciones"<<endl;
						cout<<"Desea eliminar"<<endl;
						cout<<"1. Persona"<<endl;
						cout<<"2. Mesa"<<endl;
						int respuesta;
						cout<<"Ingrese opcion: ";
						cin>>respuesta;
						if (respuesta==1){
							cout<<"Ingrese posicion: ";
							int posPersona;
							cin>>posPersona;
							vPersona.erase(vPersona.begin()+posPersona);
							cout<<"Eliminado"<<endl;
						}
						if (respuesta==2){
							cout<<"Ingrese posicion: ";
							int posPersona;
							cin>>posPersona;
							vMesa.erase(vMesa.begin()+posPersona);
							cout<<"Eliminado"<<endl;
						}
					}//fin eliminar
				}
			}while(opcMenu!=5);
		}
		//Si es un repartidor
		if (personaActual->getTipo().compare("Repartidor")==0){
			cout<<"No se puede jugar con un repartidor"<<endl;
		}
		//Si es un jugador
		if (personaActual->getTipo().compare("Jugador")==0){

			vector<int> posiciones;
			bool existeCarta;
			do{
				existeCarta=false;
				int x=rand()%52;
				for (int i = 0; i < 52; ++i){

				}
			} while (existeCarta==true);
		}
		cout<<endl;
	}while(salir==false);

	//Deletes
	for (int i = 0; i < vPersona.size(); ++i){
		delete vPersona[i];
	}
	for (int i = 0; i < vMesa.size(); ++i){
		delete vMesa[i];
	}
}
<|endoftext|>


<commit_before><commit_msg>Create main.cpp<commit_after><|endoftext|>


<commit_before><commit_msg>-adapted to changes<commit_after><|endoftext|>


<commit_before>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab

#include "tcp.h"

/******************
 * tcp crap
 */

/*
inlined, see tcp.h

bool tcp_read(int sd, char *buf, int len)
{
  while (len > 0) {
    int got = ::recv( sd, buf, len, 0 );
    if (got == 0) {
      generic_dout(18) << "tcp_read socket " << sd << " closed" << dendl;
      return false;
    }
    if (got < 0) {
      generic_dout(18) << "tcp_read bailing with " << got << dendl;
      return false;
    }
    assert(got >= 0);
    len -= got;
    buf += got;
    //generic_dout(DBL) << "tcp_read got " << got << ", " << len << " left" << dendl;
  }
  return true;
}

int tcp_write(int sd, char *buf, int len)
{
  //generic_dout(DBL) << "tcp_write writing " << len << dendl;
  assert(len > 0);
  while (len > 0) {
    int did = ::send( sd, buf, len, 0 );
    if (did < 0) {
      generic_dout(1) << "tcp_write error did = " << did << "  errno " << errno << " " << strerror(errno) << dendl;
      //derr(0) << "tcp_write error did = " << did << "  errno " << errno << " " << strerror(errno) << dendl;
    }
    //assert(did >= 0);
    if (did < 0) return did;
    len -= did;
    buf += did;
    //generic_dout(DBL) << "tcp_write did " << did << ", " << len << " left" << dendl;
  }
  return 0;
}
*/

int tcp_read(int sd, char *buf, int len) {
  while (len > 0) {
    int got = ::recv( sd, buf, len, 0 );
    if (got <= 0) {
      //generic_dout(18) << "tcp_read socket " << sd << " closed" << dendl;
      return -1;
    }
    len -= got;
    buf += got;
    //generic_dout(DBL) << "tcp_read got " << got << ", " << len << " left" << dendl;
  }
  return len;
}

int tcp_write(int sd, const char *buf, int len) {
  //generic_dout(DBL) << "tcp_write writing " << len << dendl;
  assert(len > 0);
  while (len > 0) {
    int did = ::send( sd, buf, len, 0 );
    if (did < 0) {
      //generic_dout(1) << "tcp_write error did = " << did << "  errno " << errno << " " << strerror(errno) << dendl;
      //generic_derr(1) << "tcp_write error did = " << did << "  errno " << errno << " " << strerror(errno) << dendl;
      return did;
    }
    len -= did;
    buf += did;
    //generic_dout(DBL) << "tcp_write did " << did << ", " << len << " left" << dendl;
  }
  return 0;
}

int tcp_hostlookup(char *str, sockaddr_in& ta)
{
  char *host = str;
  char *port = 0;

  for (int i=0; str[i]; i++) {
    if (str[i] == ':') {
      port = str+i+1;
      str[i] = 0;
      break;
    }
  }
  if (!port) {
    cerr << "addr '" << str << "' doesn't look like 'host:port'" << std::endl;
    return -1;
  }
  //cout << "host '" << host << "' port '" << port << "'" << std::endl;

  int iport = atoi(port);

  struct hostent *myhostname = gethostbyname( host );
  if (!myhostname) {
    cerr << "host " << host << " not found" << std::endl;
    return -1;
  }

  memset(&ta, 0, sizeof(ta));

  //cout << "addrtype " << myhostname->h_addrtype << " len " << myhostname->h_length << std::endl;

  ta.sin_family = myhostname->h_addrtype;
  memcpy((char *)&ta.sin_addr,
         myhostname->h_addr,
         myhostname->h_length);
  ta.sin_port = iport;

  cout << "lookup '" << host << ":" << port << "' -> " << ta << std::endl;

  return 0;
}
<commit_msg>msgr: kill dead code<commit_after>// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*-
// vim: ts=8 sw=2 smarttab

#include "tcp.h"

/******************
 * tcp crap
 */

int tcp_read(int sd, char *buf, int len) {
  while (len > 0) {
    int got = ::recv( sd, buf, len, 0 );
    if (got <= 0) {
      //generic_dout(18) << "tcp_read socket " << sd << " closed" << dendl;
      return -1;
    }
    len -= got;
    buf += got;
    //generic_dout(DBL) << "tcp_read got " << got << ", " << len << " left" << dendl;
  }
  return len;
}

int tcp_write(int sd, const char *buf, int len) {
  //generic_dout(DBL) << "tcp_write writing " << len << dendl;
  assert(len > 0);
  while (len > 0) {
    int did = ::send( sd, buf, len, 0 );
    if (did < 0) {
      //generic_dout(1) << "tcp_write error did = " << did << "  errno " << errno << " " << strerror(errno) << dendl;
      //generic_derr(1) << "tcp_write error did = " << did << "  errno " << errno << " " << strerror(errno) << dendl;
      return did;
    }
    len -= did;
    buf += did;
    //generic_dout(DBL) << "tcp_write did " << did << ", " << len << " left" << dendl;
  }
  return 0;
}

int tcp_hostlookup(char *str, sockaddr_in& ta)
{
  char *host = str;
  char *port = 0;

  for (int i=0; str[i]; i++) {
    if (str[i] == ':') {
      port = str+i+1;
      str[i] = 0;
      break;
    }
  }
  if (!port) {
    cerr << "addr '" << str << "' doesn't look like 'host:port'" << std::endl;
    return -1;
  }
  //cout << "host '" << host << "' port '" << port << "'" << std::endl;

  int iport = atoi(port);

  struct hostent *myhostname = gethostbyname( host );
  if (!myhostname) {
    cerr << "host " << host << " not found" << std::endl;
    return -1;
  }

  memset(&ta, 0, sizeof(ta));

  //cout << "addrtype " << myhostname->h_addrtype << " len " << myhostname->h_length << std::endl;

  ta.sin_family = myhostname->h_addrtype;
  memcpy((char *)&ta.sin_addr,
         myhostname->h_addr,
         myhostname->h_length);
  ta.sin_port = iport;

  cout << "lookup '" << host << ":" << port << "' -> " << ta << std::endl;

  return 0;
}
<|endoftext|>


<commit_before>#include "ncurses.hh"

#include <ncurses.h>
#include <stdexcept>
#include "utf8.hh"

namespace curses {

// get an array of bytes represents a UTF-8 character from window.
std::string get_utf8_char(WINDOW* window)
{
  std::array<uint8_t, 6> buf{0};

  auto ch0 = static_cast<uint8_t>(::wgetch(window) & 0x000000FF);
  size_t len = get_utf8_char_length(ch0);
  buf[0] = ch0;

  for (size_t i = 1; i < len; ++i) {
    auto ch = static_cast<uint8_t>(::wgetch(window) & 0x000000FF);
    if (!is_utf8_cont(ch)) {
      throw std::runtime_error(std::string(__FUNCTION__) + ": wrong byte exists");
    }
    buf[i] = ch;
  }

  return std::string(buf.data(), buf.data() + len);
}

Window::Window()
{
  tty_in.reset(fopen("/dev/tty", "r"));
  tty_out.reset(fopen("/dev/tty", "w"));

  // create a new terminal
  scr = ::newterm(getenv("TERM"), tty_out.get(), tty_in.get());
  win = stdscr;

  // setup
  ::noecho();           // do not echo back characters
  ::cbreak();           // without buffering
  ::keypad(win, true);  // convert escape sequeces to key code
  ::nodelay(win, true); // set delay time

  // initialize colormap.
  // start_color();
  // ::init_pair(1, COLOR_RED, COLOR_WHITE);
}

Window::~Window()
{
  // reset current screen.
  ::endwin();

  // release all resources of current session.
  ::delscreen(scr);
}

void Window::erase() { ::werase(win); }

void Window::refresh() { ::wrefresh(win); }

std::tuple<int, int> Window::get_size() const
{
  int width, height;
  getmaxyx(win, height, width);
  return std::make_tuple(width, height);
}

void Window::add_str(int x, int y, std::string const& text) { mvwaddstr(win, y, x, text.c_str()); }

void Window::change_attr(int x, int y, int n, int col) { mvwchgat(win, y, x, n, A_BOLD | A_UNDERLINE, col, nullptr); }

Event Window::poll_event()
{
  int ch = ::wgetch(win);
  if (ch == 10) {
    return Event{Key::Enter};
  }
  else if (ch == 27) {
    int ch = ::wgetch(win);
    if (ch == -1) {
      return Event{Key::Esc};
    }
    else {
      return Event{Key::Alt, ch};
    }
  }
  else if (ch == KEY_UP) {
    return Event{Key::Up};
  }
  else if (ch == KEY_DOWN) {
    return Event{Key::Down};
  }
  else if (ch == KEY_LEFT) {
    return Event{Key::Left};
  }
  else if (ch == KEY_RIGHT) {
    return Event{Key::Right};
  }
  else if (ch == 9) {
    return Event{Key::Tab};
  }
  else if (ch == 127 || ch == KEY_BACKSPACE) {
    return Event{Key::Backspace};
  }
  else if (ch == 18) {
    return Event{Key::Ctrl, 'r'};
  }
  else if (is_utf8_first(ch & 0xFF)) {
    ::ungetch(ch);
    auto ch = get_utf8_char(win);
    return Event{std::move(ch)};
  }
  else {
    return Event{Key::Unknown};
  }
}

} // namespace curses;

<commit_msg>add delay time<commit_after>#include "ncurses.hh"

#include <ncurses.h>
#include <stdexcept>
#include "utf8.hh"

namespace curses {

// get an array of bytes represents a UTF-8 character from window.
std::string get_utf8_char(WINDOW* window)
{
  std::array<uint8_t, 6> buf{0};

  auto ch0 = static_cast<uint8_t>(::wgetch(window) & 0x000000FF);
  size_t len = get_utf8_char_length(ch0);
  buf[0] = ch0;

  for (size_t i = 1; i < len; ++i) {
    auto ch = static_cast<uint8_t>(::wgetch(window) & 0x000000FF);
    if (!is_utf8_cont(ch)) {
      throw std::runtime_error(std::string(__FUNCTION__) + ": wrong byte exists");
    }
    buf[i] = ch;
  }

  return std::string(buf.data(), buf.data() + len);
}

Window::Window()
{
  tty_in.reset(fopen("/dev/tty", "r"));
  tty_out.reset(fopen("/dev/tty", "w"));

  // create a new terminal
  scr = ::newterm(getenv("TERM"), tty_out.get(), tty_in.get());
  win = stdscr;

  // setup
  ::noecho();           // do not echo back characters
  ::cbreak();           // without buffering
  ::keypad(win, true);  // convert escape sequeces to key code
  ::wtimeout(win, 1);   // set delay time

  // initialize colormap.
  // start_color();
  // ::init_pair(1, COLOR_RED, COLOR_WHITE);
}

Window::~Window()
{
  // reset current screen.
  ::endwin();

  // release all resources of current session.
  ::delscreen(scr);
}

void Window::erase() { ::werase(win); }

void Window::refresh() { ::wrefresh(win); }

std::tuple<int, int> Window::get_size() const
{
  int width, height;
  getmaxyx(win, height, width);
  return std::make_tuple(width, height);
}

void Window::add_str(int x, int y, std::string const& text) { mvwaddstr(win, y, x, text.c_str()); }

void Window::change_attr(int x, int y, int n, int col) { mvwchgat(win, y, x, n, A_BOLD | A_UNDERLINE, col, nullptr); }

Event Window::poll_event()
{
  int ch = ::wgetch(win);
  if (ch == 10) {
    return Event{Key::Enter};
  }
  else if (ch == 27) {
    int ch = ::wgetch(win);
    if (ch == -1) {
      return Event{Key::Esc};
    }
    else {
      return Event{Key::Alt, ch};
    }
  }
  else if (ch == KEY_UP) {
    return Event{Key::Up};
  }
  else if (ch == KEY_DOWN) {
    return Event{Key::Down};
  }
  else if (ch == KEY_LEFT) {
    return Event{Key::Left};
  }
  else if (ch == KEY_RIGHT) {
    return Event{Key::Right};
  }
  else if (ch == 9) {
    return Event{Key::Tab};
  }
  else if (ch == 127 || ch == KEY_BACKSPACE) {
    return Event{Key::Backspace};
  }
  else if (ch == 18) {
    return Event{Key::Ctrl, 'r'};
  }
  else if (is_utf8_first(ch & 0xFF)) {
    ::ungetch(ch);
    auto ch = get_utf8_char(win);
    return Event{std::move(ch)};
  }
  else {
    return Event{Key::Unknown};
  }
}

} // namespace curses;

<|endoftext|>


<commit_before>/*
 * This software is distributed under BSD 3-clause license (see LICENSE file).
 *
 * Authors: Giovanni De Toni
 *
 */

#include <shogun/lib/type_case.h>
#include <shogun/lib/observers/ParameterObserverLogger.h>

using namespace shogun;

ParameterObserverLogger::ParameterObserverLogger() {}

ParameterObserverLogger::ParameterObserverLogger(std::vector<std::string> &parameters) : ParameterObserver(
		parameters) {}

ParameterObserverLogger::~ParameterObserverLogger() {

}

void ParameterObserverLogger::on_error(std::exception_ptr ptr) {

}

void ParameterObserverLogger::on_complete() {

}

void ParameterObserverLogger::on_next_impl(const TimedObservedValue &value) {

	auto name = value.first->get<std::string>("name");
	auto any_val = value.first->get_any();
	auto print_func = [](auto v){
		SG_PRINT("[%l] Received a value called %s which contains: %s", convert_to_millis(value.second),
				 name, v);
	};

	sg_any_dispatch(any_val, sg_all_typemap, print_func, print_func, print_func);

}
<commit_msg>Fix lambda inside ParameterObserverLogger.cpp.<commit_after>/*
 * This software is distributed under BSD 3-clause license (see LICENSE file).
 *
 * Authors: Giovanni De Toni
 *
 */

#include <shogun/lib/type_case.h>
#include <shogun/lib/observers/ParameterObserverLogger.h>

using namespace shogun;

ParameterObserverLogger::ParameterObserverLogger() {}

ParameterObserverLogger::ParameterObserverLogger(std::vector<std::string> &parameters) : ParameterObserver(
		parameters) {}

ParameterObserverLogger::~ParameterObserverLogger() {

}

void ParameterObserverLogger::on_error(std::exception_ptr ptr) {

}

void ParameterObserverLogger::on_complete() {

}

void ParameterObserverLogger::on_next_impl(const TimedObservedValue &value) {

	auto name = value.first->get<std::string>("name");
	auto any_val = value.first->get_any();
	auto print_func = [&](auto v){
		SG_PRINT("[%l] Received a value called %s which contains: %s", convert_to_millis(value.second),
				 name, v);
	};

	sg_any_dispatch(any_val, sg_all_typemap, print_func, print_func, print_func);

}
<|endoftext|>