<commit_before>/**
 *
 *  Copyright 2007-2013 IMP Inventors. All rights reserved.
 *
 */
#include "rmfplugin.h"
#include <RMF/exceptions.h>

namespace {

void close_rmf_read(void *mydata) {
  Data *data = reinterpret_cast<Data *>(mydata);
  delete data;
}

void *open_rmf_read(const char *filename, const char *, int *natoms) {
  RMF_TRACE("open_rmf_read");
  try {
    return new Data(filename, natoms);
  }
  catch (std::exception &e) {
    std::cerr << "Caught exception: " << e.what() << std::endl;
    *natoms = MOLFILE_NUMATOMS_NONE;
    return NULL;
  }
}

int read_rmf_structure(void *mydata, int *optflags, molfile_atom_t *atoms) {
  RMF_TRACE("read_rmf_structure");
  try {
    Data *data = reinterpret_cast<Data *>(mydata);
    return data->read_structure(optflags, atoms);
  }
  catch (const std::exception &e) {
    std::cerr << "Caught exception: " << e.what() << std::endl;
    return VMDPLUGIN_ERROR;
  }
}

int read_rmf_timestep(void *mydata, int natoms, molfile_timestep_t *frame) {
  RMF_TRACE("Begin read_rmf_timestep: " << natoms);
  try {
    Data *data = reinterpret_cast<Data *>(mydata);
    return data->read_timestep(frame);
  }
  catch (const std::exception &e) {
    std::cerr << "Caught exception: " << e.what() << std::endl;
    return VMDPLUGIN_ERROR;
  }
}

int read_rmf_bonds(void *mydata, int *nbonds, int **fromptr, int **toptr,
                   float **bondorderptr, int **bondtype, int *nbondtypes,
                   char ***bondtypename) {
  RMF_TRACE("Begin read_rmf_bonds");
  try {
    Data *data = reinterpret_cast<Data *>(mydata);
    return data->read_bonds(nbonds, fromptr, toptr, bondorderptr, bondtype,
                            nbondtypes, bondtypename);
  }
  catch (const std::exception &e) {
    std::cerr << "Caught exception: " << e.what() << std::endl;
    return VMDPLUGIN_ERROR;
  }
}

int read_rmf_graphics(void *mydata, int *nelem,
                      const molfile_graphics_t **gdata) {
  RMF_TRACE("read_rmf_graphics");
  try {
    Data *data = reinterpret_cast<Data *>(mydata);
    return data->read_graphics(nelem, gdata);
  }
  catch (const std::exception &e) {
    std::cerr << "Caught exception: " << e.what() << std::endl;
    return VMDPLUGIN_ERROR;
  }
}
int read_rmf_timestep_metadata(void *mydata,
                               molfile_timestep_metadata_t *tdata) {
  RMF_TRACE("read_rmf_timestep_metadata");
  try {
    Data *data = reinterpret_cast<Data *>(mydata);
    return data->read_timestep_metadata(tdata);
  }
  catch (const std::exception &e) {
    std::cerr << e.what() << std::endl;
    return VMDPLUGIN_ERROR;
  }
}

void init_plugin(molfile_plugin_t &plugin) {
  memset(&plugin, 0, sizeof(molfile_plugin_t));
  plugin.abiversion = vmdplugin_ABIVERSION;
  plugin.type = MOLFILE_PLUGIN_TYPE;
  plugin.name = "rmf";
  plugin.prettyname = "RMF";
  plugin.author = "Daniel Russel";
  plugin.majorv = 0;
  plugin.minorv = 9;
  // try this
  plugin.is_reentrant = VMDPLUGIN_THREADSAFE;
  plugin.open_file_read = open_rmf_read;
  plugin.read_structure = read_rmf_structure;
  plugin.read_bonds = read_rmf_bonds;
  plugin.read_rawgraphics = read_rmf_graphics;
  plugin.close_file_read = close_rmf_read;
  plugin.read_timestep_metadata = read_rmf_timestep_metadata;
  plugin.read_next_timestep = read_rmf_timestep;
}

void init_plugins() {
  init_plugin(plugin);
  plugin.name = "rmf";
  plugin.prettyname = "RMF";
  plugin.filename_extension = "rmf";
  init_plugin(plugin3);
  plugin3.name = "rmf3";
  plugin3.prettyname = "RMF3";
  plugin3.filename_extension = "rmf3";
  init_plugin(pluginz);
  pluginz.name = "rmfz";
  pluginz.prettyname = "RMFz";
  pluginz.filename_extension = "rmfz";
  // init_plugin(pluginrestraints);
  // pluginrestraints.name = "rmf-with-restraints";
  // pluginrestraints.prettyname = "RMF with restraints";
  // pluginrestraints.filename_extension = "rmf-with-restraints";
  // pluginrestraints.read_bonds = read_rmf_bonds_and_restraints;
}
}

VMDPLUGIN_API int VMDPLUGIN_init() {
  init_plugins();
  RMF::set_log_level("trace");
  return VMDPLUGIN_SUCCESS;
}
VMDPLUGIN_API int VMDPLUGIN_register(void *v, vmdplugin_register_cb cb) {
  std::cout << "Register" << std::endl;
  (*cb)(v, (vmdplugin_t *)&plugin);
  (*cb)(v, (vmdplugin_t *)&plugin3);
  (*cb)(v, (vmdplugin_t *)&pluginz);
  return 0;
}
VMDPLUGIN_API int VMDPLUGIN_fini() {
  std::cout << "Fini" << std::endl;
  return VMDPLUGIN_SUCCESS;
}
<commit_msg>use boost lamba to unify catch code<commit_after>/**
 *
 *  Copyright 2007-2013 IMP Inventors. All rights reserved.
 *
 */
#include "rmfplugin.h"
#include <RMF/exceptions.h>
#include <boost/bind.hpp>
#include <boost/lambda/construct.hpp>

namespace {

template <class M>
int catch_exceptions(std::string name, void *mydata, M m) {
  RMF_TRACE(name);
  try {
    Data *data = reinterpret_cast<Data *>(mydata);
    return m(data);
  }
  catch (std::exception &e) {
    std::cerr << "Caught exception: " << e.what() << std::endl;
    return VMDPLUGIN_ERROR;
  }
}

void close_rmf_read(void *mydata) {
  Data *data = reinterpret_cast<Data *>(mydata);
  delete data;
}

void *open_rmf_read(const char *filename, const char *, int *natoms) {
  RMF_TRACE("open rmf file");
  try {
    return new Data(filename, natoms);
  }
  catch (std::exception &e) {
    std::cerr << "Caught exception: " << e.what() << std::endl;
    *natoms = MOLFILE_NUMATOMS_NONE;
    return NULL;
  }
}

int read_rmf_structure(void *mydata, int *optflags, molfile_atom_t *atoms) {
  return catch_exceptions(
      "read rmf structure", mydata,
      boost::bind(&Data::read_structure, _1, optflags, atoms));
}

int read_rmf_timestep(void *mydata, int, molfile_timestep_t *frame) {
  return catch_exceptions("read rmf timestep", mydata,
                          boost::bind(&Data::read_timestep, _1, frame));
}

int read_rmf_bonds(void *mydata, int *nbonds, int **fromptr, int **toptr,
                   float **bondorderptr, int **bondtype, int *nbondtypes,
                   char ***bondtypename) {
  return catch_exceptions(
      "read rmf bonds", mydata,
      boost::bind(&Data::read_bonds, _1, nbonds, fromptr, toptr, bondorderptr,
                  bondtype, nbondtypes, bondtypename));
}

int read_rmf_graphics(void *mydata, int *nelem,
                      const molfile_graphics_t **gdata) {
  return catch_exceptions("read rmf graphics", mydata,
                          boost::bind(&Data::read_graphics, _1, nelem, gdata));
}
int read_rmf_timestep_metadata(void *mydata,
                               molfile_timestep_metadata_t *tdata) {
  return catch_exceptions(
      "read rmf timestep metadata", mydata,
      boost::bind(&Data::read_timestep_metadata, _1, tdata));
}

void init_plugin(molfile_plugin_t &plugin) {
  memset(&plugin, 0, sizeof(molfile_plugin_t));
  plugin.abiversion = vmdplugin_ABIVERSION;
  plugin.type = MOLFILE_PLUGIN_TYPE;
  plugin.name = "rmf";
  plugin.prettyname = "RMF";
  plugin.author = "Daniel Russel";
  plugin.majorv = 0;
  plugin.minorv = 9;
  plugin.is_reentrant = VMDPLUGIN_THREADSAFE;
  plugin.open_file_read = open_rmf_read;
  plugin.read_structure = read_rmf_structure;
  plugin.read_bonds = read_rmf_bonds;
  plugin.read_rawgraphics = read_rmf_graphics;
  plugin.close_file_read = close_rmf_read;
  plugin.read_timestep_metadata = read_rmf_timestep_metadata;
  plugin.read_next_timestep = read_rmf_timestep;
}

void init_plugins() {
  init_plugin(plugin);
  plugin.name = "rmf";
  plugin.prettyname = "RMF";
  plugin.filename_extension = "rmf";
  init_plugin(plugin3);
  plugin3.name = "rmf3";
  plugin3.prettyname = "RMF3";
  plugin3.filename_extension = "rmf3";
  init_plugin(pluginz);
  pluginz.name = "rmfz";
  pluginz.prettyname = "RMFz";
  pluginz.filename_extension = "rmfz";
}
}

VMDPLUGIN_API int VMDPLUGIN_init() {
  init_plugins();
  RMF::set_log_level("trace");
  return VMDPLUGIN_SUCCESS;
}
VMDPLUGIN_API int VMDPLUGIN_register(void *v, vmdplugin_register_cb cb) {
  std::cout << "Register" << std::endl;
  (*cb)(v, (vmdplugin_t *)&plugin);
  (*cb)(v, (vmdplugin_t *)&plugin3);
  (*cb)(v, (vmdplugin_t *)&pluginz);
  return 0;
}
VMDPLUGIN_API int VMDPLUGIN_fini() {
  std::cout << "Fini" << std::endl;
  return VMDPLUGIN_SUCCESS;
}
<|endoftext|>


<commit_before>#ifndef AMGCL_SOLVER_BICGSTABL_HPP
#define AMGCL_SOLVER_BICGSTABL_HPP

/*
The MIT License

Copyright (c) 2012-2017 Denis Demidov <dennis.demidov@gmail.com>

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

/**
 * \file   amgcl/solver/bicgstabl.hpp
 * \author Denis Demidov <dennis.demidov@gmail.com>
 * \brief  BiCGStab(L) iterative method.
 */

#include <boost/tuple/tuple.hpp>
#include <boost/multi_array.hpp>

#include <amgcl/backend/interface.hpp>
#include <amgcl/solver/detail/default_inner_product.hpp>
#include <amgcl/util.hpp>

