<commit_before>/*
 *  Main authors:
 *     Kevin Leo <kevin.leo@monash.edu>
 *     Andrea Rendl <andrea.rendl@nicta.com.au>
 *     Guido Tack <guido.tack@monash.edu>
 */

/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifndef __MINIZINC_GECODE_CONSTRAINTS_HH__
#define __MINIZINC_GECODE_CONSTRAINTS_HH__

#include <gecode/kernel.hh>
#include <gecode/int.hh>

#include <minizinc/solver_instance_base.hh>
#include "gecode_solverinstance.hh"

namespace MiniZinc {

    namespace GecodeConstraints {

      inline Gecode::IntRelType swap(Gecode::IntRelType irt) {
	    switch (irt) {
		case Gecode::IRT_LQ: return Gecode::IRT_GQ;
		case Gecode::IRT_LE: return Gecode::IRT_GR;
		case Gecode::IRT_GQ: return Gecode::IRT_LQ;
		case Gecode::IRT_GR: return Gecode::IRT_LE;
		default:     return irt;
	    }
	}

      inline Gecode::IntRelType neg(Gecode::IntRelType irt) {
	  switch (irt) {
	    case Gecode::IRT_EQ: return Gecode::IRT_NQ;
	      case Gecode::IRT_NQ: return Gecode::IRT_EQ;
	      case Gecode::IRT_LQ: return Gecode::IRT_GR;
	      case Gecode::IRT_LE: return Gecode::IRT_GQ;
	      case Gecode::IRT_GQ: return Gecode::IRT_LE;
	      case Gecode::IRT_GR:
	      default:
			    assert(irt == Gecode::IRT_GR);
	  }
	  return Gecode::IRT_LQ;
      }

      void p_distinct(SolverInstanceBase& s, const Call* call);
      void p_distinctOffset(SolverInstanceBase& s, const Call* call);
      void p_all_equal(SolverInstanceBase& s, const Call* call);
      void p_int_CMP(GecodeSolverInstance& s, Gecode::IntRelType irt, const Call* ce);
      void p_int_eq(SolverInstanceBase& s, const Call* call);
      void p_int_ne(SolverInstanceBase& s, const Call* call);
      void p_int_ge(SolverInstanceBase& s, const Call* call);
      void p_int_gt(SolverInstanceBase& s, const Call* call);
      void p_int_le(SolverInstanceBase& s, const Call* call);
      void p_int_lt(SolverInstanceBase& s, const Call* call);
      void p_int_CMP_reif(GecodeSolverInstance& s, Gecode::IntRelType irt, Gecode::ReifyMode rm, const Call* call);
      ///* Comparisons */
      void p_int_eq_reif(SolverInstanceBase& s, const Call* call);
      void p_int_ne_reif(SolverInstanceBase& s, const Call* call);
      void p_int_ge_reif(SolverInstanceBase& s, const Call* call);
      void p_int_gt_reif(SolverInstanceBase& s, const Call* call);
      void p_int_le_reif(SolverInstanceBase& s, const Call* call);
      void p_int_lt_reif(SolverInstanceBase& s, const Call* call);
      void p_int_eq_imp(SolverInstanceBase& s, const Call* call);
      void p_int_ne_imp(SolverInstanceBase& s, const Call* call);
      void p_int_ge_imp(SolverInstanceBase& s, const Call* call);
      void p_int_gt_imp(SolverInstanceBase& s, const Call* call);
      void p_int_le_imp(SolverInstanceBase& s, const Call* call);
      void p_int_lt_imp(SolverInstanceBase& s, const Call* call);
      void p_int_lin_CMP(GecodeSolverInstance& s, Gecode::IntRelType irt, const Call* call) ;
      void p_int_lin_CMP_reif(GecodeSolverInstance& s, Gecode::IntRelType irt, Gecode::ReifyMode rm, const Call* call);
      void p_int_lin_eq(SolverInstanceBase& s, const Call* call);
      void p_int_lin_eq_reif(SolverInstanceBase& s, const Call* call);
      void p_int_lin_eq_imp(SolverInstanceBase& s, const Call* call);
      void p_int_lin_ne(SolverInstanceBase& s, const Call* call);
      void p_int_lin_ne_reif(SolverInstanceBase& s, const Call* call);
      void p_int_lin_ne_imp(SolverInstanceBase& s, const Call* call);
      void p_int_lin_le(SolverInstanceBase& s, const Call* call) ;
      void p_int_lin_le_reif(SolverInstanceBase& s, const Call* call);
      void p_int_lin_le_imp(SolverInstanceBase& s, const Call* call);
      void p_int_lin_lt(SolverInstanceBase& s, const Call* call);
      void p_int_lin_lt_reif(SolverInstanceBase& s, const Call* call);
      void p_int_lin_lt_imp(SolverInstanceBase& s, const Call* call);
      void p_int_lin_ge(SolverInstanceBase& s, const Call* call);
      void p_int_lin_ge_reif(SolverInstanceBase& s, const Call* call);
      void p_int_lin_ge_imp(SolverInstanceBase& s, const Call* call);
      void p_int_lin_gt(SolverInstanceBase& s, const Call* call);
      void p_int_lin_gt_reif(SolverInstanceBase& s, const Call* call);
      void p_int_lin_gt_imp(SolverInstanceBase& s, const Call* call);
      void p_bool_lin_CMP(GecodeSolverInstance& s, Gecode::IntRelType irt, const Call* call);
      void p_bool_lin_CMP_reif(GecodeSolverInstance& s, Gecode::IntRelType irt, Gecode::ReifyMode rm, const Call* call);
      void p_bool_lin_eq(SolverInstanceBase& s, const Call* call);
      void p_bool_lin_eq_reif(SolverInstanceBase& s, const Call* call);
      void p_bool_lin_eq_imp(SolverInstanceBase& s, const Call* call) ;
      void p_bool_lin_ne(SolverInstanceBase& s, const Call* call);
      void p_bool_lin_ne_reif(SolverInstanceBase& s, const Call* call) ;
      void p_bool_lin_ne_imp(SolverInstanceBase& s, const Call* call) ;
      void p_bool_lin_le(SolverInstanceBase& s, const Call* call);
      void p_bool_lin_le_reif(SolverInstanceBase& s, const Call* call) ;
      void p_bool_lin_le_imp(SolverInstanceBase& s, const Call* call) ;
      void p_bool_lin_lt(SolverInstanceBase& s, const Call* call) ;
      void p_bool_lin_lt_reif(SolverInstanceBase& s, const Call* call);
      void p_bool_lin_lt_imp(SolverInstanceBase& s, const Call* call) ;
      void p_bool_lin_ge(SolverInstanceBase& s, const Call* call);
      void p_bool_lin_ge_reif(SolverInstanceBase& s, const Call* call) ;
      void p_bool_lin_ge_imp(SolverInstanceBase& s, const Call* call) ;
      void p_bool_lin_gt(SolverInstanceBase& s, const Call* call) ;
      void p_bool_lin_gt_reif(SolverInstanceBase& s, const Call* call) ;
      void p_bool_lin_gt_imp(SolverInstanceBase& s, const Call* call) ;

      ///* arithmetic constraints */
      void p_int_plus(SolverInstanceBase& s, const Call* call);
      void p_int_minus(SolverInstanceBase& s, const Call* call);
      void p_int_times(SolverInstanceBase& s, const Call* call);
      void p_int_div(SolverInstanceBase& s, const Call* call);
      void p_int_mod(SolverInstanceBase& s, const Call* call);
      void p_int_min(SolverInstanceBase& s, const Call* call);
      void p_int_max(SolverInstanceBase& s, const Call* call);
      void p_int_negate(SolverInstanceBase& s, const Call* call) ;

      ///* Boolean constraints */
      void p_bool_CMP(GecodeSolverInstance& s, Gecode::IntRelType irt, const Call* call);
      void p_bool_CMP_reif(GecodeSolverInstance& s, Gecode::IntRelType irt, Gecode::ReifyMode rm, const Call* call);
      void p_bool_eq(SolverInstanceBase& s, const Call* call);
      void p_bool_eq_reif(SolverInstanceBase& s, const Call* call) ;
      void p_bool_eq_imp(SolverInstanceBase& s, const Call* call);
      void p_bool_ne(SolverInstanceBase& s, const Call* call);
      void p_bool_ne_reif(SolverInstanceBase& s, const Call* call);
      void p_bool_ne_imp(SolverInstanceBase& s, const Call* call);
      void p_bool_ge(SolverInstanceBase& s, const Call* call);
      void p_bool_ge_reif(SolverInstanceBase& s, const Call* call);
      void p_bool_ge_imp(SolverInstanceBase& s, const Call* call);
      void p_bool_le(SolverInstanceBase& s, const Call* call);
      void p_bool_le_reif(SolverInstanceBase& s, const Call* call);
      void p_bool_le_imp(SolverInstanceBase& s, const Call* call);
      void p_bool_gt(SolverInstanceBase& s, const Call* call);
      void p_bool_gt_reif(SolverInstanceBase& s, const Call* call);
      void p_bool_gt_imp(SolverInstanceBase& s, const Call* call);
      void p_bool_lt(SolverInstanceBase& s, const Call* call);
      void p_bool_lt_reif(SolverInstanceBase& s, const Call* call);
      void p_bool_lt_imp(SolverInstanceBase& s, const Call* call);
      void p_bool_or(SolverInstanceBase& s, const Call* call) ;
      void p_bool_or_imp(SolverInstanceBase& s, const Call* call);
      void p_bool_and(SolverInstanceBase& s, const Call* call);
      void p_bool_and_imp(SolverInstanceBase& s, const Call* call);
      void p_array_bool_and(SolverInstanceBase& s, const Call* call);
      void p_array_bool_and_imp(SolverInstanceBase& s, const Call* call);
      void p_array_bool_or(SolverInstanceBase& s, const Call* call);
      void p_array_bool_or_imp(SolverInstanceBase& s, const Call* call);
      void p_array_bool_xor(SolverInstanceBase& s, const Call* call);
      void p_array_bool_xor_imp(SolverInstanceBase& s, const Call* call);
      void p_array_bool_clause(SolverInstanceBase& s, const Call* call);
      void p_array_bool_clause_reif(SolverInstanceBase& s, const Call* call);
      void p_array_bool_clause_imp(SolverInstanceBase& s, const Call* call);
      void p_bool_xor(SolverInstanceBase& s, const Call* call);
      void p_bool_xor_imp(SolverInstanceBase& s, const Call* call);
      void p_bool_l_imp(SolverInstanceBase& s, const Call* call);
      void p_bool_r_imp(SolverInstanceBase& s, const Call* call);
      void p_bool_not(SolverInstanceBase& s, const Call* call);

      ///* element constraints */
      void p_array_int_element(SolverInstanceBase& s, const Call* call);
      void p_array_bool_element(SolverInstanceBase& s, const Call* call);

      ///* coercion constraints */
      void p_bool2int(SolverInstanceBase& s, const Call* call);
      void p_int_in(SolverInstanceBase& s, const Call* call);
      void p_int_in_reif(SolverInstanceBase& s, const Call* call);
      void p_int_in_imp(SolverInstanceBase& s, const Call* call);

