<commit_before>// ---------------------------------------------------------------------
// $Id$
//
// Copyright (C) 2005 - 2013 by the deal.II authors
//
// This file is part of the deal.II library.
//
// The deal.II library is free software; you can use it, 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.
// The full text of the license can be found in the file LICENSE at
// the top level of the deal.II distribution.
//
// ---------------------------------------------------------------------

#include <deal.II/base/function_parser.h>
#include <deal.II/base/utilities.h>
#include <deal.II/lac/vector.h>

#ifdef DEAL_II_WITH_MUPARSER
#include <muParser.h>
#else

namespace fparser
{
  class FunctionParser
  {};
}
#endif

DEAL_II_NAMESPACE_OPEN

template <int dim>
FunctionParser<dim>::FunctionParser(const unsigned int n_components,
                                    const double       initial_time)
  :
  Function<dim>(n_components, initial_time)
{}

template <int dim>
FunctionParser<dim>::~FunctionParser()
{}

#ifdef DEAL_II_WITH_MUPARSER
template <int dim>
void FunctionParser<dim>::initialize (const std::string                   &variables,
                                      const std::vector<std::string>      &expressions,
                                      const std::map<std::string, double> &constants,
                                      const bool time_dependent,
                                      const bool use_degrees)
{
  initialize (variables,
              expressions,
              constants,
              std::map< std::string, double >(),
              time_dependent,
              use_degrees);
}

template <int dim>
void FunctionParser<dim>::initialize (const std::string              &vars,
				      const std::vector<std::string> &expressions,
				      const std::map<std::string, double> &constants,
				      const bool time_dependent)
  {
    initialize(vars, expressions, constants, time_dependent, false);
  }

namespace internal
{
  // convert double into int
  int mu_round(double val)
  {
    return static_cast<int>(val + ((val>=0.0) ? 0.5 : -0.5) );
  }

  double mu_if(double condition, double thenvalue, double elsevalue)
  {
    if (mu_round(condition))
      return thenvalue;
    else
      return elsevalue;
  }

  double mu_or(double left, double right)
  {
    return (mu_round(left)) || (mu_round(right));
  }

  double mu_and(double left, double right)
  {
    return (mu_round(left)) && (mu_round(right));
  }

  double mu_int(double value)
  {
    return static_cast<double>(mu_round(value));
  }
  double mu_ceil(double value)
  {
    return ceil(value);
  }
  double mu_floor(double value)
  {
    return floor(value);
  }
  double mu_cot(double value)
  {
    return 1.0/tan(value);
  }
  double mu_csc(double value)
  {
    return 1.0/sin(value);
  }
 double mu_sec(double value)
  {
    return 1.0/cos(value);
  }
 double mu_log(double value)
  {
    return log(value);
  }

}

template <int dim>
void FunctionParser<dim>:: init_muparser() const
{
  if (fp.get().size()>0)
    return;

  fp.get().resize(this->n_components);
  vars.get().resize(var_names.size());
  for (unsigned int i=0; i<this->n_components; ++i)
    {
      std::map< std::string, double >::const_iterator
	constant = constants.begin(),
	endc  = constants.end();

      for (; constant != endc; ++constant)
        {
 	  fp.get()[i].DefineConst(constant->first.c_str(), constant->second);
	}

      for (unsigned int iv=0;iv<var_names.size();++iv)
	fp.get()[i].DefineVar(var_names[iv].c_str(), &vars.get()[iv]);

      // define some compatibility functions:
      fp.get()[i].DefineFun("if",internal::mu_if, true);
      fp.get()[i].DefineOprt("|", internal::mu_or, 1);
      fp.get()[i].DefineOprt("&", internal::mu_and, 2);
      fp.get()[i].DefineFun("int", internal::mu_int, true);
      fp.get()[i].DefineFun("ceil", internal::mu_ceil, true);
      fp.get()[i].DefineFun("cot", internal::mu_cot, true);
      fp.get()[i].DefineFun("csc", internal::mu_csc, true);
      fp.get()[i].DefineFun("floor", internal::mu_floor, true);
      fp.get()[i].DefineFun("sec", internal::mu_sec, true);
      fp.get()[i].DefineFun("log", internal::mu_log, true);

      try
	{
	  fp.get()[i].SetExpr(expressions[i]);
	}
      catch (mu::ParserError &e)
	{
          std::cerr << "Message:  " << e.GetMsg() << "\n";
	  std::cerr << "Formula:  " << e.GetExpr() << "\n";
	  std::cerr << "Token:    " << e.GetToken() << "\n";
	  std::cerr << "Position: " << e.GetPos() << "\n";
	  std::cerr << "Errc:     " << e.GetCode() << std::endl;
	  AssertThrow(false, ExcParseError(e.GetCode(), e.GetMsg().c_str()));
	}
    }
}

template <int dim>
void FunctionParser<dim>::initialize (const std::string   &variables,
                                      const std::vector<std::string>      &expressions,
                                      const std::map<std::string, double> &constants,
                                      const std::map<std::string, double> &units,
                                      const bool time_dependent,
                                      const bool use_degrees)
{

  this->fp.clear(); // this will reset all thread-local objects

  this->constants = constants;
  this->var_names = Utilities::split_string_list(variables, ',');
  this->expressions = expressions;
  AssertThrow(((time_dependent)?dim+1:dim) == var_names.size(),
	      ExcMessage("wrong number of variables"));
  AssertThrow(!use_degrees, ExcNotImplemented());

  // We check that the number of
  // components of this function
  // matches the number of components
  // passed in as a vector of
  // strings.
  AssertThrow(this->n_components == expressions.size(),
              ExcInvalidExpressionSize(this->n_components,
                                       expressions.size()) );

  // we no longer support units:
  AssertThrow(units.size()==0, ExcNotImplemented());

  // Now we define how many variables
  // we expect to read in.  We
  // distinguish between two cases:
  // Time dependent problems, and not
  // time dependent problems. In the
  // first case the number of
  // variables is given by the
  // dimension plus one. In the other
  // case, the number of variables is
  // equal to the dimension. Once we
  // parsed the variables string, if
  // none of this is the case, then
  // an exception is thrown.
  if (time_dependent)
    n_vars = dim+1;
  else
    n_vars = dim;

  init_muparser();

  // Now set the initialization bit.
  initialized = true;
}

template <int dim>
void FunctionParser<dim>::initialize (const std::string &vars,
                   const std::string &expression,
                   const std::map<std::string, double> &constants,
                   const bool time_dependent)
{
  initialize(vars, expression, constants, time_dependent, false);
}

template <int dim>
void FunctionParser<dim>::initialize (const std::string &variables,
                                      const std::string &expression,
                                      const std::map<std::string, double> &constants,
                                      const bool time_dependent,
                                      const bool use_degrees)
{
  // initialize with the things
  // we got.
  initialize (variables,
              Utilities::split_string_list (expression, ';'),
              constants,
              time_dependent,
              use_degrees);
}

template <int dim>
void FunctionParser<dim>::initialize (const std::string &variables,
                                      const std::string &expression,
                                      const std::map<std::string, double> &constants,
                                      const std::map<std::string, double> &units,
                                      const bool time_dependent,
                                      const bool use_degrees)
{
  // initialize with the things
  // we got.
  initialize (variables,
              Utilities::split_string_list (expression, ';'),
              constants,
              units,
              time_dependent,
              use_degrees);
}

template <int dim>
double FunctionParser<dim>::value (const Point<dim>  &p,
                                   const unsigned int component) const
{
  Assert (initialized==true, ExcNotInitialized());
  Assert (component < this->n_components,
          ExcIndexRange(component, 0, this->n_components));

  // initialize if not done so on this thread yet:
  init_muparser();

  for (unsigned int i=0; i<dim; ++i)
    vars.get()[i] = p(i);
  if (dim != n_vars)
    vars.get()[dim] = this->get_time();

  try
    {
      return fp.get()[component].Eval();
    }
  catch (mu::ParserError &e)
    {
      std::cerr << "Message:  " << e.GetMsg() << "\n";
      std::cerr << "Formula:  " << e.GetExpr() << "\n";
      std::cerr << "Token:    " << e.GetToken() << "\n";
      std::cerr << "Position: " << e.GetPos() << "\n";
      std::cerr << "Errc:     " << e.GetCode() << std::endl;
      AssertThrow(false, ExcParseError(e.GetCode(), e.GetMsg().c_str()));
      return 0.0;
    }
}

template <int dim>
void FunctionParser<dim>::vector_value (const Point<dim> &p,
                                        Vector<double>   &values) const
{
  Assert (initialized==true, ExcNotInitialized());
  Assert (values.size() == this->n_components,
          ExcDimensionMismatch (values.size(), this->n_components));

  // initialize if not done so on this thread yet:
  init_muparser();

  for (unsigned int i=0; i<dim; ++i)
    vars.get()[i] = p(i);
  if (dim != n_vars)
    vars.get()[dim] = this->get_time();

  for (unsigned int component = 0; component < this->n_components;
       ++component)
    values(component) = fp.get()[component].Eval();
}

#else

template <int dim>
void
FunctionParser<dim>::initialize(const std::string &,
                                const std::vector<std::string> &,
                                const std::map<std::string, double> &,
                                const bool,
                                const bool)
{
  Assert(false, ExcNeedsFunctionparser());
}

template <int dim>
void
FunctionParser<dim>::initialize(const std::string &,
                                const std::vector<std::string> &,
                                const std::map<std::string, double> &,
                                const std::map<std::string, double> &,
                                const bool,
                                const bool)
{
  Assert(false, ExcNeedsFunctionparser());
}

template <int dim>
void
FunctionParser<dim>::initialize(const std::string &,
                                const std::string &,
                                const std::map<std::string, double> &,
                                const bool,
                                const bool)
{
  Assert(false, ExcNeedsFunctionparser());
}

template <int dim>
void
FunctionParser<dim>::initialize(const std::string &,
                                const std::string &,
                                const std::map<std::string, double> &,
                                const std::map<std::string, double> &,
                                const bool,
                                const bool)
{
  Assert(false, ExcNeedsFunctionparser());
}

template <int dim>
double FunctionParser<dim>::value (
  const Point<dim> &, unsigned int) const
{
  Assert(false, ExcNeedsFunctionparser());
  return 0.;
}

template <int dim>
void FunctionParser<dim>::vector_value (
  const Point<dim> &, Vector<double> &) const
{
  Assert(false, ExcNeedsFunctionparser());
}

#endif

// Explicit Instantiations.

template class FunctionParser<1>;
template class FunctionParser<2>;
template class FunctionParser<3>;