namespace amgcl {
namespace solver {

/** BiCGStab(L) method.
 * \rst
 * Generalization of BiCGStab method [SlDi93]_.
 * \endrst
 */
template <
    class Backend,
    class InnerProduct = detail::default_inner_product
    >
class bicgstabl {
    public:
        typedef Backend backend_type;

        typedef typename Backend::vector     vector;
        typedef typename Backend::value_type value_type;
        typedef typename Backend::params     backend_params;

        typedef typename math::scalar_of<value_type>::type scalar_type;

        typedef typename math::inner_product_impl<
            typename math::rhs_of<value_type>::type
            >::return_type coef_type;

        /// Solver parameters.
        struct params {
            /// Order of the method.
            int L;

            /// Maximum number of iterations.
            size_t maxiter;

            /// Target relative residual error.
            scalar_type tol;

            /// Target absolute residual error.
            scalar_type abstol;

            params(int L = 2, size_t maxiter = 100, scalar_type tol = 1e-8)
                : L(L), maxiter(maxiter), tol(tol),
                  abstol(std::numeric_limits<scalar_type>::min())
            {
                precondition(L > 0, "L in BiCGStab(L) should be >=1");
            }

            params(const boost::property_tree::ptree &p)
                : AMGCL_PARAMS_IMPORT_VALUE(p, L),
                  AMGCL_PARAMS_IMPORT_VALUE(p, maxiter),
                  AMGCL_PARAMS_IMPORT_VALUE(p, tol),
                  AMGCL_PARAMS_IMPORT_VALUE(p, abstol)
            {
                AMGCL_PARAMS_CHECK(p, (L)(maxiter)(tol)(abstol));
            }

            void get(boost::property_tree::ptree &p, const std::string &path) const {
                AMGCL_PARAMS_EXPORT_VALUE(p, path, L);
                AMGCL_PARAMS_EXPORT_VALUE(p, path, maxiter);
                AMGCL_PARAMS_EXPORT_VALUE(p, path, tol);
                AMGCL_PARAMS_EXPORT_VALUE(p, path, abstol);
            }
        };

        /// Preallocates necessary data structures for the system of size \p n.
        bicgstabl(
                size_t n,
                const params &prm = params(),
                const backend_params &backend_prm = backend_params(),
                const InnerProduct &inner_product = InnerProduct()
                )
            : prm(prm), n(n),
              r0( Backend::create_vector(n, backend_prm) ),
              q ( Backend::create_vector(n, backend_prm) ),
              r(prm.L + 1), u(prm.L + 1),
              tau(boost::extents[prm.L][prm.L]),
              sigma(prm.L), gamma(prm.L), gamma1(prm.L), gamma2(prm.L),
              inner_product(inner_product)
        {
            for(int i = 0; i <= prm.L; ++i) {
                r[i] = Backend::create_vector(n, backend_prm);
                u[i] = Backend::create_vector(n, backend_prm);
            }
        }

        /* Computes the solution for the given system matrix \p A and the
         * right-hand side \p rhs.  Returns the number of iterations made and
         * the achieved residual as a ``boost::tuple``. The solution vector
         * \p x provides initial approximation in input and holds the computed
         * solution on output.
         *
         * The system matrix may differ from the matrix used during
         * initialization. This may be used for the solution of non-stationary
         * problems with slowly changing coefficients. There is a strong chance
         * that a preconditioner built for a time step will act as a reasonably
         * good preconditioner for several subsequent time steps [DeSh12]_.
         */
        template <class Matrix, class Precond, class Vec1, class Vec2>
        boost::tuple<size_t, scalar_type> operator()(
                Matrix  const &A,
                Precond const &P,
                Vec1    const &rhs,
#ifdef BOOST_NO_CXX11_RVALUE_REFERENCES
                Vec2          &x
#else
                Vec2          &&x
#endif
                ) const
        {
            static const coef_type one  = math::identity<coef_type>();
            static const coef_type zero = math::zero<coef_type>();

            const int L = prm.L;

            backend::residual(rhs, A, x, *r0);

            scalar_type norm_rhs = norm(rhs);
            if (norm_rhs < amgcl::detail::eps<scalar_type>(n)) {
                backend::clear(x);
                return boost::make_tuple(0, norm_rhs);
            }

            scalar_type res_norm = norm(*r0);
            scalar_type eps      = std::max(prm.tol * norm_rhs, prm.abstol);

            if(res_norm < eps)
                return boost::make_tuple(0, res_norm / norm_rhs);

            backend::copy(*r0, *r[0]);
            backend::clear( *u[0] );
            coef_type rho0 = one, alpha = zero, omega = one;

            size_t iter = 0;

            for(; res_norm > eps && iter < prm.maxiter; iter += prm.L) {
                rho0 = -omega * rho0;

                // Bi-CG part
                for(int j = 0; j < L; ++j) {
                    precondition(!math::is_zero(rho0), "Zero rho in BiCGStab(L)");

                    coef_type rho1 = inner_product(*r[j], *r0);
                    coef_type beta = alpha * rho1 / rho0;
                    rho0 = rho1;

                    for(int i = 0; i <= j; ++i)
                        backend::axpby(one, *r[i], -beta, *u[i]);

                    P.apply(*u[j], *q);
                    backend::spmv(one, A, *q, zero, *u[j+1]);

                    alpha = inner_product(*u[j+1], *r0);

                    if (math::is_zero(alpha)) break;

                    alpha = rho0 / alpha;

                    for(int i = 0; i <= j; ++i)
                        backend::axpby(-alpha, *u[i+1], one, *r[i]);

                    backend::axpby(alpha, *u[0], one, x);

                    res_norm = norm(*r[j]);
                    if (res_norm <= eps) goto done;

                    P.apply(*r[j], *q);
                    backend::spmv(one, A, *q, zero, *r[j+1]);
                }

                // MR part
                for(int j = 0; j < L; ++j) {
                    for(int i = 0; i < j; ++i) {
                        tau[i][j] = inner_product(*r[j+1], *r[i+1]) / sigma[i];
                        backend::axpby(-tau[i][j], *r[i+1], one, *r[j+1]);
                    }
                    sigma[j] = inner_product(*r[j+1], *r[j+1]);
                    gamma1[j] = inner_product(*r[0], *r[j+1]) / sigma[j];
                }

                omega = gamma[L-1] = gamma1[L-1];
                for(int j = L-2; j >= 0; --j) {
                    gamma[j] = gamma1[j];
                    for(int i = j+1; i < L; ++i)
                        gamma[j] -= tau[j][i] * gamma[i];
                }

                for(int j = 0; j < L-1; ++j) {
                    gamma2[j] = gamma[j+1];
                    for(int i = j+1; i < L-1; ++i)
                        gamma2[j] += tau[j][i] * gamma[i+1];
                }

                // Update
                backend::axpby(gamma[0], *r[0], one, x);
                backend::axpby(-gamma1[L-1], *r[L], one, *r[0]);
                backend::axpby(-gamma[L-1], *u[L], one, *u[0]);

                for(int j = 1; j < L; ++j) {
                    backend::axpby(-gamma[j-1], *u[j], one, *u[0]);
                    backend::axpby(gamma2[j-1], *r[j], one, x);
                    backend::axpby(-gamma1[j-1], *r[j], one, *r[0]);
                }

                res_norm = norm(*r[0]);
            }

done:
            P.apply(x, *q);
            backend::copy(*q, x);
            backend::residual(rhs, A, x, *r0);
            res_norm = norm(*r0);

            return boost::make_tuple(iter, res_norm / norm_rhs);
        }

        /* Computes the solution for the given right-hand side \p rhs. The
         * system matrix is the same that was used for the setup of the
         * preconditioner \p P.  Returns the number of iterations made and the
         * achieved residual as a ``boost::tuple``. The solution vector \p x
         * provides initial approximation in input and holds the computed
         * solution on output.
         */
        template <class Precond, class Vec1, class Vec2>
        boost::tuple<size_t, scalar_type> operator()(
                Precond const &P,
                Vec1    const &rhs,
#ifdef BOOST_NO_CXX11_RVALUE_REFERENCES
                Vec2          &x
#else
                Vec2          &&x
#endif
                ) const
        {
            return (*this)(P.system_matrix(), P, rhs, x);
        }

        friend std::ostream& operator<<(std::ostream &os, const bicgstabl &s) {
            return os << "bicgstab(" << s.prm.L << "): " << s.n << " unknowns";
        }
    public:
        params prm;

    private:
        size_t n;

        mutable boost::shared_ptr< vector > r0;
        mutable boost::shared_ptr< vector > q;

        mutable std::vector< boost::shared_ptr< vector > > r;
        mutable std::vector< boost::shared_ptr< vector > > u;

        mutable boost::multi_array<coef_type, 2> tau;
        mutable std::vector<coef_type> sigma;
        mutable std::vector<coef_type> gamma, gamma1, gamma2;

        InnerProduct inner_product;

        template <class Vec>
        scalar_type norm(const Vec &x) const {
            return sqrt(math::norm(inner_product(x, x)));
        }
};

} // namespace solver
} // namespace amgcl

#endif
<commit_msg>Support non-zero initial condition in BiCGStab(L)<commit_after>#ifndef AMGCL_SOLVER_BICGSTABL_HPP
#define AMGCL_SOLVER_BICGSTABL_HPP

/*
The MIT License

Copyright (c) 2012-2017 Denis Demidov <dennis.demidov@gmail.com>

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

/**
 * \file   amgcl/solver/bicgstabl.hpp
 * \author Denis Demidov <dennis.demidov@gmail.com>
 * \brief  BiCGStab(L) iterative method.
 */

#include <boost/tuple/tuple.hpp>
#include <boost/multi_array.hpp>

#include <amgcl/backend/interface.hpp>
#include <amgcl/solver/detail/default_inner_product.hpp>
#include <amgcl/util.hpp>

namespace amgcl {
namespace solver {

/** BiCGStab(L) method.
 * \rst
 * Generalization of BiCGStab method [SlDi93]_.
 * \endrst
 */
template <
    class Backend,
    class InnerProduct = detail::default_inner_product
    >
class bicgstabl {
    public:
        typedef Backend backend_type;

        typedef typename Backend::vector     vector;
        typedef typename Backend::value_type value_type;
        typedef typename Backend::params     backend_params;

        typedef typename math::scalar_of<value_type>::type scalar_type;

        typedef typename math::inner_product_impl<
            typename math::rhs_of<value_type>::type
            >::return_type coef_type;

        /// Solver parameters.
        struct params {
            /// Order of the method.
            int L;

            /// Maximum number of iterations.
            size_t maxiter;

            /// Target relative residual error.
            scalar_type tol;

            /// Target absolute residual error.
            scalar_type abstol;

            params(int L = 2, size_t maxiter = 100, scalar_type tol = 1e-8)
                : L(L), maxiter(maxiter), tol(tol),
                  abstol(std::numeric_limits<scalar_type>::min())
            {
                precondition(L > 0, "L in BiCGStab(L) should be >=1");
            }