      ///* constraints from the standard library */
      void p_abs(SolverInstanceBase& s, const Call* call);
      void p_array_int_lt(SolverInstanceBase& s, const Call* call);
      void p_array_int_lq(SolverInstanceBase& s, const Call* call);
      void p_array_bool_lt(SolverInstanceBase& s, const Call* call);
      void p_array_bool_lq(SolverInstanceBase& s, const Call* call);
      void p_count(SolverInstanceBase& s, const Call* call);
      void p_count_reif(SolverInstanceBase& s, const Call* call);
      void p_count_imp(SolverInstanceBase& s, const Call* call);
      void count_rel(Gecode::IntRelType irt, SolverInstanceBase& s, const Call* call);
      void p_at_most(SolverInstanceBase& s, const Call* call);
      void p_at_least(SolverInstanceBase& s, const Call* call);
      void p_bin_packing_load(SolverInstanceBase& s, const Call* call);
      void p_global_cardinality(SolverInstanceBase& s, const Call* call);
      void p_global_cardinality_closed(SolverInstanceBase& s, const Call* call);
      void p_global_cardinality_low_up(SolverInstanceBase& s, const Call* call);
      void p_global_cardinality_low_up_closed(SolverInstanceBase& s, const Call* call);
      void p_minimum(SolverInstanceBase& s, const Call* call);
      void p_maximum(SolverInstanceBase& s, const Call* call);
      void p_sort(SolverInstanceBase& s, const Call* call);
      void p_inverse_offsets(SolverInstanceBase& s, const Call* call);
      void p_increasing_int(SolverInstanceBase& s, const Call* call);
      void p_increasing_bool(SolverInstanceBase& s, const Call* call);
      void p_decreasing_int(SolverInstanceBase& s, const Call* call);
      void p_decreasing_bool(SolverInstanceBase& s, const Call* call);
      void p_table_int(SolverInstanceBase& s, const Call* call);
      void p_table_bool(SolverInstanceBase& s, const Call* call);
      void p_cumulatives(SolverInstanceBase& s, const Call* call);
      void p_among_seq_int(SolverInstanceBase& s, const Call* call);
      void p_among_seq_bool(SolverInstanceBase& s, const Call* call);
      void p_schedule_unary(SolverInstanceBase& s, const Call* call);
      void p_schedule_unary_optional(SolverInstanceBase& s, const Call* call);
      void p_circuit(SolverInstanceBase& s, const Call* call);
      void p_circuit_cost_array(SolverInstanceBase& s, const Call* call);
      void p_circuit_cost(SolverInstanceBase& s, const Call* call);
      void p_nooverlap(SolverInstanceBase& s, const Call* call);
      void p_precede(SolverInstanceBase& s, const Call* call);
      void p_nvalue(SolverInstanceBase& s, const Call* call);
      void p_among(SolverInstanceBase& s, const Call* call);
      void p_member_int(SolverInstanceBase& s, const Call* call);
      void p_member_int_reif(SolverInstanceBase& s, const Call* call);
      void p_member_bool(SolverInstanceBase& s, const Call* call);
      void p_member_bool_reif(SolverInstanceBase& s, const Call* call);

      #ifdef GECODE_HAS_FLOAT_VARS
      void p_int2float(SolverInstanceBase& s, const Call* ce);
      void p_float_lin_cmp(GecodeSolverInstance& s, Gecode::FloatRelType frt, const Call* ce);
      void p_float_lin_cmp_reif(GecodeSolverInstance& s, Gecode::FloatRelType frt, const Call* ce);
      void p_float_lin_eq(SolverInstanceBase& s, const Call* ce);
      void p_float_lin_eq_reif(SolverInstanceBase& s, const Call* ce);
      void p_float_lin_le(SolverInstanceBase& s, const Call* ce);
      void p_float_lin_le_reif(SolverInstanceBase& s, const Call* ce);
      void p_float_times(SolverInstanceBase& s, const Call* ce);
      void p_float_div(SolverInstanceBase& s, const Call* ce);
      void p_float_plus(SolverInstanceBase& s, const Call* ce) ;
      void p_float_sqrt(SolverInstanceBase& s, const Call* ce);
      void p_float_abs(SolverInstanceBase& s, const Call* ce);
      void p_float_eq(SolverInstanceBase& s, const Call* ce);
      void p_float_eq_reif(SolverInstanceBase& s, const Call* ce);
      void p_float_le(SolverInstanceBase& s, const Call* ce);
      void p_float_le_reif(SolverInstanceBase& s, const Call* ce);
      void p_float_max(SolverInstanceBase& s, const Call* ce);
      void p_float_min(SolverInstanceBase& s, const Call* ce);
      void p_float_lt(SolverInstanceBase& s, const Call* ce);
      void p_float_lt_reif(SolverInstanceBase& s, const Call* ce);
      void p_float_ne(SolverInstanceBase& s, const Call* ce);
      #ifdef GECODE_HAS_MPFR
#define P_FLOAT_OP(Op) \
      void p_float_ ## Op (SolverInstanceBase& s, const Call* ce) {\
	  GecodeSolverInstance& gi = (GecodeSolverInstance&)s; \
	  FloatVar x = gi.arg2FloatVar(ce->args()[0]);\
	  FloatVar y = gi.arg2FloatVar(ce->args()[1]);\
	  Op(gi ,x,y);\
      }
      P_FLOAT_OP(acos)
	  P_FLOAT_OP(asin)
	  P_FLOAT_OP(atan)
	  P_FLOAT_OP(cos)
	  P_FLOAT_OP(exp)
	  P_FLOAT_OP(sin)
	  P_FLOAT_OP(tan)
#undef P_FLOAT_OP
      void p_float_ln(SolverInstanceBase& s, const Call* ce);
      void p_float_log10(SolverInstanceBase& s, const Call* ce);
      void p_float_log2(SolverInstanceBase& s, const Call* ce);
      #endif
      #endif

    }
}

#endif<commit_msg>Gecode Constraints: Added macro for constraint posters<commit_after>/*
 *  Main authors:
 *     Kevin Leo <kevin.leo@monash.edu>
 *     Andrea Rendl <andrea.rendl@nicta.com.au>
 *     Guido Tack <guido.tack@monash.edu>
 */

/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifndef __MINIZINC_GECODE_CONSTRAINTS_HH__
#define __MINIZINC_GECODE_CONSTRAINTS_HH__

#include <gecode/kernel.hh>
#include <gecode/int.hh>

#include <minizinc/solver_instance_base.hh>
#include "gecode_solverinstance.hh"

namespace MiniZinc {

    namespace GecodeConstraints {

      inline Gecode::IntRelType swap(Gecode::IntRelType irt) {
	    switch (irt) {
		case Gecode::IRT_LQ: return Gecode::IRT_GQ;
		case Gecode::IRT_LE: return Gecode::IRT_GR;
		case Gecode::IRT_GQ: return Gecode::IRT_LQ;
		case Gecode::IRT_GR: return Gecode::IRT_LE;
		default:     return irt;
	    }
	}

      inline Gecode::IntRelType neg(Gecode::IntRelType irt) {
	  switch (irt) {
	    case Gecode::IRT_EQ: return Gecode::IRT_NQ;
	      case Gecode::IRT_NQ: return Gecode::IRT_EQ;
	      case Gecode::IRT_LQ: return Gecode::IRT_GR;
	      case Gecode::IRT_LE: return Gecode::IRT_GQ;
	      case Gecode::IRT_GQ: return Gecode::IRT_LE;
	      case Gecode::IRT_GR:
	      default:
			    assert(irt == Gecode::IRT_GR);
	  }
	  return Gecode::IRT_LQ;
      }

#define PosterImpl(X) void X(SolverInstanceBase&, const Call*)

      PosterImpl(p_distinct);
      PosterImpl(p_distinctOffset);
      PosterImpl(p_all_equal);
      void p_int_CMP(GecodeSolverInstance& s, Gecode::IntRelType irt, const Call* ce);
      PosterImpl(p_int_eq);
      PosterImpl(p_int_ne);
      PosterImpl(p_int_ge);
      PosterImpl(p_int_gt);
      PosterImpl(p_int_le);
      PosterImpl(p_int_lt);
      void p_int_CMP_reif(GecodeSolverInstance& s, Gecode::IntRelType irt, Gecode::ReifyMode rm, const Call* call);
      ///* Comparisons */
      PosterImpl(p_int_eq_reif);
      PosterImpl(p_int_ne_reif);
      PosterImpl(p_int_ge_reif);
      PosterImpl(p_int_gt_reif);
      PosterImpl(p_int_le_reif);
      PosterImpl(p_int_lt_reif);
      PosterImpl(p_int_eq_imp);
      PosterImpl(p_int_ne_imp);
      PosterImpl(p_int_ge_imp);
      PosterImpl(p_int_gt_imp);
      PosterImpl(p_int_le_imp);
      PosterImpl(p_int_lt_imp);
      void p_int_lin_CMP(GecodeSolverInstance& s, Gecode::IntRelType irt, const Call* call) ;
      void p_int_lin_CMP_reif(GecodeSolverInstance& s, Gecode::IntRelType irt, Gecode::ReifyMode rm, const Call* call);
      PosterImpl(p_int_lin_eq);
      PosterImpl(p_int_lin_eq_reif);
      PosterImpl(p_int_lin_eq_imp);
      PosterImpl(p_int_lin_ne);
      PosterImpl(p_int_lin_ne_reif);
      PosterImpl(p_int_lin_ne_imp);
      PosterImpl(p_int_lin_le) ;
      PosterImpl(p_int_lin_le_reif);
      PosterImpl(p_int_lin_le_imp);
      PosterImpl(p_int_lin_lt);
      PosterImpl(p_int_lin_lt_reif);
      PosterImpl(p_int_lin_lt_imp);
      PosterImpl(p_int_lin_ge);
      PosterImpl(p_int_lin_ge_reif);
      PosterImpl(p_int_lin_ge_imp);
      PosterImpl(p_int_lin_gt);
      PosterImpl(p_int_lin_gt_reif);
      PosterImpl(p_int_lin_gt_imp);
      void p_bool_lin_CMP(GecodeSolverInstance& s, Gecode::IntRelType irt, const Call* call);
      void p_bool_lin_CMP_reif(GecodeSolverInstance& s, Gecode::IntRelType irt, Gecode::ReifyMode rm, const Call* call);
      PosterImpl(p_bool_lin_eq);
      PosterImpl(p_bool_lin_eq_reif);
      PosterImpl(p_bool_lin_eq_imp) ;
      PosterImpl(p_bool_lin_ne);
      PosterImpl(p_bool_lin_ne_reif) ;
      PosterImpl(p_bool_lin_ne_imp) ;
      PosterImpl(p_bool_lin_le);
      PosterImpl(p_bool_lin_le_reif) ;
      PosterImpl(p_bool_lin_le_imp) ;
      PosterImpl(p_bool_lin_lt) ;
      PosterImpl(p_bool_lin_lt_reif);
      PosterImpl(p_bool_lin_lt_imp) ;
      PosterImpl(p_bool_lin_ge);
      PosterImpl(p_bool_lin_ge_reif) ;
      PosterImpl(p_bool_lin_ge_imp) ;
      PosterImpl(p_bool_lin_gt) ;
      PosterImpl(p_bool_lin_gt_reif) ;
      PosterImpl(p_bool_lin_gt_imp) ;

      ///* arithmetic constraints */
      PosterImpl(p_int_plus);
      PosterImpl(p_int_minus);
      PosterImpl(p_int_times);
      PosterImpl(p_int_div);
      PosterImpl(p_int_mod);
      PosterImpl(p_int_min);
      PosterImpl(p_int_max);
      PosterImpl(p_int_negate) ;

      ///* Boolean constraints */
      void p_bool_CMP(GecodeSolverInstance& s, Gecode::IntRelType irt, const Call* call);
      void p_bool_CMP_reif(GecodeSolverInstance& s, Gecode::IntRelType irt, Gecode::ReifyMode rm, const Call* call);
      PosterImpl(p_bool_eq);
      PosterImpl(p_bool_eq_reif) ;
      PosterImpl(p_bool_eq_imp);
      PosterImpl(p_bool_ne);
      PosterImpl(p_bool_ne_reif);
      PosterImpl(p_bool_ne_imp);
      PosterImpl(p_bool_ge);
      PosterImpl(p_bool_ge_reif);
      PosterImpl(p_bool_ge_imp);
      PosterImpl(p_bool_le);
      PosterImpl(p_bool_le_reif);
      PosterImpl(p_bool_le_imp);
      PosterImpl(p_bool_gt);
      PosterImpl(p_bool_gt_reif);
      PosterImpl(p_bool_gt_imp);
      PosterImpl(p_bool_lt);
      PosterImpl(p_bool_lt_reif);
      PosterImpl(p_bool_lt_imp);
      PosterImpl(p_bool_or) ;
      PosterImpl(p_bool_or_imp);
      PosterImpl(p_bool_and);
      PosterImpl(p_bool_and_imp);
      PosterImpl(p_array_bool_and);
      PosterImpl(p_array_bool_and_imp);
      PosterImpl(p_array_bool_or);
      PosterImpl(p_array_bool_or_imp);
      PosterImpl(p_array_bool_xor);
      PosterImpl(p_array_bool_xor_imp);
      PosterImpl(p_array_bool_clause);
      PosterImpl(p_array_bool_clause_reif);
      PosterImpl(p_array_bool_clause_imp);
      PosterImpl(p_bool_xor);
      PosterImpl(p_bool_xor_imp);
      PosterImpl(p_bool_l_imp);
      PosterImpl(p_bool_r_imp);
      PosterImpl(p_bool_not);