DEAL_II_NAMESPACE_CLOSE
<commit_msg>add missing instantiations if not configuring muparser<commit_after>// ---------------------------------------------------------------------
// $Id$
//
// Copyright (C) 2005 - 2013 by the deal.II authors
//
// This file is part of the deal.II library.
//
// The deal.II library is free software; you can use it, 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.
// The full text of the license can be found in the file LICENSE at
// the top level of the deal.II distribution.
//
// ---------------------------------------------------------------------

#include <deal.II/base/function_parser.h>
#include <deal.II/base/utilities.h>
#include <deal.II/lac/vector.h>

#ifdef DEAL_II_WITH_MUPARSER
#include <muParser.h>
#else

namespace fparser
{
  class FunctionParser
  {};
}
#endif

DEAL_II_NAMESPACE_OPEN

template <int dim>
FunctionParser<dim>::FunctionParser(const unsigned int n_components,
                                    const double       initial_time)
  :
  Function<dim>(n_components, initial_time)
{}

template <int dim>
FunctionParser<dim>::~FunctionParser()
{}

#ifdef DEAL_II_WITH_MUPARSER
template <int dim>
void FunctionParser<dim>::initialize (const std::string                   &variables,
                                      const std::vector<std::string>      &expressions,
                                      const std::map<std::string, double> &constants,
                                      const bool time_dependent,
                                      const bool use_degrees)
{
  initialize (variables,
              expressions,
              constants,
              std::map< std::string, double >(),
              time_dependent,
              use_degrees);
}

template <int dim>
void FunctionParser<dim>::initialize (const std::string              &vars,
				      const std::vector<std::string> &expressions,
				      const std::map<std::string, double> &constants,
				      const bool time_dependent)
  {
    initialize(vars, expressions, constants, time_dependent, false);
  }

namespace internal
{
  // convert double into int
  int mu_round(double val)
  {
    return static_cast<int>(val + ((val>=0.0) ? 0.5 : -0.5) );
  }

  double mu_if(double condition, double thenvalue, double elsevalue)
  {
    if (mu_round(condition))
      return thenvalue;
    else
      return elsevalue;
  }

  double mu_or(double left, double right)
  {
    return (mu_round(left)) || (mu_round(right));
  }

  double mu_and(double left, double right)
  {
    return (mu_round(left)) && (mu_round(right));
  }

  double mu_int(double value)
  {
    return static_cast<double>(mu_round(value));
  }
  double mu_ceil(double value)
  {
    return ceil(value);
  }
  double mu_floor(double value)
  {
    return floor(value);
  }
  double mu_cot(double value)
  {
    return 1.0/tan(value);
  }
  double mu_csc(double value)
  {
    return 1.0/sin(value);
  }
 double mu_sec(double value)
  {
    return 1.0/cos(value);
  }
 double mu_log(double value)
  {
    return log(value);
  }

}

template <int dim>
void FunctionParser<dim>:: init_muparser() const
{
  if (fp.get().size()>0)
    return;

  fp.get().resize(this->n_components);
  vars.get().resize(var_names.size());
  for (unsigned int i=0; i<this->n_components; ++i)
    {
      std::map< std::string, double >::const_iterator
	constant = constants.begin(),
	endc  = constants.end();

      for (; constant != endc; ++constant)
        {
 	  fp.get()[i].DefineConst(constant->first.c_str(), constant->second);
	}

      for (unsigned int iv=0;iv<var_names.size();++iv)
	fp.get()[i].DefineVar(var_names[iv].c_str(), &vars.get()[iv]);

      // define some compatibility functions:
      fp.get()[i].DefineFun("if",internal::mu_if, true);
      fp.get()[i].DefineOprt("|", internal::mu_or, 1);
      fp.get()[i].DefineOprt("&", internal::mu_and, 2);
      fp.get()[i].DefineFun("int", internal::mu_int, true);
      fp.get()[i].DefineFun("ceil", internal::mu_ceil, true);
      fp.get()[i].DefineFun("cot", internal::mu_cot, true);
      fp.get()[i].DefineFun("csc", internal::mu_csc, true);
      fp.get()[i].DefineFun("floor", internal::mu_floor, true);
      fp.get()[i].DefineFun("sec", internal::mu_sec, true);
      fp.get()[i].DefineFun("log", internal::mu_log, true);

      try
	{
	  fp.get()[i].SetExpr(expressions[i]);
	}
      catch (mu::ParserError &e)
	{
          std::cerr << "Message:  " << e.GetMsg() << "\n";
	  std::cerr << "Formula:  " << e.GetExpr() << "\n";
	  std::cerr << "Token:    " << e.GetToken() << "\n";
	  std::cerr << "Position: " << e.GetPos() << "\n";
	  std::cerr << "Errc:     " << e.GetCode() << std::endl;
	  AssertThrow(false, ExcParseError(e.GetCode(), e.GetMsg().c_str()));
	}
    }
}

template <int dim>
void FunctionParser<dim>::initialize (const std::string   &variables,
                                      const std::vector<std::string>      &expressions,
                                      const std::map<std::string, double> &constants,
                                      const std::map<std::string, double> &units,
                                      const bool time_dependent,
                                      const bool use_degrees)
{

  this->fp.clear(); // this will reset all thread-local objects

  this->constants = constants;
  this->var_names = Utilities::split_string_list(variables, ',');
  this->expressions = expressions;
  AssertThrow(((time_dependent)?dim+1:dim) == var_names.size(),
	      ExcMessage("wrong number of variables"));
  AssertThrow(!use_degrees, ExcNotImplemented());

  // We check that the number of
  // components of this function
  // matches the number of components
  // passed in as a vector of
  // strings.
  AssertThrow(this->n_components == expressions.size(),
              ExcInvalidExpressionSize(this->n_components,
                                       expressions.size()) );

  // we no longer support units:
  AssertThrow(units.size()==0, ExcNotImplemented());

  // Now we define how many variables
  // we expect to read in.  We
  // distinguish between two cases:
  // Time dependent problems, and not
  // time dependent problems. In the
  // first case the number of
  // variables is given by the
  // dimension plus one. In the other
  // case, the number of variables is
  // equal to the dimension. Once we
  // parsed the variables string, if
  // none of this is the case, then
  // an exception is thrown.
  if (time_dependent)
    n_vars = dim+1;
  else
    n_vars = dim;

  init_muparser();

  // Now set the initialization bit.
  initialized = true;
}

template <int dim>
void FunctionParser<dim>::initialize (const std::string &vars,
                   const std::string &expression,
                   const std::map<std::string, double> &constants,
                   const bool time_dependent)
{
  initialize(vars, expression, constants, time_dependent, false);
}

template <int dim>
void FunctionParser<dim>::initialize (const std::string &variables,
                                      const std::string &expression,
                                      const std::map<std::string, double> &constants,
                                      const bool time_dependent,
                                      const bool use_degrees)
{
  // initialize with the things
  // we got.
  initialize (variables,
              Utilities::split_string_list (expression, ';'),
              constants,
              time_dependent,
              use_degrees);
}

template <int dim>
void FunctionParser<dim>::initialize (const std::string &variables,
                                      const std::string &expression,
                                      const std::map<std::string, double> &constants,
                                      const std::map<std::string, double> &units,
                                      const bool time_dependent,
                                      const bool use_degrees)
{
  // initialize with the things
  // we got.
  initialize (variables,
              Utilities::split_string_list (expression, ';'),
              constants,
              units,
              time_dependent,
              use_degrees);
}

template <int dim>
double FunctionParser<dim>::value (const Point<dim>  &p,
                                   const unsigned int component) const
{
  Assert (initialized==true, ExcNotInitialized());
  Assert (component < this->n_components,
          ExcIndexRange(component, 0, this->n_components));

  // initialize if not done so on this thread yet:
  init_muparser();

  for (unsigned int i=0; i<dim; ++i)
    vars.get()[i] = p(i);
  if (dim != n_vars)
    vars.get()[dim] = this->get_time();

  try
    {
      return fp.get()[component].Eval();
    }
  catch (mu::ParserError &e)
    {
      std::cerr << "Message:  " << e.GetMsg() << "\n";
      std::cerr << "Formula:  " << e.GetExpr() << "\n";
      std::cerr << "Token:    " << e.GetToken() << "\n";
      std::cerr << "Position: " << e.GetPos() << "\n";
      std::cerr << "Errc:     " << e.GetCode() << std::endl;
      AssertThrow(false, ExcParseError(e.GetCode(), e.GetMsg().c_str()));
      return 0.0;
    }
}

template <int dim>
void FunctionParser<dim>::vector_value (const Point<dim> &p,
                                        Vector<double>   &values) const
{
  Assert (initialized==true, ExcNotInitialized());
  Assert (values.size() == this->n_components,
          ExcDimensionMismatch (values.size(), this->n_components));

  // initialize if not done so on this thread yet:
  init_muparser();

  for (unsigned int i=0; i<dim; ++i)
    vars.get()[i] = p(i);
  if (dim != n_vars)
    vars.get()[dim] = this->get_time();

  for (unsigned int component = 0; component < this->n_components;
       ++component)
    values(component) = fp.get()[component].Eval();
}

#else

template <int dim>
void
FunctionParser<dim>::initialize(const std::string &,
                                const std::vector<std::string> &,
                                const std::map<std::string, double> &,
                                const bool,
                                const bool)
{
  Assert(false, ExcNeedsFunctionparser());
}

template <int dim>
void
FunctionParser<dim>::initialize(const std::string &,
                                const std::vector<std::string> &,
                                const std::map<std::string, double> &,
                                const std::map<std::string, double> &,
                                const bool,
                                const bool)
{
  Assert(false, ExcNeedsFunctionparser());
}

template <int dim>
void
FunctionParser<dim>::initialize(const std::string &,
                                const std::string &,
                                const std::map<std::string, double> &,
                                const bool,
                                const bool)
{
  Assert(false, ExcNeedsFunctionparser());
}

template <int dim>
void
FunctionParser<dim>::initialize(const std::string &,
                                const std::string &,
                                const std::map<std::string, double> &,
                                const std::map<std::string, double> &,
                                const bool,
                                const bool)
{
  Assert(false, ExcNeedsFunctionparser());
}

template <int dim>
void
FunctionParser<dim>::initialize(const std::string &,
                                const std::vector<std::string> &,
                                const std::map<std::string, double> &,
                                const bool)
{
  Assert(false, ExcNeedsFunctionparser());
}

template <int dim>
void
FunctionParser<dim>::initialize(const std::string &,
                                const std::string &,
                                const std::map<std::string, double> &,
                                const bool)
{
  Assert(false, ExcNeedsFunctionparser());
}

template <int dim>
double FunctionParser<dim>::value (
  const Point<dim> &, unsigned int) const
{
  Assert(false, ExcNeedsFunctionparser());
  return 0.;
}