            params(const boost::property_tree::ptree &p)
                : AMGCL_PARAMS_IMPORT_VALUE(p, L),
                  AMGCL_PARAMS_IMPORT_VALUE(p, maxiter),
                  AMGCL_PARAMS_IMPORT_VALUE(p, tol),
                  AMGCL_PARAMS_IMPORT_VALUE(p, abstol)
            {
                AMGCL_PARAMS_CHECK(p, (L)(maxiter)(tol)(abstol));
            }

            void get(boost::property_tree::ptree &p, const std::string &path) const {
                AMGCL_PARAMS_EXPORT_VALUE(p, path, L);
                AMGCL_PARAMS_EXPORT_VALUE(p, path, maxiter);
                AMGCL_PARAMS_EXPORT_VALUE(p, path, tol);
                AMGCL_PARAMS_EXPORT_VALUE(p, path, abstol);
            }
        };

        /// Preallocates necessary data structures for the system of size \p n.
        bicgstabl(
                size_t n,
                const params &prm = params(),
                const backend_params &backend_prm = backend_params(),
                const InnerProduct &inner_product = InnerProduct()
                )
            : prm(prm), n(n),
              r0( Backend::create_vector(n, backend_prm) ),
              x0( Backend::create_vector(n, backend_prm) ),
              q ( Backend::create_vector(n, backend_prm) ),
              r(prm.L + 1), u(prm.L + 1),
              tau(boost::extents[prm.L][prm.L]),
              sigma(prm.L), gamma(prm.L), gamma1(prm.L), gamma2(prm.L),
              inner_product(inner_product)
        {
            for(int i = 0; i <= prm.L; ++i) {
                r[i] = Backend::create_vector(n, backend_prm);
                u[i] = Backend::create_vector(n, backend_prm);
            }
        }

        /* Computes the solution for the given system matrix \p A and the
         * right-hand side \p rhs.  Returns the number of iterations made and
         * the achieved residual as a ``boost::tuple``. The solution vector
         * \p x provides initial approximation in input and holds the computed
         * solution on output.
         *
         * The system matrix may differ from the matrix used during
         * initialization. This may be used for the solution of non-stationary
         * problems with slowly changing coefficients. There is a strong chance
         * that a preconditioner built for a time step will act as a reasonably
         * good preconditioner for several subsequent time steps [DeSh12]_.
         */
        template <class Matrix, class Precond, class Vec1, class Vec2>
        boost::tuple<size_t, scalar_type> operator()(
                Matrix  const &A,
                Precond const &P,
                Vec1    const &rhs,
#ifdef BOOST_NO_CXX11_RVALUE_REFERENCES
                Vec2          &x
#else
                Vec2          &&x
#endif
                ) const
        {
            static const coef_type one  = math::identity<coef_type>();
            static const coef_type zero = math::zero<coef_type>();

            const int L = prm.L;

            scalar_type norm_rhs = norm(rhs);
            if (norm_rhs < amgcl::detail::eps<scalar_type>(n)) {
                backend::clear(x);
                return boost::make_tuple(0, norm_rhs);
            }

            backend::residual(rhs, A, x, *r0);

            scalar_type res_norm = norm(*r0);
            scalar_type eps      = std::max(prm.tol * norm_rhs, prm.abstol);

            if(res_norm < eps)
                return boost::make_tuple(0, res_norm / norm_rhs);

            backend::copy(*r0, *r[0]);
            backend::clear(*u[0]);
            backend::clear(*x0);
            coef_type rho0 = one, alpha = zero, omega = one;

            size_t iter = 0;

            for(; res_norm > eps && iter < prm.maxiter; iter += prm.L) {
                rho0 = -omega * rho0;

                // Bi-CG part
                for(int j = 0; j < L; ++j) {
                    precondition(!math::is_zero(rho0), "Zero rho in BiCGStab(L)");

                    coef_type rho1 = inner_product(*r[j], *r0);
                    coef_type beta = alpha * rho1 / rho0;
                    rho0 = rho1;

                    for(int i = 0; i <= j; ++i)
                        backend::axpby(one, *r[i], -beta, *u[i]);

                    P.apply(*u[j], *q);
                    backend::spmv(one, A, *q, zero, *u[j+1]);

                    alpha = inner_product(*u[j+1], *r0);

                    if (math::is_zero(alpha)) break;

                    alpha = rho0 / alpha;

                    for(int i = 0; i <= j; ++i)
                        backend::axpby(-alpha, *u[i+1], one, *r[i]);

                    backend::axpby(alpha, *u[0], one, *x0);

                    res_norm = norm(*r[j]);
                    if (res_norm <= eps) goto done;

                    P.apply(*r[j], *q);
                    backend::spmv(one, A, *q, zero, *r[j+1]);
                }

                // MR part
                for(int j = 0; j < L; ++j) {
                    for(int i = 0; i < j; ++i) {
                        tau[i][j] = inner_product(*r[j+1], *r[i+1]) / sigma[i];
                        backend::axpby(-tau[i][j], *r[i+1], one, *r[j+1]);
                    }
                    sigma[j] = inner_product(*r[j+1], *r[j+1]);
                    gamma1[j] = inner_product(*r[0], *r[j+1]) / sigma[j];
                }

                omega = gamma[L-1] = gamma1[L-1];
                for(int j = L-2; j >= 0; --j) {
                    gamma[j] = gamma1[j];
                    for(int i = j+1; i < L; ++i)
                        gamma[j] -= tau[j][i] * gamma[i];
                }

                for(int j = 0; j < L-1; ++j) {
                    gamma2[j] = gamma[j+1];
                    for(int i = j+1; i < L-1; ++i)
                        gamma2[j] += tau[j][i] * gamma[i+1];
                }

                // Update
                backend::axpby(gamma[0], *r[0], one, *x0);
                backend::axpby(-gamma1[L-1], *r[L], one, *r[0]);
                backend::axpby(-gamma[L-1], *u[L], one, *u[0]);

                for(int j = 1; j < L; ++j) {
                    backend::axpby(-gamma[j-1], *u[j], one, *u[0]);
                    backend::axpby(gamma2[j-1], *r[j], one, *x0);
                    backend::axpby(-gamma1[j-1], *r[j], one, *r[0]);
                }

                res_norm = norm(*r[0]);
            }

done:
            P.apply(*x0, *q);
            backend::axpby(one, *q, one, x);
            backend::residual(rhs, A, x, *r0);
            res_norm = norm(*r0);

            return boost::make_tuple(iter, res_norm / norm_rhs);
        }

        /* Computes the solution for the given right-hand side \p rhs. The
         * system matrix is the same that was used for the setup of the
         * preconditioner \p P.  Returns the number of iterations made and the
         * achieved residual as a ``boost::tuple``. The solution vector \p x
         * provides initial approximation in input and holds the computed
         * solution on output.
         */
        template <class Precond, class Vec1, class Vec2>
        boost::tuple<size_t, scalar_type> operator()(
                Precond const &P,
                Vec1    const &rhs,
#ifdef BOOST_NO_CXX11_RVALUE_REFERENCES
                Vec2          &x
#else
                Vec2          &&x
#endif
                ) const
        {
            return (*this)(P.system_matrix(), P, rhs, x);
        }

        friend std::ostream& operator<<(std::ostream &os, const bicgstabl &s) {
            return os << "bicgstab(" << s.prm.L << "): " << s.n << " unknowns";
        }
    public:
        params prm;

    private:
        size_t n;

        mutable boost::shared_ptr< vector > r0;
        mutable boost::shared_ptr< vector > x0;
        mutable boost::shared_ptr< vector > q;

        mutable std::vector< boost::shared_ptr< vector > > r;
        mutable std::vector< boost::shared_ptr< vector > > u;

        mutable boost::multi_array<coef_type, 2> tau;
        mutable std::vector<coef_type> sigma;
        mutable std::vector<coef_type> gamma, gamma1, gamma2;

        InnerProduct inner_product;

        template <class Vec>
        scalar_type norm(const Vec &x) const {
            return sqrt(math::norm(inner_product(x, x)));
        }
};

} // namespace solver
} // namespace amgcl

#endif
<|endoftext|>


<commit_before>// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/common/native_mate_converters/content_converter.h"

#include <string>
#include <vector>

#include "atom/browser/api/atom_api_web_contents.h"
#include "atom/browser/web_contents_permission_helper.h"
#include "atom/common/native_mate_converters/blink_converter.h"
#include "atom/common/native_mate_converters/callback.h"
#include "atom/common/native_mate_converters/gurl_converter.h"
#include "atom/common/native_mate_converters/string16_converter.h"
#include "atom/common/native_mate_converters/ui_base_types_converter.h"
#include "brave/browser/api/navigation_controller.h"
#include "brave/browser/api/navigation_handle.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/context_menu_params.h"
#include "native_mate/dictionary.h"

namespace {

void ExecuteCommand(content::WebContents* web_contents,
                    int action,
                    const content::CustomContextMenuContext& context) {
  web_contents->ExecuteCustomContextMenuCommand(action, context);
}

// Forward declaration for nested recursive call.
v8::Local<v8::Value> MenuToV8(v8::Isolate* isolate,
                              content::WebContents* web_contents,
                              const content::CustomContextMenuContext& context,
                              const std::vector<content::MenuItem>& menu);

v8::Local<v8::Value> MenuItemToV8(
    v8::Isolate* isolate,
    content::WebContents* web_contents,
    const content::CustomContextMenuContext& context,
    const content::MenuItem& item) {
  mate::Dictionary v8_item = mate::Dictionary::CreateEmpty(isolate);
  switch (item.type) {
    case content::MenuItem::CHECKABLE_OPTION:
    case content::MenuItem::GROUP:
      v8_item.Set("checked", item.checked);
    case content::MenuItem::OPTION:
    case content::MenuItem::SUBMENU:
      v8_item.Set("label", item.label);
      v8_item.Set("enabled", item.enabled);
    default:
      v8_item.Set("type", item.type);
  }
  if (item.type == content::MenuItem::SUBMENU)
    v8_item.Set("submenu",
                MenuToV8(isolate, web_contents, context, item.submenu));
  else if (item.action > 0)
    v8_item.Set("click",
                base::Bind(ExecuteCommand, web_contents, item.action, context));
  return v8_item.GetHandle();
}

v8::Local<v8::Value> MenuToV8(v8::Isolate* isolate,
                              content::WebContents* web_contents,
                              const content::CustomContextMenuContext& context,
                              const std::vector<content::MenuItem>& menu) {
  std::vector<v8::Local<v8::Value>> v8_menu;
  for (const auto& menu_item : menu)
    v8_menu.push_back(MenuItemToV8(isolate, web_contents, context, menu_item));
  return mate::ConvertToV8(isolate, v8_menu);
}

}  // namespace