      ///* element constraints */
      PosterImpl(p_array_int_element);
      PosterImpl(p_array_bool_element);

      ///* coercion constraints */
      PosterImpl(p_bool2int);
      PosterImpl(p_int_in);
      PosterImpl(p_int_in_reif);
      PosterImpl(p_int_in_imp);

      ///* constraints from the standard library */
      PosterImpl(p_abs);
      PosterImpl(p_array_int_lt);
      PosterImpl(p_array_int_lq);
      PosterImpl(p_array_bool_lt);
      PosterImpl(p_array_bool_lq);
      PosterImpl(p_count);
      PosterImpl(p_count_reif);
      PosterImpl(p_count_imp);
      void count_rel(Gecode::IntRelType irt, SolverInstanceBase& s, const Call* call);
      PosterImpl(p_at_most);
      PosterImpl(p_at_least);
      PosterImpl(p_bin_packing_load);
      PosterImpl(p_global_cardinality);
      PosterImpl(p_global_cardinality_closed);
      PosterImpl(p_global_cardinality_low_up);
      PosterImpl(p_global_cardinality_low_up_closed);
      PosterImpl(p_minimum);
      PosterImpl(p_maximum);
      //PosterImpl(p_regular);
      PosterImpl(p_sort);
      PosterImpl(p_inverse_offsets);
      PosterImpl(p_increasing_int);
      PosterImpl(p_increasing_bool);
      PosterImpl(p_decreasing_int);
      PosterImpl(p_decreasing_bool);
      PosterImpl(p_table_int);
      PosterImpl(p_table_bool);
      PosterImpl(p_cumulatives);
      PosterImpl(p_among_seq_int);
      PosterImpl(p_among_seq_bool);
      PosterImpl(p_schedule_unary);
      PosterImpl(p_schedule_unary_optional);
      PosterImpl(p_circuit);
      PosterImpl(p_circuit_cost_array);
      PosterImpl(p_circuit_cost);
      PosterImpl(p_nooverlap);
      PosterImpl(p_precede);
      PosterImpl(p_nvalue);
      PosterImpl(p_among);
      PosterImpl(p_member_int);
      PosterImpl(p_member_int_reif);
      PosterImpl(p_member_bool);
      PosterImpl(p_member_bool_reif);

      #ifdef GECODE_HAS_FLOAT_VARS
      PosterImpl(p_int2float);
      void p_float_lin_cmp(GecodeSolverInstance& s, Gecode::FloatRelType frt, const Call* ce);
      void p_float_lin_cmp_reif(GecodeSolverInstance& s, Gecode::FloatRelType frt, const Call* ce);
      PosterImpl(p_float_lin_eq);
      PosterImpl(p_float_lin_eq_reif);
      PosterImpl(p_float_lin_le);
      PosterImpl(p_float_lin_le_reif);
      PosterImpl(p_float_times);
      PosterImpl(p_float_div);
      PosterImpl(p_float_plus) ;
      PosterImpl(p_float_sqrt);
      PosterImpl(p_float_abs);
      PosterImpl(p_float_eq);
      PosterImpl(p_float_eq_reif);
      PosterImpl(p_float_le);
      PosterImpl(p_float_le_reif);
      PosterImpl(p_float_max);
      PosterImpl(p_float_min);
      PosterImpl(p_float_lt);
      PosterImpl(p_float_lt_reif);
      PosterImpl(p_float_ne);
      #ifdef GECODE_HAS_MPFR
#define P_FLOAT_OP(Op) \
      PosterImpl(p_float_ ## Op ) {\
	  GecodeSolverInstance& gi = (GecodeSolverInstance&)s; \
	  FloatVar x = gi.arg2FloatVar(ce->args()[0]);\
	  FloatVar y = gi.arg2FloatVar(ce->args()[1]);\
	  Op(gi ,x,y);\
      }
      P_FLOAT_OP(acos)
	  P_FLOAT_OP(asin)
	  P_FLOAT_OP(atan)
	  P_FLOAT_OP(cos)
	  P_FLOAT_OP(exp)
	  P_FLOAT_OP(sin)
	  P_FLOAT_OP(tan)
#undef P_FLOAT_OP
      PosterImpl(p_float_ln);
      PosterImpl(p_float_log10);
      PosterImpl(p_float_log2);
      #endif
      #endif

    }
}

#endif
<|endoftext|>


<commit_before>//===-- DynamicLinker.cpp - Implement DynamicLinker interface -------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Lightweight interface to dynamic library linking and loading, and dynamic
// symbol lookup functionality, in whatever form the operating system
// provides it.
//
// Possible future extensions include support for the HPUX shl_load()
// interface, the Mac OS X NSLinkModule() interface, and the Windows
// LoadLibrary() interface.
//
// Note that we assume that if dlopen() is available, then dlsym() is too.
//
//===----------------------------------------------------------------------===//

#include "Support/DynamicLinker.h"
#include "Config/dlfcn.h"
#include <cassert>

bool LinkDynamicObject (const char *filename, std::string *ErrorMessage) {
#if defined (HAVE_DLOPEN)
  if (dlopen (filename, RTLD_NOW | RTLD_GLOBAL) == 0) {
    if (ErrorMessage) *ErrorMessage = dlerror ();
    return true;
  }
  return false;
#else
  assert (0 && "Dynamic object linking not implemented for this platform");
#endif
}

void *GetAddressOfSymbol (const char *symbolName) {
#if defined (HAVE_DLOPEN)
  return dlsym (RTLD_DEFAULT, symbolName);
#else
  assert (0 && "Dynamic symbol lookup not implemented for this platform");
#endif
}

// soft, cushiony C++ interface.
void *GetAddressOfSymbol (const std::string &symbolName) {
  return GetAddressOfSymbol (symbolName.c_str ());
}
<commit_msg>Attempt to provide support for those without RTLD_DEFAULT.<commit_after>//===-- DynamicLinker.cpp - Implement DynamicLinker interface -------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Lightweight interface to dynamic library linking and loading, and dynamic
// symbol lookup functionality, in whatever form the operating system
// provides it.
//
// Possible future extensions include support for the HPUX shl_load()
// interface, the Mac OS X NSLinkModule() interface, and the Windows
// LoadLibrary() interface.
//
// Note that we assume that if dlopen() is available, then dlsym() is too.
//
//===----------------------------------------------------------------------===//

#include "Support/DynamicLinker.h"
#include "Config/dlfcn.h"
#include <cassert>

bool LinkDynamicObject (const char *filename, std::string *ErrorMessage) {
#if defined (HAVE_DLOPEN)
  if (dlopen (filename, RTLD_NOW | RTLD_GLOBAL) == 0) {
    if (ErrorMessage) *ErrorMessage = dlerror ();
    return true;
  }
  return false;
#else
  assert (0 && "Dynamic object linking not implemented for this platform");
#endif
}

void *GetAddressOfSymbol (const char *symbolName) {
#if defined (HAVE_DLOPEN)
#ifdef RTLD_DEFAULT
  return dlsym (RTLD_DEFAULT, symbolName);
#else
  static void* CurHandle = dlopen(0, RTLD_LAZY);
  return dlsym(CurHandle, symbolName);
#endif
#else
  assert (0 && "Dynamic symbol lookup not implemented for this platform");
#endif
}

// soft, cushiony C++ interface.
void *GetAddressOfSymbol (const std::string &symbolName) {
  return GetAddressOfSymbol (symbolName.c_str ());
}
<|endoftext|>


<commit_before>// Copyright (c) 2008 The Chromium Authors. All rights reserved.  Use of this
// source code is governed by a BSD-style license that can be found in the
// LICENSE file.

#include "config.h"
#include "ChromiumBridge.h"

#include "ClipboardUtilitiesChromium.h"
#include "Cursor.h"
#include "Frame.h"
#include "FrameView.h"
#include "HostWindow.h"
#include "KURL.h"
#include "NativeImageSkia.h"
#include "Page.h"
#include "PasteboardPrivate.h"
#include "PlatformString.h"
#include "PlatformWidget.h"
#include "PluginData.h"
#include "PluginInfoStore.h"
#include "ScrollbarTheme.h"
#include "ScrollView.h"
#include "Widget.h"

#undef LOG
#include "base/clipboard.h"
#include "base/file_util.h"
#include "base/stats_counters.h"
#include "base/string_util.h"
#include "base/trace_event.h"
#include "net/base/mime_util.h"
#if USE(V8)
#include <v8.h>
#endif
#include "webkit/glue/chrome_client_impl.h"
#include "webkit/glue/glue_util.h"
#include "webkit/glue/scoped_clipboard_writer_glue.h"
#include "webkit/glue/webcursor.h"
#include "webkit/glue/webkit_glue.h"
#include "webkit/glue/webplugin.h"
#include "webkit/glue/webkit_resources.h"
#include "webkit/glue/webview_impl.h"
#include "webkit/glue/webview_delegate.h"

namespace {

PlatformWidget ToPlatform(WebCore::Widget* widget) {
  return widget ? widget->root()->hostWindow()->platformWindow() : 0;
}

ChromeClientImpl* ToChromeClient(WebCore::Widget* widget) {
  WebCore::FrameView* view;
  if (widget->isFrameView()) {
    view = static_cast<WebCore::FrameView*>(widget);
  } else if (widget->parent() && widget->parent()->isFrameView()) {
    view = static_cast<WebCore::FrameView*>(widget->parent());
  } else {
    return NULL;
  }

  WebCore::Page* page = view->frame() ? view->frame()->page() : NULL;
  if (!page)
    return NULL;

  return static_cast<ChromeClientImpl*>(page->chrome()->client());
}

std::wstring UrlToImageMarkup(const WebCore::KURL& url,
                              const WebCore::String& alt_str) {
  std::wstring markup(L"");
  return markup;
}

}  // namespace