template <int dim>
void FunctionParser<dim>::vector_value (
  const Point<dim> &, Vector<double> &) const
{
  Assert(false, ExcNeedsFunctionparser());
}

#endif

// Explicit Instantiations.

template class FunctionParser<1>;
template class FunctionParser<2>;
template class FunctionParser<3>;

DEAL_II_NAMESPACE_CLOSE
<|endoftext|>


<commit_before>/*
 *            Copyright 2009-2019 The VOTCA Development Team
 *                       (http://www.votca.org)
 *
 *      Licensed under the Apache License, Version 2.0 (the "License")
 *
 * You may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *              http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
#include "votca/xtp/diis.h"
#include <iostream>

namespace votca {
namespace xtp {

void DIIS::Update(int maxerrorindex, const Eigen::MatrixXd& errormatrix) {

  if (int(_errormatrixhist.size()) == _histlength) {
    _errormatrixhist.erase(_errormatrixhist.begin() + maxerrorindex);
    _Diis_Bs.erase(_Diis_Bs.begin() + maxerrorindex);
    for (std::vector<double>& subvec : _Diis_Bs) {
      subvec.erase(subvec.begin() + maxerrorindex);
    }
  }

  _errormatrixhist.push_back(errormatrix);

  std::vector<double> Bijs;
  for (int i = 0; i < int(_errormatrixhist.size()) - 1; i++) {
    double value =
        errormatrix.cwiseProduct((_errormatrixhist[i]).transpose()).sum();
    Bijs.push_back(value);
    _Diis_Bs[i].push_back(value);
  }
  Bijs.push_back(errormatrix.cwiseProduct(errormatrix.transpose()).sum());
  _Diis_Bs.push_back(Bijs);
  return;
}

Eigen::VectorXd DIIS::CalcCoeff() {
  success = true;
  const bool _useold = false;
  const int size = _errormatrixhist.size();

  // C2-DIIS
  Eigen::MatrixXd B = Eigen::MatrixXd::Zero(size, size);

  for (int i = 0; i < B.rows(); i++) {
    for (int j = 0; j <= i; j++) {
      B(i, j) = _Diis_Bs[i][j];
      if (i != j) {
        B(j, i) = B(i, j);
      }
    }
  }
  Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(B);
  Eigen::MatrixXd eigenvectors = Eigen::MatrixXd::Zero(size, size);

  for (int i = 0; i < es.eigenvectors().cols(); i++) {
    double norm = es.eigenvectors().col(i).sum();
    eigenvectors.col(i) = es.eigenvectors().col(i) / norm;
  }

  // Choose solution by picking out solution with smallest absolute error
  Eigen::VectorXd errors =
      (eigenvectors.transpose() * B * eigenvectors).diagonal().cwiseAbs();

  double MaxWeight = 10.0;
  int mincoeff = 0;
  success = false;
  for (int i = 0; i < errors.size(); i++) {
    errors.minCoeff(&mincoeff);
    if (std::abs(eigenvectors.col(mincoeff).maxCoeff()) > MaxWeight) {
      errors[mincoeff] = std::numeric_limits<double>::max();
    } else {
      success = true;
      break;
    }
  }

  Eigen::VectorXd coeffs = eigenvectors.col(mincoeff);

  if (std::abs(coeffs[coeffs.size() - 1]) < 0.001) {
    success = false;
  }

  return coeffs;
}

}  // namespace xtp
}  // namespace votca
<commit_msg>diis.cc: fix a warning<commit_after>/*
 *            Copyright 2009-2019 The VOTCA Development Team
 *                       (http://www.votca.org)
 *
 *      Licensed under the Apache License, Version 2.0 (the "License")
 *
 * You may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *              http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
#include "votca/xtp/diis.h"
#include <iostream>

namespace votca {
namespace xtp {

void DIIS::Update(int maxerrorindex, const Eigen::MatrixXd& errormatrix) {

  if (int(_errormatrixhist.size()) == _histlength) {
    _errormatrixhist.erase(_errormatrixhist.begin() + maxerrorindex);
    _Diis_Bs.erase(_Diis_Bs.begin() + maxerrorindex);
    for (std::vector<double>& subvec : _Diis_Bs) {
      subvec.erase(subvec.begin() + maxerrorindex);
    }
  }

  _errormatrixhist.push_back(errormatrix);

  std::vector<double> Bijs;
  for (int i = 0; i < int(_errormatrixhist.size()) - 1; i++) {
    double value =
        errormatrix.cwiseProduct((_errormatrixhist[i]).transpose()).sum();
    Bijs.push_back(value);
    _Diis_Bs[i].push_back(value);
  }
  Bijs.push_back(errormatrix.cwiseProduct(errormatrix.transpose()).sum());
  _Diis_Bs.push_back(Bijs);
  return;
}

Eigen::VectorXd DIIS::CalcCoeff() {
  success = true;
  const int size = _errormatrixhist.size();

  // C2-DIIS
  Eigen::MatrixXd B = Eigen::MatrixXd::Zero(size, size);

  for (int i = 0; i < B.rows(); i++) {
    for (int j = 0; j <= i; j++) {
      B(i, j) = _Diis_Bs[i][j];
      if (i != j) {
        B(j, i) = B(i, j);
      }
    }
  }
  Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> es(B);
  Eigen::MatrixXd eigenvectors = Eigen::MatrixXd::Zero(size, size);

  for (int i = 0; i < es.eigenvectors().cols(); i++) {
    double norm = es.eigenvectors().col(i).sum();
    eigenvectors.col(i) = es.eigenvectors().col(i) / norm;
  }

  // Choose solution by picking out solution with smallest absolute error
  Eigen::VectorXd errors =
      (eigenvectors.transpose() * B * eigenvectors).diagonal().cwiseAbs();

  double MaxWeight = 10.0;
  int mincoeff = 0;
  success = false;
  for (int i = 0; i < errors.size(); i++) {
    errors.minCoeff(&mincoeff);
    if (std::abs(eigenvectors.col(mincoeff).maxCoeff()) > MaxWeight) {
      errors[mincoeff] = std::numeric_limits<double>::max();
    } else {
      success = true;
      break;
    }
  }

  Eigen::VectorXd coeffs = eigenvectors.col(mincoeff);

  if (std::abs(coeffs[coeffs.size() - 1]) < 0.001) {
    success = false;
  }

  return coeffs;
}

}  // namespace xtp
}  // namespace votca
<|endoftext|>


<commit_before>#include "linear_interpolate_d.hpp"

#include <cmath>

#include <algorithm>
#include <map>
#include <numeric>
#include <string>
#include <vector>

#include "sexp_matrix_iterator.hpp"

std::vector<double> find_barycentric_coords(std::size_t size,
                                            Point const & point,
                                            std::vector<Point> const & simplex)
{
  std::vector<double> a(size * size);
  for (size_t i = 0; i < size; ++i)
  {
    for (size_t j = 0; j < size; ++j)
    {
      a[i*size+j] = *(simplex[i].cartesian_begin()+j) - *(simplex[size].cartesian_begin()+j);
    }
  }

  std::vector<double> b(size + 1);
  for (size_t i = 0; i < size; ++i)
  {
    b[i] = *(point.cartesian_begin()+i) - *(simplex[size].cartesian_begin()+i);
  }

  // additional variables needed for LAPACK
  std::vector<int> ipiv(size);
  int info;
  int size_int = size;
  int b_size = 1;

  // solve a*x = b
  // result will be in b
  F77_NAME(dgesv)(&size_int, &b_size, &a[0], &size_int, &ipiv[0],
    &b[0], &size_int, &info);

  // calculate last coordinate
  b[size] = 1 - std::accumulate(b.begin(), b.end() - 1, 0.);

  return b;
}

void make_toroidal(std::size_t size,
                   std::vector<Point> & points,
                   std::vector<double> & values)
{
  /*shifts = [
      np.amax(points[:, i]) - np.amin(points[:, i])
      for i in xrange(points.shape[1])
  ]
  directions = np.array([0, 1, -1])
  all_shifts = itertools.product(*[
      directions * shift for shift in shifts
  ])

  toroidal = np.empty((0,) + points.shape[1:])
  for total_shift in all_shifts:
      toroidal = np.append(toroidal, points + np.array(total_shift), axis=0)*/

  size_t old_values_size = values.size();
  size_t values_size = std::pow(3, size) * old_values_size;
  values.resize(values_size);
  for (size_t i = 1; i < values_size; ++i)
  {
    for (size_t j = 0; j < old_values_size; ++j)
    {
      values[i * old_values_size + j] = values[j];
    }
  }
}

//vector<double>
SEXP linear_interpolate_d(SEXP dimentions,
                          SEXP points,
                          SEXP values,
                          SEXP xi,
                          SEXP fill_value)
{
  auto d = INTEGER(dimentions)[0];

  Delaunay triangulation(d);
  std::map<Vertex_handle, double> vertices_to_values;
  int points_count = length(values);
  for (auto i = 0; i < points_count; ++i)
  {
    Point point(
        d,
        sexp_matrix_iterator(points, points_count, i),
        sexp_matrix_iterator(points, points_count, i + d * points_count));
    auto vertex_handle = triangulation.insert(point);
    vertices_to_values[vertex_handle] = REAL(values)[i];
  }

  auto double_fill_value = REAL(fill_value)[0];

  auto recalc_point =
      [&]
      (Point const & point)
  {
    auto simplex = triangulation.locate(point);
    if (simplex == Delaunay::Simplex_handle())
    {
      return double_fill_value;
    }
    std::vector<Point>  vertices(d + 1);
    std::vector<double> vertex_values(d + 1);
    for (auto i = 0; i <= triangulation.current_dimension(); ++i)
    {
      auto vertex = triangulation.vertex_of_simplex(simplex, i);
      double vertex_val = vertices_to_values[vertex];
      if (ISNAN(vertex_val))
      {
        return double_fill_value;
      }
      vertices[i] = triangulation.associated_point(vertex);
      vertex_values[i] = vertex_val;
    }
    auto barycentric = find_barycentric_coords(triangulation.current_dimension(), point, vertices);
    return std::inner_product(vertex_values.begin(), vertex_values.end(), barycentric.begin(), 0.);
  };

  auto result_length = length(xi) / d;
  SEXP results = PROTECT(allocVector(REALSXP, result_length));
  for(int i = 0; i < result_length; ++i)
  {
    Point point(
        d,
        sexp_matrix_iterator(xi, result_length, i),
        sexp_matrix_iterator(xi, result_length, i + result_length * d));
    REAL(results)[i] = recalc_point(point);
  }
  UNPROTECT(1);
  return results;
}