namespace mate {

// static
v8::Local<v8::Value> Converter<content::MenuItem::Type>::ToV8(
    v8::Isolate* isolate, const content::MenuItem::Type& val) {
  switch (val) {
    case content::MenuItem::CHECKABLE_OPTION:
      return StringToV8(isolate, "checkbox");
    case content::MenuItem::GROUP:
      return StringToV8(isolate, "radio");
    case content::MenuItem::SEPARATOR:
      return StringToV8(isolate, "separator");
    case content::MenuItem::SUBMENU:
      return StringToV8(isolate, "submenu");
    case content::MenuItem::OPTION:
    default:
      return StringToV8(isolate, "normal");
  }
}

// static
v8::Local<v8::Value> Converter<ContextMenuParamsWithWebContents>::ToV8(
    v8::Isolate* isolate, const ContextMenuParamsWithWebContents& val) {
  const auto& params = val.first;
  mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
  dict.Set("x", params.x);
  dict.Set("y", params.y);
  dict.Set("linkURL", params.link_url);
  dict.Set("linkText", params.link_text);
  dict.Set("pageURL", params.page_url);
  dict.Set("frameURL", params.frame_url);
  dict.Set("srcURL", params.src_url);
  dict.Set("mediaType", params.media_type);
  dict.Set("mediaFlags", MediaFlagsToV8(isolate, params.media_flags));
  bool has_image_contents =
    (params.media_type == blink::WebContextMenuData::kMediaTypeImage) &&
    params.has_image_contents;
  dict.Set("hasImageContents", has_image_contents);
  dict.Set("isEditable", params.is_editable);
  dict.Set("editFlags", EditFlagsToV8(isolate, params.edit_flags));
  dict.Set("selectionText", params.selection_text);
  dict.Set("titleText", params.title_text);
  dict.Set("misspelledWord", params.misspelled_word);
  dict.Set("dictionarySuggestions", params.dictionary_suggestions);
  dict.Set("frameCharset", params.frame_charset);
  dict.Set("inputFieldType", params.input_field_type);
  dict.Set("menuSourceType",  params.source_type);
  dict.Set("properties", params.properties);

  if (params.custom_context.request_id || params.custom_context.is_pepper_menu)
    dict.Set("menu", MenuToV8(isolate, val.second, params.custom_context,
                              params.custom_items));
  return mate::ConvertToV8(isolate, dict);
}

// static
bool Converter<blink::mojom::PermissionStatus>::FromV8(
    v8::Isolate* isolate,
    v8::Local<v8::Value> val,
    blink::mojom::PermissionStatus* out) {
  bool result;
  if (!ConvertFromV8(isolate, val, &result))
    return false;

  if (result)
    *out = blink::mojom::PermissionStatus::GRANTED;
  else
    *out = blink::mojom::PermissionStatus::DENIED;

  return true;
}

// static
v8::Local<v8::Value> Converter<content::PermissionType>::ToV8(
    v8::Isolate* isolate, const content::PermissionType& val) {
  using PermissionType = atom::WebContentsPermissionHelper::PermissionType;
  switch (val) {
    case content::PermissionType::MIDI_SYSEX:
      return StringToV8(isolate, "midiSysex");
    case content::PermissionType::PUSH_MESSAGING:
      return StringToV8(isolate, "pushMessaging");
    case content::PermissionType::NOTIFICATIONS:
      return StringToV8(isolate, "notifications");
    case content::PermissionType::GEOLOCATION:
      return StringToV8(isolate, "geolocation");
    case content::PermissionType::AUDIO_CAPTURE:
    case content::PermissionType::VIDEO_CAPTURE:
      return StringToV8(isolate, "media");
    case content::PermissionType::PROTECTED_MEDIA_IDENTIFIER:
      return StringToV8(isolate, "mediaKeySystem");
    case content::PermissionType::MIDI:
      return StringToV8(isolate, "midi");
    default:
      break;
  }

  if (val == (content::PermissionType)(PermissionType::POINTER_LOCK))
    return StringToV8(isolate, "pointerLock");
  else if (val == (content::PermissionType)(PermissionType::FULLSCREEN))
    return StringToV8(isolate, "fullscreen");
  else if (val == (content::PermissionType)(PermissionType::OPEN_EXTERNAL))
    return StringToV8(isolate, "openExternal");
  else if (val == (content::PermissionType)
      (PermissionType::PROTOCOL_REGISTRATION))
    return StringToV8(isolate, "protocolRegistration");

  return StringToV8(isolate, "unknown");
}

// static
bool Converter<content::StopFindAction>::FromV8(
    v8::Isolate* isolate,
    v8::Local<v8::Value> val,
    content::StopFindAction* out) {
  std::string action;
  if (!ConvertFromV8(isolate, val, &action))
    return false;

  if (action == "clearSelection")
    *out = content::STOP_FIND_ACTION_CLEAR_SELECTION;
  else if (action == "keepSelection")
    *out = content::STOP_FIND_ACTION_KEEP_SELECTION;
  else if (action == "activateSelection")
    *out = content::STOP_FIND_ACTION_ACTIVATE_SELECTION;
  else
    return false;

  return true;
}

// static
v8::Local<v8::Value> Converter<content::WebContents*>::ToV8(
    v8::Isolate* isolate, content::WebContents* val) {
  if (!val)
    return v8::Null(isolate);
  return atom::api::WebContents::CreateFrom(isolate, val).ToV8();
}

// static
bool Converter<content::WebContents*>::FromV8(
    v8::Isolate* isolate,
    v8::Local<v8::Value> val,
    content::WebContents** out) {
  atom::api::WebContents* web_contents = nullptr;
  if (!ConvertFromV8(isolate, val, &web_contents) || !web_contents)
    return false;

  *out = web_contents->web_contents();
  return true;
}

// static
v8::Local<v8::Value> Converter<content::NavigationHandle*>::ToV8(
    v8::Isolate* isolate, content::NavigationHandle* val) {
  if (!val)
    return v8::Null(isolate);
  return brave::NavigationHandle::CreateFrom(isolate, val).ToV8();
}

// static
v8::Local<v8::Value> Converter<content::NavigationEntry*>::ToV8(
    v8::Isolate* isolate, content::NavigationEntry* val) {
  if (!val)
    return v8::Null(isolate);

  mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
  dict.Set("uniqueId", val->GetUniqueID());
  dict.Set("pageType", val->GetPageType());
  dict.Set("url", val->GetURL());
  dict.Set("referrer", val->GetReferrer().url);
  dict.Set("virtualURL", val->GetVirtualURL());
  dict.Set("title", val->GetTitle());
  dict.Set("displayTitle", val->GetTitleForDisplay());
  dict.Set("viewSourceMode", val->IsViewSourceMode());
  dict.Set("transitionType", val->GetTransitionType());
  dict.Set("hasPostData", val->GetHasPostData());
  // GetFavicon
  // GetSSL
  dict.Set("originalRequestURL", val->GetOriginalRequestURL());
  dict.Set("isOverridingUserAgent", val->GetIsOverridingUserAgent());
  dict.Set("timestamp", val->GetTimestamp().ToDoubleT());
  dict.Set("httpStatusCode", val->GetHttpStatusCode());
  dict.Set("isRestored", val->IsRestored());
  dict.Set("extraHeaders",  val->GetExtraHeaders());

  return mate::ConvertToV8(isolate, dict);
}

// static
v8::Local<v8::Value> Converter<content::NavigationController*>::ToV8(
    v8::Isolate* isolate, content::NavigationController* val) {
  if (!val)
    return v8::Null(isolate);
  return brave::NavigationController::CreateFrom(isolate, val).ToV8();
}

// static
v8::Local<v8::Value> Converter<content::ReloadType>::ToV8(
    v8::Isolate* isolate, const content::ReloadType& val) {
  switch (val) {
    case content::ReloadType::NONE:
      return StringToV8(isolate, "none");
    case content::ReloadType::NORMAL:
      return StringToV8(isolate, "normal");
    case content::ReloadType::BYPASSING_CACHE:
      return StringToV8(isolate, "bypassingCache");
    case content::ReloadType::ORIGINAL_REQUEST_URL:
      return StringToV8(isolate, "originalRequestUrl");
    case content::ReloadType::DISABLE_LOFI_MODE:
      return StringToV8(isolate, "disableLofiMode");
    default:
      break;
  }

  return StringToV8(isolate, "unknown");
}

// static
v8::Local<v8::Value> Converter<content::PageType>::ToV8(
    v8::Isolate* isolate, const content::PageType& val) {
  switch (val) {
    case content::PageType::PAGE_TYPE_NORMAL:
      return StringToV8(isolate, "normal");
    case content::PageType::PAGE_TYPE_ERROR:
      return StringToV8(isolate, "error");
    case content::PageType::PAGE_TYPE_INTERSTITIAL:
      return StringToV8(isolate, "interstitial");
    default:
      return StringToV8(isolate, "unknown");
  }
}

// static
v8::Local<v8::Value> Converter<content::RestoreType>::ToV8(
    v8::Isolate* isolate, const content::RestoreType& val) {
  switch (val) {
    case content::RestoreType::LAST_SESSION_EXITED_CLEANLY:
      return StringToV8(isolate, "lastSessionExitedCleanly");
    case content::RestoreType::LAST_SESSION_CRASHED:
      return StringToV8(isolate, "lastSessionCrashed");
    case content::RestoreType::CURRENT_SESSION:
      return StringToV8(isolate, "currentSession");
    default:
      return StringToV8(isolate, "none");
  }
}

// static
v8::Local<v8::Value> Converter<ui::PageTransition>::ToV8(
    v8::Isolate* isolate, const ui::PageTransition& val) {
  if (ui::PageTransitionCoreTypeIs(val,
      ui::PageTransition::PAGE_TRANSITION_LINK))
    return StringToV8(isolate, "link");
  if (ui::PageTransitionCoreTypeIs(val,
      ui::PageTransition::PAGE_TRANSITION_TYPED))
    return StringToV8(isolate, "typed");
  if (ui::PageTransitionCoreTypeIs(val,
      ui::PageTransition::PAGE_TRANSITION_AUTO_BOOKMARK))
    return StringToV8(isolate, "autoBookmark");
  if (ui::PageTransitionCoreTypeIs(val,
      ui::PageTransition::PAGE_TRANSITION_AUTO_SUBFRAME))
    return StringToV8(isolate, "autoSubframe");
  if (ui::PageTransitionCoreTypeIs(val,
      ui::PageTransition::PAGE_TRANSITION_MANUAL_SUBFRAME))
    return StringToV8(isolate, "manualSubframe");
  if (ui::PageTransitionCoreTypeIs(val,
      ui::PageTransition::PAGE_TRANSITION_GENERATED))
    return StringToV8(isolate, "generated");
  if (ui::PageTransitionCoreTypeIs(val,
      ui::PageTransition::PAGE_TRANSITION_AUTO_TOPLEVEL))
    return StringToV8(isolate, "autoToplevel");
  if (ui::PageTransitionCoreTypeIs(val,
      ui::PageTransition::PAGE_TRANSITION_FORM_SUBMIT))
    return StringToV8(isolate, "formSubmit");
  if (ui::PageTransitionCoreTypeIs(val,
      ui::PageTransition::PAGE_TRANSITION_RELOAD))
    return StringToV8(isolate, "reload");
  if (ui::PageTransitionCoreTypeIs(val,
      ui::PageTransition::PAGE_TRANSITION_KEYWORD))
    return StringToV8(isolate, "keyword");
  if (ui::PageTransitionCoreTypeIs(val,
      ui::PageTransition::PAGE_TRANSITION_KEYWORD_GENERATED))
    return StringToV8(isolate, "keywordGenerated");

  return StringToV8(isolate, "unknown");
}

}  // namespace mate
<commit_msg>content::ReloadType::DISABLE_LOFI_MODE was renamed to DISABLE_PREVIEWS<commit_after>// Copyright (c) 2015 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/common/native_mate_converters/content_converter.h"