namespace WebCore {

bool ChromiumBridge::clipboardIsFormatAvailable(
    PasteboardPrivate::ClipboardFormat format) {
  switch (format) {
    case PasteboardPrivate::HTMLFormat:
      return webkit_glue::ClipboardIsFormatAvailable(
          ::Clipboard::GetHtmlFormatType());

    case PasteboardPrivate::WebSmartPasteFormat:
      return webkit_glue::ClipboardIsFormatAvailable(
          ::Clipboard::GetWebKitSmartPasteFormatType());

    case PasteboardPrivate::BookmarkFormat:
#if defined(OS_WIN) || defined(OS_MACOSX)
      return webkit_glue::ClipboardIsFormatAvailable(
          ::Clipboard::GetUrlWFormatType());
#endif

    default:
      NOTREACHED();
      return false;
  }
}

String ChromiumBridge::clipboardReadPlainText() {
  if (webkit_glue::ClipboardIsFormatAvailable(
      ::Clipboard::GetPlainTextWFormatType())) {
    std::wstring text;
    webkit_glue::ClipboardReadText(&text);
    if (!text.empty())
      return webkit_glue::StdWStringToString(text);
  }

  if (webkit_glue::ClipboardIsFormatAvailable(
      ::Clipboard::GetPlainTextFormatType())) {
    std::string text;
    webkit_glue::ClipboardReadAsciiText(&text);
    if (!text.empty())
      return webkit_glue::StdStringToString(text);
  }

  return String();
}

void ChromiumBridge::clipboardReadHTML(String* html, KURL* url) {
  std::wstring html_stdstr;
  GURL gurl;
  webkit_glue::ClipboardReadHTML(&html_stdstr, &gurl);
  *html = webkit_glue::StdWStringToString(html_stdstr);
  *url = webkit_glue::GURLToKURL(gurl);
}

void ChromiumBridge::clipboardWriteSelection(const String& html,
                                             const KURL& url,
                                             const String& plain_text,
                                             bool can_smart_copy_or_delete) {
  ScopedClipboardWriterGlue scw(webkit_glue::ClipboardGetClipboard());
  scw.WriteHTML(webkit_glue::StringToStdWString(html),
                webkit_glue::CStringToStdString(url.utf8String()));
  scw.WriteText(webkit_glue::StringToStdWString(plain_text));

  if (can_smart_copy_or_delete)
    scw.WriteWebSmartPaste();
}

void ChromiumBridge::clipboardWriteURL(const KURL& url, const String& title) {
  ScopedClipboardWriterGlue scw(webkit_glue::ClipboardGetClipboard());

  GURL gurl = webkit_glue::KURLToGURL(url);
  scw.WriteBookmark(webkit_glue::StringToStdWString(title), gurl.spec());

  std::wstring link(webkit_glue::StringToStdWString(urlToMarkup(url, title)));
  scw.WriteHTML(link, "");

  scw.WriteText(ASCIIToWide(gurl.spec()));
}

void ChromiumBridge::clipboardWriteImage(const NativeImageSkia* bitmap,
    const KURL& url, const String& title) {
  ScopedClipboardWriterGlue scw(webkit_glue::ClipboardGetClipboard());

#if defined(OS_WIN)
  if (bitmap)
    scw.WriteBitmap(*bitmap);
#endif
  if (!url.isEmpty()) {
    GURL gurl = webkit_glue::KURLToGURL(url);
    scw.WriteBookmark(webkit_glue::StringToStdWString(title), gurl.spec());

    scw.WriteHTML(UrlToImageMarkup(url, title), "");

    scw.WriteText(ASCIIToWide(gurl.spec()));
  }
}

//

// Cookies --------------------------------------------------------------------

void ChromiumBridge::setCookies(
    const KURL& url, const KURL& policy_url, const String& cookie) {
  webkit_glue::SetCookie(
      webkit_glue::KURLToGURL(url),
      webkit_glue::KURLToGURL(policy_url),
      webkit_glue::StringToStdString(cookie));
}

String ChromiumBridge::cookies(const KURL& url, const KURL& policy_url) {
  return webkit_glue::StdStringToString(webkit_glue::GetCookies(
      webkit_glue::KURLToGURL(url),
      webkit_glue::KURLToGURL(policy_url)));
}

// DNS ------------------------------------------------------------------------

void ChromiumBridge::prefetchDNS(const String& hostname) {
  webkit_glue::PrefetchDns(webkit_glue::StringToStdString(hostname));
}

// Font -----------------------------------------------------------------------

#if defined(OS_WIN)
bool ChromiumBridge::ensureFontLoaded(HFONT font) {
  return webkit_glue::EnsureFontLoaded(font);
}
#endif

// Forms ----------------------------------------------------------------------

void ChromiumBridge::notifyFormStateChanged(const Document* doc) {
  webkit_glue::NotifyFormStateChanged(doc);
}

// JavaScript -----------------------------------------------------------------

void ChromiumBridge::notifyJSOutOfMemory(Frame* frame) {
  webkit_glue::NotifyJSOutOfMemory(frame);
}

// Language -------------------------------------------------------------------

String ChromiumBridge::computedDefaultLanguage() {
  return webkit_glue::StdWStringToString(webkit_glue::GetWebKitLocale());
}

// LayoutTestMode -------------------------------------------------------------

bool ChromiumBridge::layoutTestMode() {
  return webkit_glue::IsLayoutTestMode();
}

// MimeType -------------------------------------------------------------------

bool ChromiumBridge::matchesMIMEType(const String& pattern,
                                     const String& type) {
  return net::MatchesMimeType(webkit_glue::StringToStdString(pattern),
                              webkit_glue::StringToStdString(type));
}

String ChromiumBridge::mimeTypeForExtension(const String& ext) {
  if (ext.isEmpty())
    return String();

  std::string type;
  webkit_glue::GetMimeTypeFromExtension(webkit_glue::StringToStdWString(ext),
                                        &type);
  return webkit_glue::StdStringToString(type);
}

String ChromiumBridge::mimeTypeFromFile(const String& file_path) {
  if (file_path.isEmpty())
    return String();

  std::string type;
  webkit_glue::GetMimeTypeFromFile(webkit_glue::StringToStdWString(file_path),
                                   &type);
  return webkit_glue::StdStringToString(type);
}

String ChromiumBridge::preferredExtensionForMIMEType(const String& mime_type) {
  if (mime_type.isEmpty())
    return String();

  std::wstring stdext;
  webkit_glue::GetPreferredExtensionForMimeType(
      webkit_glue::StringToStdString(mime_type), &stdext);
  return webkit_glue::StdWStringToString(stdext);
}

// Plugin ---------------------------------------------------------------------

bool ChromiumBridge::getPlugins(bool refresh, Vector<PluginInfo*>* plugins) {
  std::vector< ::WebPluginInfo> glue_plugins;
  if (!webkit_glue::GetPlugins(refresh, &glue_plugins))
    return false;
  for (size_t i = 0; i < glue_plugins.size(); ++i) {
    WebCore::PluginInfo* rv = new WebCore::PluginInfo;
    const ::WebPluginInfo& plugin = glue_plugins[i];
    rv->name = webkit_glue::StdWStringToString(plugin.name);
    rv->desc = webkit_glue::StdWStringToString(plugin.desc);
    rv->file = webkit_glue::StdWStringToString(
        file_util::GetFilenameFromPath(plugin.file));
    for (size_t j = 0; j < plugin.mime_types.size(); ++ j) {
      WebCore::MimeClassInfo* new_mime = new WebCore::MimeClassInfo();
      const WebPluginMimeType& mime_type = plugin.mime_types[j];
      new_mime->desc = webkit_glue::StdWStringToString(mime_type.description);

      for (size_t k = 0; k < mime_type.file_extensions.size(); ++k) {
        if (new_mime->suffixes.length())
          new_mime->suffixes.append(",");

        new_mime->suffixes.append(webkit_glue::StdStringToString(
            mime_type.file_extensions[k]));
      }

      new_mime->type = webkit_glue::StdStringToString(mime_type.mime_type);
      new_mime->plugin = rv;
      rv->mimes.append(new_mime);
    }
    plugins->append(rv);
  }
  return true;
}

// Protocol -------------------------------------------------------------------

String ChromiumBridge::uiResourceProtocol() {
  return webkit_glue::StdStringToString(webkit_glue::GetUIResourceProtocol());
}

// Screen ---------------------------------------------------------------------

int ChromiumBridge::screenDepth(Widget* widget) {
  return webkit_glue::GetScreenInfo(ToPlatform(widget)).depth;
}

int ChromiumBridge::screenDepthPerComponent(Widget* widget) {
  return webkit_glue::GetScreenInfo(ToPlatform(widget)).depth_per_component;
}

bool ChromiumBridge::screenIsMonochrome(Widget* widget) {
  return webkit_glue::GetScreenInfo(ToPlatform(widget)).is_monochrome;
}

IntRect ChromiumBridge::screenRect(Widget* widget) {
  return webkit_glue::ToIntRect(
      webkit_glue::GetScreenInfo(ToPlatform(widget)).rect);
}

IntRect ChromiumBridge::screenAvailableRect(Widget* widget) {
  return webkit_glue::ToIntRect(
      webkit_glue::GetScreenInfo(ToPlatform(widget)).available_rect);
}

// StatsCounters --------------------------------------------------------------
void ChromiumBridge::decrementStatsCounter(const wchar_t* name) {
  StatsCounter(name).Decrement();
}

void ChromiumBridge::incrementStatsCounter(const wchar_t* name) {
  StatsCounter(name).Increment();
}

#if USE(V8)
void ChromiumBridge::initV8CounterFunction() {
  v8::V8::SetCounterFunction(StatsTable::FindLocation);
}
#endif

// Trace Event ----------------------------------------------------------------
void ChromiumBridge::traceEventBegin(const char* name,
                                     void* id,
                                     const char* extra) {
  TRACE_EVENT_BEGIN(name, id, extra);
}

void ChromiumBridge::traceEventEnd(const char* name,
                                   void* id,
                                   const char* extra) {
  TRACE_EVENT_END(name, id, extra);
}

// URL ------------------------------------------------------------------------
KURL ChromiumBridge::inspectorURL() {
  return webkit_glue::GURLToKURL(webkit_glue::GetInspectorURL());
}

// Widget ---------------------------------------------------------------------

void ChromiumBridge::widgetSetCursor(Widget* widget, const Cursor& cursor) {
  ChromeClientImpl* chrome_client = ToChromeClient(widget);
  if (chrome_client)
    chrome_client->SetCursor(WebCursor(cursor.impl()));
}

void ChromiumBridge::widgetSetFocus(Widget* widget) {
  ChromeClientImpl* chrome_client = ToChromeClient(widget);
  if (chrome_client)
    chrome_client->focus();
}

}  // namespace WebCore
<commit_msg>Minor whitespace cleanup.<commit_after>// Copyright (c) 2008 The Chromium Authors. All rights reserved.  Use of this
// source code is governed by a BSD-style license that can be found in the
// LICENSE file.

#include "config.h"
#include "ChromiumBridge.h"

#include "ClipboardUtilitiesChromium.h"
#include "Cursor.h"
#include "Frame.h"
#include "FrameView.h"
#include "HostWindow.h"
#include "KURL.h"
#include "NativeImageSkia.h"
#include "Page.h"
#include "PasteboardPrivate.h"
#include "PlatformString.h"
#include "PlatformWidget.h"
#include "PluginData.h"
#include "PluginInfoStore.h"
#include "ScrollbarTheme.h"
#include "ScrollView.h"
#include "Widget.h"

#undef LOG
#include "base/clipboard.h"
#include "base/file_util.h"
#include "base/stats_counters.h"
#include "base/string_util.h"
#include "base/trace_event.h"
#include "net/base/mime_util.h"
#if USE(V8)
#include <v8.h>
#endif
#include "webkit/glue/chrome_client_impl.h"
#include "webkit/glue/glue_util.h"
#include "webkit/glue/scoped_clipboard_writer_glue.h"
#include "webkit/glue/webcursor.h"
#include "webkit/glue/webkit_glue.h"
#include "webkit/glue/webplugin.h"
#include "webkit/glue/webkit_resources.h"
#include "webkit/glue/webview_impl.h"
#include "webkit/glue/webview_delegate.h"

namespace {

PlatformWidget ToPlatform(WebCore::Widget* widget) {
  return widget ? widget->root()->hostWindow()->platformWindow() : 0;
}

ChromeClientImpl* ToChromeClient(WebCore::Widget* widget) {
  WebCore::FrameView* view;
  if (widget->isFrameView()) {
    view = static_cast<WebCore::FrameView*>(widget);
  } else if (widget->parent() && widget->parent()->isFrameView()) {
    view = static_cast<WebCore::FrameView*>(widget->parent());
  } else {
    return NULL;
  }

  WebCore::Page* page = view->frame() ? view->frame()->page() : NULL;
  if (!page)
    return NULL;

  return static_cast<ChromeClientImpl*>(page->chrome()->client());
}

std::wstring UrlToImageMarkup(const WebCore::KURL& url,
                              const WebCore::String& alt_str) {
  std::wstring markup(L"");
  return markup;
}

}  // namespace