<commit_msg>Add R files<commit_after>#include "linear_interpolate_d.hpp"

#include <cmath>

#include <algorithm>
#include <map>
#include <numeric>
#include <limits>
#include <string>
#include <tuple>
#include <vector>

#include "sexp_matrix_iterator.hpp"

std::vector<double> find_barycentric_coords(std::size_t size,
                                            Point const & point,
                                            std::vector<Point> const & simplex)
{
  std::vector<double> a(size * size);
  for (size_t i = 0; i < size; ++i)
  {
    for (size_t j = 0; j < size; ++j)
    {
      a[i*size+j] = *(simplex[i].cartesian_begin()+j) - *(simplex[size].cartesian_begin()+j);
    }
  }

  std::vector<double> b(size + 1);
  for (size_t i = 0; i < size; ++i)
  {
    b[i] = *(point.cartesian_begin()+i) - *(simplex[size].cartesian_begin()+i);
  }

  // additional variables needed for LAPACK
  std::vector<int> ipiv(size);
  int info;
  int size_int = size;
  int b_size = 1;

  // solve a*x = b
  // result will be in b
  F77_NAME(dgesv)(&size_int, &b_size, &a[0], &size_int, &ipiv[0],
    &b[0], &size_int, &info);

  // calculate last coordinate
  b[size] = 1 - std::accumulate(b.begin(), b.end() - 1, 0.);

  return b;
}

void make_toroidal(std::size_t size,
                   std::vector<Point> & points,
                   std::vector<double> & values)
{
  size_t old_length = points.size();
  size_t length = std::pow(3, size) * old_length;

  std::vector<std::tuple<double, double, double>> shifts(size);
  for (size_t i = 0; i < size; ++i)
  {
    double amin = std::numeric_limits<double>::max();
    double amax = std::numeric_limits<double>::min();
    for (auto const & p : points)
    {
      amin = std::min(amin, *(p.cartesian_begin() + i));
      amax = std::max(amax, *(p.cartesian_begin() + i));
    }
    shifts[i] = amax - amin;
    double shift = amax - amin;
    Rprintf("%lf\n", shift);
  }

  points.reserve(length);

  return;

  /*shifts = [
      np.amax(points[:, i]) - np.amin(points[:, i])
      for i in xrange(points.shape[1])
  ]
  directions = np.array([0, 1, -1])
  all_shifts = itertools.product(*[
      directions * shift for shift in shifts
  ])*/

  //toroidal = np.empty((0,) + points.shape[1:])
  //for total_shift in all_shifts:
  //    toroidal = np.append(toroidal, points + np.array(total_shift), axis=0)

  values.resize(length);
  for (size_t i = 1; i < values_size; ++i)
  {
    for (size_t j = 0; j < old_values_size; ++j)
    {
      values[i * old_values_size + j] = values[j];
    }
  }
}

//vector<double>
SEXP linear_interpolate_d(SEXP dimentions,
                          SEXP points,
                          SEXP values,
                          SEXP xi,
                          SEXP fill_value)
{
  auto d = INTEGER(dimentions)[0];

  Delaunay triangulation(d);
  std::map<Vertex_handle, double> vertices_to_values;
  int points_count = length(values);
  for (auto i = 0; i < points_count; ++i)
  {
    Point point(
        d,
        sexp_matrix_iterator(points, points_count, i),
        sexp_matrix_iterator(points, points_count, i + d * points_count));
    auto vertex_handle = triangulation.insert(point);
    vertices_to_values[vertex_handle] = REAL(values)[i];
  }

  auto double_fill_value = REAL(fill_value)[0];

  auto recalc_point =
      [&]
      (Point const & point)
  {
    auto simplex = triangulation.locate(point);
    if (simplex == Delaunay::Simplex_handle())
    {
      return double_fill_value;
    }
    std::vector<Point>  vertices(d + 1);
    std::vector<double> vertex_values(d + 1);
    for (auto i = 0; i <= triangulation.current_dimension(); ++i)
    {
      auto vertex = triangulation.vertex_of_simplex(simplex, i);
      double vertex_val = vertices_to_values[vertex];
      if (ISNAN(vertex_val))
      {
        return double_fill_value;
      }
      vertices[i] = triangulation.associated_point(vertex);
      vertex_values[i] = vertex_val;
    }
    auto barycentric = find_barycentric_coords(triangulation.current_dimension(), point, vertices);
    return std::inner_product(vertex_values.begin(), vertex_values.end(), barycentric.begin(), 0.);
  };

  auto result_length = length(xi) / d;
  SEXP results = PROTECT(allocVector(REALSXP, result_length));
  for(int i = 0; i < result_length; ++i)
  {
    Point point(
        d,
        sexp_matrix_iterator(xi, result_length, i),
        sexp_matrix_iterator(xi, result_length, i + result_length * d));
    REAL(results)[i] = recalc_point(point);
  }
  UNPROTECT(1);
  return results;
}

<|endoftext|>


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

#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
#include <strings.h>
#include <sys/select.h>
#include <pthread.h>
#include <signal.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <cstdio>

#include <iostream>
#include <sstream>

#include "Client.h"
#include "Debug.h"
#include "OKCounterD.h"
#include "Server.h"

#define BUFSIZE 8096
#define MAXCLIENTS 16

extern ostream* debugStream;

//
// Public
//

Server::Server(OKCounterD *a,int p)
{
	threadID = "server";
	app = a;
	port=p;
	if (!init())
		exit(EXIT_FAILURE);
}

Server::~Server()
{
	close(listenfd);
	for (unsigned int i=0;i<clients.size();i++)
		clients.at(i)->stop();
}

void Server::sendData(vector<int> &data){
	for (unsigned int i=0;i<clients.size();i++){
		clients.at(i)->sendData(data);
	}
}

//
// Protected
//

void Server::doWork()
{
	// SIGPIPE is delivered if the client closes the socket before we've finished replying
	// This kills the process

	DBGMSG(debugStream,"working");

	sigset_t blocked;
	sigemptyset(&blocked);
	sigaddset(&blocked,SIGPIPE);
	pthread_sigmask(SIG_BLOCK,&blocked,NULL);

	int socketfd;
	socklen_t len;
	struct sockaddr_in cli_addr;
	bzero(&cli_addr,sizeof(cli_addr));

	fd_set rfds;
  struct timeval tv;
  int retval;

	while (!stopRequested)
	{

		tv.tv_sec=5;
		tv.tv_usec=0;

		FD_ZERO(&rfds);
		FD_SET(listenfd, &rfds);

		retval = select(listenfd+1, &rfds, NULL,NULL, &tv); // note number of file descriptors!

		if (retval) {
			len= sizeof(cli_addr);
			if((socketfd = accept(listenfd, (struct sockaddr *)&cli_addr, &len)) < 0)
				app->log("ERROR in accept()");
			else{
				processRequest(socketfd);
			}
		}

		unsigned int j=0;
		while (j<clients.size()){
			Client *c = clients.at(j);
			if (!c->isRunning()){
				DBGMSG(debugStream,"stopping client");
				c->stop();
				clients.erase(clients.begin()+j);
				delete c;
			}
			else
				j++;
		}

	}

	running=false;
}

//
// Private
//

bool Server::init()
{
	struct sockaddr_in serv_addr;
	bzero(&serv_addr,sizeof(serv_addr));

	// Set up the socket
	#ifdef LINUX_PRE_2_6_27
	listenfd = socket(AF_INET, SOCK_STREAM ,0);
	if (listenfd >=0){
		fcntl(listenfd, F_SETFL, O_NONBLOCK);
	}
	else{
	#else
	if((listenfd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK,0)) <0){
	#endif
		app->log("ERROR in socket()");
		return false;
	}

	if(port < 0 || port >60000){
		app->log("ERROR invalid port number (try 1->60000)");
		return false;
	}

	serv_addr.sin_family = AF_INET;
	serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
	serv_addr.sin_port = htons(port);

	if(bind(listenfd, (struct sockaddr *)&serv_addr,sizeof(serv_addr)) <0){
		app->log("ERROR in bind()");
		return false;
	}

	if( listen(listenfd,64) <0){
		app->log("ERROR in listen()");
		return false;
	}

	ostringstream ss;
	ss << "listening on port " << port;
	app->log(ss.str());

	return true;

}

bool Server::processRequest(int socketfd)
{
	// Two requests:
	// LISTEN to counter readings
	// CONFIGURE the counter
	// QUERY the counter configuration

	long ret;
	static char buffer[BUFSIZE+1];

	ret =read(socketfd,buffer,BUFSIZE); 	// read request in one go
	if(ret == 0 || ret == -1) {	// read failure
		//app->log("failed to read client request");
		return false;
	}
	if(ret > 0 && ret < BUFSIZE)	// return code is valid chars
		buffer[ret]=0;		// terminate the buffer
	else buffer[0]=0;

	if (NULL != strstr(buffer,"CONFIGURE") ){
		DBGMSG(debugStream,"received " << buffer);
		if (NULL != strstr(buffer,"PPSSOURCE")){
			int src;
			sscanf(buffer,"%*s%*s%i",&src);
			app->setOutputPPSSource(src);
		}
		else if (NULL != strstr(buffer,"GPIO")){
			int en;
			sscanf(buffer,"%*s%*s%i",&en);
			app->setGPIOEnable((en==1));
		}
		else{
			DBGMSG(debugStream,"unknown command");
		}

		// done so close the connection
		if (-1==shutdown(socketfd,SHUT_RDWR)){
			app->log("ERROR in shutdown()");
		}
		if (-1==close(socketfd)){
			app->log("ERROR in close()");
		}
	}
	else if (NULL != strstr(buffer,"QUERY CONFIGURATION") ){
		DBGMSG(debugStream,"received " << buffer);
		string cfg = app->getConfiguration();
		writeBuffer(cfg,socketfd);
		sleep(1); // wait a bit
		// done so close the connection
		if (-1==shutdown(socketfd,SHUT_RDWR)){
			app->log("ERROR in shutdown()");
		}
		if (-1==close(socketfd)){
			app->log("ERROR in close()");
		}
	}
	else if(NULL != strstr(buffer,"LISTEN") ){
		DBGMSG(debugStream,"received " << buffer);
		// Sanity check on number of clients
		if (clients.size() == MAXCLIENTS){
			app->log("Too many connections");
			if (-1==shutdown(socketfd,SHUT_RDWR)){
				app->log("ERROR in shutdown()");
			}
			if (-1==close(socketfd)){
				app->log("ERROR in close()");
			}
		}
		else{
			Client *client = new Client(this,socketfd);
			clients.push_back(client);
			client->go();
		}
	}
	return true;
}