#include <string>
#include <vector>

#include "atom/browser/api/atom_api_web_contents.h"
#include "atom/browser/web_contents_permission_helper.h"
#include "atom/common/native_mate_converters/blink_converter.h"
#include "atom/common/native_mate_converters/callback.h"
#include "atom/common/native_mate_converters/gurl_converter.h"
#include "atom/common/native_mate_converters/string16_converter.h"
#include "atom/common/native_mate_converters/ui_base_types_converter.h"
#include "brave/browser/api/navigation_controller.h"
#include "brave/browser/api/navigation_handle.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/context_menu_params.h"
#include "native_mate/dictionary.h"

namespace {

void ExecuteCommand(content::WebContents* web_contents,
                    int action,
                    const content::CustomContextMenuContext& context) {
  web_contents->ExecuteCustomContextMenuCommand(action, context);
}

// Forward declaration for nested recursive call.
v8::Local<v8::Value> MenuToV8(v8::Isolate* isolate,
                              content::WebContents* web_contents,
                              const content::CustomContextMenuContext& context,
                              const std::vector<content::MenuItem>& menu);

v8::Local<v8::Value> MenuItemToV8(
    v8::Isolate* isolate,
    content::WebContents* web_contents,
    const content::CustomContextMenuContext& context,
    const content::MenuItem& item) {
  mate::Dictionary v8_item = mate::Dictionary::CreateEmpty(isolate);
  switch (item.type) {
    case content::MenuItem::CHECKABLE_OPTION:
    case content::MenuItem::GROUP:
      v8_item.Set("checked", item.checked);
    case content::MenuItem::OPTION:
    case content::MenuItem::SUBMENU:
      v8_item.Set("label", item.label);
      v8_item.Set("enabled", item.enabled);
    default:
      v8_item.Set("type", item.type);
  }
  if (item.type == content::MenuItem::SUBMENU)
    v8_item.Set("submenu",
                MenuToV8(isolate, web_contents, context, item.submenu));
  else if (item.action > 0)
    v8_item.Set("click",
                base::Bind(ExecuteCommand, web_contents, item.action, context));
  return v8_item.GetHandle();
}

v8::Local<v8::Value> MenuToV8(v8::Isolate* isolate,
                              content::WebContents* web_contents,
                              const content::CustomContextMenuContext& context,
                              const std::vector<content::MenuItem>& menu) {
  std::vector<v8::Local<v8::Value>> v8_menu;
  for (const auto& menu_item : menu)
    v8_menu.push_back(MenuItemToV8(isolate, web_contents, context, menu_item));
  return mate::ConvertToV8(isolate, v8_menu);
}

}  // namespace

namespace mate {

// static
v8::Local<v8::Value> Converter<content::MenuItem::Type>::ToV8(
    v8::Isolate* isolate, const content::MenuItem::Type& val) {
  switch (val) {
    case content::MenuItem::CHECKABLE_OPTION:
      return StringToV8(isolate, "checkbox");
    case content::MenuItem::GROUP:
      return StringToV8(isolate, "radio");
    case content::MenuItem::SEPARATOR:
      return StringToV8(isolate, "separator");
    case content::MenuItem::SUBMENU:
      return StringToV8(isolate, "submenu");
    case content::MenuItem::OPTION:
    default:
      return StringToV8(isolate, "normal");
  }
}

// static
v8::Local<v8::Value> Converter<ContextMenuParamsWithWebContents>::ToV8(
    v8::Isolate* isolate, const ContextMenuParamsWithWebContents& val) {
  const auto& params = val.first;
  mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
  dict.Set("x", params.x);
  dict.Set("y", params.y);
  dict.Set("linkURL", params.link_url);
  dict.Set("linkText", params.link_text);
  dict.Set("pageURL", params.page_url);
  dict.Set("frameURL", params.frame_url);
  dict.Set("srcURL", params.src_url);
  dict.Set("mediaType", params.media_type);
  dict.Set("mediaFlags", MediaFlagsToV8(isolate, params.media_flags));
  bool has_image_contents =
    (params.media_type == blink::WebContextMenuData::kMediaTypeImage) &&
    params.has_image_contents;
  dict.Set("hasImageContents", has_image_contents);
  dict.Set("isEditable", params.is_editable);
  dict.Set("editFlags", EditFlagsToV8(isolate, params.edit_flags));
  dict.Set("selectionText", params.selection_text);
  dict.Set("titleText", params.title_text);
  dict.Set("misspelledWord", params.misspelled_word);
  dict.Set("dictionarySuggestions", params.dictionary_suggestions);
  dict.Set("frameCharset", params.frame_charset);
  dict.Set("inputFieldType", params.input_field_type);
  dict.Set("menuSourceType",  params.source_type);
  dict.Set("properties", params.properties);

  if (params.custom_context.request_id || params.custom_context.is_pepper_menu)
    dict.Set("menu", MenuToV8(isolate, val.second, params.custom_context,
                              params.custom_items));
  return mate::ConvertToV8(isolate, dict);
}

// static
bool Converter<blink::mojom::PermissionStatus>::FromV8(
    v8::Isolate* isolate,
    v8::Local<v8::Value> val,
    blink::mojom::PermissionStatus* out) {
  bool result;
  if (!ConvertFromV8(isolate, val, &result))
    return false;

  if (result)
    *out = blink::mojom::PermissionStatus::GRANTED;
  else
    *out = blink::mojom::PermissionStatus::DENIED;

  return true;
}

// static
v8::Local<v8::Value> Converter<content::PermissionType>::ToV8(
    v8::Isolate* isolate, const content::PermissionType& val) {
  using PermissionType = atom::WebContentsPermissionHelper::PermissionType;
  switch (val) {
    case content::PermissionType::MIDI_SYSEX:
      return StringToV8(isolate, "midiSysex");
    case content::PermissionType::PUSH_MESSAGING:
      return StringToV8(isolate, "pushMessaging");
    case content::PermissionType::NOTIFICATIONS:
      return StringToV8(isolate, "notifications");
    case content::PermissionType::GEOLOCATION:
      return StringToV8(isolate, "geolocation");
    case content::PermissionType::AUDIO_CAPTURE:
    case content::PermissionType::VIDEO_CAPTURE:
      return StringToV8(isolate, "media");
    case content::PermissionType::PROTECTED_MEDIA_IDENTIFIER:
      return StringToV8(isolate, "mediaKeySystem");
    case content::PermissionType::MIDI:
      return StringToV8(isolate, "midi");
    default:
      break;
  }

  if (val == (content::PermissionType)(PermissionType::POINTER_LOCK))
    return StringToV8(isolate, "pointerLock");
  else if (val == (content::PermissionType)(PermissionType::FULLSCREEN))
    return StringToV8(isolate, "fullscreen");
  else if (val == (content::PermissionType)(PermissionType::OPEN_EXTERNAL))
    return StringToV8(isolate, "openExternal");
  else if (val == (content::PermissionType)
      (PermissionType::PROTOCOL_REGISTRATION))
    return StringToV8(isolate, "protocolRegistration");

  return StringToV8(isolate, "unknown");
}

// static
bool Converter<content::StopFindAction>::FromV8(
    v8::Isolate* isolate,
    v8::Local<v8::Value> val,
    content::StopFindAction* out) {
  std::string action;
  if (!ConvertFromV8(isolate, val, &action))
    return false;

  if (action == "clearSelection")
    *out = content::STOP_FIND_ACTION_CLEAR_SELECTION;
  else if (action == "keepSelection")
    *out = content::STOP_FIND_ACTION_KEEP_SELECTION;
  else if (action == "activateSelection")
    *out = content::STOP_FIND_ACTION_ACTIVATE_SELECTION;
  else
    return false;

  return true;
}

// static
v8::Local<v8::Value> Converter<content::WebContents*>::ToV8(
    v8::Isolate* isolate, content::WebContents* val) {
  if (!val)
    return v8::Null(isolate);
  return atom::api::WebContents::CreateFrom(isolate, val).ToV8();
}

// static
bool Converter<content::WebContents*>::FromV8(
    v8::Isolate* isolate,
    v8::Local<v8::Value> val,
    content::WebContents** out) {
  atom::api::WebContents* web_contents = nullptr;
  if (!ConvertFromV8(isolate, val, &web_contents) || !web_contents)
    return false;

  *out = web_contents->web_contents();
  return true;
}

// static
v8::Local<v8::Value> Converter<content::NavigationHandle*>::ToV8(
    v8::Isolate* isolate, content::NavigationHandle* val) {
  if (!val)
    return v8::Null(isolate);
  return brave::NavigationHandle::CreateFrom(isolate, val).ToV8();
}

// static
v8::Local<v8::Value> Converter<content::NavigationEntry*>::ToV8(
    v8::Isolate* isolate, content::NavigationEntry* val) {
  if (!val)
    return v8::Null(isolate);

  mate::Dictionary dict = mate::Dictionary::CreateEmpty(isolate);
  dict.Set("uniqueId", val->GetUniqueID());
  dict.Set("pageType", val->GetPageType());
  dict.Set("url", val->GetURL());
  dict.Set("referrer", val->GetReferrer().url);
  dict.Set("virtualURL", val->GetVirtualURL());
  dict.Set("title", val->GetTitle());
  dict.Set("displayTitle", val->GetTitleForDisplay());
  dict.Set("viewSourceMode", val->IsViewSourceMode());
  dict.Set("transitionType", val->GetTransitionType());
  dict.Set("hasPostData", val->GetHasPostData());
  // GetFavicon
  // GetSSL
  dict.Set("originalRequestURL", val->GetOriginalRequestURL());
  dict.Set("isOverridingUserAgent", val->GetIsOverridingUserAgent());
  dict.Set("timestamp", val->GetTimestamp().ToDoubleT());
  dict.Set("httpStatusCode", val->GetHttpStatusCode());
  dict.Set("isRestored", val->IsRestored());
  dict.Set("extraHeaders",  val->GetExtraHeaders());

  return mate::ConvertToV8(isolate, dict);
}

// static
v8::Local<v8::Value> Converter<content::NavigationController*>::ToV8(
    v8::Isolate* isolate, content::NavigationController* val) {
  if (!val)
    return v8::Null(isolate);
  return brave::NavigationController::CreateFrom(isolate, val).ToV8();
}

// static
v8::Local<v8::Value> Converter<content::ReloadType>::ToV8(
    v8::Isolate* isolate, const content::ReloadType& val) {
  switch (val) {
    case content::ReloadType::NONE:
      return StringToV8(isolate, "none");
    case content::ReloadType::NORMAL:
      return StringToV8(isolate, "normal");
    case content::ReloadType::BYPASSING_CACHE:
      return StringToV8(isolate, "bypassingCache");
    case content::ReloadType::ORIGINAL_REQUEST_URL:
      return StringToV8(isolate, "originalRequestUrl");
    case content::ReloadType::DISABLE_PREVIEWS:
      return StringToV8(isolate, "disableLofiMode");
    default:
      break;
  }

  return StringToV8(isolate, "unknown");
}

// static
v8::Local<v8::Value> Converter<content::PageType>::ToV8(
    v8::Isolate* isolate, const content::PageType& val) {
  switch (val) {
    case content::PageType::PAGE_TYPE_NORMAL:
      return StringToV8(isolate, "normal");
    case content::PageType::PAGE_TYPE_ERROR:
      return StringToV8(isolate, "error");
    case content::PageType::PAGE_TYPE_INTERSTITIAL:
      return StringToV8(isolate, "interstitial");
    default:
      return StringToV8(isolate, "unknown");
  }
}

// static
v8::Local<v8::Value> Converter<content::RestoreType>::ToV8(
    v8::Isolate* isolate, const content::RestoreType& val) {
  switch (val) {
    case content::RestoreType::LAST_SESSION_EXITED_CLEANLY:
      return StringToV8(isolate, "lastSessionExitedCleanly");
    case content::RestoreType::LAST_SESSION_CRASHED:
      return StringToV8(isolate, "lastSessionCrashed");
    case content::RestoreType::CURRENT_SESSION:
      return StringToV8(isolate, "currentSession");
    default:
      return StringToV8(isolate, "none");
  }
}

// static
v8::Local<v8::Value> Converter<ui::PageTransition>::ToV8(
    v8::Isolate* isolate, const ui::PageTransition& val) {
  if (ui::PageTransitionCoreTypeIs(val,
      ui::PageTransition::PAGE_TRANSITION_LINK))
    return StringToV8(isolate, "link");
  if (ui::PageTransitionCoreTypeIs(val,
      ui::PageTransition::PAGE_TRANSITION_TYPED))
    return StringToV8(isolate, "typed");
  if (ui::PageTransitionCoreTypeIs(val,
      ui::PageTransition::PAGE_TRANSITION_AUTO_BOOKMARK))
    return StringToV8(isolate, "autoBookmark");
  if (ui::PageTransitionCoreTypeIs(val,
      ui::PageTransition::PAGE_TRANSITION_AUTO_SUBFRAME))
    return StringToV8(isolate, "autoSubframe");
  if (ui::PageTransitionCoreTypeIs(val,
      ui::PageTransition::PAGE_TRANSITION_MANUAL_SUBFRAME))
    return StringToV8(isolate, "manualSubframe");
  if (ui::PageTransitionCoreTypeIs(val,
      ui::PageTransition::PAGE_TRANSITION_GENERATED))
    return StringToV8(isolate, "generated");
  if (ui::PageTransitionCoreTypeIs(val,
      ui::PageTransition::PAGE_TRANSITION_AUTO_TOPLEVEL))
    return StringToV8(isolate, "autoToplevel");
  if (ui::PageTransitionCoreTypeIs(val,
      ui::PageTransition::PAGE_TRANSITION_FORM_SUBMIT))
    return StringToV8(isolate, "formSubmit");
  if (ui::PageTransitionCoreTypeIs(val,
      ui::PageTransition::PAGE_TRANSITION_RELOAD))
    return StringToV8(isolate, "reload");
  if (ui::PageTransitionCoreTypeIs(val,
      ui::PageTransition::PAGE_TRANSITION_KEYWORD))
    return StringToV8(isolate, "keyword");
  if (ui::PageTransitionCoreTypeIs(val,
      ui::PageTransition::PAGE_TRANSITION_KEYWORD_GENERATED))
    return StringToV8(isolate, "keywordGenerated");

  return StringToV8(isolate, "unknown");
}

}  // namespace mate
<|endoftext|>