namespace WebCore {

bool ChromiumBridge::clipboardIsFormatAvailable(
    PasteboardPrivate::ClipboardFormat format) {
  switch (format) {
    case PasteboardPrivate::HTMLFormat:
      return webkit_glue::ClipboardIsFormatAvailable(
          ::Clipboard::GetHtmlFormatType());

    case PasteboardPrivate::WebSmartPasteFormat:
      return webkit_glue::ClipboardIsFormatAvailable(
          ::Clipboard::GetWebKitSmartPasteFormatType());

    case PasteboardPrivate::BookmarkFormat:
#if defined(OS_WIN) || defined(OS_MACOSX)
      return webkit_glue::ClipboardIsFormatAvailable(
          ::Clipboard::GetUrlWFormatType());
#endif

    default:
      NOTREACHED();
      return false;
  }
}

String ChromiumBridge::clipboardReadPlainText() {
  if (webkit_glue::ClipboardIsFormatAvailable(
      ::Clipboard::GetPlainTextWFormatType())) {
    std::wstring text;
    webkit_glue::ClipboardReadText(&text);
    if (!text.empty())
      return webkit_glue::StdWStringToString(text);
  }

  if (webkit_glue::ClipboardIsFormatAvailable(
      ::Clipboard::GetPlainTextFormatType())) {
    std::string text;
    webkit_glue::ClipboardReadAsciiText(&text);
    if (!text.empty())
      return webkit_glue::StdStringToString(text);
  }

  return String();
}

void ChromiumBridge::clipboardReadHTML(String* html, KURL* url) {
  std::wstring html_stdstr;
  GURL gurl;
  webkit_glue::ClipboardReadHTML(&html_stdstr, &gurl);
  *html = webkit_glue::StdWStringToString(html_stdstr);
  *url = webkit_glue::GURLToKURL(gurl);
}

void ChromiumBridge::clipboardWriteSelection(const String& html,
                                             const KURL& url,
                                             const String& plain_text,
                                             bool can_smart_copy_or_delete) {
  ScopedClipboardWriterGlue scw(webkit_glue::ClipboardGetClipboard());
  scw.WriteHTML(webkit_glue::StringToStdWString(html),
                webkit_glue::CStringToStdString(url.utf8String()));
  scw.WriteText(webkit_glue::StringToStdWString(plain_text));

  if (can_smart_copy_or_delete)
    scw.WriteWebSmartPaste();
}

void ChromiumBridge::clipboardWriteURL(const KURL& url, const String& title) {
  ScopedClipboardWriterGlue scw(webkit_glue::ClipboardGetClipboard());

  GURL gurl = webkit_glue::KURLToGURL(url);
  scw.WriteBookmark(webkit_glue::StringToStdWString(title), gurl.spec());

  std::wstring link(webkit_glue::StringToStdWString(urlToMarkup(url, title)));
  scw.WriteHTML(link, "");

  scw.WriteText(ASCIIToWide(gurl.spec()));
}

void ChromiumBridge::clipboardWriteImage(const NativeImageSkia* bitmap,
    const KURL& url, const String& title) {
  ScopedClipboardWriterGlue scw(webkit_glue::ClipboardGetClipboard());

#if defined(OS_WIN)
  if (bitmap)
    scw.WriteBitmap(*bitmap);
#endif
  if (!url.isEmpty()) {
    GURL gurl = webkit_glue::KURLToGURL(url);
    scw.WriteBookmark(webkit_glue::StringToStdWString(title), gurl.spec());

    scw.WriteHTML(UrlToImageMarkup(url, title), "");

    scw.WriteText(ASCIIToWide(gurl.spec()));
  }
}

// Cookies --------------------------------------------------------------------

void ChromiumBridge::setCookies(
    const KURL& url, const KURL& policy_url, const String& cookie) {
  webkit_glue::SetCookie(
      webkit_glue::KURLToGURL(url),
      webkit_glue::KURLToGURL(policy_url),
      webkit_glue::StringToStdString(cookie));
}

String ChromiumBridge::cookies(const KURL& url, const KURL& policy_url) {
  return webkit_glue::StdStringToString(webkit_glue::GetCookies(
      webkit_glue::KURLToGURL(url),
      webkit_glue::KURLToGURL(policy_url)));
}

// DNS ------------------------------------------------------------------------

void ChromiumBridge::prefetchDNS(const String& hostname) {
  webkit_glue::PrefetchDns(webkit_glue::StringToStdString(hostname));
}

// Font -----------------------------------------------------------------------

#if defined(OS_WIN)
bool ChromiumBridge::ensureFontLoaded(HFONT font) {
  return webkit_glue::EnsureFontLoaded(font);
}
#endif

// Forms ----------------------------------------------------------------------

void ChromiumBridge::notifyFormStateChanged(const Document* doc) {
  webkit_glue::NotifyFormStateChanged(doc);
}

// JavaScript -----------------------------------------------------------------

void ChromiumBridge::notifyJSOutOfMemory(Frame* frame) {
  webkit_glue::NotifyJSOutOfMemory(frame);
}

// Language -------------------------------------------------------------------

String ChromiumBridge::computedDefaultLanguage() {
  return webkit_glue::StdWStringToString(webkit_glue::GetWebKitLocale());
}

// LayoutTestMode -------------------------------------------------------------

bool ChromiumBridge::layoutTestMode() {
  return webkit_glue::IsLayoutTestMode();
}

// MimeType -------------------------------------------------------------------

bool ChromiumBridge::matchesMIMEType(const String& pattern,
                                     const String& type) {
  return net::MatchesMimeType(webkit_glue::StringToStdString(pattern),
                              webkit_glue::StringToStdString(type));
}

String ChromiumBridge::mimeTypeForExtension(const String& ext) {
  if (ext.isEmpty())
    return String();

  std::string type;
  webkit_glue::GetMimeTypeFromExtension(webkit_glue::StringToStdWString(ext),
                                        &type);
  return webkit_glue::StdStringToString(type);
}

String ChromiumBridge::mimeTypeFromFile(const String& file_path) {
  if (file_path.isEmpty())
    return String();

  std::string type;
  webkit_glue::GetMimeTypeFromFile(webkit_glue::StringToStdWString(file_path),
                                   &type);
  return webkit_glue::StdStringToString(type);
}

String ChromiumBridge::preferredExtensionForMIMEType(const String& mime_type) {
  if (mime_type.isEmpty())
    return String();

  std::wstring stdext;
  webkit_glue::GetPreferredExtensionForMimeType(
      webkit_glue::StringToStdString(mime_type), &stdext);
  return webkit_glue::StdWStringToString(stdext);
}

// Plugin ---------------------------------------------------------------------

bool ChromiumBridge::getPlugins(bool refresh, Vector<PluginInfo*>* plugins) {
  std::vector< ::WebPluginInfo> glue_plugins;
  if (!webkit_glue::GetPlugins(refresh, &glue_plugins))
    return false;
  for (size_t i = 0; i < glue_plugins.size(); ++i) {
    WebCore::PluginInfo* rv = new WebCore::PluginInfo;
    const ::WebPluginInfo& plugin = glue_plugins[i];
    rv->name = webkit_glue::StdWStringToString(plugin.name);
    rv->desc = webkit_glue::StdWStringToString(plugin.desc);
    rv->file = webkit_glue::StdWStringToString(
        file_util::GetFilenameFromPath(plugin.file));
    for (size_t j = 0; j < plugin.mime_types.size(); ++ j) {
      WebCore::MimeClassInfo* new_mime = new WebCore::MimeClassInfo();
      const WebPluginMimeType& mime_type = plugin.mime_types[j];
      new_mime->desc = webkit_glue::StdWStringToString(mime_type.description);

      for (size_t k = 0; k < mime_type.file_extensions.size(); ++k) {
        if (new_mime->suffixes.length())
          new_mime->suffixes.append(",");

        new_mime->suffixes.append(webkit_glue::StdStringToString(
            mime_type.file_extensions[k]));
      }

      new_mime->type = webkit_glue::StdStringToString(mime_type.mime_type);
      new_mime->plugin = rv;
      rv->mimes.append(new_mime);
    }
    plugins->append(rv);
  }
  return true;
}

// Protocol -------------------------------------------------------------------

String ChromiumBridge::uiResourceProtocol() {
  return webkit_glue::StdStringToString(webkit_glue::GetUIResourceProtocol());
}

// Screen ---------------------------------------------------------------------

int ChromiumBridge::screenDepth(Widget* widget) {
  return webkit_glue::GetScreenInfo(ToPlatform(widget)).depth;
}

int ChromiumBridge::screenDepthPerComponent(Widget* widget) {
  return webkit_glue::GetScreenInfo(ToPlatform(widget)).depth_per_component;
}

bool ChromiumBridge::screenIsMonochrome(Widget* widget) {
  return webkit_glue::GetScreenInfo(ToPlatform(widget)).is_monochrome;
}

IntRect ChromiumBridge::screenRect(Widget* widget) {
  return webkit_glue::ToIntRect(
      webkit_glue::GetScreenInfo(ToPlatform(widget)).rect);
}

IntRect ChromiumBridge::screenAvailableRect(Widget* widget) {
  return webkit_glue::ToIntRect(
      webkit_glue::GetScreenInfo(ToPlatform(widget)).available_rect);
}

// StatsCounters --------------------------------------------------------------

void ChromiumBridge::decrementStatsCounter(const wchar_t* name) {
  StatsCounter(name).Decrement();
}

void ChromiumBridge::incrementStatsCounter(const wchar_t* name) {
  StatsCounter(name).Increment();
}

#if USE(V8)
void ChromiumBridge::initV8CounterFunction() {
  v8::V8::SetCounterFunction(StatsTable::FindLocation);
}
#endif

// Trace Event ----------------------------------------------------------------

void ChromiumBridge::traceEventBegin(const char* name,
                                     void* id,
                                     const char* extra) {
  TRACE_EVENT_BEGIN(name, id, extra);
}

void ChromiumBridge::traceEventEnd(const char* name,
                                   void* id,
                                   const char* extra) {
  TRACE_EVENT_END(name, id, extra);
}

// URL ------------------------------------------------------------------------

KURL ChromiumBridge::inspectorURL() {
  return webkit_glue::GURLToKURL(webkit_glue::GetInspectorURL());
}

// Widget ---------------------------------------------------------------------

void ChromiumBridge::widgetSetCursor(Widget* widget, const Cursor& cursor) {
  ChromeClientImpl* chrome_client = ToChromeClient(widget);
  if (chrome_client)
    chrome_client->SetCursor(WebCursor(cursor.impl()));
}

void ChromiumBridge::widgetSetFocus(Widget* widget) {
  ChromeClientImpl* chrome_client = ToChromeClient(widget);
  if (chrome_client)
    chrome_client->focus();
}

}  // namespace WebCore
<|endoftext|>


<commit_before>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: PiecewiseFunction_test.C,v 1.9 2003/06/12 14:50:13 anker Exp $
//

#include <BALL/CONCEPT/classTest.h>

///////////////////////////

#include <BALL/MATHS/piecewiseFunction.h>

///////////////////////////

START_TEST(PiecewiseFunction, "$Id: PiecewiseFunction_test.C,v 1.9 2003/06/12 14:50:13 anker Exp $")

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////

using namespace BALL;

Coefficients coef;
vector<Coefficients> coefs;
vector<Interval> intervals;

coef.push_back(0.0); coef.push_back(0.0);
coef.push_back(0.0); coef.push_back(0.0);
coefs.push_back(coef);
coef.clear();

coef.push_back(1.0); coef.push_back(1.0);
coef.push_back(0.0); coef.push_back(0.0);
coefs.push_back(coef);
coef.clear();

coef.push_back(0.0); coef.push_back(0.0);
coef.push_back(1.0); coef.push_back(0.0);
coefs.push_back(coef);
coef.clear();

intervals.push_back(Interval(0.0, 1.0));
intervals.push_back(Interval(1.0, 2.0));
intervals.push_back(Interval(2.0, 3.0));

PiecewiseFunction* pointer;

CHECK(PiecewiseFunction() throw())
	pointer = new PiecewiseFunction;
	TEST_NOT_EQUAL(pointer, 0)
RESULT