void Server::writeBuffer(string msg,int socketfd){

	int nw,nEINTR=0;
	int nleft = msg.size();
	const char* pbuf=msg.c_str();

	while (nleft > 0){
		if (( nw = write(socketfd,pbuf,nleft)) <= 0){
			if (errno==EINTR){ // interrupted by signal
				nw=0;
				nEINTR++;
				if (10==nEINTR){
					DBGMSG(debugStream, "too many interrrupts - write() aborted");
					return;
				}
			}
			else{
				DBGMSG(debugStream, strerror(errno));
				return;
			}
		}
		DBGMSG(debugStream, "wrote " << nw);
		nleft -=nw;
		pbuf += nw;
	}
}

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

#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
#include <strings.h>
#include <sys/select.h>
#include <pthread.h>
#include <signal.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <cstdio>

#include <iostream>
#include <sstream>

#include "Client.h"
#include "Debug.h"
#include "OKCounterD.h"
#include "Server.h"

#define BUFSIZE 8096
#define MAXCLIENTS 16

extern ostream* debugStream;

//
// Public
//

Server::Server(OKCounterD *a,int p)
{
	threadID = "server";
	app = a;
	port=p;
	if (!init())
		exit(EXIT_FAILURE);
}

Server::~Server()
{
	close(listenfd);
	for (unsigned int i=0;i<clients.size();i++)
		clients.at(i)->stop();
}

void Server::sendData(vector<int> &data){
	for (unsigned int i=0;i<clients.size();i++){
		clients.at(i)->sendData(data);
	}
}

//
// Protected
//

void Server::doWork()
{
	// SIGPIPE is delivered if the client closes the socket before we've finished replying
	// This kills the process

	DBGMSG(debugStream,"working");

	sigset_t blocked;
	sigemptyset(&blocked);
	sigaddset(&blocked,SIGPIPE);
	pthread_sigmask(SIG_BLOCK,&blocked,NULL);

	int socketfd;
	socklen_t len;
	struct sockaddr_in cli_addr;
	bzero(&cli_addr,sizeof(cli_addr));

	fd_set rfds;
  struct timeval tv;
  int retval;

	while (!stopRequested)
	{

		tv.tv_sec=5;
		tv.tv_usec=0;

		FD_ZERO(&rfds);
		FD_SET(listenfd, &rfds);

		retval = select(listenfd+1, &rfds, NULL,NULL, &tv); // note number of file descriptors!

		if (retval) {
			len= sizeof(cli_addr);
			if((socketfd = accept(listenfd, (struct sockaddr *)&cli_addr, &len)) < 0)
				app->log("ERROR in accept()");
			else{
				processRequest(socketfd);
			}
		}

		unsigned int j=0;
		while (j<clients.size()){
			Client *c = clients.at(j);
			if (!c->isRunning()){
				DBGMSG(debugStream,"stopping client");
				c->stop();
				clients.erase(clients.begin()+j);
				delete c;
			}
			else
				j++;
		}

	}

	running=false;
}

//
// Private
//

bool Server::init()
{
	struct sockaddr_in serv_addr;
	bzero(&serv_addr,sizeof(serv_addr));

	// Set up the socket
	#ifdef LINUX_PRE_2_6_27
	listenfd = socket(AF_INET, SOCK_STREAM ,0);
	if (listenfd >=0){
		fcntl(listenfd, F_SETFL, O_NONBLOCK);
	}
	else{
	#else
	if((listenfd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK,0)) <0){
	#endif
		app->log("ERROR in socket()");
		return false;
	}

	int on = 1;
	if (setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) <0){
		app->log("ERROR setsockopt()");
		// don't return
	}

	if(port < 0 || port >60000){
		app->log("ERROR invalid port number (try 1->60000)");
		return false;
	}

	serv_addr.sin_family = AF_INET;
	serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
	serv_addr.sin_port = htons(port);

	if(bind(listenfd, (struct sockaddr *)&serv_addr,sizeof(serv_addr)) <0){
		app->log("ERROR in bind()");
		return false;
	}

	if( listen(listenfd,64) <0){
		app->log("ERROR in listen()");
		return false;
	}

	ostringstream ss;
	ss << "listening on port " << port;
	app->log(ss.str());

	return true;

}

bool Server::processRequest(int socketfd)
{
	// Two requests:
	// LISTEN to counter readings
	// CONFIGURE the counter
	// QUERY the counter configuration

	long ret;
	static char buffer[BUFSIZE+1];

	ret =read(socketfd,buffer,BUFSIZE); 	// read request in one go
	if(ret == 0 || ret == -1) {	// read failure
		//app->log("failed to read client request");
		return false;
	}
	if(ret > 0 && ret < BUFSIZE)	// return code is valid chars
		buffer[ret]=0;		// terminate the buffer
	else buffer[0]=0;

	if (NULL != strstr(buffer,"CONFIGURE") ){
		DBGMSG(debugStream,"received " << buffer);
		if (NULL != strstr(buffer,"PPSSOURCE")){
			int src;
			sscanf(buffer,"%*s%*s%i",&src);
			app->setOutputPPSSource(src);
		}
		else if (NULL != strstr(buffer,"GPIO")){
			int en;
			sscanf(buffer,"%*s%*s%i",&en);
			app->setGPIOEnable((en==1));
		}
		else{
			DBGMSG(debugStream,"unknown command");
		}

		// done so close the connection
		if (-1==shutdown(socketfd,SHUT_RDWR)){
			app->log("ERROR in shutdown()");
		}
		if (-1==close(socketfd)){
			app->log("ERROR in close()");
		}
	}
	else if (NULL != strstr(buffer,"QUERY CONFIGURATION") ){
		DBGMSG(debugStream,"received " << buffer);
		string cfg = app->getConfiguration();
		writeBuffer(cfg,socketfd);
		sleep(1); // wait a bit
		// done so close the connection
		if (-1==shutdown(socketfd,SHUT_RDWR)){
			app->log("ERROR in shutdown()");
		}
		if (-1==close(socketfd)){
			app->log("ERROR in close()");
		}
	}
	else if(NULL != strstr(buffer,"LISTEN") ){
		DBGMSG(debugStream,"received " << buffer);
		// Sanity check on number of clients
		if (clients.size() == MAXCLIENTS){
			app->log("Too many connections");
			if (-1==shutdown(socketfd,SHUT_RDWR)){
				app->log("ERROR in shutdown()");
			}
			if (-1==close(socketfd)){
				app->log("ERROR in close()");
			}
		}
		else{
			Client *client = new Client(this,socketfd);
			clients.push_back(client);
			client->go();
		}
	}
	return true;
}

void Server::writeBuffer(string msg,int socketfd){

	int nw,nEINTR=0;
	int nleft = msg.size();
	const char* pbuf=msg.c_str();

	while (nleft > 0){
		if (( nw = write(socketfd,pbuf,nleft)) <= 0){
			if (errno==EINTR){ // interrupted by signal
				nw=0;
				nEINTR++;
				if (10==nEINTR){
					DBGMSG(debugStream, "too many interrrupts - write() aborted");
					return;
				}
			}
			else{
				DBGMSG(debugStream, strerror(errno));
				return;
			}
		}
		DBGMSG(debugStream, "wrote " << nw);
		nleft -=nw;
		pbuf += nw;
	}
}

<|endoftext|>


<commit_before>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: modelSettingsDialog.C,v 1.14 2004/01/20 16:47:56 amoll Exp $
//

#include <BALL/VIEW/DIALOGS/modelSettingsDialog.h>
#include <BALL/DATATYPE/string.h>
#include <BALL/FORMAT/INIFile.h>

#include <qslider.h>
#include <qlabel.h>
#include <qlistbox.h>
#include <qwidgetstack.h>

namespace BALL
{
	namespace VIEW
	{

		ModelSettingsDialog::ModelSettingsDialog( QWidget* parent,  const char* name, WFlags fl )
				: ModelSettingsDialogData( parent, name, fl )
		{
			setDefaults();
		}

		void ModelSettingsDialog::setDefaults(bool all)
			throw()
		{
			if (all || list_box->currentItem() == 0)
			{
				stick_radius_slider->setValue(2);
			}

			if (all || list_box->currentItem() == 1)
			{
				ball_stick_cylinder_radius_slider->setValue(2);
				ball_stick_sphere_radius_slider->setValue(4);
			}

			if (all || list_box->currentItem() == 2)
			{
				vdw_radius_factor_slider->setValue(10);
			}

			if (all || list_box->currentItem() == 3)
			{
				surface_probe_radius_slider->setValue(15);
			}

			if (all || list_box->currentItem() == 4)
			{
				tube_radius_slider->setValue(4);
			}

			if (all || list_box->currentItem() == 5)
			{
				cartoon_tube_radius_slider->setValue(4);
				cartoon_helix_radius_slider->setValue(20);
				cartoon_arrow_width_slider->setValue(4);
				cartoon_arrow_height_slider->setValue(8);
			}

			if (all || list_box->currentItem() == 6)
			{
				hbonds_radius_slider->setValue(3);
			}
		}

		float ModelSettingsDialog::getFloatValue_(const QSlider* const& slider) const
			throw()
		{
			return (float(slider->value())) / 10.0;
		}

		void ModelSettingsDialog::setValue_(QSlider* le, float value)
			throw()
		{
			le->setValue((Size)(value * 10.0));
		}

		void ModelSettingsDialog::setLabelText_(QLabel* label, const QSlider* const from)
			throw()
		{
			String s((float)from->value() / 10.0);
			s.trimRight("0");
			if (s.hasSuffix(".")) s+= "0";
			label->setText(s.c_str());
		}

		void ModelSettingsDialog::fetchPreference_(const INIFile& inifile, const String& entry, QSlider& slider)
			throw()
		{
			if (!inifile.hasEntry("MODEL_OPTIONS", entry)) return;
			setValue_(&slider, inifile.getValue("MODEL_OPTIONS", entry).toFloat());
		}

		void ModelSettingsDialog::writePreference_(INIFile& inifile, const String& entry, const QSlider& slider) const
			throw()
		{
			inifile.insertValue("MODEL_OPTIONS", entry, getFloatValue_(&slider));
		}