<commit_before>#pragma once

#include <c2py/callback_wrapper.hpp>

#include "iTapTradeAPI.h"

namespace c2py
{
    // // TapAPIOrderInfoNotice
    // struct FixedTapAPIOrderInfoNotice : ITapTrade::TapAPIOrderInfoNotice
    // {
    //     ITapTrade::TapAPIOrderInfo order_info;
    //
    //     // copy from original structure
    //     FixedTapAPIOrderInfoNotice(const ITapTrade::TapAPIOrderInfoNotice* info)
    //         : TapAPIOrderInfoNotice(*info), order_info(info->OrderInfo != nullptr ? *info->OrderInfo : ITapTrade::TapAPIOrderInfo{})
    //     {
    //         // fix pointer if there is one
    //         this->OrderInfo = info->OrderInfo != nullptr ? &this->order_info : nullptr;
    //     }
    //
    //     // copy constructor
    //     FixedTapAPIOrderInfoNotice(const FixedTapAPIOrderInfoNotice& fixed)
    //         : TapAPIOrderInfoNotice(fixed), order_info(fixed.order_info)
    //     {
    //         // fix pointer if there is one
    //         this->OrderInfo = this->OrderInfo != nullptr ? &this->order_info : nullptr;
    //     }
    // };
    // // TapAPIPositionProfit
    // struct FixedTapAPIPositionProfitNotice : ITapTrade::TapAPIPositionProfitNotice
    // {
    //     ITapTrade::TapAPIPositionProfit data;
    //
    //     // copy from original structure
    //     FixedTapAPIPositionProfitNotice(const ITapTrade::TapAPIPositionProfitNotice* info)
    //         : TapAPIPositionProfitNotice(*info), data(info->Data != nullptr ? *info->Data : ITapTrade::TapAPIPositionProfit{})
    //     {
    //         // fix pointer if there is one
    //         this->Data = info->Data != nullptr ? &this->data : nullptr;
    //     }
    //
    //     // copy constructor
    //     FixedTapAPIPositionProfitNotice(const FixedTapAPIPositionProfitNotice& fixed)
    //         : TapAPIPositionProfitNotice(fixed), data(fixed.data)
    //     {
    //         // fix pointer if there is one
    //         this->Data = this->Data != nullptr ? &this->data : nullptr;
    //     }
    // };
    //
    // namespace arg_helper
    // {
    //     inline auto save(const ITapTrade::TapAPIOrderInfoNotice* info)
    //     { // match char []
    //         return FixedTapAPIOrderInfoNotice(info);
    //     }
    //
    //     template <>
    //     struct loader<ITapTrade::TapAPIOrderInfoNotice>
    //     {
    //         inline FixedTapAPIOrderInfoNotice operator ()(FixedTapAPIOrderInfoNotice& val)
    //         {
    //             return val;
    //         }
    //     };
    //
    //     inline auto save(const ITapTrade::TapAPIPositionProfitNotice* info)
    //     { // match char []
    //         return FixedTapAPIPositionProfitNotice(info);
    //     }
    //
    //     template <>
    //     struct loader<ITapTrade::TapAPIPositionProfitNotice>
    //     {
    //         inline FixedTapAPIPositionProfitNotice operator ()(FixedTapAPIPositionProfitNotice& val)
    //         {
    //             return val;
    //         }
    //     };
    // }

    template<>
    struct callback_wrapper<&ITapTrade::ITapTradeAPINotify::OnRspOrderAction>
    {
        inline static void call(ITapTrade::ITapTradeAPINotify* instance, const char* py_func_name, ITapTrade::TAPIUINT32 sessionID, ITapTrade::TAPIINT32 errorCode, const ITapTrade::TapAPIOrderActionRsp* info)
        {
            ITapTrade::TapAPIOrderInfo orderInfo;
            if (info->OrderInfo != nullptr)
            {
                orderInfo = *info->OrderInfo;
            }
            ITapTrade::TapAPIOrderActionRsp copied_info = *info;
            auto task = [=]() mutable
            {
                if (copied_info.OrderInfo != nullptr)
                {
                    copied_info.OrderInfo = &orderInfo;  // ensure pointer is pointer to the correct address(address changes after constructed lambda)
                }
                try
                {
                    return default_callback_wrapper<&ITapTrade::ITapTradeAPINotify::OnRspOrderAction>::sync(instance, py_func_name, sessionID, errorCode, &copied_info);
                }
                catch (const async_dispatch_exception& e)
                {
                    async_callback_exception_handler::handle_excepiton(e);
                }

            };
            dispatcher::instance().add(std::move(task));
        }
    };

    template<>
    struct callback_wrapper<&ITapTrade::ITapTradeAPINotify::OnRtnOrder>
    {
        inline static void call(ITapTrade::ITapTradeAPINotify* instance, const char* py_func_name, const ITapTrade::TapAPIOrderInfoNotice* info)
        {
            ITapTrade::TapAPIOrderInfo orderInfo;
            if (info->OrderInfo != nullptr)
            {
                orderInfo = *info->OrderInfo;
            }
            ITapTrade::TapAPIOrderInfoNotice copied_info = *info;
            auto task = [=]() mutable
            {
                if (copied_info.OrderInfo != nullptr)
                {
                    copied_info.OrderInfo = &orderInfo;  // ensure pointer is pointer to the correct address(address changes after constructed lambda)
                }
                try
                {
                    return default_callback_wrapper<&ITapTrade::ITapTradeAPINotify::OnRtnOrder>::sync(instance, py_func_name, &copied_info);
                }
                catch (const async_dispatch_exception& e)
                {
                    async_callback_exception_handler::handle_excepiton(e);
                }
            };
            dispatcher::instance().add(std::move(task));
        }
    };

    template<>
    struct callback_wrapper<&ITapTrade::ITapTradeAPINotify::OnRtnPositionProfit>
    {
        inline static void call(ITapTrade::ITapTradeAPINotify* instance, const char* py_func_name, const ITapTrade::TapAPIPositionProfitNotice* info)
        {

            ITapTrade::TapAPIPositionProfit profit;
            if (info->Data != nullptr)
            {
                profit = *info->Data;
            }
            ITapTrade::TapAPIPositionProfitNotice copied_info = *info;
            auto task = [=]() mutable
            {
                if (copied_info.Data != nullptr)
                {
                    copied_info.Data = &profit;  // ensure pointer is pointer to the correct address(address changes after constructed lambda)
                }
                try
                {
                    return default_callback_wrapper<&ITapTrade::ITapTradeAPINotify::OnRtnPositionProfit>::sync(instance, py_func_name, &copied_info);
                }
                catch (const async_dispatch_exception& e)
                {
                    async_callback_exception_handler::handle_excepiton(e);
                }
            };
            dispatcher::instance().add(std::move(task));
        }
    };
}
<commit_msg>Delete custom_wrappers.hpp<commit_after><|endoftext|>