CHECK(~PiecewiseFunction() throw())
	delete pointer;
RESULT

CHECK(PiecewiseFunction(const PiecewiseFunction& function) throw())
	// ?????
	PiecewiseFunction PWF;
	PWF.setIntervals(intervals);
	PiecewiseFunction PWF2(PWF);
	TEST_EQUAL(PWF2.getIntervals().size(), PWF.getIntervals().size())
RESULT

CHECK(PiecewiseFunction(const std::vector<Interval>& intervals, const std::vector<Coefficients>& coeffs) throw())
	PiecewiseFunction PWF2(intervals, coefs);
	// Unter der Annahme, da operator== fr std::vector definiert ist und
	// funktioniert.
	bool test = (PWF2.getIntervals() == intervals);
	TEST_EQUAL(test, true);
	test = (PWF2.getCoefficients() == coefs);
	TEST_EQUAL(test, true);
	std::vector<Coefficients> naught;
	test = (PWF2.getCoefficients() == naught);
	TEST_EQUAL(test, false)
RESULT

CHECK(void clear() throw())
	PiecewiseFunction PWF2(intervals, coefs);
	PWF2.clear();
	std::vector<Interval> i2 = PWF2.getIntervals();
	std::vector<Interval> i3;
	bool test = (i2 == i3);
	TEST_EQUAL(test, true);
RESULT

CHECK(void set(const std::vector<Interval>& intervals, const std::vector<Coefficients>& coeffs) throw())
	PiecewiseFunction PWF2;
	PWF2.set(intervals, coefs);
	bool test = (PWF2.getIntervals() == intervals);
	TEST_EQUAL(test, true)
	test = (PWF2.getCoefficients() == coefs);
	TEST_EQUAL(test, true);
	std::vector<Coefficients> naught;
	test = (PWF2.getCoefficients() == naught);
	TEST_EQUAL(test, false)
RESULT

CHECK(PiecewiseFunction& operator = (const PiecewiseFunction& function) throw())
	PiecewiseFunction PWF2;
	PiecewiseFunction PWF3;
	PWF2 = PWF3;
	bool test = (PWF2.getIntervals() == PWF3.getIntervals());
	TEST_EQUAL(test, true);
	test = (PWF2.getCoefficients() == PWF3.getCoefficients());
	TEST_EQUAL(test, true);
RESULT

CHECK(void setIntervals(const std::vector<Interval>& intervals) throw())
	PiecewiseFunction PWF2;
	PWF2.setIntervals(intervals);
	bool test = (PWF2.getIntervals() == intervals);
	TEST_EQUAL(test,true);
RESULT

CHECK(const Interval& getInterval(double x) const throw(Exception::OutOfRange))
	PiecewiseFunction PWF2(intervals, coefs);
	TEST_REAL_EQUAL(PWF2.getInterval(0.5).first, 0.0)
	TEST_REAL_EQUAL(PWF2.getInterval(0.5).second, 1.0)
	TEST_REAL_EQUAL(PWF2.getInterval(1.0).first, 1.0)
	TEST_REAL_EQUAL(PWF2.getInterval(1.0).second, 2.0)
RESULT

CHECK(const Interval& getInterval(Position index) const throw(Exception::IndexOverflow))
	PiecewiseFunction PWF2(intervals, coefs);
	Position index = 1;
	TEST_REAL_EQUAL(PWF2.getInterval(index).first, 1.0)
	TEST_REAL_EQUAL(PWF2.getInterval(index).second, 2.0)
RESULT

CHECK(Position getIntervalIndex(double x) const throw(Exception::OutOfRange))
	PiecewiseFunction PWF2(intervals, coefs);
	TEST_EQUAL(PWF2.getIntervalIndex(0.5), 0)
RESULT

CHECK(const Interval& getRange() const throw())
	PiecewiseFunction PWF2(intervals, coefs);
	Interval val = PWF2.getRange();
	TEST_REAL_EQUAL(val.first, 0.0)
	TEST_REAL_EQUAL(val.second, 3.0)
RESULT

CHECK(void setCoefficients(const vector<Coefficients>& coefficients) throw())
	PiecewiseFunction PWF2;
	PWF2.setCoefficients(coefs);
	bool test = (PWF2.getCoefficients() == coefs);
	TEST_EQUAL(test, true)
	// ?????: false
RESULT

CHECK(const Coefficients& getCoefficients(double x) const throw(Exception::OutOfRange))
	PiecewiseFunction PWF2;
	PWF2.setCoefficients(coefs);
	Coefficients cf;
	// bool test = (PWF2.getCoefficients(0.5) == cf);
	TEST_EXCEPTION(Exception::OutOfRange, PWF2.getCoefficients(0.5))
	PWF2.setIntervals(intervals);
	bool test = (PWF2.getCoefficients(0.5) == coefs[0]);
	TEST_EQUAL(test, true)
RESULT

CHECK(const Coefficients& getCoefficients(Position index) const throw(Exception::IndexOverflow))
	PiecewiseFunction PWF2;
	PWF2.setCoefficients(coefs);
	Position index = 0;
	bool test = (PWF2.getCoefficients(index) == coefs[0]);
	TEST_EQUAL(test, true)
RESULT

CHECK(double operator () (double x) const throw())
  //?????: Quasi abstrakt.
RESULT

CHECK(bool isInRange(double x) const throw())
	PiecewiseFunction PWF2(intervals, coefs);
	TEST_EQUAL(PWF2.isInRange(2.5), true)
	TEST_EQUAL(PWF2.isInRange(6.5), false)
RESULT

CHECK(bool isValid() const throw())
	PiecewiseFunction PWF2;
	TEST_EQUAL(PWF2.isValid(), false)
	PWF2 = PiecewiseFunction(intervals, coefs);
	TEST_EQUAL(PWF2.isValid(), true);
RESULT

CHECK(BALL_CREATE(PiecewiseFunction))
  // ???
RESULT

CHECK(bool operator == (const PiecewiseFunction& function) const throw())
  // ???
RESULT

CHECK(const std::vector<Coefficients>& getCoefficients() const throw())
  // ???
RESULT

CHECK(const std::vector<Interval>& getIntervals() const throw())
  // ???
RESULT

CHECK(void dump(std::ostream& s = std::cout, Size depth = 0) const throw())
  // ???
RESULT

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
<commit_msg>added some tests<commit_after>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: PiecewiseFunction_test.C,v 1.10 2003/06/12 15:15:11 anker Exp $
//

#include <BALL/CONCEPT/classTest.h>

///////////////////////////

#include <BALL/MATHS/piecewiseFunction.h>

///////////////////////////

START_TEST(PiecewiseFunction, "$Id: PiecewiseFunction_test.C,v 1.10 2003/06/12 15:15:11 anker Exp $")

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////

using namespace BALL;

Coefficients coef;
vector<Coefficients> coefs;
vector<Interval> intervals;

coef.push_back(0.0); coef.push_back(0.0);
coef.push_back(0.0); coef.push_back(0.0);
coefs.push_back(coef);
coef.clear();

coef.push_back(1.0); coef.push_back(1.0);
coef.push_back(0.0); coef.push_back(0.0);
coefs.push_back(coef);
coef.clear();

coef.push_back(0.0); coef.push_back(0.0);
coef.push_back(1.0); coef.push_back(0.0);
coefs.push_back(coef);
coef.clear();

intervals.push_back(Interval(0.0, 1.0));
intervals.push_back(Interval(1.0, 2.0));
intervals.push_back(Interval(2.0, 3.0));

PiecewiseFunction* pointer;

CHECK(PiecewiseFunction() throw())
	pointer = new PiecewiseFunction;
	TEST_NOT_EQUAL(pointer, 0)
RESULT

CHECK(~PiecewiseFunction() throw())
	delete pointer;
RESULT

CHECK(PiecewiseFunction(const PiecewiseFunction& function) throw())
	PiecewiseFunction PWF;
	PWF.setIntervals(intervals);
	PiecewiseFunction PWF2(PWF);
	TEST_EQUAL(PWF2.getIntervals().size(), PWF.getIntervals().size())
RESULT

CHECK(PiecewiseFunction(const std::vector<Interval>& intervals, const std::vector<Coefficients>& coeffs) throw())
	PiecewiseFunction PWF2(intervals, coefs);
	// Unter der Annahme, da operator== fr std::vector definiert ist und
	// funktioniert.
	bool test = (PWF2.getIntervals() == intervals);
	TEST_EQUAL(test, true);
	test = (PWF2.getCoefficients() == coefs);
	TEST_EQUAL(test, true);
	std::vector<Coefficients> naught;
	test = (PWF2.getCoefficients() == naught);
	TEST_EQUAL(test, false)
RESULT

CHECK(void clear() throw())
	PiecewiseFunction PWF2(intervals, coefs);
	PWF2.clear();
	std::vector<Interval> i2 = PWF2.getIntervals();
	std::vector<Interval> i3;
	bool test = (i2 == i3);
	TEST_EQUAL(test, true);
RESULT

CHECK(void set(const std::vector<Interval>& intervals, const std::vector<Coefficients>& coeffs) throw())
	PiecewiseFunction PWF2;
	PWF2.set(intervals, coefs);
	bool test = (PWF2.getIntervals() == intervals);
	TEST_EQUAL(test, true)
	test = (PWF2.getCoefficients() == coefs);
	TEST_EQUAL(test, true);
	std::vector<Coefficients> naught;
	test = (PWF2.getCoefficients() == naught);
	TEST_EQUAL(test, false)
RESULT

CHECK(PiecewiseFunction& operator = (const PiecewiseFunction& function) throw())
	PiecewiseFunction PWF2;
	PiecewiseFunction PWF3;
	PWF2 = PWF3;
	bool test = (PWF2.getIntervals() == PWF3.getIntervals());
	TEST_EQUAL(test, true);
	test = (PWF2.getCoefficients() == PWF3.getCoefficients());
	TEST_EQUAL(test, true);
RESULT

CHECK(void setIntervals(const std::vector<Interval>& intervals) throw())
	PiecewiseFunction PWF2;
	PWF2.setIntervals(intervals);
	bool test = (PWF2.getIntervals() == intervals);
	TEST_EQUAL(test,true);
RESULT

CHECK(const Interval& getInterval(double x) const throw(Exception::OutOfRange))
	PiecewiseFunction PWF2(intervals, coefs);
	TEST_REAL_EQUAL(PWF2.getInterval(0.5).first, 0.0)
	TEST_REAL_EQUAL(PWF2.getInterval(0.5).second, 1.0)
	TEST_REAL_EQUAL(PWF2.getInterval(1.0).first, 1.0)
	TEST_REAL_EQUAL(PWF2.getInterval(1.0).second, 2.0)
RESULT

CHECK(const Interval& getInterval(Position index) const throw(Exception::IndexOverflow))
	PiecewiseFunction PWF2(intervals, coefs);
	Position index = 1;
	TEST_REAL_EQUAL(PWF2.getInterval(index).first, 1.0)
	TEST_REAL_EQUAL(PWF2.getInterval(index).second, 2.0)
RESULT

CHECK(Position getIntervalIndex(double x) const throw(Exception::OutOfRange))
	PiecewiseFunction PWF2(intervals, coefs);
	TEST_EQUAL(PWF2.getIntervalIndex(0.5), 0)
RESULT

CHECK(const Interval& getRange() const throw())
	PiecewiseFunction PWF2(intervals, coefs);
	Interval val = PWF2.getRange();
	TEST_REAL_EQUAL(val.first, 0.0)
	TEST_REAL_EQUAL(val.second, 3.0)
RESULT

CHECK(void setCoefficients(const vector<Coefficients>& coefficients) throw())
	PiecewiseFunction PWF2;
	PWF2.setCoefficients(coefs);
	bool test = (PWF2.getCoefficients() == coefs);
	TEST_EQUAL(test, true)
RESULT