		void ModelSettingsDialog::writePreferences(INIFile& file)
			throw()
		{
			file.appendSection("MODEL_OPTIONS");
			writePreference_(file, "stick_radius", *stick_radius_slider);
			writePreference_(file, "ball_stick_cylinder_radius", *ball_stick_cylinder_radius_slider);
			writePreference_(file, "ball_stick_sphere_radius", *ball_stick_sphere_radius_slider);
			writePreference_(file, "vdw_radius_factor", *vdw_radius_factor_slider);
			writePreference_(file, "surface_probe_radius", *surface_probe_radius_slider);
			writePreference_(file, "tube_radius", *tube_radius_slider);
			writePreference_(file, "cartoon_tube_radius", *cartoon_tube_radius_slider);
			writePreference_(file, "cartoon_helix_radius", *cartoon_helix_radius_slider);
			writePreference_(file, "cartoon_arrow_height", *cartoon_arrow_height_slider);
			writePreference_(file, "cartoon_arrow_width", *cartoon_arrow_width_slider);
			writePreference_(file, "cartoon_arrow_width", *cartoon_arrow_width_slider);
			writePreference_(file, "hbonds_radius", *hbonds_radius_slider);
		}

		void ModelSettingsDialog::fetchPreferences(const INIFile& file)
			throw()
		{
			fetchPreference_(file, "stick_radius", *stick_radius_slider);
			fetchPreference_(file, "ball_stick_cylinder_radius", *ball_stick_cylinder_radius_slider);
			fetchPreference_(file, "ball_stick_sphere_radius", *ball_stick_sphere_radius_slider);
			fetchPreference_(file, "vdw_radius_factor", *vdw_radius_factor_slider);
			fetchPreference_(file, "surface_probe_radius", *surface_probe_radius_slider);
			fetchPreference_(file, "tube_radius", *tube_radius_slider);
			fetchPreference_(file, "cartoon_tube_radius", *cartoon_tube_radius_slider);
			fetchPreference_(file, "cartoon_helix_radius", *cartoon_helix_radius_slider);
			fetchPreference_(file, "cartoon_arrow_height", *cartoon_arrow_height_slider);
			fetchPreference_(file, "cartoon_arrow_width", *cartoon_arrow_width_slider);
			fetchPreference_(file, "hbonds_radius", *hbonds_radius_slider);
		}

		void ModelSettingsDialog::setDefaultValues()
			throw()
		{
			setDefaults(false);
		}

		void ModelSettingsDialog::showPage(int nr)
		{
			if (widget_stack->widget(nr) == 0)
			{
				return;
			}

			if (list_box->currentItem() != nr)
			{
				list_box->setCurrentItem(nr);
			}
			widget_stack->raiseWidget(nr);
		}

	} // namespace VIEW
} // namespace BALL
<commit_msg>no message<commit_after>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: modelSettingsDialog.C,v 1.15 2004/02/24 19:03:48 amoll Exp $
//

#include <BALL/VIEW/DIALOGS/modelSettingsDialog.h>
#include <BALL/DATATYPE/string.h>
#include <BALL/FORMAT/INIFile.h>

#include <qslider.h>
#include <qlabel.h>
#include <qlistbox.h>
#include <qwidgetstack.h>

namespace BALL
{
	namespace VIEW
	{

		ModelSettingsDialog::ModelSettingsDialog( QWidget* parent,  const char* name, WFlags fl )
				: ModelSettingsDialogData( parent, name, fl )
		{
			setDefaults();
		}

		void ModelSettingsDialog::setDefaults(bool all)
			throw()
		{
			if (all || list_box->currentItem() == 0)
			{
				stick_radius_slider->setValue(2);
			}

			if (all || list_box->currentItem() == 1)
			{
				ball_stick_cylinder_radius_slider->setValue(2);
				ball_stick_sphere_radius_slider->setValue(4);
			}

			if (all || list_box->currentItem() == 2)
			{
				vdw_radius_factor_slider->setValue(10);
			}

			if (all || list_box->currentItem() == 3)
			{
				surface_probe_radius_slider->setValue(15);
			}

			if (all || list_box->currentItem() == 4)
			{
				tube_radius_slider->setValue(4);
			}

			if (all || list_box->currentItem() == 5)
			{
				cartoon_tube_radius_slider->setValue(4);
				cartoon_helix_radius_slider->setValue(20);
				cartoon_arrow_width_slider->setValue(20);
				cartoon_arrow_height_slider->setValue(4);
			}

			if (all || list_box->currentItem() == 6)
			{
				hbonds_radius_slider->setValue(3);
			}
		}

		float ModelSettingsDialog::getFloatValue_(const QSlider* const& slider) const
			throw()
		{
			return (float(slider->value())) / 10.0;
		}

		void ModelSettingsDialog::setValue_(QSlider* le, float value)
			throw()
		{
			le->setValue((Size)(value * 10.0));
		}

		void ModelSettingsDialog::setLabelText_(QLabel* label, const QSlider* const from)
			throw()
		{
			String s((float)from->value() / 10.0);
			s.trimRight("0");
			if (s.hasSuffix(".")) s+= "0";
			label->setText(s.c_str());
		}

		void ModelSettingsDialog::fetchPreference_(const INIFile& inifile, const String& entry, QSlider& slider)
			throw()
		{
			if (!inifile.hasEntry("MODEL_OPTIONS", entry)) return;
			setValue_(&slider, inifile.getValue("MODEL_OPTIONS", entry).toFloat());
		}

		void ModelSettingsDialog::writePreference_(INIFile& inifile, const String& entry, const QSlider& slider) const
			throw()
		{
			inifile.insertValue("MODEL_OPTIONS", entry, getFloatValue_(&slider));
		}

		void ModelSettingsDialog::writePreferences(INIFile& file)
			throw()
		{
			file.appendSection("MODEL_OPTIONS");
			writePreference_(file, "stick_radius", *stick_radius_slider);
			writePreference_(file, "ball_stick_cylinder_radius", *ball_stick_cylinder_radius_slider);
			writePreference_(file, "ball_stick_sphere_radius", *ball_stick_sphere_radius_slider);
			writePreference_(file, "vdw_radius_factor", *vdw_radius_factor_slider);
			writePreference_(file, "surface_probe_radius", *surface_probe_radius_slider);
			writePreference_(file, "tube_radius", *tube_radius_slider);
			writePreference_(file, "cartoon_tube_radius", *cartoon_tube_radius_slider);
			writePreference_(file, "cartoon_helix_radius", *cartoon_helix_radius_slider);
			writePreference_(file, "cartoon_arrow_height", *cartoon_arrow_height_slider);
			writePreference_(file, "cartoon_arrow_width", *cartoon_arrow_width_slider);
			writePreference_(file, "cartoon_arrow_width", *cartoon_arrow_width_slider);
			writePreference_(file, "hbonds_radius", *hbonds_radius_slider);
		}

		void ModelSettingsDialog::fetchPreferences(const INIFile& file)
			throw()
		{
			fetchPreference_(file, "stick_radius", *stick_radius_slider);
			fetchPreference_(file, "ball_stick_cylinder_radius", *ball_stick_cylinder_radius_slider);
			fetchPreference_(file, "ball_stick_sphere_radius", *ball_stick_sphere_radius_slider);
			fetchPreference_(file, "vdw_radius_factor", *vdw_radius_factor_slider);
			fetchPreference_(file, "surface_probe_radius", *surface_probe_radius_slider);
			fetchPreference_(file, "tube_radius", *tube_radius_slider);
			fetchPreference_(file, "cartoon_tube_radius", *cartoon_tube_radius_slider);
			fetchPreference_(file, "cartoon_helix_radius", *cartoon_helix_radius_slider);
			fetchPreference_(file, "cartoon_arrow_height", *cartoon_arrow_height_slider);
			fetchPreference_(file, "cartoon_arrow_width", *cartoon_arrow_width_slider);
			fetchPreference_(file, "hbonds_radius", *hbonds_radius_slider);
		}

		void ModelSettingsDialog::setDefaultValues()
			throw()
		{
			setDefaults(false);
		}

		void ModelSettingsDialog::showPage(int nr)
		{
			if (widget_stack->widget(nr) == 0)
			{
				return;
			}

			if (list_box->currentItem() != nr)
			{
				list_box->setCurrentItem(nr);
			}
			widget_stack->raiseWidget(nr);
		}

	} // namespace VIEW
} // namespace BALL
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: PostItMgr.hxx,v $
 * $Revision: 1.7 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _POSTITMGR_HXX
#define _POSTITMGR_HXX

#include <svtools/lstner.hxx>

#include <list>
#include <vector>

#include <tools/link.hxx>
#include <swrect.hxx>

class SwWrtShell;
class SwDoc;
class SwView;
class SwPostItField;
class SwFmtFld;
class SwField;
class SfxBroadcaster;
class SfxHint;
class SwPostIt;
class SwEditWin;
class Color;
class SvxSearchItem;
class SvxLanguageItem;

#define SORT_POS    1
#define SORT_AUTHOR 2
#define SORT_DATE   3

#define COL_NOTES_SIDEPANE_ARROW_ENABLED    RGB_COLORDATA(0,0,0)
#define COL_NOTES_SIDEPANE_ARROW_DISABLED   RGB_COLORDATA(172,168,153)

struct SwPostItItem;

typedef std::list<SwPostItItem*> SwPostItItem_list;

struct SwPostItPageItem
{
    bool bScrollbar;
    bool bMarginSide;
    long lOffset;
    SwRect mPageRect;
    SwPostItItem_list* mList;
    SwPostItPageItem(): bScrollbar(false),lOffset(0)
    {
        mList = new SwPostItItem_list;
    }
    ~SwPostItPageItem()
    {
        mList->clear();
        delete mList;
    }

};

struct FieldShadowState
{
    const SwPostItField* mpShadowFld;
    bool bCursor;
    bool bMouse;
    FieldShadowState(): mpShadowFld(0),bCursor(false),bMouse(false)
    {
    }
};

class SwPostItMgr: public SfxListener
{
    private:
        SwView*                         mpView;
        SwWrtShell*                     mpWrtShell;
        SwEditWin*                      mpEditWin;
        std::list< SwPostItItem*>       mvPostItFlds;
        std::vector<SwPostItPageItem*>  mPages;
        ULONG                           mnEventId;
        bool                            mbWaitingForCalcRects;
        SwPostIt*                       mpActivePostIt;
        bool                            mbLayout;
        long                            mbLayoutHeight;
        long                            mbLayouting;
        bool                            mbReadOnly;
        bool                            mbDeleteNote;
        FieldShadowState                mShadowState;

        typedef std::list<SwPostItItem*>::iterator  SwPostItItem_iterator;
        typedef std::list<SwPostIt*>::iterator      SwPostIt_iterator;

        void            AddPostIts(bool bCheckExistance = true,bool bFocus = true);
        void            RemovePostIts();
        void            PreparePageContainer();
        void            Scroll(const long lScroll,const unsigned long aPage );
        void            AutoScroll(const SwPostIt* pPostIt,const unsigned long aPage );
        bool            ScrollbarHit(const unsigned long aPage,const Point &aPoint);
        bool            LayoutByPage(std::list<SwPostIt*> &aVisiblePostItList,const Rectangle aBorder,long lNeededHeight);
        void            CheckForRemovedPostIts();
        bool            ArrowEnabled(USHORT aDirection,unsigned long aPage) const;
        bool            BorderOverPageBorder(unsigned long aPage) const;
        bool            HasScrollbars() const;