<commit_before>/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */

#pragma once

#include <map>
#include <string>

#include <db.h>

#include "exceptions.hpp"

namespace ftcxx {

    class DBEnv {
    public:
        explicit DBEnv(DB_ENV *e, bool close_on_destroy=false)
            : _env(e),
              _close_on_destroy(close_on_destroy)
        {}

        ~DBEnv() {
            if (_env && _close_on_destroy) {
                close();
            }
        }

        DBEnv(const DBEnv &) = delete;
        DBEnv& operator=(const DBEnv &) = delete;

        DBEnv(DBEnv &&o)
            : _env(nullptr),
              _close_on_destroy(false)
        {
            std::swap(_env, o._env);
            std::swap(_close_on_destroy, o._close_on_destroy);
        }

        DBEnv& operator=(DBEnv &&o) {
            std::swap(_env, o._env);
            std::swap(_close_on_destroy, o._close_on_destroy);
            return *this;
        }

        DB_ENV *env() const { return _env; }

        void close() {
            int r = _env->close(_env, 0);
            handle_ft_retval(r);
            _env = nullptr;
        }

        typedef std::map<std::string, TOKU_ENGINE_STATUS_ROW_S> Status;
        void get_status(Status &status, fs_redzone_state &redzone_state, uint64_t &env_panic, std::string &panic_string) const;

        void log_flush() {
            int r = _env->log_flush(_env, NULL);
            handle_ft_retval(r);
        }

    private:
        DB_ENV *_env;
        bool _close_on_destroy;
    };

    class DBEnvBuilder {
        typedef int (*bt_compare_func)(DB *, const DBT *, const DBT *);
        bt_compare_func _bt_compare;

        typedef int (*update_func)(DB *, const DBT *, const DBT *, const DBT *, void (*)(const DBT *, void *), void *);
        update_func _update_function;

        generate_row_for_put_func _generate_row_for_put;
        generate_row_for_del_func _generate_row_for_del;

        uint32_t _cleaner_period;
        uint32_t _cleaner_iterations;
        uint32_t _checkpointing_period;

        uint64_t _lk_max_memory;
        uint64_t _lock_wait_time_msec;

        typedef uint64_t (*get_lock_wait_time_cb_func)(uint64_t);
        get_lock_wait_time_cb_func _get_lock_wait_time_cb;
        lock_timeout_callback _lock_timeout_callback;
        uint64_t (*_loader_memory_size_callback)(void);

        uint32_t _cachesize_gbytes;
        uint32_t _cachesize_bytes;

        std::string _lg_dir;
        std::string _tmp_dir;

        bool _direct_io;
        bool _compress_buffers;

    public:
        DBEnvBuilder()
            : _bt_compare(nullptr),
              _update_function(nullptr),
              _generate_row_for_put(nullptr),
              _generate_row_for_del(nullptr),
              _cleaner_period(0),
              _cleaner_iterations(0),
              _checkpointing_period(0),
              _lk_max_memory(0),
              _lock_wait_time_msec(0),
              _get_lock_wait_time_cb(nullptr),
              _lock_timeout_callback(nullptr),
              _loader_memory_size_callback(nullptr),
              _cachesize_gbytes(0),
              _cachesize_bytes(0),
              _lg_dir(""),
              _tmp_dir(""),
              _direct_io(false),
              _compress_buffers(true)
        {}

        DBEnv open(const char *env_dir, uint32_t flags, int mode) const {
            db_env_set_direct_io(_direct_io);
            db_env_set_compress_buffers_before_eviction(_compress_buffers);

            DB_ENV *env;
            int r = db_env_create(&env, 0);
            handle_ft_retval(r);

            if (_bt_compare) {
                r = env->set_default_bt_compare(env, _bt_compare);
                handle_ft_retval(r);
            }

            if (_update_function) {
                env->set_update(env, _update_function);
            }

            if (_generate_row_for_put) {
                r = env->set_generate_row_callback_for_put(env, _generate_row_for_put);
                handle_ft_retval(r);
            }

            if (_generate_row_for_del) {
                r = env->set_generate_row_callback_for_del(env, _generate_row_for_del);
                handle_ft_retval(r);
            }

            if (_lk_max_memory) {
                r = env->set_lk_max_memory(env, _lk_max_memory);
                handle_ft_retval(r);
            }

            if (_lock_wait_time_msec || _get_lock_wait_time_cb) {
                uint64_t wait_time = _lock_wait_time_msec;
                if (!wait_time) {
                    r = env->get_lock_timeout(env, &wait_time);
                    handle_ft_retval(r);
                }
                r = env->set_lock_timeout(env, wait_time, _get_lock_wait_time_cb);
                handle_ft_retval(r);
            }

            if (_lock_timeout_callback) {
                r = env->set_lock_timeout_callback(env, _lock_timeout_callback);
                handle_ft_retval(r);
            }

            if (_loader_memory_size_callback) {
                env->set_loader_memory_size(env, _loader_memory_size_callback);
            }

            if (_cachesize_gbytes || _cachesize_bytes) {
                r = env->set_cachesize(env, _cachesize_gbytes, _cachesize_bytes, 1);
                handle_ft_retval(r);
            }

            if (!_lg_dir.empty()) {
                r = env->set_lg_dir(env, _lg_dir.c_str());
                handle_ft_retval(r);
            }

            if (!_tmp_dir.empty()) {
                r = env->set_tmp_dir(env, _tmp_dir.c_str());
                handle_ft_retval(r);
            }

            r = env->open(env, env_dir, flags, mode);
            handle_ft_retval(r);

            if (_cleaner_period) {
                r = env->cleaner_set_period(env, _cleaner_period);
                handle_ft_retval(r);
            }

            if (_cleaner_iterations) {
                r = env->cleaner_set_iterations(env, _cleaner_iterations);
                handle_ft_retval(r);
            }

            if (_checkpointing_period) {
                r = env->checkpointing_set_period(env, _checkpointing_period);
                handle_ft_retval(r);
            }

            return DBEnv(env, true);
        }

        DBEnvBuilder& set_direct_io(bool direct_io) {
            _direct_io = direct_io;
            return *this;
        }

        DBEnvBuilder& set_compress_buffers_before_eviction(bool compress_buffers) {
            _compress_buffers = compress_buffers;
            return *this;
        }

        DBEnvBuilder& set_default_bt_compare(bt_compare_func bt_compare) {
            _bt_compare = bt_compare;
            return *this;
        }

        DBEnvBuilder& set_update(update_func update_function) {
            _update_function = update_function;
            return *this;
        }

        DBEnvBuilder& set_generate_row_callback_for_put(generate_row_for_put_func generate_row_for_put) {
            _generate_row_for_put = generate_row_for_put;
            return *this;
        }

        DBEnvBuilder& set_generate_row_callback_for_del(generate_row_for_del_func generate_row_for_del) {
            _generate_row_for_del = generate_row_for_del;
            return *this;
        }

        DBEnvBuilder& cleaner_set_period(uint32_t period) {
            _cleaner_period = period;
            return *this;
        }

        DBEnvBuilder& cleaner_set_iterations(uint32_t iterations) {
            _cleaner_iterations = iterations;
            return *this;
        }

        DBEnvBuilder& checkpointing_set_period(uint32_t period) {
            _checkpointing_period = period;
            return *this;
        }

        DBEnvBuilder& set_lk_max_memory(uint64_t sz) {
            _lk_max_memory = sz;
            return *this;
        }

        DBEnvBuilder& set_lock_wait_time_msec(uint64_t lock_wait_time_msec) {
            _lock_wait_time_msec = lock_wait_time_msec;
            return *this;
        }

        DBEnvBuilder& set_lock_wait_time_cb(get_lock_wait_time_cb_func get_lock_wait_time_cb) {
            _get_lock_wait_time_cb = get_lock_wait_time_cb;
            return *this;
        }

        DBEnvBuilder& set_lock_timeout_callback(lock_timeout_callback callback) {
            _lock_timeout_callback = callback;
            return *this;
        }

        DBEnvBuilder& set_loader_memory_size(uint64_t (*callback)(void)) {
            _loader_memory_size_callback = callback;
            return *this;
        }

        DBEnvBuilder& set_cachesize(uint32_t gbytes, uint32_t bytes) {
            _cachesize_gbytes = gbytes;
            _cachesize_bytes = bytes;
            return *this;
        }

        DBEnvBuilder& set_lg_dir(const char *lg_dir) {
            _lg_dir = std::string(lg_dir);
            return *this;
        }

        DBEnvBuilder& set_tmp_dir(const char *tmp_dir) {
            _tmp_dir = std::string(tmp_dir);
            return *this;
        }
    };

} // namespace ftcxx
<commit_msg>ftcxx: Add log flush period<commit_after>/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */

#pragma once

#include <map>
#include <string>

#include <db.h>

#include "exceptions.hpp"

namespace ftcxx {

    class DBEnv {
    public:
        explicit DBEnv(DB_ENV *e, bool close_on_destroy=false)
            : _env(e),
              _close_on_destroy(close_on_destroy)
        {}

        ~DBEnv() {
            if (_env && _close_on_destroy) {
                close();
            }
        }

        DBEnv(const DBEnv &) = delete;
        DBEnv& operator=(const DBEnv &) = delete;

        DBEnv(DBEnv &&o)
            : _env(nullptr),
              _close_on_destroy(false)
        {
            std::swap(_env, o._env);
            std::swap(_close_on_destroy, o._close_on_destroy);
        }

        DBEnv& operator=(DBEnv &&o) {
            std::swap(_env, o._env);
            std::swap(_close_on_destroy, o._close_on_destroy);
            return *this;
        }

        DB_ENV *env() const { return _env; }

        void close() {
            int r = _env->close(_env, 0);
            handle_ft_retval(r);
            _env = nullptr;
        }

        typedef std::map<std::string, TOKU_ENGINE_STATUS_ROW_S> Status;
        void get_status(Status &status, fs_redzone_state &redzone_state, uint64_t &env_panic, std::string &panic_string) const;

        void log_flush() {
            int r = _env->log_flush(_env, NULL);
            handle_ft_retval(r);
        }

    private:
        DB_ENV *_env;
        bool _close_on_destroy;
    };

    class DBEnvBuilder {
        typedef int (*bt_compare_func)(DB *, const DBT *, const DBT *);
        bt_compare_func _bt_compare;

        typedef int (*update_func)(DB *, const DBT *, const DBT *, const DBT *, void (*)(const DBT *, void *), void *);
        update_func _update_function;

        generate_row_for_put_func _generate_row_for_put;
        generate_row_for_del_func _generate_row_for_del;

        uint32_t _cleaner_period;
        uint32_t _cleaner_iterations;
        uint32_t _checkpointing_period;
        uint32_t _fsync_log_period_msec;