CHECK(const Coefficients& getCoefficients(double x) const throw(Exception::OutOfRange))
	PiecewiseFunction PWF2;
	PWF2.setCoefficients(coefs);
	Coefficients cf;
	// bool test = (PWF2.getCoefficients(0.5) == cf);
	TEST_EXCEPTION(Exception::OutOfRange, PWF2.getCoefficients(0.5))
	PWF2.setIntervals(intervals);
	bool test = (PWF2.getCoefficients(0.5) == coefs[0]);
	TEST_EQUAL(test, true)
RESULT

CHECK(const Coefficients& getCoefficients(Position index) const throw(Exception::IndexOverflow))
	PiecewiseFunction PWF2;
	PWF2.setCoefficients(coefs);
	Position index = 0;
	bool test = (PWF2.getCoefficients(index) == coefs[0]);
	TEST_EQUAL(test, true)
RESULT

CHECK(double operator () (double x) const throw())
  //?????: Quasi abstrakt.
RESULT

CHECK(bool isInRange(double x) const throw())
	PiecewiseFunction PWF2(intervals, coefs);
	TEST_EQUAL(PWF2.isInRange(2.5), true)
	TEST_EQUAL(PWF2.isInRange(6.5), false)
RESULT

CHECK(bool isValid() const throw())
	PiecewiseFunction PWF2;
	TEST_EQUAL(PWF2.isValid(), false)
	PWF2 = PiecewiseFunction(intervals, coefs);
	TEST_EQUAL(PWF2.isValid(), true);
RESULT

CHECK(BALL_CREATE(PiecewiseFunction))
  // ???
RESULT

CHECK(bool operator == (const PiecewiseFunction& function) const throw())
	PiecewiseFunction PWF2;
	PiecewiseFunction PWF3;
	bool test = (PWF2 == PWF3);
	TEST_EQUAL(test, true)
	PWF2.setCoefficients(coefs);
	test = (PWF2 == PWF3);
	TEST_NOT_EQUAL(test, true)
	PWF3.setCoefficients(coefs);
	test = (PWF2 == PWF3);
	TEST_EQUAL(test, true)
	PWF2.setIntervals(intervals);
	test = (PWF2 == PWF3);
	TEST_NOT_EQUAL(test, true)
	PWF3.setIntervals(intervals);
	test = (PWF2 == PWF3);
	TEST_EQUAL(test, true)
RESULT

CHECK(const std::vector<Coefficients>& getCoefficients() const throw())
	PiecewiseFunction PWF2;
	TEST_EQUAL(PWF2.getCoefficients().size(), 0)
	PWF2.setCoefficients(coefs);
	TEST_EQUAL(PWF2.getCoefficients().size(), 3)
RESULT

CHECK(const std::vector<Interval>& getIntervals() const throw())
	PiecewiseFunction PWF2;
	TEST_EQUAL(PWF2.getIntervals().size(), 0)
	PWF2.setIntervals(intervals);
	TEST_EQUAL(PWF2.getIntervals().size(), 3)
RESULT

CHECK(void dump(std::ostream& s = std::cout, Size depth = 0) const throw())
	PiecewiseFunction PWF2(intervals, coefs);
	String filename;
	NEW_TMP_FILE(filename)
	std::ofstream outfile(filename.c_str(), std::ios::out);
	PWF2.dump(outfile);
	outfile.close();
	TEST_FILE(filename.c_str(), "data/PiecewiseFunction_test.txt")
RESULT

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


<commit_before>/*
 * Copyright 2006-2008 The FLWOR Foundation.
 *
 * 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 <sstream>
#include <map>

#include <zorba/zorba.h>
#include <zorba/external_module.h>
#include <zorba/external_function.h>
#include <zorba/item_factory.h>
#include <zorba/singleton_item_sequence.h>
#include <zorba/base64.h>

#include "md5_impl.h"
#include "sha1.h"

namespace zorba { namespace security {

zorba::String getOneStringArgument(const StatelessExternalFunction::Arguments_t& aArgs, int aIndex)
{
  zorba::Item lItem;
  if (!(aArgs[aIndex]->next(lItem))) {
    std::stringstream lErrorMessage;
    lErrorMessage << "An empty-sequence is not allowed as "
                  << aIndex << ". parameter.";
    throw zorba::ExternalFunctionData::createZorbaException(XPTY0004,
        lErrorMessage.str().c_str(),
        __FILE__,
        __LINE__);
  }
  zorba::String lTmpString = lItem.getStringValue();
  if (aArgs[aIndex]->next(lItem)) {
    std::stringstream lErrorMessage;
    lErrorMessage << "A sequence of more then one item is not allowed as "
      << aIndex << ". parameter.";
    throw zorba::ExternalFunctionData::createZorbaException(XPTY0004,
        lErrorMessage.str().c_str(),
        __FILE__,
        __LINE__);
  }
  return lTmpString;
}

static zorba::String getNodeText(
    const StatelessExternalFunction::Arguments_t&  aArgs,
    int                 aArgumentIndex)
{
  zorba::Item lItem;
  if (!(aArgs[aArgumentIndex]->next(lItem))) {
    std::stringstream lErrorMessage;
    lErrorMessage << "An empty-sequence is not allowed as " << aArgumentIndex << ". parameter.";
    throw zorba::ExternalFunctionData::createZorbaException(XPTY0004, lErrorMessage.str().c_str(), __FILE__, __LINE__);
  }
  std::stringstream lTmpStream;
  zorba::String lText = lItem.getStringValue();
  if (aArgs[aArgumentIndex]->next(lItem)) {
    std::stringstream lErrorMessage;
    lErrorMessage << "A sequence of more then one item is not allowed as " << aArgumentIndex << ". parameter.";
    throw zorba::ExternalFunctionData::createZorbaException(XPTY0004, lErrorMessage.str().c_str(), __FILE__, __LINE__);
  }
  return lText;
}

class HashModule : public ExternalModule
{
private:
  static ItemFactory* theFactory;

protected:
  class ltstr
  {
  public:
    bool operator()(const String& s1, const String& s2) const
    {
      return s1.compare(s2) < 0;
    }
  };

  typedef std::map<String, StatelessExternalFunction*, ltstr> FuncMap_t;
  mutable FuncMap_t theFunctions;

public:
  virtual ~HashModule()
  {
    for (FuncMap_t::const_iterator lIter = theFunctions.begin();
         lIter != theFunctions.end(); ++lIter) {
      delete lIter->second;
    }
    theFunctions.clear();
  }

  virtual String
  getURI() const { return "http://www.zorba-xquery.com/modules/security/hash"; }

  virtual StatelessExternalFunction*
  getExternalFunction(String aLocalname) const;

  virtual void
  destroy()
  {
    if (!dynamic_cast<HashModule*>(this)) {
      return;
    }
    delete this;
  }

  static ItemFactory*
  getItemFactory()
  {
    if(!theFactory)
      theFactory = Zorba::getInstance(0)->getItemFactory();
    return theFactory;
  }

};

class HashFunction : public PureStatelessExternalFunction
{
protected:
  const HashModule* theModule;

  static void throwError(
      const std::string aErrorMessage,
      const XQUERY_ERROR& aErrorType)
  {
    throw zorba::ExternalFunctionData::createZorbaException(
        aErrorType,
        aErrorMessage.c_str(),
        __FILE__, __LINE__);
  }

public:
  HashFunction(const HashModule* aModule): theModule(aModule){}
  ~HashFunction(){}

  virtual String
  getLocalName() const { return "hash-unchecked"; }

  virtual zorba::ItemSequence_t
  evaluate(const Arguments_t& aArgs) const
  {
    std::string lText = (getNodeText(aArgs, 0)).c_str();
    std::string lAlg = (getOneStringArgument(aArgs, 1)).c_str();
    zorba::String lHash;
    if (lAlg == "sha1") {
      CSHA1 lSha1;
      const unsigned char* lData = (const unsigned char*) lText.c_str();
      lSha1.Update(lData, lText.size());
      lSha1.Final();
      char lRes[65];
      lSha1.GetHash((UINT_8 *)lRes);
      lRes[20] = 0; // SHA1 is 20 bytes long
      zorba::String lDigest(lRes);
      lHash = zorba::encoding::Base64::encode(lDigest);
    } else {
      lHash = md5(lText);
    }
    // implement here
    zorba::Item lItem;
    lItem = theModule->getItemFactory()->createString(lHash);
    return zorba::ItemSequence_t(new zorba::SingletonItemSequence(lItem));
  }

  virtual String
  getURI() const
  {
    return theModule->getURI();
  }

};

StatelessExternalFunction* HashModule::getExternalFunction(
    String aLocalname) const
{
  StatelessExternalFunction*& lFunc = theFunctions[aLocalname];
  if (!lFunc) {
    if (aLocalname.equals("hash-unchecked")) {
      lFunc = new HashFunction(this);
    }
  }
  return lFunc;
}

ItemFactory* HashModule::theFactory = 0;

} /* namespace security */ } /* namespace zorba */

#ifdef WIN32
#  define DLL_EXPORT __declspec(dllexport)
#else
#  define DLL_EXPORT __attribute__ ((visibility("default")))
#endif

extern "C" DLL_EXPORT zorba::ExternalModule* createModule() {
  return new zorba::security::HashModule();
}
<commit_msg>avoid using a string because the sha1 hash might contain 0's, i.e. is null terminated<commit_after>/*
 * Copyright 2006-2008 The FLWOR Foundation.
 *
 * 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 <sstream>
#include <map>

#include <zorba/zorba.h>
#include <zorba/external_module.h>
#include <zorba/external_function.h>
#include <zorba/item_factory.h>
#include <zorba/singleton_item_sequence.h>
#include <zorba/base64.h>

#include "md5_impl.h"
#include "sha1.h"

namespace zorba { namespace security {

zorba::String getOneStringArgument(const StatelessExternalFunction::Arguments_t& aArgs, int aIndex)
{
  zorba::Item lItem;
  if (!(aArgs[aIndex]->next(lItem))) {
    std::stringstream lErrorMessage;
    lErrorMessage << "An empty-sequence is not allowed as "
                  << aIndex << ". parameter.";
    throw zorba::ExternalFunctionData::createZorbaException(XPTY0004,
        lErrorMessage.str().c_str(),
        __FILE__,
        __LINE__);
  }
  zorba::String lTmpString = lItem.getStringValue();
  if (aArgs[aIndex]->next(lItem)) {
    std::stringstream lErrorMessage;
    lErrorMessage << "A sequence of more then one item is not allowed as "
      << aIndex << ". parameter.";
    throw zorba::ExternalFunctionData::createZorbaException(XPTY0004,
        lErrorMessage.str().c_str(),
        __FILE__,
        __LINE__);
  }
  return lTmpString;
}

static zorba::String getNodeText(
    const StatelessExternalFunction::Arguments_t&  aArgs,
    int                 aArgumentIndex)
{
  zorba::Item lItem;
  if (!(aArgs[aArgumentIndex]->next(lItem))) {
    std::stringstream lErrorMessage;
    lErrorMessage << "An empty-sequence is not allowed as " << aArgumentIndex << ". parameter.";
    throw zorba::ExternalFunctionData::createZorbaException(XPTY0004, lErrorMessage.str().c_str(), __FILE__, __LINE__);
  }
  std::stringstream lTmpStream;
  zorba::String lText = lItem.getStringValue();
  if (aArgs[aArgumentIndex]->next(lItem)) {
    std::stringstream lErrorMessage;
    lErrorMessage << "A sequence of more then one item is not allowed as " << aArgumentIndex << ". parameter.";
    throw zorba::ExternalFunctionData::createZorbaException(XPTY0004, lErrorMessage.str().c_str(), __FILE__, __LINE__);
  }
  return lText;
}

class HashModule : public ExternalModule
{
private:
  static ItemFactory* theFactory;

protected:
  class ltstr
  {
  public:
    bool operator()(const String& s1, const String& s2) const
    {
      return s1.compare(s2) < 0;
    }
  };

  typedef std::map<String, StatelessExternalFunction*, ltstr> FuncMap_t;
  mutable FuncMap_t theFunctions;

public:
  virtual ~HashModule()
  {
    for (FuncMap_t::const_iterator lIter = theFunctions.begin();
         lIter != theFunctions.end(); ++lIter) {
      delete lIter->second;
    }
    theFunctions.clear();
  }