        void            SetColors(SwPostIt* pPostIt, SwPostItField* pFld);

        Color           GetColorDark(sal_uInt16 aAuthorIndex);
        Color           GetColorLight(sal_uInt16 aAuthorIndex);
        Color           GetColorAnkor(sal_uInt16 aAuthorIndex);

        sal_Int32       GetInitialAnchorDistance() const;
        sal_Int32       GetScrollSize() const;
        sal_Int32       GetSpaceBetween() const;
        void            SetReadOnlyState();
                        DECL_LINK( CalcHdl, void*);

    protected:

    public:
            SwPostItMgr(SwView* aDoc);
            ~SwPostItMgr();

            typedef std::list< SwPostItItem* >::const_iterator const_iterator;
            const_iterator begin()  const { return mvPostItFlds.begin(); }
            const_iterator end()    const { return mvPostItFlds.end();  }

            void InsertFld( SwFmtFld* aField, bool bCheckExistance, bool bFocus);
            void RemoveFld( SfxBroadcaster* pFld );
            void Notify( SfxBroadcaster& rBC, const SfxHint& rHint );

            void LayoutPostIts();
            bool CalcRects();

            void MakeVisible(const SwPostIt* pPostIt,long aPage = -1);

            bool ShowScrollbar(const unsigned long aPage) const;
            bool HasNotes() const ;
            bool ShowNotes() const;
            unsigned long GetSidebarWidth(bool bPx = false) const;
            unsigned long GetSidebarBorderWidth(bool bPx = false) const;
            unsigned long GetNoteWidth();

            void PrepareView(bool bIgnoreCount = false);

            void CorrectPositions();

            void Sort(const short aType);

            void SetLayout() { mbLayout = true; };
            void Delete(String aAuthor);
            void Delete();

            void Hide( SwPostItField* pPostItField );
            void Hide( const String& rAuthor );
            void Hide();
            void Show();

            void Rescale();

            Rectangle GetBottomScrollRect(const unsigned long aPage) const;
            Rectangle GetTopScrollRect(const unsigned long aPage) const;

            bool IsHit(const Point &aPointPixel);
            Color GetArrowColor(USHORT aDirection,unsigned long aPage) const;

            SwPostIt* GetNextPostIt(USHORT aDirection, SwPostIt* aPostIt);
            long GetNextBorder();
            SwPostIt* GetActivePostIt() { return mpActivePostIt; }
            void      SetActivePostIt( SwPostIt* p);
            sal_Int32 GetMinimumSizeWithMeta() const;
            sal_Int32 GetSidebarScrollerHeight() const;

            SwFmtFld* GetFmtFld(SwPostIt* mpPostIt) const;
            SwPostIt* GetPostIt(const SwFmtFld* pFld) const;
            SwPostIt* GetPostIt(const SwPostItField* pFld) const;
            SwPostIt* GetPostIt(SwFmtFld* pFld) const;
            SwPostIt* GetPostIt(SwPostItField* pFld) const;

            void SetShadowState(const SwPostItField* pFld,bool bCursor = true);

            void SetSpellChecking();

            bool ShowPreview(const SwField* pFld,SwFmtFld*& pFmtFld) const;
};

#endif
<commit_msg>INTEGRATION: CWS notes6 (1.6.24); FILE MERGED 2008/06/10 18:29:37 mod 1.6.24.1: notes5 import<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: PostItMgr.hxx,v $
 * $Revision: 1.8 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _POSTITMGR_HXX
#define _POSTITMGR_HXX

#include <svtools/lstner.hxx>

#include <list>
#include <vector>

#include <tools/link.hxx>
#include <swrect.hxx>

class SwWrtShell;
class SwDoc;
class SwView;
class SwPostItField;
class SwFmtFld;
class SwField;
class SfxBroadcaster;
class SfxHint;
class SwPostIt;
class SwEditWin;
class Color;
class SvxSearchItem;
class SvxLanguageItem;

#define SORT_POS    1
#define SORT_AUTHOR 2
#define SORT_DATE   3

#define COL_NOTES_SIDEPANE_ARROW_ENABLED    RGB_COLORDATA(0,0,0)
#define COL_NOTES_SIDEPANE_ARROW_DISABLED   RGB_COLORDATA(172,168,153)

struct SwPostItItem;

typedef std::list<SwPostItItem*> SwPostItItem_list;

struct SwPostItPageItem
{
    bool bScrollbar;
    bool bMarginSide;
    long lOffset;
    SwRect mPageRect;
    SwPostItItem_list* mList;
    SwPostItPageItem(): bScrollbar(false),lOffset(0)
    {
        mList = new SwPostItItem_list;
    }
    ~SwPostItPageItem()
    {
        mList->clear();
        delete mList;
    }

};

struct FieldShadowState
{
    const SwPostItField* mpShadowFld;
    bool bCursor;
    bool bMouse;
    FieldShadowState(): mpShadowFld(0),bCursor(false),bMouse(false)
    {
    }
};

class SwPostItMgr: public SfxListener
{
    private:
        SwView*                         mpView;
        SwWrtShell*                     mpWrtShell;
        SwEditWin*                      mpEditWin;
        std::list< SwPostItItem*>       mvPostItFlds;
        std::vector<SwPostItPageItem*>  mPages;
        ULONG                           mnEventId;
        bool                            mbWaitingForCalcRects;
        SwPostIt*                       mpActivePostIt;
        bool                            mbLayout;
        long                            mbLayoutHeight;
        long                            mbLayouting;
        bool                            mbReadOnly;
        bool                            mbDeleteNote;
        FieldShadowState                mShadowState;

        typedef std::list<SwPostItItem*>::iterator  SwPostItItem_iterator;
        typedef std::list<SwPostIt*>::iterator      SwPostIt_iterator;

        void            AddPostIts(bool bCheckExistance = true,bool bFocus = true);
        void            RemovePostIts();
        void            PreparePageContainer();
        void            Scroll(const long lScroll,const unsigned long aPage );
        void            AutoScroll(const SwPostIt* pPostIt,const unsigned long aPage );
        bool            ScrollbarHit(const unsigned long aPage,const Point &aPoint);
        bool            LayoutByPage(std::list<SwPostIt*> &aVisiblePostItList,const Rectangle aBorder,long lNeededHeight);
        void            CheckForRemovedPostIts();
        bool            ArrowEnabled(USHORT aDirection,unsigned long aPage) const;
        bool            BorderOverPageBorder(unsigned long aPage) const;
        bool            HasScrollbars() const;

        void            SetColors(SwPostIt* pPostIt, SwPostItField* pFld);

        Color           GetColorDark(sal_uInt16 aAuthorIndex);
        Color           GetColorLight(sal_uInt16 aAuthorIndex);
        Color           GetColorAnkor(sal_uInt16 aAuthorIndex);

        sal_Int32       GetInitialAnchorDistance() const;
        sal_Int32       GetScrollSize() const;
        sal_Int32       GetSpaceBetween() const;
        void            SetReadOnlyState();
                        DECL_LINK( CalcHdl, void*);

    protected:

    public:
            SwPostItMgr(SwView* aDoc);
            ~SwPostItMgr();

            typedef std::list< SwPostItItem* >::const_iterator const_iterator;
            const_iterator begin()  const { return mvPostItFlds.begin(); }
            const_iterator end()    const { return mvPostItFlds.end();  }

            void InsertFld( SwFmtFld* aField, bool bCheckExistance, bool bFocus);
            void RemoveFld( SfxBroadcaster* pFld );
            void Notify( SfxBroadcaster& rBC, const SfxHint& rHint );

            void LayoutPostIts();
            bool CalcRects();

            void MakeVisible(const SwPostIt* pPostIt,long aPage = -1);

            bool ShowScrollbar(const unsigned long aPage) const;
            bool HasNotes() const ;
            bool ShowNotes() const;
            unsigned long GetSidebarWidth(bool bPx = false) const;
            unsigned long GetSidebarBorderWidth(bool bPx = false) const;
            unsigned long GetNoteWidth();

            void PrepareView(bool bIgnoreCount = false);

            void CorrectPositions();

            void Sort(const short aType);

            void SetLayout() { mbLayout = true; };
            void Delete(String aAuthor);
            void Delete();

            void Hide( SwPostItField* pPostItField );
            void Hide( const String& rAuthor );
            void Hide();
            void Show();

            void Rescale();

            Rectangle GetBottomScrollRect(const unsigned long aPage) const;
            Rectangle GetTopScrollRect(const unsigned long aPage) const;

            bool IsHit(const Point &aPointPixel);
            Color GetArrowColor(USHORT aDirection,unsigned long aPage) const;

            SwPostIt* GetNextPostIt(USHORT aDirection, SwPostIt* aPostIt);
            long GetNextBorder();
            SwPostIt* GetActivePostIt() { return mpActivePostIt; }
            void      SetActivePostIt( SwPostIt* p);
            sal_Int32 GetMinimumSizeWithMeta() const;
            sal_Int32 GetSidebarScrollerHeight() const;

            SwFmtFld* GetFmtFld(SwPostIt* mpPostIt) const;
            SwPostIt* GetPostIt(const SwFmtFld* pFld) const;
            SwPostIt* GetPostIt(const SwPostItField* pFld) const;
            SwPostIt* GetPostIt(SwFmtFld* pFld) const;
            SwPostIt* GetPostIt(SwPostItField* pFld) const;

            void SetShadowState(const SwPostItField* pFld,bool bCursor = true);

            void SetSpellChecking();

            bool ShowPreview(const SwField* pFld,SwFmtFld*& pFmtFld) const;
};

#endif
<|endoftext|>


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

#ifndef _POSTITMGR_HXX
#define _POSTITMGR_HXX

#ifndef _SFXLSTNER_HXX
#include <svtools/lstner.hxx>
#endif

#include <list>
#include <vector>

#include <tools/link.hxx>
#include <swrect.hxx>

class SwWrtShell;
class SwDoc;
class SwView;
class SwPostItField;
class SwFmtFld;
class SfxBroadcaster;
class SfxHint;
class SwPostIt;
class SwEditWin;
class Color;

#define SORT_POS    1
#define SORT_AUTHOR 2
#define SORT_DATE   3

#define COL_NOTES_SIDEPANE_ARROW_ENABLED    RGB_COLORDATA(0,0,0)
#define COL_NOTES_SIDEPANE_ARROW_DISABLED   RGB_COLORDATA(172,168,153)