        uint64_t _lk_max_memory;
        uint64_t _lock_wait_time_msec;

        typedef uint64_t (*get_lock_wait_time_cb_func)(uint64_t);
        get_lock_wait_time_cb_func _get_lock_wait_time_cb;
        lock_timeout_callback _lock_timeout_callback;
        uint64_t (*_loader_memory_size_callback)(void);

        uint32_t _cachesize_gbytes;
        uint32_t _cachesize_bytes;

        std::string _lg_dir;
        std::string _tmp_dir;

        bool _direct_io;
        bool _compress_buffers;

    public:
        DBEnvBuilder()
            : _bt_compare(nullptr),
              _update_function(nullptr),
              _generate_row_for_put(nullptr),
              _generate_row_for_del(nullptr),
              _cleaner_period(0),
              _cleaner_iterations(0),
              _checkpointing_period(0),
              _fsync_log_period_msec(0),
              _lk_max_memory(0),
              _lock_wait_time_msec(0),
              _get_lock_wait_time_cb(nullptr),
              _lock_timeout_callback(nullptr),
              _loader_memory_size_callback(nullptr),
              _cachesize_gbytes(0),
              _cachesize_bytes(0),
              _lg_dir(""),
              _tmp_dir(""),
              _direct_io(false),
              _compress_buffers(true)
        {}

        DBEnv open(const char *env_dir, uint32_t flags, int mode) const {
            db_env_set_direct_io(_direct_io);
            db_env_set_compress_buffers_before_eviction(_compress_buffers);

            DB_ENV *env;
            int r = db_env_create(&env, 0);
            handle_ft_retval(r);

            if (_bt_compare) {
                r = env->set_default_bt_compare(env, _bt_compare);
                handle_ft_retval(r);
            }

            if (_update_function) {
                env->set_update(env, _update_function);
            }

            if (_generate_row_for_put) {
                r = env->set_generate_row_callback_for_put(env, _generate_row_for_put);
                handle_ft_retval(r);
            }

            if (_generate_row_for_del) {
                r = env->set_generate_row_callback_for_del(env, _generate_row_for_del);
                handle_ft_retval(r);
            }

            if (_lk_max_memory) {
                r = env->set_lk_max_memory(env, _lk_max_memory);
                handle_ft_retval(r);
            }

            if (_lock_wait_time_msec || _get_lock_wait_time_cb) {
                uint64_t wait_time = _lock_wait_time_msec;
                if (!wait_time) {
                    r = env->get_lock_timeout(env, &wait_time);
                    handle_ft_retval(r);
                }
                r = env->set_lock_timeout(env, wait_time, _get_lock_wait_time_cb);
                handle_ft_retval(r);
            }

            if (_lock_timeout_callback) {
                r = env->set_lock_timeout_callback(env, _lock_timeout_callback);
                handle_ft_retval(r);
            }

            if (_loader_memory_size_callback) {
                env->set_loader_memory_size(env, _loader_memory_size_callback);
            }

            if (_cachesize_gbytes || _cachesize_bytes) {
                r = env->set_cachesize(env, _cachesize_gbytes, _cachesize_bytes, 1);
                handle_ft_retval(r);
            }

            if (!_lg_dir.empty()) {
                r = env->set_lg_dir(env, _lg_dir.c_str());
                handle_ft_retval(r);
            }

            if (!_tmp_dir.empty()) {
                r = env->set_tmp_dir(env, _tmp_dir.c_str());
                handle_ft_retval(r);
            }

            r = env->open(env, env_dir, flags, mode);
            handle_ft_retval(r);

            if (_cleaner_period) {
                r = env->cleaner_set_period(env, _cleaner_period);
                handle_ft_retval(r);
            }

            if (_cleaner_iterations) {
                r = env->cleaner_set_iterations(env, _cleaner_iterations);
                handle_ft_retval(r);
            }

            if (_checkpointing_period) {
                r = env->checkpointing_set_period(env, _checkpointing_period);
                handle_ft_retval(r);
            }

            if (_fsync_log_period_msec) {
                env->change_fsync_log_period(env, _fsync_log_period_msec);
            }

            return DBEnv(env, true);
        }

        DBEnvBuilder& set_direct_io(bool direct_io) {
            _direct_io = direct_io;
            return *this;
        }

        DBEnvBuilder& set_compress_buffers_before_eviction(bool compress_buffers) {
            _compress_buffers = compress_buffers;
            return *this;
        }

        DBEnvBuilder& set_default_bt_compare(bt_compare_func bt_compare) {
            _bt_compare = bt_compare;
            return *this;
        }

        DBEnvBuilder& set_update(update_func update_function) {
            _update_function = update_function;
            return *this;
        }

        DBEnvBuilder& set_generate_row_callback_for_put(generate_row_for_put_func generate_row_for_put) {
            _generate_row_for_put = generate_row_for_put;
            return *this;
        }

        DBEnvBuilder& set_generate_row_callback_for_del(generate_row_for_del_func generate_row_for_del) {
            _generate_row_for_del = generate_row_for_del;
            return *this;
        }

        DBEnvBuilder& cleaner_set_period(uint32_t period) {
            _cleaner_period = period;
            return *this;
        }

        DBEnvBuilder& cleaner_set_iterations(uint32_t iterations) {
            _cleaner_iterations = iterations;
            return *this;
        }

        DBEnvBuilder& checkpointing_set_period(uint32_t period) {
            _checkpointing_period = period;
            return *this;
        }

        DBEnvBuilder& change_fsync_log_period(uint32_t period) {
            _fsync_log_period_msec = period;
            return *this;
        }

        DBEnvBuilder& set_lk_max_memory(uint64_t sz) {
            _lk_max_memory = sz;
            return *this;
        }

        DBEnvBuilder& set_lock_wait_time_msec(uint64_t lock_wait_time_msec) {
            _lock_wait_time_msec = lock_wait_time_msec;
            return *this;
        }

        DBEnvBuilder& set_lock_wait_time_cb(get_lock_wait_time_cb_func get_lock_wait_time_cb) {
            _get_lock_wait_time_cb = get_lock_wait_time_cb;
            return *this;
        }

        DBEnvBuilder& set_lock_timeout_callback(lock_timeout_callback callback) {
            _lock_timeout_callback = callback;
            return *this;
        }

        DBEnvBuilder& set_loader_memory_size(uint64_t (*callback)(void)) {
            _loader_memory_size_callback = callback;
            return *this;
        }

        DBEnvBuilder& set_cachesize(uint32_t gbytes, uint32_t bytes) {
            _cachesize_gbytes = gbytes;
            _cachesize_bytes = bytes;
            return *this;
        }

        DBEnvBuilder& set_lg_dir(const char *lg_dir) {
            _lg_dir = std::string(lg_dir);
            return *this;
        }

        DBEnvBuilder& set_tmp_dir(const char *tmp_dir) {
            _tmp_dir = std::string(tmp_dir);
            return *this;
        }
    };

} // namespace ftcxx
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at http://qt.nokia.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QFile>
#include <QtGui/QIcon>
#include "v4lvideodevicecontrol.h"
#include "v4lcamerasession.h"

V4LVideoDeviceControl::V4LVideoDeviceControl(QObject *parent)
    : QVideoDeviceControl(parent)
{
    m_session = qobject_cast<V4LCameraSession*>(parent);

    QString name;
    QFile video0("/sys/class/video4linux/video0/name");
    if (video0.exists()) {
        devices.append("dev/video0");
        char str[30];
        memset(str,0,30);
        video0.open(QIODevice::ReadOnly);
        video0.read(str,30);
        name = QString(str);
        descriptions.append(name.simplified());
        video0.close();
    }

    QFile video1("/sys/class/video4linux/video1/name");
    if (video0.exists()) {
        devices.append("dev/video1");
        char str[30];
        memset(str,0,30);
        video1.open(QIODevice::ReadOnly);
        video1.read(str,30);
        name = QString(str);
        descriptions.append(name.simplified());
        video1.close();
    }
    selected = 0;
}

int V4LVideoDeviceControl::deviceCount() const
{
    return devices.count();
}

QString V4LVideoDeviceControl::name(int index) const
{
    if(index >= 0 && index <= devices.count())
        return devices.at(index);

    return QString();
}

QString V4LVideoDeviceControl::description(int index) const
{
    if(index >= 0 && index <= descriptions.count())
        return descriptions.at(index);

    return QString();
}

QIcon V4LVideoDeviceControl::icon(int index) const
{
    Q_UNUSED(index)

    return QIcon();
}

int V4LVideoDeviceControl::defaultDevice() const
{
    return 0;
}

int V4LVideoDeviceControl::selectedDevice() const
{
    return selected;
}

void V4LVideoDeviceControl::setSelectedDevice(int index)
{
    if(index >= 0 && index <= devices.count()) {
        if (m_session)
            m_session->setDevice(devices.at(index));
        selected = index;
    }
}

<commit_msg>Fixed bug in v4l plugin, wasnt setting device correctly.<commit_after>/****************************************************************************
**
** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at http://qt.nokia.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QFile>
#include <QtGui/QIcon>
#include "v4lvideodevicecontrol.h"
#include "v4lcamerasession.h"

V4LVideoDeviceControl::V4LVideoDeviceControl(QObject *parent)
    : QVideoDeviceControl(parent)
{
    m_session = qobject_cast<V4LCameraSession*>(parent);

    QString name;
    QFile video0("/sys/class/video4linux/video0/name");
    if (video0.exists()) {
        devices.append("/dev/video0");
        char str[30];
        memset(str,0,30);
        video0.open(QIODevice::ReadOnly);
        video0.read(str,30);
        name = QString(str);
        descriptions.append(name.simplified());
        video0.close();
    }

    QFile video1("/sys/class/video4linux/video1/name");
    if (video0.exists()) {
        devices.append("/dev/video1");
        char str[30];
        memset(str,0,30);
        video1.open(QIODevice::ReadOnly);
        video1.read(str,30);
        name = QString(str);
        descriptions.append(name.simplified());
        video1.close();
    }
    selected = 0;
}

int V4LVideoDeviceControl::deviceCount() const
{
    return devices.count();
}

QString V4LVideoDeviceControl::name(int index) const
{
    if(index >= 0 && index <= devices.count())
        return devices.at(index);

    return QString();
}

QString V4LVideoDeviceControl::description(int index) const
{
    if(index >= 0 && index <= descriptions.count())
        return descriptions.at(index);

    return QString();
}

QIcon V4LVideoDeviceControl::icon(int index) const
{
    Q_UNUSED(index)

    return QIcon();
}

int V4LVideoDeviceControl::defaultDevice() const
{
    return 0;
}

int V4LVideoDeviceControl::selectedDevice() const
{
    return selected;
}

void V4LVideoDeviceControl::setSelectedDevice(int index)
{
    if(index >= 0 && index <= devices.count()) {
        if (m_session)
            m_session->setDevice(devices.at(index));
        selected = index;
    }
}

<|endoftext|>