  virtual String
  getURI() const { return "http://www.zorba-xquery.com/modules/security/hash"; }

  virtual StatelessExternalFunction*
  getExternalFunction(String aLocalname) const;

  virtual void
  destroy()
  {
    if (!dynamic_cast<HashModule*>(this)) {
      return;
    }
    delete this;
  }

  static ItemFactory*
  getItemFactory()
  {
    if(!theFactory)
      theFactory = Zorba::getInstance(0)->getItemFactory();
    return theFactory;
  }

};

class HashFunction : public PureStatelessExternalFunction
{
protected:
  const HashModule* theModule;

  static void throwError(
      const std::string aErrorMessage,
      const XQUERY_ERROR& aErrorType)
  {
    throw zorba::ExternalFunctionData::createZorbaException(
        aErrorType,
        aErrorMessage.c_str(),
        __FILE__, __LINE__);
  }

public:
  HashFunction(const HashModule* aModule): theModule(aModule){}
  ~HashFunction(){}

  virtual String
  getLocalName() const { return "hash-unchecked"; }

  virtual zorba::ItemSequence_t
  evaluate(const Arguments_t& aArgs) const
  {
    std::string lText = (getNodeText(aArgs, 0)).c_str();
    std::string lAlg = (getOneStringArgument(aArgs, 1)).c_str();
    zorba::String lHash;
    if (lAlg == "sha1") {
      CSHA1 lSha1;
      const unsigned char* lData = (const unsigned char*) lText.c_str();
      lSha1.Update(lData, lText.size());
      lSha1.Final();
      char lRes[65];
      lSha1.GetHash((UINT_8 *)lRes);

      // SHA1 is always 20bytes long
      // avoid using a stream here because it might contain 0's
      // (i.e. be null terminated)
      std::stringstream lTmp;
      lTmp.write(lRes, 20);

      lHash = zorba::encoding::Base64::encode(lTmp);
    } else {
      lHash = md5(lText);
    }
    // implement here
    zorba::Item lItem;
    lItem = theModule->getItemFactory()->createString(lHash);
    return zorba::ItemSequence_t(new zorba::SingletonItemSequence(lItem));
  }

  virtual String
  getURI() const
  {
    return theModule->getURI();
  }

};

StatelessExternalFunction* HashModule::getExternalFunction(
    String aLocalname) const
{
  StatelessExternalFunction*& lFunc = theFunctions[aLocalname];
  if (!lFunc) {
    if (aLocalname.equals("hash-unchecked")) {
      lFunc = new HashFunction(this);
    }
  }
  return lFunc;
}

ItemFactory* HashModule::theFactory = 0;

} /* namespace security */ } /* namespace zorba */

#ifdef WIN32
#  define DLL_EXPORT __declspec(dllexport)
#else
#  define DLL_EXPORT __attribute__ ((visibility("default")))
#endif

extern "C" DLL_EXPORT zorba::ExternalModule* createModule() {
  return new zorba::security::HashModule();
}
<|endoftext|>


<commit_before>/// \file minimizer_mapper.cpp
///
/// unit tests for the minimizer mapper

#include <iostream>
#include "json2pb.h"
#include <vg/vg.pb.h>
#include "../minimizer_mapper.hpp"
#include "../build_index.hpp"
#include "xg.hpp"
#include "vg.hpp"
#include "catch.hpp"

namespace vg {
namespace unittest {

// We define a child class to expose all the protected stuff for testing
class TestMinimizerMapper : public MinimizerMapper {
public:
    using MinimizerMapper::MinimizerMapper;
    using MinimizerMapper::score_extension_group;
};

TEST_CASE("MinimizerMapper::score_extension_group works", "[giraffe][mapping]") {

    // Define an Alignment to score extensions against.
    Alignment aln;
    aln.set_sequence("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");

    // Define a bunch of fake GaplessExtensions to chain up and score
    vector<GaplessExtension> to_score;

    SECTION("Score of no gapless extensions is 0") {
        REQUIRE(TestMinimizerMapper::score_extension_group(aln, to_score, 6, 1) == 0);
    }

    SECTION("One-base extensions work") {

        to_score.emplace_back();
        to_score.back().read_interval.first = 1;
        to_score.back().read_interval.second = 2;
        to_score.back().score = 1;

        SECTION("Score of a 1-base gapless extension is 1") {
            REQUIRE(TestMinimizerMapper::score_extension_group(aln, to_score, 6, 1) == 1);
        }

        to_score.emplace_back();
        to_score.back().read_interval.first = 2;
        to_score.back().read_interval.second = 3;
        to_score.back().score = 1;

        SECTION("Score of two adjacent 1-base gapless extensions is 2") {
            REQUIRE(TestMinimizerMapper::score_extension_group(aln, to_score, 6, 1) == 2);
        }

    }

    SECTION("Longer extensions work") {

        to_score.emplace_back();
        to_score.back().read_interval.first = 1;
        to_score.back().read_interval.second = 10;
        to_score.back().score = 9;

        SECTION("Score of one 9-base extension is 9") {
            REQUIRE(TestMinimizerMapper::score_extension_group(aln, to_score, 6, 1) == 9);
        }

        to_score.emplace_back();
        to_score.back().read_interval.first = 10;
        to_score.back().read_interval.second = 19;
        to_score.back().score = 9;

        SECTION("Score of two 9-base extensions abutting is 18") {
            REQUIRE(TestMinimizerMapper::score_extension_group(aln, to_score, 6, 1) == 18);
        }

        to_score.back().read_interval.first++;
        to_score.back().read_interval.second++;

        SECTION("Score of two 9-base extensions separated by a 1-base gap is 12") {
            REQUIRE(TestMinimizerMapper::score_extension_group(aln, to_score, 6, 1) == 12);
        }

        to_score.back().read_interval.first++;
        to_score.back().read_interval.second++;

        SECTION("Score of two 9-base extensions separated by a 2-base gap is 11") {
            REQUIRE(TestMinimizerMapper::score_extension_group(aln, to_score, 6, 1) == 11);
        }

        to_score.back().read_interval.first -= 3;
        to_score.back().read_interval.second -= 3;

        SECTION("Score of two 9-base extensions with a 1-base ovealap is 12") {
            REQUIRE(TestMinimizerMapper::score_extension_group(aln, to_score, 6, 1) == 11);
        }
    }
}

}

}
<commit_msg>Add more unit tests for new scoring<commit_after>/// \file minimizer_mapper.cpp
///
/// unit tests for the minimizer mapper

#include <iostream>
#include "json2pb.h"
#include <vg/vg.pb.h>
#include "../minimizer_mapper.hpp"
#include "../build_index.hpp"
#include "xg.hpp"
#include "vg.hpp"
#include "catch.hpp"

namespace vg {
namespace unittest {

// We define a child class to expose all the protected stuff for testing
class TestMinimizerMapper : public MinimizerMapper {
public:
    using MinimizerMapper::MinimizerMapper;
    using MinimizerMapper::score_extension_group;
};

TEST_CASE("MinimizerMapper::score_extension_group works", "[giraffe][mapping]") {

    // Define an Alignment to score extensions against.
    Alignment aln;
    aln.set_sequence("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");

    // Define a bunch of fake GaplessExtensions to chain up and score
    vector<GaplessExtension> to_score;

    SECTION("Score of no gapless extensions is 0") {
        REQUIRE(TestMinimizerMapper::score_extension_group(aln, to_score, 6, 1) == 0);
    }

    SECTION("One-base extensions work") {

        to_score.emplace_back();
        to_score.back().read_interval.first = 1;
        to_score.back().read_interval.second = 2;
        to_score.back().score = 1;

        SECTION("Score of a 1-base gapless extension is 1") {
            REQUIRE(TestMinimizerMapper::score_extension_group(aln, to_score, 6, 1) == 1);
        }

        to_score.emplace_back();
        to_score.back().read_interval.first = 2;
        to_score.back().read_interval.second = 3;
        to_score.back().score = 1;

        SECTION("Score of two adjacent 1-base gapless extensions is 2") {
            REQUIRE(TestMinimizerMapper::score_extension_group(aln, to_score, 6, 1) == 2);
        }

    }

    SECTION("Longer extensions work") {

        to_score.emplace_back();
        to_score.back().read_interval.first = 1;
        to_score.back().read_interval.second = 10;
        to_score.back().score = 9;

        SECTION("Score of one 9-base extension is 9") {
            REQUIRE(TestMinimizerMapper::score_extension_group(aln, to_score, 6, 1) == 9);
        }

        to_score.emplace_back();
        to_score.back().read_interval.first = 10;
        to_score.back().read_interval.second = 19;
        to_score.back().score = 9;

        SECTION("Score of two 9-base extensions abutting is 18") {
            REQUIRE(TestMinimizerMapper::score_extension_group(aln, to_score, 6, 1) == 18);
        }

        to_score.back().read_interval.first++;
        to_score.back().read_interval.second++;

        SECTION("Score of two 9-base extensions separated by a 1-base gap is 12") {
            REQUIRE(TestMinimizerMapper::score_extension_group(aln, to_score, 6, 1) == 12);
        }

        to_score.back().read_interval.first++;
        to_score.back().read_interval.second++;

        SECTION("Score of two 9-base extensions separated by a 2-base gap is 11") {
            REQUIRE(TestMinimizerMapper::score_extension_group(aln, to_score, 6, 1) == 11);
        }

        to_score.back().read_interval.first -= 3;
        to_score.back().read_interval.second -= 3;

        SECTION("Score of two 9-base extensions with a 1-base ovealap is 12") {
            REQUIRE(TestMinimizerMapper::score_extension_group(aln, to_score, 6, 1) == 11);
        }
    }

    SECTION("Many possibly overlapping extensions work") {

        to_score.emplace_back();
        to_score.back().read_interval.first = 0;
        to_score.back().read_interval.second = 1;
        to_score.back().score = 1;

        for (size_t i = 0; i < 35; i++) {

            to_score.emplace_back();
            to_score.back().read_interval.first = i + 1;
            to_score.back().read_interval.second = i + 1 + 30;
            to_score.back().score = 30;

        }

        SECTION("Score of one 1-base extensions and 2 30-base extensions is 61") {
            REQUIRE(TestMinimizerMapper::score_extension_group(aln, to_score, 6, 1) == 61);
        }

        to_score.emplace_back();
        to_score.back().read_interval.first = 28;
        to_score.back().read_interval.second = 28 + 45;
        to_score.back().score = 45;

        // Sort by read interval as is required
        std::sort(to_score.begin(), to_score.end(), [](const GaplessExtension& a, const GaplessExtension& b) {
            return (a.read_interval.first < b.read_interval.first) ||
                (a.read_interval.first == b.read_interval.first && a.read_interval.second < b.read_interval.second);
        });

        SECTION("Score of one 1-base extension, a 30-base extension, a backtrack of 4, and a 45-base extension is correct") {
            REQUIRE(TestMinimizerMapper::score_extension_group(aln, to_score, 6, 1) == (31 + 45 - 6 - 3));
        }

        for (size_t i = 3; i < 29; i++) {
             to_score.emplace_back();
            to_score.back().read_interval.first = i;
            to_score.back().read_interval.second = i + 15;
            to_score.back().score = 15;
        }

        // Sort by read interval as is required
        std::sort(to_score.begin(), to_score.end(), [](const GaplessExtension& a, const GaplessExtension& b) {
            return (a.read_interval.first < b.read_interval.first) ||
                (a.read_interval.first == b.read_interval.first && a.read_interval.second < b.read_interval.second);
        });

        SECTION("Score of one 1-base extension, a 30-base extension, a backtrack of 4, and a 45-base extension is not distracted") {
            REQUIRE(TestMinimizerMapper::score_extension_group(aln, to_score, 6, 1) == (31 + 45 - 6 - 3));
        }

    }
}

}

}
<|endoftext|>