struct SwPostItItem
{
    bool bShow;
    bool bFocus;
    SwFmtFld* pFmtFld;
    SwPostIt* pPostIt;
    SwRect mPos;
    SwRect mFramePos;
    SwRect mPagePos;
    SwPostItItem( SwFmtFld* p, bool aShow, bool aFocus)
        : bShow(aShow),
        bFocus(aFocus),
        pFmtFld(p),
        pPostIt(0)
    {
    }
};

typedef std::list<SwPostItItem*> SwPostItItem_list;

struct SwPostItPageItem
{
    bool bScrollbar;
    bool bMarginSide;
    long lOffset;
    SwRect mPageRect;
    SwPostItItem_list* mList;
    SwPostItPageItem(): bScrollbar(false),lOffset(0)
    {
        mList = new SwPostItItem_list;
    }
    ~SwPostItPageItem()
    {
        mList->clear();
        delete mList;
    }

};

class SwPostItMgr: public SfxListener
{
    private:
        SwView*                         mpView;
        SwWrtShell*                     mpWrtShell;
        SwEditWin*                      mpEditWin;
        std::list< SwPostItItem*>       mvPostItFlds;
        std::vector<SwPostItPageItem*>  mPages;
        ULONG                           mnEventId;
        bool                            mbWaitingForCalcRects;
        SwPostIt*                       mpActivePostIt;
        bool                            mbLayout;
        long                            mbLayoutHeight;
        long                            mbLayouting;
        bool                            mbDeletingSeveral;

        typedef std::list<SwPostItItem*>::iterator  SwPostItItem_iterator;
        typedef std::list<SwPostIt*>::iterator      SwPostIt_iterator;

        void            AddPostIts(bool bCheckExistance = true,bool bFocus = true);
        void            RemovePostIts();
        void            PreparePageContainer();
        void            Scroll(const long lScroll,const unsigned long aPage );
        void            AutoScroll(const SwPostIt* pPostIt,const unsigned long aPage );
        bool            ScrollbarHit(const unsigned long aPage,const Point &aPoint);
        bool            LayoutByPage(std::list<SwPostIt*> &aVisiblePostItList,const Rectangle aBorder,long lNeededHeight);
        void            CheckForRemovedPostIts();
        bool            ArrowEnabled(USHORT aDirection,unsigned long aPage);
        bool            BorderOverPageBorder(unsigned long aPage);
        bool            HasScrollbars();
        sal_Int32       GetInitialAnchorDistance();
        sal_Int32       GetScrollSize();
        sal_Int32       GetSpaceBetween();
        void            SetReadOnlyState();
                        DECL_LINK( CalcHdl, void*);

    protected:

    public:
            SwPostItMgr(SwView* aDoc);
            ~SwPostItMgr();

            typedef std::list< SwPostItItem* >::const_iterator const_iterator;
            const_iterator begin()  const { return mvPostItFlds.begin(); }
            const_iterator end()    const { return mvPostItFlds.end();  }

            void InsertFld( SwFmtFld* aField, bool bCheckExistance, bool bFocus);
            void RemoveFld( SfxBroadcaster* pFld );
            void Notify( SfxBroadcaster& rBC, const SfxHint& rHint );

            void LayoutPostIts();
            bool CalcRects();

            void AutoScroll(const SwPostIt* pPostIt);
            bool ShowScrollbar(const unsigned long aPage);
            bool HasNotes();
            bool ShowNotes();
            unsigned long GetSidebarWidth(bool bPx = false);
            unsigned long GetSidebarBorderWidth(bool bPx = false);
            unsigned long GetNoteWidth();

            void PrepareView(bool bIgnoreCount = false);

            void CorrectPositions();
            void SetColors(SwPostIt* pPostIt, SwPostItField* pFld);

            void Sort(const short aType);

            void SetLayout() { mbLayout = true; };
            void Delete(String aAuthor);
            void Delete();

            void Hide(SwPostItField* aPostItField, bool All = false);
            void Hide();
            void Show();

            void Rescale();

            Rectangle GetBottomScrollRect(const unsigned long aPage);
            Rectangle GetTopScrollRect(const unsigned long aPage);

            bool IsHit(const Point &aPointPixel);
            Color GetArrowColor(USHORT aDirection,unsigned long aPage);

            SwPostIt* GetNextPostIt(USHORT aDirection, SwPostIt* aPostIt);
            long GetNextBorder();
            SwFmtFld* GetFmtFld(SwPostIt* mpPostIt);
            SwPostIt* GetActivePostIt() { return mpActivePostIt; }
            void      SetActivePostIt( SwPostIt* p);
            sal_Int32 GetMinimumSizeWithMeta();
            sal_Int32 GetSidebarScrollerHeight();

            void SetSpellChecking(bool bEnable);
};

#endif

<commit_msg>INTEGRATION: CWS pages01_DEV300 (1.2.4); FILE MERGED 2008/02/26 10:15:00 fme 1.2.4.1: #i1598# Multiple page view - sync with new notes feature<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: PostItMgr.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: kz $ $Date: 2008-03-07 14:48:41 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _POSTITMGR_HXX
#define _POSTITMGR_HXX

#ifndef _SFXLSTNER_HXX
#include <svtools/lstner.hxx>
#endif

#include <list>
#include <vector>

#include <tools/link.hxx>
#include <swrect.hxx>

class SwWrtShell;
class SwDoc;
class SwView;
class SwPostItField;
class SwFmtFld;
class SfxBroadcaster;
class SfxHint;
class SwPostIt;
class SwEditWin;
class Color;

#define SORT_POS    1
#define SORT_AUTHOR 2
#define SORT_DATE   3

#define COL_NOTES_SIDEPANE_ARROW_ENABLED    RGB_COLORDATA(0,0,0)
#define COL_NOTES_SIDEPANE_ARROW_DISABLED   RGB_COLORDATA(172,168,153)

struct SwPostItItem
{
    bool bShow;
    bool bFocus;
    SwFmtFld* pFmtFld;
    SwPostIt* pPostIt;
    SwRect mPos;
    SwRect mFramePos;
    SwRect mPagePos;
    SwPostItItem( SwFmtFld* p, bool aShow, bool aFocus)
        : bShow(aShow),
        bFocus(aFocus),
        pFmtFld(p),
        pPostIt(0)
    {
    }
};

typedef std::list<SwPostItItem*> SwPostItItem_list;

struct SwPostItPageItem
{
    bool bScrollbar;
    bool bMarginSide;
    long lOffset;
    SwRect mPageRect;
    SwPostItItem_list* mList;
    SwPostItPageItem(): bScrollbar(false),lOffset(0)
    {
        mList = new SwPostItItem_list;
    }
    ~SwPostItPageItem()
    {
        mList->clear();
        delete mList;
    }

};

class SwPostItMgr: public SfxListener
{
    private:
        SwView*                         mpView;
        SwWrtShell*                     mpWrtShell;
        SwEditWin*                      mpEditWin;
        std::list< SwPostItItem*>       mvPostItFlds;
        std::vector<SwPostItPageItem*>  mPages;
        ULONG                           mnEventId;
        bool                            mbWaitingForCalcRects;
        SwPostIt*                       mpActivePostIt;
        bool                            mbLayout;
        long                            mbLayoutHeight;
        long                            mbLayouting;
        bool                            mbDeletingSeveral;

        typedef std::list<SwPostItItem*>::iterator  SwPostItItem_iterator;
        typedef std::list<SwPostIt*>::iterator      SwPostIt_iterator;

        void            AddPostIts(bool bCheckExistance = true,bool bFocus = true);
        void            RemovePostIts();
        void            PreparePageContainer();
        void            Scroll(const long lScroll,const unsigned long aPage );
        void            AutoScroll(const SwPostIt* pPostIt,const unsigned long aPage );
        bool            ScrollbarHit(const unsigned long aPage,const Point &aPoint);
        bool            LayoutByPage(std::list<SwPostIt*> &aVisiblePostItList,const Rectangle aBorder,long lNeededHeight);
        void            CheckForRemovedPostIts();
        bool            ArrowEnabled(USHORT aDirection,unsigned long aPage) const;
        bool            BorderOverPageBorder(unsigned long aPage) const;
        bool            HasScrollbars() const;
        sal_Int32       GetInitialAnchorDistance() const;
        sal_Int32       GetScrollSize() const;
        sal_Int32       GetSpaceBetween() const;
        void            SetReadOnlyState();
                        DECL_LINK( CalcHdl, void*);

    protected:

    public:
            SwPostItMgr(SwView* aDoc);
            ~SwPostItMgr();

            typedef std::list< SwPostItItem* >::const_iterator const_iterator;
            const_iterator begin()  const { return mvPostItFlds.begin(); }
            const_iterator end()    const { return mvPostItFlds.end();  }

            void InsertFld( SwFmtFld* aField, bool bCheckExistance, bool bFocus);
            void RemoveFld( SfxBroadcaster* pFld );
            void Notify( SfxBroadcaster& rBC, const SfxHint& rHint );

            void LayoutPostIts();
            bool CalcRects();

            void AutoScroll(const SwPostIt* pPostIt);
            bool ShowScrollbar(const unsigned long aPage) const;
            bool HasNotes() const ;
            bool ShowNotes() const;
            unsigned long GetSidebarWidth(bool bPx = false) const;
            unsigned long GetSidebarBorderWidth(bool bPx = false) const;
            unsigned long GetNoteWidth();

            void PrepareView(bool bIgnoreCount = false);

            void CorrectPositions();
            void SetColors(SwPostIt* pPostIt, SwPostItField* pFld);

            void Sort(const short aType);

            void SetLayout() { mbLayout = true; };
            void Delete(String aAuthor);
            void Delete();

            void Hide(SwPostItField* aPostItField, bool All = false);
            void Hide();
            void Show();

            void Rescale();

            Rectangle GetBottomScrollRect(const unsigned long aPage) const;
            Rectangle GetTopScrollRect(const unsigned long aPage) const;

            bool IsHit(const Point &aPointPixel);
            Color GetArrowColor(USHORT aDirection,unsigned long aPage) const;

            SwPostIt* GetNextPostIt(USHORT aDirection, SwPostIt* aPostIt);
            long GetNextBorder();
            SwFmtFld* GetFmtFld(SwPostIt* mpPostIt);
            SwPostIt* GetActivePostIt() { return mpActivePostIt; }
            void      SetActivePostIt( SwPostIt* p);
            sal_Int32 GetMinimumSizeWithMeta() const;
            sal_Int32 GetSidebarScrollerHeight() const;

            void SetSpellChecking(bool bEnable);
};

#endif

<|endoftext|>